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,32 @@
1
+ """Module for led controls."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ...interfaces.led import Led as LedInterface
6
+ from ..iotmodule import IotModule
7
+
8
+
9
+ class Led(IotModule, LedInterface):
10
+ """Implementation of led controls."""
11
+
12
+ def query(self) -> dict:
13
+ """Query to execute during the update cycle."""
14
+ return {}
15
+
16
+ @property
17
+ def mode(self):
18
+ """LED mode setting.
19
+
20
+ "always", "never"
21
+ """
22
+ return "always" if self.led else "never"
23
+
24
+ @property
25
+ def led(self) -> bool:
26
+ """Return the state of the led."""
27
+ sys_info = self.data
28
+ return bool(1 - sys_info["led_off"])
29
+
30
+ async def set_led(self, state: bool):
31
+ """Set the state of the led (night mode)."""
32
+ return await self.call("set_led_off", {"off": int(not state)})
@@ -0,0 +1,221 @@
1
+ """Implementation of brightness module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+ from typing import TYPE_CHECKING, cast
7
+
8
+ from ...device_type import DeviceType
9
+ from ...exceptions import KasaException
10
+ from ...feature import Feature
11
+ from ...interfaces.light import HSV, ColorTempRange, LightState
12
+ from ...interfaces.light import Light as LightInterface
13
+ from ..iotmodule import IotModule
14
+
15
+ if TYPE_CHECKING:
16
+ from ..iotbulb import IotBulb
17
+ from ..iotdimmer import IotDimmer
18
+
19
+
20
+ BRIGHTNESS_MIN = 0
21
+ BRIGHTNESS_MAX = 100
22
+
23
+
24
+ class Light(IotModule, LightInterface):
25
+ """Implementation of brightness module."""
26
+
27
+ _device: IotBulb | IotDimmer
28
+
29
+ def _initialize_features(self):
30
+ """Initialize features."""
31
+ super()._initialize_features()
32
+ device = self._device
33
+
34
+ if self._device._is_dimmable:
35
+ self._add_feature(
36
+ Feature(
37
+ device,
38
+ id="brightness",
39
+ name="Brightness",
40
+ container=self,
41
+ attribute_getter="brightness",
42
+ attribute_setter="set_brightness",
43
+ minimum_value=BRIGHTNESS_MIN,
44
+ maximum_value=BRIGHTNESS_MAX,
45
+ type=Feature.Type.Number,
46
+ category=Feature.Category.Primary,
47
+ )
48
+ )
49
+ if self._device._is_variable_color_temp:
50
+ self._add_feature(
51
+ Feature(
52
+ device=device,
53
+ id="color_temperature",
54
+ name="Color temperature",
55
+ container=self,
56
+ attribute_getter="color_temp",
57
+ attribute_setter="set_color_temp",
58
+ range_getter="valid_temperature_range",
59
+ category=Feature.Category.Primary,
60
+ type=Feature.Type.Number,
61
+ )
62
+ )
63
+ if self._device._is_color:
64
+ self._add_feature(
65
+ Feature(
66
+ device=device,
67
+ id="hsv",
68
+ name="HSV",
69
+ container=self,
70
+ attribute_getter="hsv",
71
+ attribute_setter="set_hsv",
72
+ # TODO proper type for setting hsv
73
+ type=Feature.Type.Unknown,
74
+ )
75
+ )
76
+
77
+ def query(self) -> dict:
78
+ """Query to execute during the update cycle."""
79
+ # Brightness is contained in the main device info response.
80
+ return {}
81
+
82
+ def _get_bulb_device(self) -> IotBulb | None:
83
+ """For type checker this gets an IotBulb.
84
+
85
+ IotDimmer is not a subclass of IotBulb and using isinstance
86
+ here at runtime would create a circular import.
87
+ """
88
+ if self._device.device_type in {DeviceType.Bulb, DeviceType.LightStrip}:
89
+ return cast("IotBulb", self._device)
90
+ return None
91
+
92
+ @property # type: ignore
93
+ def is_dimmable(self) -> int:
94
+ """Whether the bulb supports brightness changes."""
95
+ return self._device._is_dimmable
96
+
97
+ @property # type: ignore
98
+ def brightness(self) -> int:
99
+ """Return the current brightness in percentage."""
100
+ return self._device._brightness
101
+
102
+ async def set_brightness(
103
+ self, brightness: int, *, transition: int | None = None
104
+ ) -> dict:
105
+ """Set the brightness in percentage.
106
+
107
+ :param int brightness: brightness in percent
108
+ :param int transition: transition in milliseconds.
109
+ """
110
+ return await self._device._set_brightness(brightness, transition=transition)
111
+
112
+ @property
113
+ def is_color(self) -> bool:
114
+ """Whether the light supports color changes."""
115
+ if (bulb := self._get_bulb_device()) is None:
116
+ return False
117
+ return bulb._is_color
118
+
119
+ @property
120
+ def is_variable_color_temp(self) -> bool:
121
+ """Whether the bulb supports color temperature changes."""
122
+ if (bulb := self._get_bulb_device()) is None:
123
+ return False
124
+ return bulb._is_variable_color_temp
125
+
126
+ @property
127
+ def has_effects(self) -> bool:
128
+ """Return True if the device supports effects."""
129
+ if (bulb := self._get_bulb_device()) is None:
130
+ return False
131
+ return bulb._has_effects
132
+
133
+ @property
134
+ def hsv(self) -> HSV:
135
+ """Return the current HSV state of the bulb.
136
+
137
+ :return: hue, saturation and value (degrees, %, %)
138
+ """
139
+ if (bulb := self._get_bulb_device()) is None or not bulb._is_color:
140
+ raise KasaException("Light does not support color.")
141
+ return bulb._hsv
142
+
143
+ async def set_hsv(
144
+ self,
145
+ hue: int,
146
+ saturation: int,
147
+ value: int | None = None,
148
+ *,
149
+ transition: int | None = None,
150
+ ) -> dict:
151
+ """Set new HSV.
152
+
153
+ Note, transition is not supported and will be ignored.
154
+
155
+ :param int hue: hue in degrees
156
+ :param int saturation: saturation in percentage [0,100]
157
+ :param int value: value in percentage [0, 100]
158
+ :param int transition: transition in milliseconds.
159
+ """
160
+ if (bulb := self._get_bulb_device()) is None or not bulb._is_color:
161
+ raise KasaException("Light does not support color.")
162
+ return await bulb._set_hsv(hue, saturation, value, transition=transition)
163
+
164
+ @property
165
+ def valid_temperature_range(self) -> ColorTempRange:
166
+ """Return the device-specific white temperature range (in Kelvin).
167
+
168
+ :return: White temperature range in Kelvin (minimum, maximum)
169
+ """
170
+ if (
171
+ bulb := self._get_bulb_device()
172
+ ) is None or not bulb._is_variable_color_temp:
173
+ raise KasaException("Light does not support colortemp.")
174
+ return bulb._valid_temperature_range
175
+
176
+ @property
177
+ def color_temp(self) -> int:
178
+ """Whether the bulb supports color temperature changes."""
179
+ if (
180
+ bulb := self._get_bulb_device()
181
+ ) is None or not bulb._is_variable_color_temp:
182
+ raise KasaException("Light does not support colortemp.")
183
+ return bulb._color_temp
184
+
185
+ async def set_color_temp(
186
+ self, temp: int, *, brightness=None, transition: int | None = None
187
+ ) -> dict:
188
+ """Set the color temperature of the device in kelvin.
189
+
190
+ Note, transition is not supported and will be ignored.
191
+
192
+ :param int temp: The new color temperature, in Kelvin
193
+ :param int transition: transition in milliseconds.
194
+ """
195
+ if (
196
+ bulb := self._get_bulb_device()
197
+ ) is None or not bulb._is_variable_color_temp:
198
+ raise KasaException("Light does not support colortemp.")
199
+ return await bulb._set_color_temp(
200
+ temp, brightness=brightness, transition=transition
201
+ )
202
+
203
+ async def set_state(self, state: LightState) -> dict:
204
+ """Set the light state."""
205
+ if (bulb := self._get_bulb_device()) is None:
206
+ return await self.set_brightness(state.brightness or 0)
207
+ else:
208
+ transition = state.transition
209
+ state_dict = asdict(state)
210
+ state_dict = {k: v for k, v in state_dict.items() if v is not None}
211
+ state_dict["on_off"] = 1 if state.light_on is None else int(state.light_on)
212
+ return await bulb._set_light_state(state_dict, transition=transition)
213
+
214
+ async def _deprecated_set_light_state(
215
+ self, state: dict, *, transition: int | None = None
216
+ ) -> dict:
217
+ """Set the light state."""
218
+ if (bulb := self._get_bulb_device()) is None:
219
+ raise KasaException("Device does not support set_light_state")
220
+ else:
221
+ return await bulb._set_light_state(state, transition=transition)
@@ -0,0 +1,122 @@
1
+ """Module for light effects."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ...interfaces.lighteffect import LightEffect as LightEffectInterface
6
+ from ..effects import EFFECT_MAPPING_V1, EFFECT_NAMES_V1
7
+ from ..iotmodule import IotModule
8
+
9
+
10
+ class LightEffect(IotModule, LightEffectInterface):
11
+ """Implementation of dynamic light effects."""
12
+
13
+ @property
14
+ def effect(self) -> str:
15
+ """Return effect state.
16
+
17
+ Example:
18
+ {'brightness': 50,
19
+ 'custom': 0,
20
+ 'enable': 0,
21
+ 'id': '',
22
+ 'name': ''}
23
+ """
24
+ eff = self.data["lighting_effect_state"]
25
+ name = eff["name"]
26
+ if eff["enable"]:
27
+ return name
28
+
29
+ return self.LIGHT_EFFECTS_OFF
30
+
31
+ @property
32
+ def effect_list(self) -> list[str]:
33
+ """Return built-in effects list.
34
+
35
+ Example:
36
+ ['Aurora', 'Bubbling Cauldron', ...]
37
+ """
38
+ effect_list = [self.LIGHT_EFFECTS_OFF]
39
+ effect_list.extend(EFFECT_NAMES_V1)
40
+ return effect_list
41
+
42
+ async def set_effect(
43
+ self,
44
+ effect: str,
45
+ *,
46
+ brightness: int | None = None,
47
+ transition: int | None = None,
48
+ ) -> None:
49
+ """Set an effect on the device.
50
+
51
+ If brightness or transition is defined,
52
+ its value will be used instead of the effect-specific default.
53
+
54
+ See :meth:`effect_list` for available effects,
55
+ or use :meth:`set_custom_effect` for custom effects.
56
+
57
+ :param str effect: The effect to set
58
+ :param int brightness: The wanted brightness
59
+ :param int transition: The wanted transition time
60
+ """
61
+ if effect == self.LIGHT_EFFECTS_OFF:
62
+ effect_dict = dict(self.data["lighting_effect_state"])
63
+ effect_dict["enable"] = 0
64
+ elif effect not in EFFECT_MAPPING_V1:
65
+ raise ValueError(f"The effect {effect} is not a built in effect.")
66
+ else:
67
+ effect_dict = EFFECT_MAPPING_V1[effect]
68
+
69
+ if brightness is not None:
70
+ effect_dict["brightness"] = brightness
71
+ if transition is not None:
72
+ effect_dict["transition"] = transition
73
+
74
+ await self.set_custom_effect(effect_dict)
75
+
76
+ async def set_custom_effect(
77
+ self,
78
+ effect_dict: dict,
79
+ ) -> None:
80
+ """Set a custom effect on the device.
81
+
82
+ :param str effect_dict: The custom effect dict to set
83
+ """
84
+ return await self.call(
85
+ "set_lighting_effect",
86
+ effect_dict,
87
+ )
88
+
89
+ @property
90
+ def has_custom_effects(self) -> bool:
91
+ """Return True if the device supports setting custom effects."""
92
+ return True
93
+
94
+ def query(self):
95
+ """Return the base query."""
96
+ return {}
97
+
98
+ @property # type: ignore
99
+ def _deprecated_effect(self) -> dict:
100
+ """Return effect state.
101
+
102
+ Example:
103
+ {'brightness': 50,
104
+ 'custom': 0,
105
+ 'enable': 0,
106
+ 'id': '',
107
+ 'name': ''}
108
+ """
109
+ # LightEffectModule returns the current effect name
110
+ # so return the dict here for backwards compatibility
111
+ return self.data["lighting_effect_state"]
112
+
113
+ @property # type: ignore
114
+ def _deprecated_effect_list(self) -> list[str] | None:
115
+ """Return built-in effects list.
116
+
117
+ Example:
118
+ ['Aurora', 'Bubbling Cauldron', ...]
119
+ """
120
+ # LightEffectModule returns effect names along with a LIGHT_EFFECTS_OFF value
121
+ # so return the original effect names here for backwards compatibility
122
+ return EFFECT_NAMES_V1
@@ -0,0 +1,151 @@
1
+ """Light preset module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import asdict
6
+ from typing import TYPE_CHECKING, Optional, Sequence
7
+
8
+ from pydantic.v1 import BaseModel, Field
9
+
10
+ from ...exceptions import KasaException
11
+ from ...interfaces import LightPreset as LightPresetInterface
12
+ from ...interfaces import LightState
13
+ from ...module import Module
14
+ from ..iotmodule import IotModule
15
+
16
+ if TYPE_CHECKING:
17
+ pass
18
+
19
+
20
+ class IotLightPreset(BaseModel, LightState):
21
+ """Light configuration preset."""
22
+
23
+ index: int = Field(kw_only=True)
24
+ brightness: int = Field(kw_only=True)
25
+
26
+ # These are not available for effect mode presets on light strips
27
+ hue: Optional[int] = Field(kw_only=True, default=None) # noqa: UP007
28
+ saturation: Optional[int] = Field(kw_only=True, default=None) # noqa: UP007
29
+ color_temp: Optional[int] = Field(kw_only=True, default=None) # noqa: UP007
30
+
31
+ # Variables for effect mode presets
32
+ custom: Optional[int] = Field(kw_only=True, default=None) # noqa: UP007
33
+ id: Optional[str] = Field(kw_only=True, default=None) # noqa: UP007
34
+ mode: Optional[int] = Field(kw_only=True, default=None) # noqa: UP007
35
+
36
+
37
+ class LightPreset(IotModule, LightPresetInterface):
38
+ """Class for setting light presets."""
39
+
40
+ _presets: dict[str, IotLightPreset]
41
+ _preset_list: list[str]
42
+
43
+ def _post_update_hook(self):
44
+ """Update the internal presets."""
45
+ self._presets = {
46
+ f"Light preset {index+1}": IotLightPreset(**vals)
47
+ for index, vals in enumerate(self.data["preferred_state"])
48
+ }
49
+ self._preset_list = [self.PRESET_NOT_SET]
50
+ self._preset_list.extend(self._presets.keys())
51
+
52
+ @property
53
+ def preset_list(self) -> list[str]:
54
+ """Return built-in effects list.
55
+
56
+ Example:
57
+ ['Off', 'Preset 1', 'Preset 2', ...]
58
+ """
59
+ return self._preset_list
60
+
61
+ @property
62
+ def preset_states_list(self) -> Sequence[IotLightPreset]:
63
+ """Return built-in effects list.
64
+
65
+ Example:
66
+ ['Off', 'Preset 1', 'Preset 2', ...]
67
+ """
68
+ return list(self._presets.values())
69
+
70
+ @property
71
+ def preset(self) -> str:
72
+ """Return current preset name."""
73
+ light = self._device.modules[Module.Light]
74
+ brightness = light.brightness
75
+ color_temp = light.color_temp if light.is_variable_color_temp else None
76
+ h, s = (light.hsv.hue, light.hsv.saturation) if light.is_color else (None, None)
77
+ for preset_name, preset in self._presets.items():
78
+ if (
79
+ preset.brightness == brightness
80
+ and (
81
+ preset.color_temp == color_temp or not light.is_variable_color_temp
82
+ )
83
+ and (preset.hue == h or not light.is_color)
84
+ and (preset.saturation == s or not light.is_color)
85
+ ):
86
+ return preset_name
87
+ return self.PRESET_NOT_SET
88
+
89
+ async def set_preset(
90
+ self,
91
+ preset_name: str,
92
+ ) -> None:
93
+ """Set a light preset for the device."""
94
+ light = self._device.modules[Module.Light]
95
+ if preset_name == self.PRESET_NOT_SET:
96
+ if light.is_color:
97
+ preset = LightState(hue=0, saturation=0, brightness=100)
98
+ else:
99
+ preset = LightState(brightness=100)
100
+ elif (preset := self._presets.get(preset_name)) is None: # type: ignore[assignment]
101
+ raise ValueError(f"{preset_name} is not a valid preset: {self.preset_list}")
102
+
103
+ await light.set_state(preset)
104
+
105
+ @property
106
+ def has_save_preset(self) -> bool:
107
+ """Return True if the device supports updating presets."""
108
+ return True
109
+
110
+ async def save_preset(
111
+ self,
112
+ preset_name: str,
113
+ preset_state: LightState,
114
+ ) -> None:
115
+ """Update the preset with preset_name with the new preset_info."""
116
+ if len(self._presets) == 0:
117
+ raise KasaException("Device does not supported saving presets")
118
+ if preset_name not in self._presets:
119
+ raise ValueError(f"{preset_name} is not a valid preset: {self.preset_list}")
120
+
121
+ index = list(self._presets.keys()).index(preset_name)
122
+ state = asdict(preset_state)
123
+ state = {k: v for k, v in state.items() if v is not None}
124
+ state["index"] = index
125
+
126
+ return await self.call("set_preferred_state", state)
127
+
128
+ def query(self):
129
+ """Return the base query."""
130
+ return {}
131
+
132
+ @property # type: ignore
133
+ def _deprecated_presets(self) -> list[IotLightPreset]:
134
+ """Return a list of available bulb setting presets."""
135
+ return [
136
+ IotLightPreset(**vals) for vals in self._device.sys_info["preferred_state"]
137
+ ]
138
+
139
+ async def _deprecated_save_preset(self, preset: IotLightPreset):
140
+ """Save a setting preset.
141
+
142
+ You can either construct a preset object manually, or pass an existing one
143
+ obtained using :func:`presets`.
144
+ """
145
+ if len(self._presets) == 0:
146
+ raise KasaException("Device does not supported saving presets")
147
+
148
+ if preset.index >= len(self._presets):
149
+ raise KasaException("Invalid preset index")
150
+
151
+ return await self.call("set_preferred_state", preset.dict(exclude_none=True))
@@ -1,9 +1,11 @@
1
1
  """Implementation of the motion detection (PIR) module found in some dimmers."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  from enum import Enum
3
- from typing import Optional
4
6
 
5
- from ..exceptions import SmartDeviceException
6
- from .module import Module
7
+ from ...exceptions import KasaException
8
+ from ..iotmodule import IotModule
7
9
 
8
10
 
9
11
  class Range(Enum):
@@ -20,7 +22,7 @@ class Range(Enum):
20
22
  # "min_adc":0,"max_adc":4095,"array":[80,50,20,0],"err_code":0}}}
21
23
 
22
24
 
23
- class Motion(Module):
25
+ class Motion(IotModule):
24
26
  """Implements the motion detection (PIR) module."""
25
27
 
26
28
  def query(self):
@@ -42,7 +44,7 @@ class Motion(Module):
42
44
  return await self.call("set_enable", {"enable": int(state)})
43
45
 
44
46
  async def set_range(
45
- self, *, range: Optional[Range] = None, custom_range: Optional[int] = None
47
+ self, *, range: Range | None = None, custom_range: int | None = None
46
48
  ):
47
49
  """Set the range for the sensor.
48
50
 
@@ -54,9 +56,7 @@ class Motion(Module):
54
56
  elif range is not None:
55
57
  payload = {"index": range.value}
56
58
  else:
57
- raise SmartDeviceException(
58
- "Either range or custom_range need to be defined"
59
- )
59
+ raise KasaException("Either range or custom_range need to be defined")
60
60
 
61
61
  return await self.call("set_trigger_sens", payload)
62
62
 
@@ -1,15 +1,14 @@
1
1
  """Base implementation for all rule-based modules."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  import logging
3
6
  from enum import Enum
4
7
  from typing import Dict, List, Optional
5
8
 
6
- try:
7
- from pydantic.v1 import BaseModel
8
- except ImportError:
9
- from pydantic import BaseModel
10
-
9
+ from pydantic.v1 import BaseModel
11
10
 
12
- from .module import Module, merge
11
+ from ..iotmodule import IotModule, merge
13
12
 
14
13
 
15
14
  class Action(Enum):
@@ -36,26 +35,26 @@ class Rule(BaseModel):
36
35
  id: str
37
36
  name: str
38
37
  enable: bool
39
- wday: List[int]
38
+ wday: List[int] # noqa: UP006
40
39
  repeat: bool
41
40
 
42
41
  # start action
43
- sact: Optional[Action]
42
+ sact: Optional[Action] # noqa: UP007
44
43
  stime_opt: TimeOption
45
44
  smin: int
46
45
 
47
- eact: Optional[Action]
46
+ eact: Optional[Action] # noqa: UP007
48
47
  etime_opt: TimeOption
49
48
  emin: int
50
49
 
51
50
  # Only on bulbs
52
- s_light: Optional[Dict]
51
+ s_light: Optional[Dict] # noqa: UP006,UP007
53
52
 
54
53
 
55
54
  _LOGGER = logging.getLogger(__name__)
56
55
 
57
56
 
58
- class RuleModule(Module):
57
+ class RuleModule(IotModule):
59
58
  """Base class for rule-based modules, such as countdown and antitheft."""
60
59
 
61
60
  def query(self):
@@ -64,7 +63,7 @@ class RuleModule(Module):
64
63
  return merge(q, self.query_for_command("get_next_action"))
65
64
 
66
65
  @property
67
- def rules(self) -> List[Rule]:
66
+ def rules(self) -> list[Rule]:
68
67
  """Return the list of rules for the service."""
69
68
  try:
70
69
  return [
@@ -1,4 +1,5 @@
1
1
  """Schedule module implementation."""
2
+
2
3
  from .rulemodule import RuleModule
3
4
 
4
5
 
@@ -1,11 +1,12 @@
1
1
  """Provides the current time and timezone information."""
2
+
2
3
  from datetime import datetime
3
4
 
4
- from ..exceptions import SmartDeviceException
5
- from .module import Module, merge
5
+ from ...exceptions import KasaException
6
+ from ..iotmodule import IotModule, merge
6
7
 
7
8
 
8
- class Time(Module):
9
+ class Time(IotModule):
9
10
  """Implements the timezone settings."""
10
11
 
11
12
  def query(self):
@@ -46,7 +47,7 @@ class Time(Module):
46
47
  res["min"],
47
48
  res["sec"],
48
49
  )
49
- except SmartDeviceException:
50
+ except KasaException:
50
51
  return None
51
52
 
52
53
  async def get_timezone(self):