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/iot/modules/led.py CHANGED
@@ -30,3 +30,8 @@ class Led(IotModule, LedInterface):
30
30
  async def set_led(self, state: bool):
31
31
  """Set the state of the led (night mode)."""
32
32
  return await self.call("set_led_off", {"off": int(not state)})
33
+
34
+ @property
35
+ def is_supported(self) -> bool:
36
+ """Return whether the module is supported by the device."""
37
+ return "led_off" in self.data
kasa/module.py CHANGED
@@ -33,6 +33,8 @@ class Module(ABC):
33
33
  """
34
34
 
35
35
  # Common Modules
36
+ Energy: Final[ModuleName[interfaces.Energy]] = ModuleName("Energy")
37
+ Fan: Final[ModuleName[interfaces.Fan]] = ModuleName("Fan")
36
38
  LightEffect: Final[ModuleName[interfaces.LightEffect]] = ModuleName("LightEffect")
37
39
  Led: Final[ModuleName[interfaces.Led]] = ModuleName("Led")
38
40
  Light: Final[ModuleName[interfaces.Light]] = ModuleName("Light")
@@ -42,7 +44,6 @@ class Module(ABC):
42
44
  IotAmbientLight: Final[ModuleName[iot.AmbientLight]] = ModuleName("ambient")
43
45
  IotAntitheft: Final[ModuleName[iot.Antitheft]] = ModuleName("anti_theft")
44
46
  IotCountdown: Final[ModuleName[iot.Countdown]] = ModuleName("countdown")
45
- IotEmeter: Final[ModuleName[iot.Emeter]] = ModuleName("emeter")
46
47
  IotMotion: Final[ModuleName[iot.Motion]] = ModuleName("motion")
47
48
  IotSchedule: Final[ModuleName[iot.Schedule]] = ModuleName("schedule")
48
49
  IotUsage: Final[ModuleName[iot.Usage]] = ModuleName("usage")
@@ -62,8 +63,6 @@ class Module(ABC):
62
63
  )
63
64
  ContactSensor: Final[ModuleName[smart.ContactSensor]] = ModuleName("ContactSensor")
64
65
  DeviceModule: Final[ModuleName[smart.DeviceModule]] = ModuleName("DeviceModule")
65
- Energy: Final[ModuleName[smart.Energy]] = ModuleName("Energy")
66
- Fan: Final[ModuleName[smart.Fan]] = ModuleName("Fan")
67
66
  Firmware: Final[ModuleName[smart.Firmware]] = ModuleName("Firmware")
68
67
  FrostProtection: Final[ModuleName[smart.FrostProtection]] = ModuleName(
69
68
  "FrostProtection"
@@ -2,60 +2,17 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from typing import TYPE_CHECKING
6
-
7
5
  from ...emeterstatus import EmeterStatus
8
- from ...feature import Feature
6
+ from ...exceptions import KasaException
7
+ from ...interfaces.energy import Energy as EnergyInterface
9
8
  from ..smartmodule import SmartModule
10
9
 
11
- if TYPE_CHECKING:
12
- from ..smartdevice import SmartDevice
13
-
14
10
 
15
- class Energy(SmartModule):
11
+ class Energy(SmartModule, EnergyInterface):
16
12
  """Implementation of energy monitoring module."""
17
13
 
18
14
  REQUIRED_COMPONENT = "energy_monitoring"
19
15
 
20
- def __init__(self, device: SmartDevice, module: str):
21
- super().__init__(device, module)
22
- self._add_feature(
23
- Feature(
24
- device,
25
- "consumption_current",
26
- name="Current consumption",
27
- attribute_getter="current_power",
28
- container=self,
29
- unit="W",
30
- precision_hint=1,
31
- category=Feature.Category.Primary,
32
- )
33
- )
34
- self._add_feature(
35
- Feature(
36
- device,
37
- "consumption_today",
38
- name="Today's consumption",
39
- attribute_getter="emeter_today",
40
- container=self,
41
- unit="Wh",
42
- precision_hint=2,
43
- category=Feature.Category.Info,
44
- )
45
- )
46
- self._add_feature(
47
- Feature(
48
- device,
49
- "consumption_this_month",
50
- name="This month's consumption",
51
- attribute_getter="emeter_this_month",
52
- container=self,
53
- unit="Wh",
54
- precision_hint=2,
55
- category=Feature.Category.Info,
56
- )
57
- )
58
-
59
16
  def query(self) -> dict:
60
17
  """Query to execute during the update cycle."""
61
18
  req = {
@@ -66,9 +23,9 @@ class Energy(SmartModule):
66
23
  return req
67
24
 
68
25
  @property
69
- def current_power(self) -> float | None:
26
+ def current_consumption(self) -> float | None:
70
27
  """Current power in watts."""
71
- if power := self.energy.get("current_power"):
28
+ if (power := self.energy.get("current_power")) is not None:
72
29
  return power / 1_000
73
30
  return None
74
31
 
@@ -79,23 +36,64 @@ class Energy(SmartModule):
79
36
  return en
80
37
  return self.data
81
38
 
82
- @property
83
- def emeter_realtime(self):
84
- """Get the emeter status."""
85
- # TODO: Perhaps we should get rid of emeterstatus altogether for smartdevices
39
+ def _get_status_from_energy(self, energy) -> EmeterStatus:
86
40
  return EmeterStatus(
87
41
  {
88
- "power_mw": self.energy.get("current_power"),
89
- "total": self.energy.get("today_energy") / 1_000,
42
+ "power_mw": energy.get("current_power"),
43
+ "total": energy.get("today_energy") / 1_000,
90
44
  }
91
45
  )
92
46
 
93
47
  @property
94
- def emeter_this_month(self) -> float | None:
95
- """Get the emeter value for this month."""
96
- return self.energy.get("month_energy")
48
+ def status(self):
49
+ """Get the emeter status."""
50
+ return self._get_status_from_energy(self.energy)
51
+
52
+ async def get_status(self):
53
+ """Return real-time statistics."""
54
+ res = await self.call("get_energy_usage")
55
+ return self._get_status_from_energy(res["get_energy_usage"])
56
+
57
+ @property
58
+ def consumption_this_month(self) -> float | None:
59
+ """Get the emeter value for this month in kWh."""
60
+ return self.energy.get("month_energy") / 1_000
61
+
62
+ @property
63
+ def consumption_today(self) -> float | None:
64
+ """Get the emeter value for today in kWh."""
65
+ return self.energy.get("today_energy") / 1_000
66
+
67
+ @property
68
+ def consumption_total(self) -> float | None:
69
+ """Return total consumption since last reboot in kWh."""
70
+ return None
71
+
72
+ @property
73
+ def current(self) -> float | None:
74
+ """Return the current in A."""
75
+ return None
97
76
 
98
77
  @property
99
- def emeter_today(self) -> float | None:
100
- """Get the emeter value for today."""
101
- return self.energy.get("today_energy")
78
+ def voltage(self) -> float | None:
79
+ """Get the current voltage in V."""
80
+ return None
81
+
82
+ async def _deprecated_get_realtime(self) -> EmeterStatus:
83
+ """Retrieve current energy readings."""
84
+ return self.status
85
+
86
+ async def erase_stats(self):
87
+ """Erase all stats."""
88
+ raise KasaException("Device does not support periodic statistics")
89
+
90
+ async def get_daily_stats(self, *, year=None, month=None, kwh=True) -> dict:
91
+ """Return daily stats for the given year & month.
92
+
93
+ The return value is a dictionary of {day: energy, ...}.
94
+ """
95
+ raise KasaException("Device does not support periodic statistics")
96
+
97
+ async def get_monthly_stats(self, *, year=None, kwh=True) -> dict:
98
+ """Return monthly stats for the given year."""
99
+ raise KasaException("Device does not support periodic statistics")
@@ -2,16 +2,27 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from typing import TYPE_CHECKING
6
+
5
7
  from ...interfaces.lighteffect import LightEffect as LightEffectInterface
6
8
  from ..effects import EFFECT_MAPPING, EFFECT_NAMES
7
9
  from ..smartmodule import SmartModule
8
10
 
11
+ if TYPE_CHECKING:
12
+ from ..smartdevice import SmartDevice
13
+
9
14
 
10
15
  class LightStripEffect(SmartModule, LightEffectInterface):
11
16
  """Implementation of dynamic light effects."""
12
17
 
13
18
  REQUIRED_COMPONENT = "light_strip_lighting_effect"
14
19
 
20
+ def __init__(self, device: SmartDevice, module: str):
21
+ super().__init__(device, module)
22
+ effect_list = [self.LIGHT_EFFECTS_OFF]
23
+ effect_list.extend(EFFECT_NAMES)
24
+ self._effect_list = effect_list
25
+
15
26
  @property
16
27
  def name(self) -> str:
17
28
  """Name of the module.
@@ -37,7 +48,8 @@ class LightStripEffect(SmartModule, LightEffectInterface):
37
48
  """
38
49
  eff = self.data["lighting_effect"]
39
50
  name = eff["name"]
40
- if eff["enable"]:
51
+ # When devices are unpaired effect name is softAP which is not in our list
52
+ if eff["enable"] and name in self._effect_list:
41
53
  return name
42
54
  return self.LIGHT_EFFECTS_OFF
43
55
 
@@ -48,9 +60,7 @@ class LightStripEffect(SmartModule, LightEffectInterface):
48
60
  Example:
49
61
  ['Aurora', 'Bubbling Cauldron', ...]
50
62
  """
51
- effect_list = [self.LIGHT_EFFECTS_OFF]
52
- effect_list.extend(EFFECT_NAMES)
53
- return effect_list
63
+ return self._effect_list
54
64
 
55
65
  async def set_effect(
56
66
  self,
@@ -181,3 +181,13 @@ class LightTransition(SmartModule):
181
181
  return {}
182
182
  else:
183
183
  return {self.QUERY_GETTER_NAME: None}
184
+
185
+ async def _check_supported(self):
186
+ """Additional check to see if the module is supported by the device.
187
+
188
+ Parent devices that report components of children such as ks240 will not have
189
+ the brightness value is sysinfo.
190
+ """
191
+ # Look in _device.sys_info here because self.data is either sys_info or
192
+ # get_preset_rules depending on whether it's a child device or not.
193
+ return "brightness" in self._device.sys_info
@@ -51,7 +51,13 @@ class Time(SmartModule):
51
51
  async def set_time(self, dt: datetime):
52
52
  """Set device time."""
53
53
  unixtime = mktime(dt.timetuple())
54
+ offset = cast(timedelta, dt.utcoffset())
55
+ diff = offset / timedelta(minutes=1)
54
56
  return await self.call(
55
57
  "set_device_time",
56
- {"timestamp": unixtime, "time_diff": dt.utcoffset(), "region": dt.tzname()},
58
+ {
59
+ "timestamp": int(unixtime),
60
+ "time_diff": int(diff),
61
+ "region": dt.tzname(),
62
+ },
57
63
  )
kasa/smart/smartdevice.py CHANGED
@@ -4,14 +4,13 @@ from __future__ import annotations
4
4
 
5
5
  import base64
6
6
  import logging
7
- from datetime import datetime, timedelta
7
+ from datetime import datetime, timedelta, timezone
8
8
  from typing import TYPE_CHECKING, Any, Mapping, Sequence, cast
9
9
 
10
10
  from ..aestransport import AesTransport
11
11
  from ..device import Device, WifiNetwork
12
12
  from ..device_type import DeviceType
13
13
  from ..deviceconfig import DeviceConfig
14
- from ..emeterstatus import EmeterStatus
15
14
  from ..exceptions import AuthenticationError, DeviceError, KasaException, SmartErrorCode
16
15
  from ..feature import Feature
17
16
  from ..module import Module
@@ -357,12 +356,25 @@ class SmartDevice(Device):
357
356
  @property
358
357
  def time(self) -> datetime:
359
358
  """Return the time."""
360
- if self._parent and Module.Time in self._parent.modules:
361
- _timemod = self._parent.modules[Module.Time]
362
- else:
363
- _timemod = self.modules[Module.Time]
359
+ if (self._parent and (time_mod := self._parent.modules.get(Module.Time))) or (
360
+ time_mod := self.modules.get(Module.Time)
361
+ ):
362
+ return time_mod.time
364
363
 
365
- return _timemod.time
364
+ # We have no device time, use current local time.
365
+ return datetime.now(timezone.utc).astimezone().replace(microsecond=0)
366
+
367
+ @property
368
+ def on_since(self) -> datetime | None:
369
+ """Return the time that the device was turned on or None if turned off."""
370
+ if (
371
+ not self._info.get("device_on")
372
+ or (on_time := self._info.get("on_time")) is None
373
+ ):
374
+ return None
375
+
376
+ on_time = cast(float, on_time)
377
+ return self.time - timedelta(seconds=on_time)
366
378
 
367
379
  @property
368
380
  def timezone(self) -> dict:
@@ -464,45 +476,6 @@ class SmartDevice(Device):
464
476
  self._discovery_info = info
465
477
  self._info = info
466
478
 
467
- async def get_emeter_realtime(self) -> EmeterStatus:
468
- """Retrieve current energy readings."""
469
- _LOGGER.warning("Deprecated, use `emeter_realtime`.")
470
- if not self.has_emeter:
471
- raise KasaException("Device has no emeter")
472
- return self.emeter_realtime
473
-
474
- @property
475
- def emeter_realtime(self) -> EmeterStatus:
476
- """Get the emeter status."""
477
- energy = self.modules[Module.Energy]
478
- return energy.emeter_realtime
479
-
480
- @property
481
- def emeter_this_month(self) -> float | None:
482
- """Get the emeter value for this month."""
483
- energy = self.modules[Module.Energy]
484
- return energy.emeter_this_month
485
-
486
- @property
487
- def emeter_today(self) -> float | None:
488
- """Get the emeter value for today."""
489
- energy = self.modules[Module.Energy]
490
- return energy.emeter_today
491
-
492
- @property
493
- def on_since(self) -> datetime | None:
494
- """Return the time that the device was turned on or None if turned off."""
495
- if (
496
- not self._info.get("device_on")
497
- or (on_time := self._info.get("on_time")) is None
498
- ):
499
- return None
500
- on_time = cast(float, on_time)
501
- if (timemod := self.modules.get(Module.Time)) is not None:
502
- return timemod.time - timedelta(seconds=on_time)
503
- else: # We have no device time, use current local time.
504
- return datetime.now().replace(microsecond=0) - timedelta(seconds=on_time)
505
-
506
479
  async def wifi_scan(self) -> list[WifiNetwork]:
507
480
  """Scan for available wifi networks."""
508
481