python-kasa 0.7.0.dev4__py3-none-any.whl → 0.7.0.dev5__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/cli.py CHANGED
@@ -9,6 +9,7 @@ import logging
9
9
  import re
10
10
  import sys
11
11
  from contextlib import asynccontextmanager
12
+ from datetime import datetime
12
13
  from functools import singledispatch, wraps
13
14
  from pprint import pformat as pf
14
15
  from typing import Any, cast
@@ -70,6 +71,12 @@ except ImportError:
70
71
  echo = _do_echo
71
72
 
72
73
 
74
+ def error(msg: str):
75
+ """Print an error and exit."""
76
+ echo(f"[bold red]{msg}[/bold red]")
77
+ sys.exit(1)
78
+
79
+
73
80
  TYPE_TO_CLASS = {
74
81
  "plug": IotPlug,
75
82
  "switch": IotWallSwitch,
@@ -366,6 +373,9 @@ async def cli(
366
373
  credentials = None
367
374
 
368
375
  if host is None:
376
+ if ctx.invoked_subcommand and ctx.invoked_subcommand != "discover":
377
+ error("Only discover is available without --host or --alias")
378
+
369
379
  echo("No host name given, trying discovery..")
370
380
  return await ctx.invoke(discover)
371
381
 
@@ -763,7 +773,7 @@ async def emeter(dev: Device, index: int, name: str, year, month, erase):
763
773
  """
764
774
  if index is not None or name is not None:
765
775
  if not dev.is_strip:
766
- echo("Index and name are only for power strips!")
776
+ error("Index and name are only for power strips!")
767
777
  return
768
778
 
769
779
  if index is not None:
@@ -773,11 +783,11 @@ async def emeter(dev: Device, index: int, name: str, year, month, erase):
773
783
 
774
784
  echo("[bold]== Emeter ==[/bold]")
775
785
  if not dev.has_emeter:
776
- echo("Device has no emeter")
786
+ error("Device has no emeter")
777
787
  return
778
788
 
779
789
  if (year or month or erase) and not isinstance(dev, IotDevice):
780
- echo("Device has no historical statistics")
790
+ error("Device has no historical statistics")
781
791
  return
782
792
  else:
783
793
  dev = cast(IotDevice, dev)
@@ -864,7 +874,7 @@ async def usage(dev: Device, year, month, erase):
864
874
  async def brightness(dev: Device, brightness: int, transition: int):
865
875
  """Get or set brightness."""
866
876
  if not (light := dev.modules.get(Module.Light)) or not light.is_dimmable:
867
- echo("This device does not support brightness.")
877
+ error("This device does not support brightness.")
868
878
  return
869
879
 
870
880
  if brightness is None:
@@ -884,7 +894,7 @@ async def brightness(dev: Device, brightness: int, transition: int):
884
894
  async def temperature(dev: Device, temperature: int, transition: int):
885
895
  """Get or set color temperature."""
886
896
  if not (light := dev.modules.get(Module.Light)) or not light.is_variable_color_temp:
887
- echo("Device does not support color temperature")
897
+ error("Device does not support color temperature")
888
898
  return
889
899
 
890
900
  if temperature is None:
@@ -910,7 +920,7 @@ async def temperature(dev: Device, temperature: int, transition: int):
910
920
  async def effect(dev: Device, ctx, effect):
911
921
  """Set an effect."""
912
922
  if not (light_effect := dev.modules.get(Module.LightEffect)):
913
- echo("Device does not support effects")
923
+ error("Device does not support effects")
914
924
  return
915
925
  if effect is None:
916
926
  echo(
@@ -938,7 +948,7 @@ async def effect(dev: Device, ctx, effect):
938
948
  async def hsv(dev: Device, ctx, h, s, v, transition):
939
949
  """Get or set color in HSV."""
940
950
  if not (light := dev.modules.get(Module.Light)) or not light.is_color:
941
- echo("Device does not support colors")
951
+ error("Device does not support colors")
942
952
  return
943
953
 
944
954
  if h is None and s is None and v is None:
@@ -957,7 +967,7 @@ async def hsv(dev: Device, ctx, h, s, v, transition):
957
967
  async def led(dev: Device, state):
958
968
  """Get or set (Plug's) led state."""
959
969
  if not (led := dev.modules.get(Module.Led)):
960
- echo("Device does not support led.")
970
+ error("Device does not support led.")
961
971
  return
962
972
  if state is not None:
963
973
  echo(f"Turning led to {state}")
@@ -967,15 +977,43 @@ async def led(dev: Device, state):
967
977
  return led.led
968
978
 
969
979
 
970
- @cli.command()
980
+ @cli.group(invoke_without_command=True)
981
+ @click.pass_context
982
+ async def time(ctx: click.Context):
983
+ """Get and set time."""
984
+ if ctx.invoked_subcommand is None:
985
+ await ctx.invoke(time_get)
986
+
987
+
988
+ @time.command(name="get")
971
989
  @pass_dev
972
- async def time(dev):
990
+ async def time_get(dev: Device):
973
991
  """Get the device time."""
974
992
  res = dev.time
975
993
  echo(f"Current time: {res}")
976
994
  return res
977
995
 
978
996
 
997
+ @time.command(name="sync")
998
+ @pass_dev
999
+ async def time_sync(dev: SmartDevice):
1000
+ """Set the device time to current time."""
1001
+ if not isinstance(dev, SmartDevice):
1002
+ raise NotImplementedError("setting time currently only implemented on smart")
1003
+
1004
+ if (time := dev.modules.get(Module.Time)) is None:
1005
+ echo("Device does not have time module")
1006
+ return
1007
+
1008
+ echo("Old time: %s" % time.time)
1009
+
1010
+ local_tz = datetime.now().astimezone().tzinfo
1011
+ await time.set_time(datetime.now(tz=local_tz))
1012
+
1013
+ await dev.update()
1014
+ echo("New time: %s" % time.time)
1015
+
1016
+
979
1017
  @cli.command()
980
1018
  @click.option("--index", type=int, required=False)
981
1019
  @click.option("--name", type=str, required=False)
@@ -985,7 +1023,7 @@ async def on(dev: Device, index: int, name: str, transition: int):
985
1023
  """Turn the device on."""
986
1024
  if index is not None or name is not None:
987
1025
  if not dev.children:
988
- echo("Index and name are only for devices with children.")
1026
+ error("Index and name are only for devices with children.")
989
1027
  return
990
1028
 
991
1029
  if index is not None:
@@ -1006,7 +1044,7 @@ async def off(dev: Device, index: int, name: str, transition: int):
1006
1044
  """Turn the device off."""
1007
1045
  if index is not None or name is not None:
1008
1046
  if not dev.children:
1009
- echo("Index and name are only for devices with children.")
1047
+ error("Index and name are only for devices with children.")
1010
1048
  return
1011
1049
 
1012
1050
  if index is not None:
@@ -1027,7 +1065,7 @@ async def toggle(dev: Device, index: int, name: str, transition: int):
1027
1065
  """Toggle the device on/off."""
1028
1066
  if index is not None or name is not None:
1029
1067
  if not dev.children:
1030
- echo("Index and name are only for devices with children.")
1068
+ error("Index and name are only for devices with children.")
1031
1069
  return
1032
1070
 
1033
1071
  if index is not None:
@@ -1067,7 +1105,7 @@ def _schedule_list(dev, type):
1067
1105
  for rule in sched.rules:
1068
1106
  print(rule)
1069
1107
  else:
1070
- echo(f"No rules of type {type}")
1108
+ error(f"No rules of type {type}")
1071
1109
 
1072
1110
  return sched.rules
1073
1111
 
@@ -1083,7 +1121,7 @@ async def delete_rule(dev, id):
1083
1121
  echo(f"Deleting rule id {id}")
1084
1122
  return await schedule.delete_rule(rule_to_delete)
1085
1123
  else:
1086
- echo(f"No rule with id {id} was found")
1124
+ error(f"No rule with id {id} was found")
1087
1125
 
1088
1126
 
1089
1127
  @cli.group(invoke_without_command=True)
@@ -1099,7 +1137,7 @@ async def presets(ctx):
1099
1137
  def presets_list(dev: IotBulb):
1100
1138
  """List presets."""
1101
1139
  if not dev.is_bulb or not isinstance(dev, IotBulb):
1102
- echo("Presets only supported on iot bulbs")
1140
+ error("Presets only supported on iot bulbs")
1103
1141
  return
1104
1142
 
1105
1143
  for preset in dev.presets:
@@ -1121,7 +1159,7 @@ async def presets_modify(dev: IotBulb, index, brightness, hue, saturation, tempe
1121
1159
  if preset.index == index:
1122
1160
  break
1123
1161
  else:
1124
- echo(f"No preset found for index {index}")
1162
+ error(f"No preset found for index {index}")
1125
1163
  return
1126
1164
 
1127
1165
  if brightness is not None:
@@ -1146,7 +1184,7 @@ async def presets_modify(dev: IotBulb, index, brightness, hue, saturation, tempe
1146
1184
  async def turn_on_behavior(dev: IotBulb, type, last, preset):
1147
1185
  """Modify bulb turn-on behavior."""
1148
1186
  if not dev.is_bulb or not isinstance(dev, IotBulb):
1149
- echo("Presets only supported on iot bulbs")
1187
+ error("Presets only supported on iot bulbs")
1150
1188
  return
1151
1189
  settings = await dev.get_turn_on_behavior()
1152
1190
  echo(f"Current turn on behavior: {settings}")
@@ -1183,9 +1221,7 @@ async def turn_on_behavior(dev: IotBulb, type, last, preset):
1183
1221
  async def update_credentials(dev, username, password):
1184
1222
  """Update device credentials for authenticated devices."""
1185
1223
  if not isinstance(dev, SmartDevice):
1186
- raise NotImplementedError(
1187
- "Credentials can only be updated on authenticated devices."
1188
- )
1224
+ error("Credentials can only be updated on authenticated devices.")
1189
1225
 
1190
1226
  click.confirm("Do you really want to replace the existing credentials?", abort=True)
1191
1227
 
@@ -1242,7 +1278,7 @@ async def feature(dev: Device, child: str, name: str, value):
1242
1278
  return
1243
1279
 
1244
1280
  if name not in dev.features:
1245
- echo(f"No feature by name '{name}'")
1281
+ error(f"No feature by name '{name}'")
1246
1282
  return
1247
1283
 
1248
1284
  feat = dev.features[name]
kasa/device.py CHANGED
@@ -19,7 +19,6 @@ from .deviceconfig import (
19
19
  DeviceEncryptionType,
20
20
  DeviceFamily,
21
21
  )
22
- from .emeterstatus import EmeterStatus
23
22
  from .exceptions import KasaException
24
23
  from .feature import Feature
25
24
  from .iotprotocol import IotProtocol
@@ -323,27 +322,6 @@ class Device(ABC):
323
322
  def on_since(self) -> datetime | None:
324
323
  """Return the time that the device was turned on or None if turned off."""
325
324
 
326
- @abstractmethod
327
- async def get_emeter_realtime(self) -> EmeterStatus:
328
- """Retrieve current energy readings."""
329
-
330
- @property
331
- @abstractmethod
332
- def emeter_realtime(self) -> EmeterStatus:
333
- """Get the emeter status."""
334
-
335
- @property
336
- @abstractmethod
337
- def emeter_this_month(self) -> float | None:
338
- """Get the emeter value for this month."""
339
-
340
- @property
341
- @abstractmethod
342
- def emeter_today(self) -> float | None | Any:
343
- """Get the emeter value for today."""
344
- # Return type of Any ensures consumers being shielded from the return
345
- # type by @update_required are not affected.
346
-
347
325
  @abstractmethod
348
326
  async def wifi_scan(self) -> list[WifiNetwork]:
349
327
  """Scan for available wifi networks."""
@@ -373,12 +351,15 @@ class Device(ABC):
373
351
  }
374
352
 
375
353
  def _get_replacing_attr(self, module_name: ModuleName, *attrs):
376
- if module_name not in self.modules:
354
+ # If module name is None check self
355
+ if not module_name:
356
+ check = self
357
+ elif (check := self.modules.get(module_name)) is None:
377
358
  return None
378
359
 
379
360
  for attr in attrs:
380
- if hasattr(self.modules[module_name], attr):
381
- return getattr(self.modules[module_name], attr)
361
+ if hasattr(check, attr):
362
+ return attr
382
363
 
383
364
  return None
384
365
 
@@ -411,6 +392,16 @@ class Device(ABC):
411
392
  # light preset attributes
412
393
  "presets": (Module.LightPreset, ["_deprecated_presets", "preset_states_list"]),
413
394
  "save_preset": (Module.LightPreset, ["_deprecated_save_preset"]),
395
+ # Emeter attribues
396
+ "get_emeter_realtime": (Module.Energy, ["get_status"]),
397
+ "emeter_realtime": (Module.Energy, ["status"]),
398
+ "emeter_today": (Module.Energy, ["consumption_today"]),
399
+ "emeter_this_month": (Module.Energy, ["consumption_this_month"]),
400
+ "current_consumption": (Module.Energy, ["current_consumption"]),
401
+ "get_emeter_daily": (Module.Energy, ["get_daily_stats"]),
402
+ "get_emeter_monthly": (Module.Energy, ["get_monthly_stats"]),
403
+ # Other attributes
404
+ "supported_modules": (None, ["modules"]),
414
405
  }
415
406
 
416
407
  def __getattr__(self, name):
@@ -427,11 +418,10 @@ class Device(ABC):
427
418
  (replacing_attr := self._get_replacing_attr(dep_attr[0], *dep_attr[1]))
428
419
  is not None
429
420
  ):
430
- module_name = dep_attr[0]
431
- msg = (
432
- f"{name} is deprecated, use: "
433
- + f"Module.{module_name} in device.modules instead"
434
- )
421
+ mod = dep_attr[0]
422
+ dev_or_mod = self.modules[mod] if mod else self
423
+ replacing = f"Module.{mod} in device.modules" if mod else replacing_attr
424
+ msg = f"{name} is deprecated, use: {replacing} instead"
435
425
  warn(msg, DeprecationWarning, stacklevel=1)
436
- return replacing_attr
426
+ return getattr(dev_or_mod, replacing_attr)
437
427
  raise AttributeError(f"Device has no attribute {name!r}")
kasa/feature.py CHANGED
@@ -10,7 +10,6 @@ from typing import TYPE_CHECKING, Any, Callable
10
10
  if TYPE_CHECKING:
11
11
  from .device import Device
12
12
 
13
-
14
13
  _LOGGER = logging.getLogger(__name__)
15
14
 
16
15
 
@@ -140,22 +139,24 @@ class Feature:
140
139
  raise ValueError("Not an action and no attribute_getter set")
141
140
 
142
141
  container = self.container if self.container is not None else self.device
143
- if isinstance(self.attribute_getter, Callable):
142
+ if callable(self.attribute_getter):
144
143
  return self.attribute_getter(container)
145
144
  return getattr(container, self.attribute_getter)
146
145
 
147
- async def set_value(self, value):
146
+ async def set_value(self, value: int | float | bool | str | Enum | None) -> Any:
148
147
  """Set the value."""
149
148
  if self.attribute_setter is None:
150
149
  raise ValueError("Tried to set read-only feature.")
151
150
  if self.type == Feature.Type.Number: # noqa: SIM102
151
+ if not isinstance(value, (int, float)):
152
+ raise ValueError("value must be a number")
152
153
  if value < self.minimum_value or value > self.maximum_value:
153
154
  raise ValueError(
154
155
  f"Value {value} out of range "
155
156
  f"[{self.minimum_value}, {self.maximum_value}]"
156
157
  )
157
158
  elif self.type == Feature.Type.Choice: # noqa: SIM102
158
- if value not in self.choices:
159
+ if not self.choices or value not in self.choices:
159
160
  raise ValueError(
160
161
  f"Unexpected value for {self.name}: {value}"
161
162
  f" - allowed: {self.choices}"
@@ -1,5 +1,6 @@
1
1
  """Package for interfaces."""
2
2
 
3
+ from .energy import Energy
3
4
  from .fan import Fan
4
5
  from .led import Led
5
6
  from .light import Light, LightState
@@ -8,6 +9,7 @@ from .lightpreset import LightPreset
8
9
 
9
10
  __all__ = [
10
11
  "Fan",
12
+ "Energy",
11
13
  "Led",
12
14
  "Light",
13
15
  "LightEffect",
@@ -0,0 +1,181 @@
1
+ """Module for base energy module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from enum import IntFlag, auto
7
+ from warnings import warn
8
+
9
+ from ..emeterstatus import EmeterStatus
10
+ from ..feature import Feature
11
+ from ..module import Module
12
+
13
+
14
+ class Energy(Module, ABC):
15
+ """Base interface to represent an Energy module."""
16
+
17
+ class ModuleFeature(IntFlag):
18
+ """Features supported by the device."""
19
+
20
+ #: Device reports :attr:`voltage` and :attr:`current`
21
+ VOLTAGE_CURRENT = auto()
22
+ #: Device reports :attr:`consumption_total`
23
+ CONSUMPTION_TOTAL = auto()
24
+ #: Device reports periodic stats via :meth:`get_daily_stats`
25
+ #: and :meth:`get_monthly_stats`
26
+ PERIODIC_STATS = auto()
27
+
28
+ _supported: ModuleFeature = ModuleFeature(0)
29
+
30
+ def supports(self, module_feature: ModuleFeature) -> bool:
31
+ """Return True if module supports the feature."""
32
+ return module_feature in self._supported
33
+
34
+ def _initialize_features(self):
35
+ """Initialize features."""
36
+ device = self._device
37
+ self._add_feature(
38
+ Feature(
39
+ device,
40
+ name="Current consumption",
41
+ attribute_getter="current_consumption",
42
+ container=self,
43
+ unit="W",
44
+ id="current_consumption",
45
+ precision_hint=1,
46
+ category=Feature.Category.Primary,
47
+ )
48
+ )
49
+ self._add_feature(
50
+ Feature(
51
+ device,
52
+ name="Today's consumption",
53
+ attribute_getter="consumption_today",
54
+ container=self,
55
+ unit="kWh",
56
+ id="consumption_today",
57
+ precision_hint=3,
58
+ category=Feature.Category.Info,
59
+ )
60
+ )
61
+ self._add_feature(
62
+ Feature(
63
+ device,
64
+ id="consumption_this_month",
65
+ name="This month's consumption",
66
+ attribute_getter="consumption_this_month",
67
+ container=self,
68
+ unit="kWh",
69
+ precision_hint=3,
70
+ category=Feature.Category.Info,
71
+ )
72
+ )
73
+ if self.supports(self.ModuleFeature.CONSUMPTION_TOTAL):
74
+ self._add_feature(
75
+ Feature(
76
+ device,
77
+ name="Total consumption since reboot",
78
+ attribute_getter="consumption_total",
79
+ container=self,
80
+ unit="kWh",
81
+ id="consumption_total",
82
+ precision_hint=3,
83
+ category=Feature.Category.Info,
84
+ )
85
+ )
86
+ if self.supports(self.ModuleFeature.VOLTAGE_CURRENT):
87
+ self._add_feature(
88
+ Feature(
89
+ device,
90
+ name="Voltage",
91
+ attribute_getter="voltage",
92
+ container=self,
93
+ unit="V",
94
+ id="voltage",
95
+ precision_hint=1,
96
+ category=Feature.Category.Primary,
97
+ )
98
+ )
99
+ self._add_feature(
100
+ Feature(
101
+ device,
102
+ name="Current",
103
+ attribute_getter="current",
104
+ container=self,
105
+ unit="A",
106
+ id="current",
107
+ precision_hint=2,
108
+ category=Feature.Category.Primary,
109
+ )
110
+ )
111
+
112
+ @property
113
+ @abstractmethod
114
+ def status(self) -> EmeterStatus:
115
+ """Return current energy readings."""
116
+
117
+ @property
118
+ @abstractmethod
119
+ def current_consumption(self) -> float | None:
120
+ """Get the current power consumption in Watt."""
121
+
122
+ @property
123
+ @abstractmethod
124
+ def consumption_today(self) -> float | None:
125
+ """Return today's energy consumption in kWh."""
126
+
127
+ @property
128
+ @abstractmethod
129
+ def consumption_this_month(self) -> float | None:
130
+ """Return this month's energy consumption in kWh."""
131
+
132
+ @property
133
+ @abstractmethod
134
+ def consumption_total(self) -> float | None:
135
+ """Return total consumption since last reboot in kWh."""
136
+
137
+ @property
138
+ @abstractmethod
139
+ def current(self) -> float | None:
140
+ """Return the current in A."""
141
+
142
+ @property
143
+ @abstractmethod
144
+ def voltage(self) -> float | None:
145
+ """Get the current voltage in V."""
146
+
147
+ @abstractmethod
148
+ async def get_status(self):
149
+ """Return real-time statistics."""
150
+
151
+ @abstractmethod
152
+ async def erase_stats(self):
153
+ """Erase all stats."""
154
+
155
+ @abstractmethod
156
+ async def get_daily_stats(self, *, year=None, month=None, kwh=True) -> dict:
157
+ """Return daily stats for the given year & month.
158
+
159
+ The return value is a dictionary of {day: energy, ...}.
160
+ """
161
+
162
+ @abstractmethod
163
+ async def get_monthly_stats(self, *, year=None, kwh=True) -> dict:
164
+ """Return monthly stats for the given year."""
165
+
166
+ _deprecated_attributes = {
167
+ "emeter_today": "consumption_today",
168
+ "emeter_this_month": "consumption_this_month",
169
+ "realtime": "status",
170
+ "get_realtime": "get_status",
171
+ "erase_emeter_stats": "erase_stats",
172
+ "get_daystat": "get_daily_stats",
173
+ "get_monthstat": "get_monthly_stats",
174
+ }
175
+
176
+ def __getattr__(self, name):
177
+ if attr := self._deprecated_attributes.get(name):
178
+ msg = f"{name} is deprecated, use {attr} instead"
179
+ warn(msg, DeprecationWarning, stacklevel=1)
180
+ return getattr(self, attr)
181
+ raise AttributeError(f"Energy module has no attribute {name!r}")
kasa/iot/iotbulb.py CHANGED
@@ -220,7 +220,7 @@ class IotBulb(IotDevice):
220
220
  Module.IotAntitheft, Antitheft(self, "smartlife.iot.common.anti_theft")
221
221
  )
222
222
  self.add_module(Module.IotTime, Time(self, "smartlife.iot.common.timesetting"))
223
- self.add_module(Module.IotEmeter, Emeter(self, self.emeter_type))
223
+ self.add_module(Module.Energy, Emeter(self, self.emeter_type))
224
224
  self.add_module(Module.IotCountdown, Countdown(self, "countdown"))
225
225
  self.add_module(Module.IotCloud, Cloud(self, "smartlife.iot.common.cloud"))
226
226
  self.add_module(Module.Light, Light(self, self.LIGHT_SERVICE))