python-kasa 0.7.0.dev5__py3-none-any.whl → 0.7.0.2__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.
- kasa/aestransport.py +13 -4
- kasa/cli.py +60 -45
- kasa/device.py +110 -2
- kasa/discover.py +2 -1
- kasa/exceptions.py +10 -0
- kasa/feature.py +88 -11
- kasa/httpclient.py +1 -1
- kasa/interfaces/energy.py +6 -0
- kasa/interfaces/light.py +61 -1
- kasa/interfaces/lighteffect.py +41 -1
- kasa/interfaces/lightpreset.py +70 -2
- kasa/iot/iotdevice.py +6 -1
- kasa/iot/iotstrip.py +23 -8
- kasa/iot/modules/lightpreset.py +2 -1
- kasa/module.py +42 -1
- kasa/smart/effects.py +25 -0
- kasa/smart/modules/__init__.py +2 -0
- kasa/smart/modules/alarm.py +1 -0
- kasa/smart/modules/autooff.py +3 -1
- kasa/smart/modules/brightness.py +14 -1
- kasa/smart/modules/childdevice.py +39 -1
- kasa/smart/modules/firmware.py +4 -1
- kasa/smart/modules/frostprotection.py +0 -22
- kasa/smart/modules/humiditysensor.py +1 -0
- kasa/smart/modules/led.py +1 -1
- kasa/smart/modules/lighteffect.py +70 -6
- kasa/smart/modules/lightpreset.py +2 -1
- kasa/smart/modules/lightstripeffect.py +38 -8
- kasa/smart/modules/lighttransition.py +101 -55
- kasa/smart/modules/reportmode.py +2 -0
- kasa/smart/modules/temperaturecontrol.py +3 -2
- kasa/smart/modules/temperaturesensor.py +3 -2
- kasa/smart/modules/time.py +3 -2
- kasa/smart/modules/waterleaksensor.py +2 -0
- kasa/smart/smartdevice.py +10 -5
- kasa/smartprotocol.py +42 -6
- kasa/tests/device_fixtures.py +9 -3
- kasa/tests/discovery_fixtures.py +6 -2
- kasa/tests/fakeprotocol_smart.py +73 -4
- kasa/tests/fixtureinfo.py +21 -3
- kasa/tests/smart/modules/test_firmware.py +12 -1
- kasa/tests/smart/modules/test_light_effect.py +42 -0
- kasa/tests/smart/modules/test_light_strip_effect.py +101 -0
- kasa/tests/smart/modules/test_lighttransition.py +80 -0
- kasa/tests/test_aestransport.py +27 -0
- kasa/tests/test_childdevice.py +21 -1
- kasa/tests/test_cli.py +18 -3
- kasa/tests/test_common_modules.py +9 -5
- kasa/tests/test_device.py +2 -1
- kasa/tests/test_device_factory.py +35 -17
- kasa/tests/test_emeter.py +8 -8
- kasa/tests/test_feature.py +6 -2
- kasa/tests/test_httpclient.py +2 -2
- kasa/tests/test_iotdevice.py +5 -4
- kasa/tests/test_readme_examples.py +59 -0
- kasa/tests/test_smartdevice.py +4 -3
- kasa/tests/test_smartprotocol.py +109 -7
- kasa/tests/test_strip.py +15 -2
- kasa/xortransport.py +3 -3
- {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/METADATA +102 -129
- {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/RECORD +64 -62
- {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/LICENSE +0 -0
- {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.dist-info}/WHEEL +0 -0
- {python_kasa-0.7.0.dev5.dist-info → python_kasa-0.7.0.2.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,
|
|
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
|
|
@@ -139,8 +140,13 @@ class AesTransport(BaseTransport):
|
|
|
139
140
|
return un, pw
|
|
140
141
|
|
|
141
142
|
def _handle_response_error_code(self, resp_dict: Any, msg: str) -> None:
|
|
142
|
-
|
|
143
|
-
|
|
143
|
+
error_code_raw = resp_dict.get("error_code")
|
|
144
|
+
try:
|
|
145
|
+
error_code = SmartErrorCode.from_int(error_code_raw)
|
|
146
|
+
except ValueError:
|
|
147
|
+
_LOGGER.warning("Received unknown error code: %s", error_code_raw)
|
|
148
|
+
error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR
|
|
149
|
+
if error_code is SmartErrorCode.SUCCESS:
|
|
144
150
|
return
|
|
145
151
|
msg = f"{msg}: {self._host}: {error_code.name}({error_code.value})"
|
|
146
152
|
if error_code in SMART_RETRYABLE_ERRORS:
|
|
@@ -371,7 +377,10 @@ class AesEncyptionSession:
|
|
|
371
377
|
handshake_key_bytes: bytes = base64.b64decode(handshake_key.encode("UTF-8"))
|
|
372
378
|
private_key_data = base64.b64decode(keypair.get_private_key().encode("UTF-8"))
|
|
373
379
|
|
|
374
|
-
private_key =
|
|
380
|
+
private_key = cast(
|
|
381
|
+
rsa.RSAPrivateKey,
|
|
382
|
+
serialization.load_der_private_key(private_key_data, None, None),
|
|
383
|
+
)
|
|
375
384
|
key_and_iv = private_key.decrypt(
|
|
376
385
|
handshake_key_bytes, asymmetric_padding.PKCS1v15()
|
|
377
386
|
)
|
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.
|
|
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
|
-
|
|
401
|
-
|
|
402
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
626
|
+
echo(f"[bold]\n{indent}== {title_prefix} ==[/bold]")
|
|
627
627
|
_echo_features(
|
|
628
628
|
features,
|
|
629
|
-
title="
|
|
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="
|
|
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="
|
|
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="
|
|
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"
|
|
662
|
-
echo(f"
|
|
663
|
-
echo(f"
|
|
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("
|
|
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}
|
|
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:
|
|
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:
|
|
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:
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1286
|
+
_echo_all_features(
|
|
1273
1287
|
child_dev.features,
|
|
1274
|
-
|
|
1275
|
-
|
|
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
|
-
"""
|
|
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
|
|
112
|
+
from typing import TYPE_CHECKING, Any
|
|
10
113
|
from warnings import warn
|
|
11
114
|
|
|
12
115
|
from typing_extensions import TypeAlias
|
|
@@ -225,6 +328,11 @@ class Device(ABC):
|
|
|
225
328
|
"""Send a raw query to the device."""
|
|
226
329
|
return await self.protocol.query(request=request)
|
|
227
330
|
|
|
331
|
+
@property
|
|
332
|
+
def parent(self) -> Device | None:
|
|
333
|
+
"""Return the parent on child devices."""
|
|
334
|
+
return self._parent
|
|
335
|
+
|
|
228
336
|
@property
|
|
229
337
|
def children(self) -> Sequence[Device]:
|
|
230
338
|
"""Returns the child devices."""
|
kasa/discover.py
CHANGED
|
@@ -86,7 +86,8 @@ import binascii
|
|
|
86
86
|
import ipaddress
|
|
87
87
|
import logging
|
|
88
88
|
import socket
|
|
89
|
-
from
|
|
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/exceptions.py
CHANGED
|
@@ -4,6 +4,7 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
from asyncio import TimeoutError as _asyncioTimeoutError
|
|
6
6
|
from enum import IntEnum
|
|
7
|
+
from functools import cache
|
|
7
8
|
from typing import Any
|
|
8
9
|
|
|
9
10
|
|
|
@@ -63,6 +64,12 @@ class SmartErrorCode(IntEnum):
|
|
|
63
64
|
def __str__(self):
|
|
64
65
|
return f"{self.name}({self.value})"
|
|
65
66
|
|
|
67
|
+
@staticmethod
|
|
68
|
+
@cache
|
|
69
|
+
def from_int(value: int) -> SmartErrorCode:
|
|
70
|
+
"""Convert an integer to a SmartErrorCode."""
|
|
71
|
+
return SmartErrorCode(value)
|
|
72
|
+
|
|
66
73
|
SUCCESS = 0
|
|
67
74
|
|
|
68
75
|
# Transport Errors
|
|
@@ -119,6 +126,9 @@ class SmartErrorCode(IntEnum):
|
|
|
119
126
|
DST_ERROR = -2301
|
|
120
127
|
DST_SAVE_ERROR = -2302
|
|
121
128
|
|
|
129
|
+
# Library internal for unknown error codes
|
|
130
|
+
INTERNAL_UNKNOWN_ERROR = -100_000
|
|
131
|
+
|
|
122
132
|
|
|
123
133
|
SMART_RETRYABLE_ERRORS = [
|
|
124
134
|
SmartErrorCode.TRANSPORT_NOT_AVAILABLE_ERROR,
|
kasa/feature.py
CHANGED
|
@@ -1,4 +1,67 @@
|
|
|
1
|
-
"""
|
|
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
|
-
#
|
|
102
|
+
# Aliases for easy access
|
|
40
103
|
Sensor = Type.Sensor
|
|
41
104
|
BinarySensor = Type.BinarySensor
|
|
42
105
|
Switch = Type.Switch
|
|
@@ -44,6 +107,8 @@ class Feature:
|
|
|
44
107
|
Number = Type.Number
|
|
45
108
|
Choice = Type.Choice
|
|
46
109
|
|
|
110
|
+
DEFAULT_MAX = 2**16 # Arbitrary max
|
|
111
|
+
|
|
47
112
|
class Category(Enum):
|
|
48
113
|
"""Category hint to allow feature grouping."""
|
|
49
114
|
|
|
@@ -66,6 +131,8 @@ class Feature:
|
|
|
66
131
|
id: str
|
|
67
132
|
#: User-friendly short description
|
|
68
133
|
name: str
|
|
134
|
+
#: Type of the feature
|
|
135
|
+
type: Feature.Type
|
|
69
136
|
#: Name of the property that allows accessing the value
|
|
70
137
|
attribute_getter: str | Callable | None = None
|
|
71
138
|
#: Name of the method that allows changing the value
|
|
@@ -76,10 +143,11 @@ class Feature:
|
|
|
76
143
|
icon: str | None = None
|
|
77
144
|
#: Unit, if applicable
|
|
78
145
|
unit: str | None = None
|
|
146
|
+
#: Attribute containing the name of the unit getter property.
|
|
147
|
+
#: If set, this property will be used to set *unit*.
|
|
148
|
+
unit_getter: str | None = None
|
|
79
149
|
#: Category hint for downstreams
|
|
80
150
|
category: Feature.Category = Category.Unset
|
|
81
|
-
#: Type of the feature
|
|
82
|
-
type: Feature.Type = Type.Sensor
|
|
83
151
|
|
|
84
152
|
# Display hints offer a way suggest how the value should be shown to users
|
|
85
153
|
#: Hint to help rounding the sensor values to given after-comma digits
|
|
@@ -89,7 +157,7 @@ class Feature:
|
|
|
89
157
|
#: Minimum value
|
|
90
158
|
minimum_value: int = 0
|
|
91
159
|
#: Maximum value
|
|
92
|
-
maximum_value: int =
|
|
160
|
+
maximum_value: int = DEFAULT_MAX
|
|
93
161
|
#: Attribute containing the name of the range getter property.
|
|
94
162
|
#: If set, this property will be used to set *minimum_value* and *maximum_value*.
|
|
95
163
|
range_getter: str | None = None
|
|
@@ -114,6 +182,10 @@ class Feature:
|
|
|
114
182
|
if self.choices_getter is not None:
|
|
115
183
|
self.choices = getattr(container, self.choices_getter)
|
|
116
184
|
|
|
185
|
+
# Populate unit, if unit_getter is given
|
|
186
|
+
if self.unit_getter is not None:
|
|
187
|
+
self.unit = getattr(container, self.unit_getter)
|
|
188
|
+
|
|
117
189
|
# Set the category, if unset
|
|
118
190
|
if self.category is Feature.Category.Unset:
|
|
119
191
|
if self.attribute_setter:
|
|
@@ -121,14 +193,19 @@ class Feature:
|
|
|
121
193
|
else:
|
|
122
194
|
self.category = Feature.Category.Info
|
|
123
195
|
|
|
124
|
-
if self.
|
|
196
|
+
if self.type in (
|
|
125
197
|
Feature.Type.Sensor,
|
|
126
198
|
Feature.Type.BinarySensor,
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
199
|
+
):
|
|
200
|
+
if self.category == Feature.Category.Config:
|
|
201
|
+
raise ValueError(
|
|
202
|
+
f"Invalid type for configurable feature: {self.name} ({self.id}):"
|
|
203
|
+
f" {self.type}"
|
|
204
|
+
)
|
|
205
|
+
elif self.attribute_setter is not None:
|
|
206
|
+
raise ValueError(
|
|
207
|
+
f"Read-only feat defines attribute_setter: {self.name} ({self.id}):"
|
|
208
|
+
)
|
|
132
209
|
|
|
133
210
|
@property
|
|
134
211
|
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
|
|