python-kasa 0.6.2.1__py3-none-any.whl → 0.7.0.dev1__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 +90 -27
  2. kasa/aestransport.py +51 -34
  3. kasa/cli.py +326 -130
  4. kasa/device.py +414 -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 +138 -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} +103 -147
  22. kasa/{smartdevice.py → iot/iotdevice.py} +176 -286
  23. kasa/{smartdimmer.py → iot/iotdimmer.py} +45 -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 +263 -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 +166 -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 +116 -86
  120. kasa/tests/test_childdevice.py +19 -7
  121. kasa/tests/test_cli.py +453 -99
  122. kasa/tests/test_common_modules.py +242 -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 +42 -33
  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.dev1.dist-info}/METADATA +45 -143
  144. python_kasa-0.7.0.dev1.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.dev1.dist-info}/LICENSE +0 -0
  163. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/WHEEL +0 -0
  164. {python_kasa-0.6.2.1.dist-info → python_kasa-0.7.0.dev1.dist-info}/entry_points.txt +0 -0
@@ -1,12 +1,17 @@
1
1
  """Module for dimmers (currently only HS220)."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  from enum import Enum
3
- from typing import Any, Dict, Optional
6
+ from typing import Any
4
7
 
5
- from kasa.deviceconfig import DeviceConfig
6
- from kasa.modules import AmbientLight, Motion
7
- from kasa.protocol import BaseProtocol
8
- from kasa.smartdevice import DeviceType, SmartDeviceException, requires_update
9
- from kasa.smartplug import SmartPlug
8
+ from ..device_type import DeviceType
9
+ from ..deviceconfig import DeviceConfig
10
+ from ..module import Module
11
+ from ..protocol import BaseProtocol
12
+ from .iotdevice import KasaException, requires_update
13
+ from .iotplug import IotPlug
14
+ from .modules import AmbientLight, Light, Motion
10
15
 
11
16
 
12
17
  class ButtonAction(Enum):
@@ -32,7 +37,7 @@ class FadeType(Enum):
32
37
  FadeOff = "fade_off"
33
38
 
34
39
 
35
- class SmartDimmer(SmartPlug):
40
+ class IotDimmer(IotPlug):
36
41
  r"""Representation of a TP-Link Smart Dimmer.
37
42
 
38
43
  Dimmers work similarly to plugs, but provide also support for
@@ -45,12 +50,12 @@ class SmartDimmer(SmartPlug):
45
50
  which will not change the cached values,
46
51
  but you must await :func:`update()` separately.
47
52
 
48
- Errors reported by the device are raised as :class:`SmartDeviceException`\s,
53
+ Errors reported by the device are raised as :class:`KasaException`\s,
49
54
  and should be handled by the user of the library.
50
55
 
51
56
  Examples:
52
57
  >>> import asyncio
53
- >>> dimmer = SmartDimmer("192.168.1.105")
58
+ >>> dimmer = IotDimmer("192.168.1.105")
54
59
  >>> asyncio.run(dimmer.turn_on())
55
60
  >>> dimmer.brightness
56
61
  25
@@ -69,40 +74,43 @@ class SmartDimmer(SmartPlug):
69
74
  self,
70
75
  host: str,
71
76
  *,
72
- config: Optional[DeviceConfig] = None,
73
- protocol: Optional[BaseProtocol] = None,
77
+ config: DeviceConfig | None = None,
78
+ protocol: BaseProtocol | None = None,
74
79
  ) -> None:
75
80
  super().__init__(host=host, config=config, protocol=protocol)
76
81
  self._device_type = DeviceType.Dimmer
82
+
83
+ async def _initialize_modules(self):
84
+ """Initialize modules."""
85
+ await super()._initialize_modules()
77
86
  # TODO: need to be verified if it's okay to call these on HS220 w/o these
78
87
  # TODO: need to be figured out what's the best approach to detect support
79
- self.add_module("motion", Motion(self, "smartlife.iot.PIR"))
80
- self.add_module("ambient", AmbientLight(self, "smartlife.iot.LAS"))
88
+ self.add_module(Module.IotMotion, Motion(self, "smartlife.iot.PIR"))
89
+ self.add_module(Module.IotAmbientLight, AmbientLight(self, "smartlife.iot.LAS"))
90
+ self.add_module(Module.Light, Light(self, "light"))
81
91
 
82
92
  @property # type: ignore
83
93
  @requires_update
84
- def brightness(self) -> int:
94
+ def _brightness(self) -> int:
85
95
  """Return current brightness on dimmers.
86
96
 
87
97
  Will return a range between 0 - 100.
88
98
  """
89
- if not self.is_dimmable:
90
- raise SmartDeviceException("Device is not dimmable.")
99
+ if not self._is_dimmable:
100
+ raise KasaException("Device is not dimmable.")
91
101
 
92
102
  sys_info = self.sys_info
93
103
  return int(sys_info["brightness"])
94
104
 
95
105
  @requires_update
96
- async def set_brightness(
97
- self, brightness: int, *, transition: Optional[int] = None
98
- ):
106
+ async def _set_brightness(self, brightness: int, *, transition: int | None = None):
99
107
  """Set the new dimmer brightness level in percentage.
100
108
 
101
109
  :param int transition: transition duration in milliseconds.
102
110
  Using a transition will cause the dimmer to turn on.
103
111
  """
104
- if not self.is_dimmable:
105
- raise SmartDeviceException("Device is not dimmable.")
112
+ if not self._is_dimmable:
113
+ raise KasaException("Device is not dimmable.")
106
114
 
107
115
  if not isinstance(brightness, int):
108
116
  raise ValueError(
@@ -124,7 +132,7 @@ class SmartDimmer(SmartPlug):
124
132
  self.DIMMER_SERVICE, "set_brightness", {"brightness": brightness}
125
133
  )
126
134
 
127
- async def turn_off(self, *, transition: Optional[int] = None, **kwargs):
135
+ async def turn_off(self, *, transition: int | None = None, **kwargs):
128
136
  """Turn the bulb off.
129
137
 
130
138
  :param int transition: transition duration in milliseconds.
@@ -135,7 +143,7 @@ class SmartDimmer(SmartPlug):
135
143
  return await super().turn_off()
136
144
 
137
145
  @requires_update
138
- async def turn_on(self, *, transition: Optional[int] = None, **kwargs):
146
+ async def turn_on(self, *, transition: int | None = None, **kwargs):
139
147
  """Turn the bulb on.
140
148
 
141
149
  :param int transition: transition duration in milliseconds.
@@ -160,6 +168,9 @@ class SmartDimmer(SmartPlug):
160
168
  if not 0 <= brightness <= 100:
161
169
  raise ValueError("Brightness value %s is not valid." % brightness)
162
170
 
171
+ # If zero set to 1 millisecond
172
+ if transition == 0:
173
+ transition = 1
163
174
  if not isinstance(transition, int):
164
175
  raise ValueError(
165
176
  "Transition must be integer, " "not of %s.", type(transition)
@@ -183,7 +194,7 @@ class SmartDimmer(SmartPlug):
183
194
 
184
195
  @requires_update
185
196
  async def set_button_action(
186
- self, action_type: ActionType, action: ButtonAction, index: Optional[int] = None
197
+ self, action_type: ActionType, action: ButtonAction, index: int | None = None
187
198
  ):
188
199
  """Set action to perform on button click/hold.
189
200
 
@@ -194,7 +205,7 @@ class SmartDimmer(SmartPlug):
194
205
  """
195
206
  action_type_setter = f"set_{action_type}"
196
207
 
197
- payload: Dict[str, Any] = {"mode": str(action)}
208
+ payload: dict[str, Any] = {"mode": str(action)}
198
209
  if index is not None:
199
210
  payload["index"] = index
200
211
 
@@ -210,16 +221,17 @@ class SmartDimmer(SmartPlug):
210
221
 
211
222
  @property # type: ignore
212
223
  @requires_update
213
- def is_dimmable(self) -> bool:
224
+ def _is_dimmable(self) -> bool:
214
225
  """Whether the switch supports brightness changes."""
215
226
  sys_info = self.sys_info
216
227
  return "brightness" in sys_info
217
228
 
218
- @property # type: ignore
219
- @requires_update
220
- def state_information(self) -> Dict[str, Any]:
221
- """Return switch-specific state information."""
222
- info = super().state_information
223
- info["Brightness"] = self.brightness
229
+ @property
230
+ def _is_variable_color_temp(self) -> bool:
231
+ """Whether the device supports variable color temp."""
232
+ return False
224
233
 
225
- return info
234
+ @property
235
+ def _is_color(self) -> bool:
236
+ """Whether the device supports color."""
237
+ return False
@@ -0,0 +1,71 @@
1
+ """Module for light strips (KL430)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ..device_type import DeviceType
6
+ from ..deviceconfig import DeviceConfig
7
+ from ..module import Module
8
+ from ..protocol import BaseProtocol
9
+ from .iotbulb import IotBulb
10
+ from .iotdevice import requires_update
11
+ from .modules.lighteffect import LightEffect
12
+
13
+
14
+ class IotLightStrip(IotBulb):
15
+ """Representation of a TP-Link Smart light strip.
16
+
17
+ Light strips work similarly to bulbs, but use a different service for controlling,
18
+ and expose some extra information (such as length and active effect).
19
+ This class extends :class:`SmartBulb` interface.
20
+
21
+ Examples:
22
+ >>> import asyncio
23
+ >>> strip = IotLightStrip("127.0.0.1")
24
+ >>> asyncio.run(strip.update())
25
+ >>> print(strip.alias)
26
+ KL430 pantry lightstrip
27
+
28
+ Getting the length of the strip:
29
+
30
+ >>> strip.length
31
+ 16
32
+
33
+ Currently active effect:
34
+
35
+ >>> strip.effect
36
+ {'brightness': 50, 'custom': 0, 'enable': 0, 'id': '', 'name': ''}
37
+
38
+ .. note::
39
+ The device supports some features that are not currently implemented,
40
+ feel free to find out how to control them and create a PR!
41
+
42
+
43
+ See :class:`SmartBulb` for more examples.
44
+ """
45
+
46
+ LIGHT_SERVICE = "smartlife.iot.lightStrip"
47
+ SET_LIGHT_METHOD = "set_light_state"
48
+
49
+ def __init__(
50
+ self,
51
+ host: str,
52
+ *,
53
+ config: DeviceConfig | None = None,
54
+ protocol: BaseProtocol | None = None,
55
+ ) -> None:
56
+ super().__init__(host=host, config=config, protocol=protocol)
57
+ self._device_type = DeviceType.LightStrip
58
+
59
+ async def _initialize_modules(self):
60
+ """Initialize modules not added in init."""
61
+ await super()._initialize_modules()
62
+ self.add_module(
63
+ Module.LightEffect,
64
+ LightEffect(self, "smartlife.iot.lighting_effect"),
65
+ )
66
+
67
+ @property # type: ignore
68
+ @requires_update
69
+ def length(self) -> int:
70
+ """Return length of the strip."""
71
+ return self.sys_info["length"]
@@ -1,19 +1,15 @@
1
- """Base class for all module implementations."""
1
+ """Base class for IOT module implementations."""
2
+
2
3
  import collections
3
4
  import logging
4
- from abc import ABC, abstractmethod
5
- from typing import TYPE_CHECKING
6
-
7
- from ..exceptions import SmartDeviceException
8
-
9
- if TYPE_CHECKING:
10
- from kasa import SmartDevice
11
5
 
6
+ from ..exceptions import KasaException
7
+ from ..module import Module
12
8
 
13
9
  _LOGGER = logging.getLogger(__name__)
14
10
 
15
11
 
16
- # TODO: This is used for query construcing
12
+ # TODO: This is used for query constructing, check for a better place
17
13
  def merge(d, u):
18
14
  """Update dict recursively."""
19
15
  for k, v in u.items():
@@ -24,24 +20,16 @@ def merge(d, u):
24
20
  return d
25
21
 
26
22
 
27
- class Module(ABC):
28
- """Base class implemention for all modules.
23
+ class IotModule(Module):
24
+ """Base class implemention for all IOT modules."""
29
25
 
30
- The base classes should implement `query` to return the query they want to be
31
- executed during the regular update cycle.
32
- """
33
-
34
- def __init__(self, device: "SmartDevice", module: str):
35
- self._device: "SmartDevice" = device
36
- self._module = module
37
-
38
- @abstractmethod
39
- def query(self):
40
- """Query to execute during the update cycle.
26
+ def call(self, method, params=None):
27
+ """Call the given method with the given parameters."""
28
+ return self._device._query_helper(self._module, method, params)
41
29
 
42
- The inheriting modules implement this to include their wanted
43
- queries to the query that gets executed when Device.update() gets called.
44
- """
30
+ def query_for_command(self, query, params=None):
31
+ """Create a request object for the given parameters."""
32
+ return self._device._create_request(self._module, query, params)
45
33
 
46
34
  @property
47
35
  def estimated_query_response_size(self):
@@ -55,13 +43,19 @@ class Module(ABC):
55
43
  @property
56
44
  def data(self):
57
45
  """Return the module specific raw data from the last update."""
58
- if self._module not in self._device._last_update:
59
- raise SmartDeviceException(
46
+ dev = self._device
47
+ q = self.query()
48
+
49
+ if not q:
50
+ return dev.sys_info
51
+
52
+ if self._module not in dev._last_update:
53
+ raise KasaException(
60
54
  f"You need to call update() prior accessing module data"
61
55
  f" for '{self._module}'"
62
56
  )
63
57
 
64
- return self._device._last_update[self._module]
58
+ return dev._last_update[self._module]
65
59
 
66
60
  @property
67
61
  def is_supported(self) -> bool:
@@ -71,17 +65,3 @@ class Module(ABC):
71
65
  return True
72
66
 
73
67
  return "err_code" not in self.data
74
-
75
- def call(self, method, params=None):
76
- """Call the given method with the given parameters."""
77
- return self._device._query_helper(self._module, method, params)
78
-
79
- def query_for_command(self, query, params=None):
80
- """Create a request object for the given parameters."""
81
- return self._device._create_request(self._module, query, params)
82
-
83
- def __repr__(self) -> str:
84
- return (
85
- f"<Module {self.__class__.__name__} ({self._module})"
86
- f" for {self._device.host}>"
87
- )
kasa/iot/iotplug.py ADDED
@@ -0,0 +1,94 @@
1
+ """Module for smart plugs (HS100, HS110, ..)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+
7
+ from ..device_type import DeviceType
8
+ from ..deviceconfig import DeviceConfig
9
+ from ..module import Module
10
+ from ..protocol import BaseProtocol
11
+ from .iotdevice import IotDevice, requires_update
12
+ from .modules import Antitheft, Cloud, Led, Schedule, Time, Usage
13
+
14
+ _LOGGER = logging.getLogger(__name__)
15
+
16
+
17
+ class IotPlug(IotDevice):
18
+ r"""Representation of a TP-Link Smart Plug.
19
+
20
+ To initialize, you have to await :func:`update()` at least once.
21
+ This will allow accessing the properties using the exposed properties.
22
+
23
+ All changes to the device are done using awaitable methods,
24
+ which will not change the cached values,
25
+ but you must await :func:`update()` separately.
26
+
27
+ Errors reported by the device are raised as :class:`KasaException`\s,
28
+ and should be handled by the user of the library.
29
+
30
+ Examples:
31
+ >>> import asyncio
32
+ >>> plug = IotPlug("127.0.0.1")
33
+ >>> asyncio.run(plug.update())
34
+ >>> plug.alias
35
+ Kitchen
36
+
37
+ Setting the LED state:
38
+
39
+ >>> asyncio.run(plug.set_led(True))
40
+ >>> asyncio.run(plug.update())
41
+ >>> plug.led
42
+ True
43
+
44
+ For more examples, see the :class:`Device` class.
45
+ """
46
+
47
+ def __init__(
48
+ self,
49
+ host: str,
50
+ *,
51
+ config: DeviceConfig | None = None,
52
+ protocol: BaseProtocol | None = None,
53
+ ) -> None:
54
+ super().__init__(host=host, config=config, protocol=protocol)
55
+ self._device_type = DeviceType.Plug
56
+
57
+ async def _initialize_modules(self):
58
+ """Initialize modules."""
59
+ await super()._initialize_modules()
60
+ self.add_module(Module.IotSchedule, Schedule(self, "schedule"))
61
+ self.add_module(Module.IotUsage, Usage(self, "schedule"))
62
+ self.add_module(Module.IotAntitheft, Antitheft(self, "anti_theft"))
63
+ self.add_module(Module.IotTime, Time(self, "time"))
64
+ self.add_module(Module.IotCloud, Cloud(self, "cnCloud"))
65
+ self.add_module(Module.Led, Led(self, "system"))
66
+
67
+ @property # type: ignore
68
+ @requires_update
69
+ def is_on(self) -> bool:
70
+ """Return whether device is on."""
71
+ sys_info = self.sys_info
72
+ return bool(sys_info["relay_state"])
73
+
74
+ async def turn_on(self, **kwargs):
75
+ """Turn the switch on."""
76
+ return await self._query_helper("system", "set_relay_state", {"state": 1})
77
+
78
+ async def turn_off(self, **kwargs):
79
+ """Turn the switch off."""
80
+ return await self._query_helper("system", "set_relay_state", {"state": 0})
81
+
82
+
83
+ class IotWallSwitch(IotPlug):
84
+ """Representation of a TP-Link Smart Wall Switch."""
85
+
86
+ def __init__(
87
+ self,
88
+ host: str,
89
+ *,
90
+ config: DeviceConfig | None = None,
91
+ protocol: BaseProtocol | None = None,
92
+ ) -> None:
93
+ super().__init__(host=host, config=config, protocol=protocol)
94
+ self._device_type = DeviceType.WallSwitch