python-kasa 0.6.2.1__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 (164) 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 +7 -5
  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 -562
  83. kasa/tests/device_fixtures.py +427 -0
  84. kasa/tests/discovery_fixtures.py +197 -0
  85. kasa/tests/fakeprotocol_iot.py +64 -6
  86. kasa/tests/fakeprotocol_smart.py +215 -22
  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/child/KE100(EU)_1.0_2.4.0.json +170 -0
  99. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +171 -0
  100. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +171 -0
  101. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +526 -0
  102. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +533 -0
  103. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +530 -0
  104. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +537 -0
  105. kasa/tests/smart/__init__.py +0 -0
  106. kasa/tests/smart/features/__init__.py +0 -0
  107. kasa/tests/smart/features/test_brightness.py +55 -0
  108. kasa/tests/smart/features/test_colortemp.py +30 -0
  109. kasa/tests/smart/modules/__init__.py +0 -0
  110. kasa/tests/smart/modules/test_contact.py +28 -0
  111. kasa/tests/smart/modules/test_fan.py +79 -0
  112. kasa/tests/smart/modules/test_firmware.py +108 -0
  113. kasa/tests/smart/modules/test_humidity.py +28 -0
  114. kasa/tests/smart/modules/test_light_effect.py +41 -0
  115. kasa/tests/smart/modules/test_temperature.py +47 -0
  116. kasa/tests/smart/modules/test_temperaturecontrol.py +137 -0
  117. kasa/tests/smart/modules/test_waterleak.py +42 -0
  118. kasa/tests/test_aestransport.py +115 -23
  119. kasa/tests/test_bulb.py +115 -85
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +216 -0
  123. kasa/tests/test_device.py +268 -0
  124. kasa/tests/test_device_factory.py +61 -35
  125. kasa/tests/test_device_type.py +1 -1
  126. kasa/tests/test_deviceconfig.py +2 -2
  127. kasa/tests/test_dimmer.py +33 -24
  128. kasa/tests/test_discovery.py +112 -63
  129. kasa/tests/test_emeter.py +14 -10
  130. kasa/tests/test_feature.py +205 -0
  131. kasa/tests/test_httpclient.py +9 -9
  132. kasa/tests/test_iotdevice.py +286 -0
  133. kasa/tests/test_klapprotocol.py +94 -37
  134. kasa/tests/test_lightstrip.py +24 -19
  135. kasa/tests/test_plug.py +46 -8
  136. kasa/tests/test_protocol.py +8 -10
  137. kasa/tests/test_readme_examples.py +87 -26
  138. kasa/tests/test_smartdevice.py +203 -311
  139. kasa/tests/test_smartprotocol.py +130 -25
  140. kasa/tests/test_strip.py +15 -6
  141. kasa/tests/test_usage.py +1 -1
  142. kasa/xortransport.py +15 -12
  143. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev0.dist-info/RECORD +239 -0
  145. kasa/modules/emeter.py +0 -111
  146. kasa/smartlightstrip.py +0 -143
  147. kasa/smartplug.py +0 -91
  148. kasa/tapo/__init__.py +0 -7
  149. kasa/tapo/childdevice.py +0 -41
  150. kasa/tapo/tapobulb.py +0 -262
  151. kasa/tapo/tapodevice.py +0 -409
  152. kasa/tapo/tapoplug.py +0 -45
  153. kasa/tests/fixtures/HS105(US)_1.0_mocked.json +0 -47
  154. kasa/tests/fixtures/HS110(EU)_2.0_mocked.json +0 -50
  155. kasa/tests/fixtures/HS110(US)_1.0_mocked.json +0 -50
  156. kasa/tests/fixtures/HS200(US)_1.0_mocked.json +0 -47
  157. kasa/tests/fixtures/HS220(US)_1.0_mocked.json +0 -75
  158. kasa/tests/fixtures/LB100(US)_1.0_mocked.json +0 -103
  159. kasa/tests/fixtures/LB120(US)_1.0_mocked.json +0 -103
  160. kasa/tests/fixtures/LB130(US)_1.0_mocked.json +0 -104
  161. python_kasa-0.6.2.1.dist-info/RECORD +0 -167
  162. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev0.dist-info}/entry_points.txt +0 -0
@@ -1,36 +1,39 @@
1
1
  """Module for multi-socket devices (HS300, HS107, KP303, ..)."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  import logging
3
6
  from collections import defaultdict
4
7
  from datetime import datetime, timedelta
5
- from typing import Any, DefaultDict, Dict, Optional
6
-
7
- from kasa.smartdevice import (
8
- DeviceType,
8
+ from typing import Any
9
+
10
+ from ..device_type import DeviceType
11
+ from ..deviceconfig import DeviceConfig
12
+ from ..exceptions import KasaException
13
+ from ..module import Module
14
+ from ..protocol import BaseProtocol
15
+ from .iotdevice import (
9
16
  EmeterStatus,
10
- SmartDevice,
11
- SmartDeviceException,
17
+ IotDevice,
12
18
  merge,
13
19
  requires_update,
14
20
  )
15
- from kasa.smartplug import SmartPlug
16
-
17
- from .deviceconfig import DeviceConfig
18
- from .modules import Antitheft, Countdown, Emeter, Schedule, Time, Usage
19
- from .protocol import BaseProtocol
21
+ from .iotplug import IotPlug
22
+ from .modules import Antitheft, Countdown, Schedule, Time, Usage
20
23
 
21
24
  _LOGGER = logging.getLogger(__name__)
22
25
 
23
26
 
24
27
  def merge_sums(dicts):
25
28
  """Merge the sum of dicts."""
26
- total_dict: DefaultDict[int, float] = defaultdict(lambda: 0.0)
29
+ total_dict: defaultdict[int, float] = defaultdict(lambda: 0.0)
27
30
  for sum_dict in dicts:
28
31
  for day, value in sum_dict.items():
29
32
  total_dict[day] += value
30
33
  return total_dict
31
34
 
32
35
 
33
- class SmartStrip(SmartDevice):
36
+ class IotStrip(IotDevice):
34
37
  r"""Representation of a TP-Link Smart Power Strip.
35
38
 
36
39
  A strip consists of the parent device and its children.
@@ -44,12 +47,12 @@ class SmartStrip(SmartDevice):
44
47
  which will not change the cached values,
45
48
  but you must await :func:`update()` separately.
46
49
 
47
- Errors reported by the device are raised as :class:`SmartDeviceException`\s,
50
+ Errors reported by the device are raised as :class:`KasaException`\s,
48
51
  and should be handled by the user of the library.
49
52
 
50
53
  Examples:
51
54
  >>> import asyncio
52
- >>> strip = SmartStrip("127.0.0.1")
55
+ >>> strip = IotStrip("127.0.0.1")
53
56
  >>> asyncio.run(strip.update())
54
57
  >>> strip.alias
55
58
  TP-LINK_Power Strip_CF69
@@ -64,6 +67,7 @@ class SmartStrip(SmartDevice):
64
67
  >>> strip.is_on
65
68
  True
66
69
  >>> asyncio.run(strip.turn_off())
70
+ >>> asyncio.run(strip.update())
67
71
 
68
72
  Accessing individual plugs can be done using the `children` property:
69
73
 
@@ -79,25 +83,24 @@ class SmartStrip(SmartDevice):
79
83
  >>> strip.is_on
80
84
  True
81
85
 
82
- For more examples, see the :class:`SmartDevice` class.
86
+ For more examples, see the :class:`Device` class.
83
87
  """
84
88
 
85
89
  def __init__(
86
90
  self,
87
91
  host: str,
88
92
  *,
89
- config: Optional[DeviceConfig] = None,
90
- protocol: Optional[BaseProtocol] = None,
93
+ config: DeviceConfig | None = None,
94
+ protocol: BaseProtocol | None = None,
91
95
  ) -> None:
92
96
  super().__init__(host=host, config=config, protocol=protocol)
93
97
  self.emeter_type = "emeter"
94
98
  self._device_type = DeviceType.Strip
95
- self.add_module("antitheft", Antitheft(self, "anti_theft"))
96
- self.add_module("schedule", Schedule(self, "schedule"))
97
- self.add_module("usage", Usage(self, "schedule"))
98
- self.add_module("time", Time(self, "time"))
99
- self.add_module("countdown", Countdown(self, "countdown"))
100
- self.add_module("emeter", Emeter(self, "emeter"))
99
+ self.add_module(Module.IotAntitheft, Antitheft(self, "anti_theft"))
100
+ self.add_module(Module.IotSchedule, Schedule(self, "schedule"))
101
+ self.add_module(Module.IotUsage, Usage(self, "schedule"))
102
+ self.add_module(Module.IotTime, Time(self, "time"))
103
+ self.add_module(Module.IotCountdown, Countdown(self, "countdown"))
101
104
 
102
105
  @property # type: ignore
103
106
  @requires_update
@@ -116,10 +119,12 @@ class SmartStrip(SmartDevice):
116
119
  if not self.children:
117
120
  children = self.sys_info["children"]
118
121
  _LOGGER.debug("Initializing %s child sockets", len(children))
119
- for child in children:
120
- self.children.append(
121
- SmartStripPlug(self.host, parent=self, child_id=child["id"])
122
+ self._children = {
123
+ f"{self.mac}_{child['id']}": IotStripPlug(
124
+ self.host, parent=self, child_id=child["id"]
122
125
  )
126
+ for child in children
127
+ }
123
128
 
124
129
  if update_children and self.has_emeter:
125
130
  for plug in self.children:
@@ -135,37 +140,13 @@ class SmartStrip(SmartDevice):
135
140
 
136
141
  @property # type: ignore
137
142
  @requires_update
138
- def on_since(self) -> Optional[datetime]:
143
+ def on_since(self) -> datetime | None:
139
144
  """Return the maximum on-time of all outlets."""
140
145
  if self.is_off:
141
146
  return None
142
147
 
143
148
  return max(plug.on_since for plug in self.children if plug.on_since is not None)
144
149
 
145
- @property # type: ignore
146
- @requires_update
147
- def led(self) -> bool:
148
- """Return the state of the led."""
149
- sys_info = self.sys_info
150
- return bool(1 - sys_info["led_off"])
151
-
152
- async def set_led(self, state: bool):
153
- """Set the state of the led (night mode)."""
154
- await self._query_helper("system", "set_led_off", {"off": int(not state)})
155
-
156
- @property # type: ignore
157
- @requires_update
158
- def state_information(self) -> Dict[str, Any]:
159
- """Return strip-specific state information.
160
-
161
- :return: Strip information dict, keys in user-presentable form.
162
- """
163
- return {
164
- "LED state": self.led,
165
- "Childs count": len(self.children),
166
- "On since": self.on_since,
167
- }
168
-
169
150
  async def current_consumption(self) -> float:
170
151
  """Get the current power consumption in watts."""
171
152
  return sum([await plug.current_consumption() for plug in self.children])
@@ -181,8 +162,8 @@ class SmartStrip(SmartDevice):
181
162
 
182
163
  @requires_update
183
164
  async def get_emeter_daily(
184
- self, year: Optional[int] = None, month: Optional[int] = None, kwh: bool = True
185
- ) -> Dict:
165
+ self, year: int | None = None, month: int | None = None, kwh: bool = True
166
+ ) -> dict:
186
167
  """Retrieve daily statistics for a given month.
187
168
 
188
169
  :param year: year for which to retrieve statistics (default: this year)
@@ -197,8 +178,8 @@ class SmartStrip(SmartDevice):
197
178
 
198
179
  @requires_update
199
180
  async def get_emeter_monthly(
200
- self, year: Optional[int] = None, kwh: bool = True
201
- ) -> Dict:
181
+ self, year: int | None = None, kwh: bool = True
182
+ ) -> dict:
202
183
  """Retrieve monthly statistics for a given year.
203
184
 
204
185
  :param year: year for which to retrieve statistics (default: this year)
@@ -208,7 +189,7 @@ class SmartStrip(SmartDevice):
208
189
  "get_emeter_monthly", {"year": year, "kwh": kwh}
209
190
  )
210
191
 
211
- async def _async_get_emeter_sum(self, func: str, kwargs: Dict[str, Any]) -> Dict:
192
+ async def _async_get_emeter_sum(self, func: str, kwargs: dict[str, Any]) -> dict:
212
193
  """Retreive emeter stats for a time period from children."""
213
194
  self._verify_emeter()
214
195
  return merge_sums(
@@ -223,15 +204,15 @@ class SmartStrip(SmartDevice):
223
204
 
224
205
  @property # type: ignore
225
206
  @requires_update
226
- def emeter_this_month(self) -> Optional[float]:
207
+ def emeter_this_month(self) -> float | None:
227
208
  """Return this month's energy consumption in kWh."""
228
- return sum(plug.emeter_this_month for plug in self.children)
209
+ return sum(v if (v := plug.emeter_this_month) else 0 for plug in self.children)
229
210
 
230
211
  @property # type: ignore
231
212
  @requires_update
232
- def emeter_today(self) -> Optional[float]:
213
+ def emeter_today(self) -> float | None:
233
214
  """Return this month's energy consumption in kWh."""
234
- return sum(plug.emeter_today for plug in self.children)
215
+ return sum(v if (v := plug.emeter_today) else 0 for plug in self.children)
235
216
 
236
217
  @property # type: ignore
237
218
  @requires_update
@@ -244,7 +225,7 @@ class SmartStrip(SmartDevice):
244
225
  return EmeterStatus(emeter)
245
226
 
246
227
 
247
- class SmartStripPlug(SmartPlug):
228
+ class IotStripPlug(IotPlug):
248
229
  """Representation of a single socket in a power strip.
249
230
 
250
231
  This allows you to use the sockets as they were SmartPlug objects.
@@ -254,7 +235,7 @@ class SmartStripPlug(SmartPlug):
254
235
  The plug inherits (most of) the system information from the parent.
255
236
  """
256
237
 
257
- def __init__(self, host: str, parent: "SmartStrip", child_id: str) -> None:
238
+ def __init__(self, host: str, parent: IotStrip, child_id: str) -> None:
258
239
  super().__init__(host)
259
240
 
260
241
  self.parent = parent
@@ -262,8 +243,11 @@ class SmartStripPlug(SmartPlug):
262
243
  self._last_update = parent._last_update
263
244
  self._set_sys_info(parent.sys_info)
264
245
  self._device_type = DeviceType.StripSocket
265
- self.modules = {}
266
246
  self.protocol = parent.protocol # Must use the same connection as the parent
247
+
248
+ async def _initialize_modules(self):
249
+ """Initialize modules not added in init."""
250
+ await super()._initialize_modules()
267
251
  self.add_module("time", Time(self, "time"))
268
252
 
269
253
  async def update(self, update_children: bool = True):
@@ -273,16 +257,14 @@ class SmartStripPlug(SmartPlug):
273
257
  """
274
258
  await self._modular_update({})
275
259
 
276
- def _create_emeter_request(
277
- self, year: Optional[int] = None, month: Optional[int] = None
278
- ):
260
+ def _create_emeter_request(self, year: int | None = None, month: int | None = None):
279
261
  """Create a request for requesting all emeter statistics at once."""
280
262
  if year is None:
281
263
  year = datetime.now().year
282
264
  if month is None:
283
265
  month = datetime.now().month
284
266
 
285
- req: Dict[str, Any] = {}
267
+ req: dict[str, Any] = {}
286
268
 
287
269
  merge(req, self._create_request("emeter", "get_realtime"))
288
270
  merge(req, self._create_request("emeter", "get_monthstat", {"year": year}))
@@ -296,16 +278,16 @@ class SmartStripPlug(SmartPlug):
296
278
  return req
297
279
 
298
280
  def _create_request(
299
- self, target: str, cmd: str, arg: Optional[Dict] = None, child_ids=None
281
+ self, target: str, cmd: str, arg: dict | None = None, child_ids=None
300
282
  ):
301
- request: Dict[str, Any] = {
283
+ request: dict[str, Any] = {
302
284
  "context": {"child_ids": [self.child_id]},
303
285
  target: {cmd: arg},
304
286
  }
305
287
  return request
306
288
 
307
289
  async def _query_helper(
308
- self, target: str, cmd: str, arg: Optional[Dict] = None, child_ids=None
290
+ self, target: str, cmd: str, arg: dict | None = None, child_ids=None
309
291
  ) -> Any:
310
292
  """Override query helper to include the child_ids."""
311
293
  return await self.parent._query_helper(
@@ -346,14 +328,14 @@ class SmartStripPlug(SmartPlug):
346
328
 
347
329
  @property # type: ignore
348
330
  @requires_update
349
- def next_action(self) -> Dict:
331
+ def next_action(self) -> dict:
350
332
  """Return next scheduled(?) action."""
351
333
  info = self._get_child_info()
352
334
  return info["next_action"]
353
335
 
354
336
  @property # type: ignore
355
337
  @requires_update
356
- def on_since(self) -> Optional[datetime]:
338
+ def on_since(self) -> datetime | None:
357
339
  """Return on-time, if available."""
358
340
  if self.is_off:
359
341
  return None
@@ -370,10 +352,10 @@ class SmartStripPlug(SmartPlug):
370
352
  sys_info = self.parent.sys_info
371
353
  return f"Socket for {sys_info['model']}"
372
354
 
373
- def _get_child_info(self) -> Dict:
355
+ def _get_child_info(self) -> dict:
374
356
  """Return the subdevice information for this device."""
375
357
  for plug in self.parent.sys_info["children"]:
376
358
  if plug["id"] == self.child_id:
377
359
  return plug
378
360
 
379
- raise SmartDeviceException(f"Unable to find children {self.child_id}")
361
+ raise KasaException(f"Unable to find children {self.child_id}")
@@ -1,10 +1,14 @@
1
1
  """Module for individual feature modules."""
2
+
2
3
  from .ambientlight import AmbientLight
3
4
  from .antitheft import Antitheft
4
5
  from .cloud import Cloud
5
6
  from .countdown import Countdown
6
7
  from .emeter import Emeter
7
- from .module import Module
8
+ from .led import Led
9
+ from .light import Light
10
+ from .lighteffect import LightEffect
11
+ from .lightpreset import IotLightPreset, LightPreset
8
12
  from .motion import Motion
9
13
  from .rulemodule import Rule, RuleModule
10
14
  from .schedule import Schedule
@@ -17,7 +21,11 @@ __all__ = [
17
21
  "Cloud",
18
22
  "Countdown",
19
23
  "Emeter",
20
- "Module",
24
+ "Led",
25
+ "Light",
26
+ "LightEffect",
27
+ "LightPreset",
28
+ "IotLightPreset",
21
29
  "Motion",
22
30
  "Rule",
23
31
  "RuleModule",
@@ -1,5 +1,7 @@
1
1
  """Implementation of the ambient light (LAS) module found in some dimmers."""
2
- from .module import Module
2
+
3
+ from ...feature import Feature
4
+ from ..iotmodule import IotModule, merge
3
5
 
4
6
  # TODO create tests and use the config reply there
5
7
  # [{"hw_id":0,"enable":0,"dark_index":1,"min_adc":0,"max_adc":2450,
@@ -11,12 +13,33 @@ from .module import Module
11
13
  # {"name":"custom","adc":2400,"value":97}]}]
12
14
 
13
15
 
14
- class AmbientLight(Module):
16
+ class AmbientLight(IotModule):
15
17
  """Implements ambient light controls for the motion sensor."""
16
18
 
19
+ def __init__(self, device, module):
20
+ super().__init__(device, module)
21
+ self._add_feature(
22
+ Feature(
23
+ device=device,
24
+ container=self,
25
+ id="ambient_light",
26
+ name="Ambient Light",
27
+ icon="mdi:brightness-percent",
28
+ attribute_getter="ambientlight_brightness",
29
+ type=Feature.Type.Sensor,
30
+ category=Feature.Category.Primary,
31
+ unit="%",
32
+ )
33
+ )
34
+
17
35
  def query(self):
18
36
  """Request configuration."""
19
- return self.query_for_command("get_config")
37
+ req = merge(
38
+ self.query_for_command("get_config"),
39
+ self.query_for_command("get_current_brt"),
40
+ )
41
+
42
+ return req
20
43
 
21
44
  @property
22
45
  def presets(self) -> dict:
@@ -28,6 +51,11 @@ class AmbientLight(Module):
28
51
  """Return True if the module is enabled."""
29
52
  return bool(self.data["enable"])
30
53
 
54
+ @property
55
+ def ambientlight_brightness(self) -> int:
56
+ """Return True if the module is enabled."""
57
+ return int(self.data["get_current_brt"]["value"])
58
+
31
59
  async def set_enabled(self, state: bool):
32
60
  """Enable/disable LAS."""
33
61
  return await self.call("set_enable", {"enable": int(state)})
@@ -1,4 +1,5 @@
1
1
  """Implementation of the antitheft module."""
2
+
2
3
  from .rulemodule import RuleModule
3
4
 
4
5
 
@@ -1,10 +1,9 @@
1
1
  """Cloud module implementation."""
2
- try:
3
- from pydantic.v1 import BaseModel
4
- except ImportError:
5
- from pydantic import BaseModel
6
2
 
7
- from .module import Module
3
+ from pydantic.v1 import BaseModel
4
+
5
+ from ...feature import Feature
6
+ from ..iotmodule import IotModule
8
7
 
9
8
 
10
9
  class CloudInfo(BaseModel):
@@ -22,9 +21,29 @@ class CloudInfo(BaseModel):
22
21
  username: str
23
22
 
24
23
 
25
- class Cloud(Module):
24
+ class Cloud(IotModule):
26
25
  """Module implementing support for cloud services."""
27
26
 
27
+ def __init__(self, device, module):
28
+ super().__init__(device, module)
29
+ self._add_feature(
30
+ Feature(
31
+ device=device,
32
+ container=self,
33
+ id="cloud_connection",
34
+ name="Cloud connection",
35
+ icon="mdi:cloud",
36
+ attribute_getter="is_connected",
37
+ type=Feature.Type.BinarySensor,
38
+ category=Feature.Category.Info,
39
+ )
40
+ )
41
+
42
+ @property
43
+ def is_connected(self) -> bool:
44
+ """Return true if device is connected to the cloud."""
45
+ return self.info.binded
46
+
28
47
  def query(self):
29
48
  """Request cloud connectivity info."""
30
49
  return self.query_for_command("get_info")
@@ -1,4 +1,5 @@
1
1
  """Implementation for the countdown timer."""
2
+
2
3
  from .rulemodule import RuleModule
3
4
 
4
5
 
@@ -0,0 +1,210 @@
1
+ """Implementation of the emeter module."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+
7
+ from ... import Device
8
+ from ...emeterstatus import EmeterStatus
9
+ from ...feature import Feature
10
+ from .usage import Usage
11
+
12
+
13
+ class Emeter(Usage):
14
+ """Emeter module."""
15
+
16
+ def __init__(self, device: Device, module: str):
17
+ super().__init__(device, module)
18
+ self._add_feature(
19
+ Feature(
20
+ device,
21
+ name="Current consumption",
22
+ attribute_getter="current_consumption",
23
+ container=self,
24
+ unit="W",
25
+ id="current_power_w", # for homeassistant backwards compat
26
+ precision_hint=1,
27
+ category=Feature.Category.Primary,
28
+ )
29
+ )
30
+ self._add_feature(
31
+ Feature(
32
+ device,
33
+ name="Today's consumption",
34
+ attribute_getter="emeter_today",
35
+ container=self,
36
+ unit="kWh",
37
+ id="today_energy_kwh", # for homeassistant backwards compat
38
+ precision_hint=3,
39
+ category=Feature.Category.Info,
40
+ )
41
+ )
42
+ self._add_feature(
43
+ Feature(
44
+ device,
45
+ id="consumption_this_month",
46
+ name="This month's consumption",
47
+ attribute_getter="emeter_this_month",
48
+ container=self,
49
+ unit="kWh",
50
+ precision_hint=3,
51
+ category=Feature.Category.Info,
52
+ )
53
+ )
54
+ self._add_feature(
55
+ Feature(
56
+ device,
57
+ name="Total consumption since reboot",
58
+ attribute_getter="emeter_total",
59
+ container=self,
60
+ unit="kWh",
61
+ id="total_energy_kwh", # for homeassistant backwards compat
62
+ precision_hint=3,
63
+ category=Feature.Category.Info,
64
+ )
65
+ )
66
+ self._add_feature(
67
+ Feature(
68
+ device,
69
+ name="Voltage",
70
+ attribute_getter="voltage",
71
+ container=self,
72
+ unit="V",
73
+ id="voltage", # for homeassistant backwards compat
74
+ precision_hint=1,
75
+ category=Feature.Category.Primary,
76
+ )
77
+ )
78
+ self._add_feature(
79
+ Feature(
80
+ device,
81
+ name="Current",
82
+ attribute_getter="current",
83
+ container=self,
84
+ unit="A",
85
+ id="current_a", # for homeassistant backwards compat
86
+ precision_hint=2,
87
+ category=Feature.Category.Primary,
88
+ )
89
+ )
90
+
91
+ @property # type: ignore
92
+ def realtime(self) -> EmeterStatus:
93
+ """Return current energy readings."""
94
+ return EmeterStatus(self.data["get_realtime"])
95
+
96
+ @property
97
+ def emeter_today(self) -> float | None:
98
+ """Return today's energy consumption in kWh."""
99
+ raw_data = self.daily_data
100
+ today = datetime.now().day
101
+ data = self._convert_stat_data(raw_data, entry_key="day", key=today)
102
+ return data.get(today)
103
+
104
+ @property
105
+ def emeter_this_month(self) -> float | None:
106
+ """Return this month's energy consumption in kWh."""
107
+ raw_data = self.monthly_data
108
+ current_month = datetime.now().month
109
+ data = self._convert_stat_data(raw_data, entry_key="month", key=current_month)
110
+ return data.get(current_month)
111
+
112
+ @property
113
+ def current_consumption(self) -> float | None:
114
+ """Get the current power consumption in Watt."""
115
+ return self.realtime.power
116
+
117
+ @property
118
+ def emeter_total(self) -> float | None:
119
+ """Return total consumption since last reboot in kWh."""
120
+ return self.realtime.total
121
+
122
+ @property
123
+ def current(self) -> float | None:
124
+ """Return the current in A."""
125
+ return self.realtime.current
126
+
127
+ @property
128
+ def voltage(self) -> float | None:
129
+ """Get the current voltage in V."""
130
+ return self.realtime.voltage
131
+
132
+ async def erase_stats(self):
133
+ """Erase all stats.
134
+
135
+ Uses different query than usage meter.
136
+ """
137
+ return await self.call("erase_emeter_stat")
138
+
139
+ async def get_realtime(self):
140
+ """Return real-time statistics."""
141
+ return await self.call("get_realtime")
142
+
143
+ async def get_daystat(self, *, year=None, month=None, kwh=True) -> dict:
144
+ """Return daily stats for the given year & month.
145
+
146
+ The return value is a dictionary of {day: energy, ...}.
147
+ """
148
+ data = await self.get_raw_daystat(year=year, month=month)
149
+ data = self._convert_stat_data(data["day_list"], entry_key="day", kwh=kwh)
150
+ return data
151
+
152
+ async def get_monthstat(self, *, year=None, kwh=True) -> dict:
153
+ """Return monthly stats for the given year.
154
+
155
+ The return value is a dictionary of {month: energy, ...}.
156
+ """
157
+ data = await self.get_raw_monthstat(year=year)
158
+ data = self._convert_stat_data(data["month_list"], entry_key="month", kwh=kwh)
159
+ return data
160
+
161
+ def _convert_stat_data(
162
+ self,
163
+ data: list[dict[str, int | float]],
164
+ entry_key: str,
165
+ kwh: bool = True,
166
+ key: int | None = None,
167
+ ) -> dict[int | float, int | float]:
168
+ """Return emeter information keyed with the day/month.
169
+
170
+ The incoming data is a list of dictionaries::
171
+
172
+ [{'year': int,
173
+ 'month': int,
174
+ 'day': int, <-- for get_daystat not get_monthstat
175
+ 'energy_wh': int, <-- for emeter in some versions (wh)
176
+ 'energy': float <-- for emeter in other versions (kwh)
177
+ }, ...]
178
+
179
+ :return: a dictionary keyed by day or month with energy as the value.
180
+ """
181
+ if not data:
182
+ return {}
183
+
184
+ scale: float = 1
185
+
186
+ if "energy_wh" in data[0]:
187
+ value_key = "energy_wh"
188
+ if kwh:
189
+ scale = 1 / 1000
190
+ else:
191
+ value_key = "energy"
192
+ if not kwh:
193
+ scale = 1000
194
+
195
+ if key is None:
196
+ # Return all the data
197
+ return {entry[entry_key]: entry[value_key] * scale for entry in data}
198
+
199
+ # In this case we want a specific key in the data
200
+ # i.e. the current day or month.
201
+ #
202
+ # Since we usually want the data at the end of the list so we can
203
+ # optimize the search by starting at the end and avoid scaling
204
+ # the data we don't need.
205
+ #
206
+ for entry in reversed(data):
207
+ if entry[entry_key] == key:
208
+ return {entry[entry_key]: entry[value_key] * scale}
209
+
210
+ return {}