python-kasa 0.6.2__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 (168) 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 +12 -7
  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 -551
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/{newfakes.py → fakeprotocol_iot.py} +61 -291
  86. kasa/tests/fakeprotocol_smart.py +318 -0
  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/P300(EU)_1.0_1.0.13.json +13 -23
  99. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +6 -6
  100. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +295 -0
  101. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +423 -0
  102. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +170 -0
  103. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  104. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  105. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  106. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  107. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  108. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  109. kasa/tests/smart/__init__.py +0 -0
  110. kasa/tests/smart/features/__init__.py +0 -0
  111. kasa/tests/smart/features/test_brightness.py +55 -0
  112. kasa/tests/smart/features/test_colortemp.py +30 -0
  113. kasa/tests/smart/modules/__init__.py +0 -0
  114. kasa/tests/smart/modules/test_contact.py +28 -0
  115. kasa/tests/smart/modules/test_fan.py +79 -0
  116. kasa/tests/smart/modules/test_firmware.py +108 -0
  117. kasa/tests/smart/modules/test_humidity.py +28 -0
  118. kasa/tests/smart/modules/test_light_effect.py +41 -0
  119. kasa/tests/smart/modules/test_temperature.py +47 -0
  120. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  121. kasa/tests/smart/modules/test_waterleak.py +42 -0
  122. kasa/tests/test_aestransport.py +115 -25
  123. kasa/tests/test_bulb.py +169 -86
  124. kasa/tests/test_childdevice.py +84 -0
  125. kasa/tests/test_cli.py +452 -100
  126. kasa/tests/test_common_modules.py +216 -0
  127. kasa/tests/test_device.py +268 -0
  128. kasa/tests/test_device_factory.py +61 -41
  129. kasa/tests/test_device_type.py +1 -1
  130. kasa/tests/test_deviceconfig.py +2 -5
  131. kasa/tests/test_dimmer.py +33 -24
  132. kasa/tests/test_discovery.py +112 -69
  133. kasa/tests/test_emeter.py +39 -12
  134. kasa/tests/test_feature.py +205 -0
  135. kasa/tests/test_httpclient.py +9 -9
  136. kasa/tests/test_iotdevice.py +286 -0
  137. kasa/tests/test_klapprotocol.py +94 -41
  138. kasa/tests/test_lightstrip.py +24 -19
  139. kasa/tests/test_plug.py +51 -9
  140. kasa/tests/test_protocol.py +8 -12
  141. kasa/tests/test_readme_examples.py +86 -27
  142. kasa/tests/test_smartdevice.py +211 -247
  143. kasa/tests/test_smartprotocol.py +129 -26
  144. kasa/tests/test_strip.py +15 -6
  145. kasa/tests/test_usage.py +1 -3
  146. kasa/xortransport.py +15 -12
  147. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -141
  148. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  149. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +1 -1
  150. kasa/modules/emeter.py +0 -111
  151. kasa/smartlightstrip.py +0 -143
  152. kasa/smartplug.py +0 -91
  153. kasa/tapo/__init__.py +0 -7
  154. kasa/tapo/childdevice.py +0 -44
  155. kasa/tapo/tapobulb.py +0 -262
  156. kasa/tapo/tapodevice.py +0 -383
  157. kasa/tapo/tapoplug.py +0 -45
  158. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  159. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  160. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  161. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  162. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  163. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  164. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  165. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  166. python_kasa-0.6.2.dist-info/RECORD +0 -163
  167. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  168. {python_kasa-0.6.2.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,216 @@
1
+ """Implementation of firmware module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from datetime import date
8
+ from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional
9
+
10
+ # When support for cpython older than 3.11 is dropped
11
+ # async_timeout can be replaced with asyncio.timeout
12
+ from async_timeout import timeout as asyncio_timeout
13
+ from pydantic.v1 import BaseModel, Field, validator
14
+
15
+ from ...exceptions import SmartErrorCode
16
+ from ...feature import Feature
17
+ from ..smartmodule import SmartModule
18
+
19
+ if TYPE_CHECKING:
20
+ from ..smartdevice import SmartDevice
21
+
22
+
23
+ _LOGGER = logging.getLogger(__name__)
24
+
25
+
26
+ class DownloadState(BaseModel):
27
+ """Download state."""
28
+
29
+ # Example:
30
+ # {'status': 0, 'download_progress': 0, 'reboot_time': 5,
31
+ # 'upgrade_time': 5, 'auto_upgrade': False}
32
+ status: int
33
+ progress: int = Field(alias="download_progress")
34
+ reboot_time: int
35
+ upgrade_time: int
36
+ auto_upgrade: bool
37
+
38
+
39
+ class UpdateInfo(BaseModel):
40
+ """Update info status object."""
41
+
42
+ status: int = Field(alias="type")
43
+ version: Optional[str] = Field(alias="fw_ver", default=None) # noqa: UP007
44
+ release_date: Optional[date] = None # noqa: UP007
45
+ release_notes: Optional[str] = Field(alias="release_note", default=None) # noqa: UP007
46
+ fw_size: Optional[int] = None # noqa: UP007
47
+ oem_id: Optional[str] = None # noqa: UP007
48
+ needs_upgrade: bool = Field(alias="need_to_upgrade")
49
+
50
+ @validator("release_date", pre=True)
51
+ def _release_date_optional(cls, v):
52
+ if not v:
53
+ return None
54
+
55
+ return v
56
+
57
+ @property
58
+ def update_available(self):
59
+ """Return True if update available."""
60
+ if self.status != 0:
61
+ return True
62
+ return False
63
+
64
+
65
+ class Firmware(SmartModule):
66
+ """Implementation of firmware module."""
67
+
68
+ REQUIRED_COMPONENT = "firmware"
69
+
70
+ def __init__(self, device: SmartDevice, module: str):
71
+ super().__init__(device, module)
72
+ if self.supported_version > 1:
73
+ self._add_feature(
74
+ Feature(
75
+ device,
76
+ id="auto_update_enabled",
77
+ name="Auto update enabled",
78
+ container=self,
79
+ attribute_getter="auto_update_enabled",
80
+ attribute_setter="set_auto_update_enabled",
81
+ type=Feature.Type.Switch,
82
+ )
83
+ )
84
+ self._add_feature(
85
+ Feature(
86
+ device,
87
+ id="update_available",
88
+ name="Update available",
89
+ container=self,
90
+ attribute_getter="update_available",
91
+ type=Feature.Type.BinarySensor,
92
+ category=Feature.Category.Info,
93
+ )
94
+ )
95
+ self._add_feature(
96
+ Feature(
97
+ device,
98
+ id="current_firmware_version",
99
+ name="Current firmware version",
100
+ container=self,
101
+ attribute_getter="current_firmware",
102
+ category=Feature.Category.Debug,
103
+ )
104
+ )
105
+ self._add_feature(
106
+ Feature(
107
+ device,
108
+ id="available_firmware_version",
109
+ name="Available firmware version",
110
+ container=self,
111
+ attribute_getter="latest_firmware",
112
+ category=Feature.Category.Debug,
113
+ )
114
+ )
115
+
116
+ def query(self) -> dict:
117
+ """Query to execute during the update cycle."""
118
+ req: dict[str, Any] = {"get_latest_fw": None}
119
+ if self.supported_version > 1:
120
+ req["get_auto_update_info"] = None
121
+ return req
122
+
123
+ @property
124
+ def current_firmware(self) -> str:
125
+ """Return the current firmware version."""
126
+ return self._device.hw_info["sw_ver"]
127
+
128
+ @property
129
+ def latest_firmware(self) -> str:
130
+ """Return the latest firmware version."""
131
+ return self.firmware_update_info.version
132
+
133
+ @property
134
+ def firmware_update_info(self):
135
+ """Return latest firmware information."""
136
+ fw = self.data.get("get_latest_fw") or self.data
137
+ if not self._device.is_cloud_connected or isinstance(fw, SmartErrorCode):
138
+ # Error in response, probably disconnected from the cloud.
139
+ return UpdateInfo(type=0, need_to_upgrade=False)
140
+
141
+ return UpdateInfo.parse_obj(fw)
142
+
143
+ @property
144
+ def update_available(self) -> bool | None:
145
+ """Return True if update is available."""
146
+ if not self._device.is_cloud_connected:
147
+ return None
148
+ return self.firmware_update_info.update_available
149
+
150
+ async def get_update_state(self) -> DownloadState:
151
+ """Return update state."""
152
+ resp = await self.call("get_fw_download_state")
153
+ state = resp["get_fw_download_state"]
154
+ return DownloadState(**state)
155
+
156
+ async def update(
157
+ self, progress_cb: Callable[[DownloadState], Coroutine] | None = None
158
+ ):
159
+ """Update the device firmware."""
160
+ current_fw = self.current_firmware
161
+ _LOGGER.info(
162
+ "Going to upgrade from %s to %s",
163
+ current_fw,
164
+ self.firmware_update_info.version,
165
+ )
166
+ await self.call("fw_download")
167
+
168
+ # TODO: read timeout from get_auto_update_info or from get_fw_download_state?
169
+ async with asyncio_timeout(60 * 5):
170
+ while True:
171
+ await asyncio.sleep(0.5)
172
+ try:
173
+ state = await self.get_update_state()
174
+ except Exception as ex:
175
+ _LOGGER.warning(
176
+ "Got exception, maybe the device is rebooting? %s", ex
177
+ )
178
+ continue
179
+
180
+ _LOGGER.debug("Update state: %s" % state)
181
+ if progress_cb is not None:
182
+ asyncio.create_task(progress_cb(state))
183
+
184
+ if state.status == 0:
185
+ _LOGGER.info(
186
+ "Update idle, hopefully updated to %s",
187
+ self.firmware_update_info.version,
188
+ )
189
+ break
190
+ elif state.status == 2:
191
+ _LOGGER.info("Downloading firmware, progress: %s", state.progress)
192
+ elif state.status == 3:
193
+ upgrade_sleep = state.upgrade_time
194
+ _LOGGER.info(
195
+ "Flashing firmware, sleeping for %s before checking status",
196
+ upgrade_sleep,
197
+ )
198
+ await asyncio.sleep(upgrade_sleep)
199
+ elif state.status < 0:
200
+ _LOGGER.error("Got error: %s", state.status)
201
+ break
202
+ else:
203
+ _LOGGER.warning("Unhandled state code: %s", state)
204
+
205
+ @property
206
+ def auto_update_enabled(self):
207
+ """Return True if autoupdate is enabled."""
208
+ return (
209
+ "get_auto_update_info" in self.data
210
+ and self.data["get_auto_update_info"]["enable"]
211
+ )
212
+
213
+ async def set_auto_update_enabled(self, enabled: bool):
214
+ """Change autoupdate setting."""
215
+ data = {**self.data["get_auto_update_info"], "enable": enabled}
216
+ await self.call("set_auto_update_info", data)
@@ -0,0 +1,59 @@
1
+ """Frost protection module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ...feature import Feature
8
+ from ..smartmodule import SmartModule
9
+
10
+ # TODO: this may not be necessary with __future__.annotations
11
+ if TYPE_CHECKING:
12
+ from ..smartdevice import SmartDevice
13
+
14
+
15
+ class FrostProtection(SmartModule):
16
+ """Implementation for frost protection module.
17
+
18
+ This basically turns the thermostat on and off.
19
+ """
20
+
21
+ REQUIRED_COMPONENT = "frost_protection"
22
+ # TODO: the information required for current features do not require this query
23
+ QUERY_GETTER_NAME = "get_frost_protection"
24
+
25
+ def __init__(self, device: SmartDevice, module: str):
26
+ super().__init__(device, module)
27
+ self._add_feature(
28
+ Feature(
29
+ device,
30
+ "frost_protection_enabled",
31
+ name="Frost protection enabled",
32
+ container=self,
33
+ attribute_getter="enabled",
34
+ attribute_setter="set_enabled",
35
+ type=Feature.Type.Switch,
36
+ )
37
+ )
38
+
39
+ @property
40
+ def enabled(self) -> bool:
41
+ """Return True if frost protection is on."""
42
+ return self._device.sys_info["frost_protection_on"]
43
+
44
+ async def set_enabled(self, enable: bool):
45
+ """Enable/disable frost protection."""
46
+ return await self.call(
47
+ "set_device_info",
48
+ {"frost_protection_on": enable},
49
+ )
50
+
51
+ @property
52
+ def minimum_temperature(self) -> int:
53
+ """Return frost protection minimum temperature."""
54
+ return self.data["min_temp"]
55
+
56
+ @property
57
+ def temperature_unit(self) -> str:
58
+ """Return frost protection temperature unit."""
59
+ return self.data["temp_unit"]
@@ -0,0 +1,55 @@
1
+ """Implementation of humidity module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ...feature import Feature
8
+ from ..smartmodule import SmartModule
9
+
10
+ if TYPE_CHECKING:
11
+ from ..smartdevice import SmartDevice
12
+
13
+
14
+ class HumiditySensor(SmartModule):
15
+ """Implementation of humidity module."""
16
+
17
+ REQUIRED_COMPONENT = "humidity"
18
+ QUERY_GETTER_NAME = "get_comfort_humidity_config"
19
+
20
+ def __init__(self, device: SmartDevice, module: str):
21
+ super().__init__(device, module)
22
+ self._add_feature(
23
+ Feature(
24
+ device,
25
+ id="humidity",
26
+ name="Humidity",
27
+ container=self,
28
+ attribute_getter="humidity",
29
+ icon="mdi:water-percent",
30
+ unit="%",
31
+ category=Feature.Category.Primary,
32
+ )
33
+ )
34
+ self._add_feature(
35
+ Feature(
36
+ device,
37
+ id="humidity_warning",
38
+ name="Humidity warning",
39
+ container=self,
40
+ attribute_getter="humidity_warning",
41
+ type=Feature.Type.BinarySensor,
42
+ icon="mdi:alert",
43
+ category=Feature.Category.Debug,
44
+ )
45
+ )
46
+
47
+ @property
48
+ def humidity(self):
49
+ """Return current humidity in percentage."""
50
+ return self._device.sys_info["current_humidity"]
51
+
52
+ @property
53
+ def humidity_warning(self) -> bool:
54
+ """Return true if humidity is outside of the wanted range."""
55
+ return self._device.sys_info["current_humidity_exception"] != 0
@@ -0,0 +1,49 @@
1
+ """Module for led controls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ...interfaces.led import Led as LedInterface
6
+ from ..smartmodule import SmartModule
7
+
8
+
9
+ class Led(SmartModule, LedInterface):
10
+ """Implementation of led controls."""
11
+
12
+ REQUIRED_COMPONENT = "led"
13
+ QUERY_GETTER_NAME = "get_led_info"
14
+
15
+ def query(self) -> dict:
16
+ """Query to execute during the update cycle."""
17
+ return {self.QUERY_GETTER_NAME: {"led_rule": None}}
18
+
19
+ @property
20
+ def mode(self):
21
+ """LED mode setting.
22
+
23
+ "always", "never", "night_mode"
24
+ """
25
+ return self.data["led_rule"]
26
+
27
+ @property
28
+ def led(self):
29
+ """Return current led status."""
30
+ return self.data["led_status"]
31
+
32
+ async def set_led(self, enable: bool):
33
+ """Set led.
34
+
35
+ This should probably be a select with always/never/nightmode.
36
+ """
37
+ rule = "always" if enable else "never"
38
+ return await self.call("set_led_info", dict(self.data, **{"led_rule": rule}))
39
+
40
+ @property
41
+ def night_mode_settings(self):
42
+ """Night mode settings."""
43
+ return {
44
+ "start": self.data["start_time"],
45
+ "end": self.data["end_time"],
46
+ "type": self.data["night_mode_type"],
47
+ "sunrise_offset": self.data["sunrise_offset"],
48
+ "sunset_offset": self.data["sunset_offset"],
49
+ }
@@ -0,0 +1,139 @@
1
+ """Module for led controls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+
7
+ from ...exceptions import KasaException
8
+ from ...interfaces.light import HSV, ColorTempRange, LightState
9
+ from ...interfaces.light import Light as LightInterface
10
+ from ...module import Module
11
+ from ..smartmodule import SmartModule
12
+
13
+
14
+ class Light(SmartModule, LightInterface):
15
+ """Implementation of a light."""
16
+
17
+ def query(self) -> dict:
18
+ """Query to execute during the update cycle."""
19
+ return {}
20
+
21
+ @property
22
+ def is_color(self) -> bool:
23
+ """Whether the bulb supports color changes."""
24
+ return Module.Color in self._device.modules
25
+
26
+ @property
27
+ def is_dimmable(self) -> bool:
28
+ """Whether the bulb supports brightness changes."""
29
+ return Module.Brightness in self._device.modules
30
+
31
+ @property
32
+ def is_variable_color_temp(self) -> bool:
33
+ """Whether the bulb supports color temperature changes."""
34
+ return Module.ColorTemperature in self._device.modules
35
+
36
+ @property
37
+ def valid_temperature_range(self) -> ColorTempRange:
38
+ """Return the device-specific white temperature range (in Kelvin).
39
+
40
+ :return: White temperature range in Kelvin (minimum, maximum)
41
+ """
42
+ if not self.is_variable_color_temp:
43
+ raise KasaException("Color temperature not supported")
44
+
45
+ return self._device.modules[Module.ColorTemperature].valid_temperature_range
46
+
47
+ @property
48
+ def hsv(self) -> HSV:
49
+ """Return the current HSV state of the bulb.
50
+
51
+ :return: hue, saturation and value (degrees, %, %)
52
+ """
53
+ if not self.is_color:
54
+ raise KasaException("Bulb does not support color.")
55
+
56
+ return self._device.modules[Module.Color].hsv
57
+
58
+ @property
59
+ def color_temp(self) -> int:
60
+ """Whether the bulb supports color temperature changes."""
61
+ if not self.is_variable_color_temp:
62
+ raise KasaException("Bulb does not support colortemp.")
63
+
64
+ return self._device.modules[Module.ColorTemperature].color_temp
65
+
66
+ @property
67
+ def brightness(self) -> int:
68
+ """Return the current brightness in percentage."""
69
+ if not self.is_dimmable: # pragma: no cover
70
+ raise KasaException("Bulb is not dimmable.")
71
+
72
+ return self._device.modules[Module.Brightness].brightness
73
+
74
+ async def set_hsv(
75
+ self,
76
+ hue: int,
77
+ saturation: int,
78
+ value: int | None = None,
79
+ *,
80
+ transition: int | None = None,
81
+ ) -> dict:
82
+ """Set new HSV.
83
+
84
+ Note, transition is not supported and will be ignored.
85
+
86
+ :param int hue: hue in degrees
87
+ :param int saturation: saturation in percentage [0,100]
88
+ :param int value: value between 1 and 100
89
+ :param int transition: transition in milliseconds.
90
+ """
91
+ if not self.is_color:
92
+ raise KasaException("Bulb does not support color.")
93
+
94
+ return await self._device.modules[Module.Color].set_hsv(hue, saturation, value)
95
+
96
+ async def set_color_temp(
97
+ self, temp: int, *, brightness=None, transition: int | None = None
98
+ ) -> dict:
99
+ """Set the color temperature of the device in kelvin.
100
+
101
+ Note, transition is not supported and will be ignored.
102
+
103
+ :param int temp: The new color temperature, in Kelvin
104
+ :param int transition: transition in milliseconds.
105
+ """
106
+ if not self.is_variable_color_temp:
107
+ raise KasaException("Bulb does not support colortemp.")
108
+ return await self._device.modules[Module.ColorTemperature].set_color_temp(temp)
109
+
110
+ async def set_brightness(
111
+ self, brightness: int, *, transition: int | None = None
112
+ ) -> dict:
113
+ """Set the brightness in percentage.
114
+
115
+ Note, transition is not supported and will be ignored.
116
+
117
+ :param int brightness: brightness in percent
118
+ :param int transition: transition in milliseconds.
119
+ """
120
+ if not self.is_dimmable: # pragma: no cover
121
+ raise KasaException("Bulb is not dimmable.")
122
+
123
+ return await self._device.modules[Module.Brightness].set_brightness(brightness)
124
+
125
+ @property
126
+ def has_effects(self) -> bool:
127
+ """Return True if the device supports effects."""
128
+ return Module.LightEffect in self._device.modules
129
+
130
+ async def set_state(self, state: LightState) -> dict:
131
+ """Set the light state."""
132
+ state_dict = asdict(state)
133
+ # brightness of 0 turns off the light, it's not a valid brightness
134
+ if state.brightness and state.brightness == 0:
135
+ state_dict["device_on"] = False
136
+ del state_dict["brightness"]
137
+
138
+ params = {k: v for k, v in state_dict.items() if v is not None}
139
+ return await self.call("set_device_info", params)
@@ -0,0 +1,115 @@
1
+ """Module for light effects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import copy
7
+ from typing import Any
8
+
9
+ from ...interfaces.lighteffect import LightEffect as LightEffectInterface
10
+ from ..smartmodule import SmartModule
11
+
12
+
13
+ class LightEffect(SmartModule, LightEffectInterface):
14
+ """Implementation of dynamic light effects."""
15
+
16
+ REQUIRED_COMPONENT = "light_effect"
17
+ QUERY_GETTER_NAME = "get_dynamic_light_effect_rules"
18
+ AVAILABLE_BULB_EFFECTS = {
19
+ "L1": "Party",
20
+ "L2": "Relax",
21
+ }
22
+
23
+ _effect: str
24
+ _effect_state_list: dict[str, dict[str, Any]]
25
+ _effect_list: list[str]
26
+ _scenes_names_to_id: dict[str, str]
27
+
28
+ def _post_update_hook(self) -> None:
29
+ """Update internal effect state."""
30
+ # Copy the effects so scene name updates do not update the underlying dict.
31
+ effects = copy.deepcopy(
32
+ {effect["id"]: effect for effect in self.data["rule_list"]}
33
+ )
34
+ for effect in effects.values():
35
+ if not effect["scene_name"]:
36
+ # If the name has not been edited scene_name will be an empty string
37
+ effect["scene_name"] = self.AVAILABLE_BULB_EFFECTS[effect["id"]]
38
+ else:
39
+ # Otherwise it will be b64 encoded
40
+ effect["scene_name"] = base64.b64decode(effect["scene_name"]).decode()
41
+
42
+ self._effect_state_list = effects
43
+ self._effect_list = [self.LIGHT_EFFECTS_OFF]
44
+ self._effect_list.extend([effect["scene_name"] for effect in effects.values()])
45
+ self._scenes_names_to_id = {
46
+ effect["scene_name"]: effect["id"] for effect in effects.values()
47
+ }
48
+ # get_dynamic_light_effect_rules also has an enable property and current_rule_id
49
+ # property that could be used here as an alternative
50
+ if self._device._info["dynamic_light_effect_enable"]:
51
+ self._effect = self._effect_state_list[
52
+ self._device._info["dynamic_light_effect_id"]
53
+ ]["scene_name"]
54
+ else:
55
+ self._effect = self.LIGHT_EFFECTS_OFF
56
+
57
+ @property
58
+ def effect_list(self) -> list[str]:
59
+ """Return built-in effects list.
60
+
61
+ Example:
62
+ ['Party', 'Relax', ...]
63
+ """
64
+ return self._effect_list
65
+
66
+ @property
67
+ def effect(self) -> str:
68
+ """Return effect name."""
69
+ return self._effect
70
+
71
+ async def set_effect(
72
+ self,
73
+ effect: str,
74
+ *,
75
+ brightness: int | None = None,
76
+ transition: int | None = None,
77
+ ) -> None:
78
+ """Set an effect for the device.
79
+
80
+ The device doesn't store an active effect while not enabled so store locally.
81
+ """
82
+ if effect != self.LIGHT_EFFECTS_OFF and effect not in self._scenes_names_to_id:
83
+ raise ValueError(
84
+ f"Cannot set light effect to {effect}, possible values "
85
+ f"are: {self.LIGHT_EFFECTS_OFF} "
86
+ f"{' '.join(self._scenes_names_to_id.keys())}"
87
+ )
88
+ enable = effect != self.LIGHT_EFFECTS_OFF
89
+ params: dict[str, bool | str] = {"enable": enable}
90
+ if enable:
91
+ effect_id = self._scenes_names_to_id[effect]
92
+ params["id"] = effect_id
93
+ return await self.call("set_dynamic_light_effect_rule_enable", params)
94
+
95
+ async def set_custom_effect(
96
+ self,
97
+ effect_dict: dict,
98
+ ) -> None:
99
+ """Set a custom effect on the device.
100
+
101
+ :param str effect_dict: The custom effect dict to set
102
+ """
103
+ raise NotImplementedError(
104
+ "Device does not support setting custom effects. "
105
+ "Use has_custom_effects to check for support."
106
+ )
107
+
108
+ @property
109
+ def has_custom_effects(self) -> bool:
110
+ """Return True if the device supports setting custom effects."""
111
+ return False
112
+
113
+ def query(self) -> dict:
114
+ """Query to execute during the update cycle."""
115
+ return {self.QUERY_GETTER_NAME: {"start_index": 0}}