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
@@ -1,11 +1,13 @@
1
1
  """Implementation of the usage interface."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  from datetime import datetime
3
- from typing import Dict
4
6
 
5
- from .module import Module, merge
7
+ from ..iotmodule import IotModule, merge
6
8
 
7
9
 
8
- class Usage(Module):
10
+ class Usage(IotModule):
9
11
  """Baseclass for emeter/usage interfaces."""
10
12
 
11
13
  def query(self):
@@ -57,7 +59,7 @@ class Usage(Module):
57
59
  return entry["time"]
58
60
  return None
59
61
 
60
- async def get_raw_daystat(self, *, year=None, month=None) -> Dict:
62
+ async def get_raw_daystat(self, *, year=None, month=None) -> dict:
61
63
  """Return raw daily stats for the given year & month."""
62
64
  if year is None:
63
65
  year = datetime.now().year
@@ -66,14 +68,14 @@ class Usage(Module):
66
68
 
67
69
  return await self.call("get_daystat", {"year": year, "month": month})
68
70
 
69
- async def get_raw_monthstat(self, *, year=None) -> Dict:
71
+ async def get_raw_monthstat(self, *, year=None) -> dict:
70
72
  """Return raw monthly stats for the given year."""
71
73
  if year is None:
72
74
  year = datetime.now().year
73
75
 
74
76
  return await self.call("get_monthstat", {"year": year})
75
77
 
76
- async def get_daystat(self, *, year=None, month=None) -> Dict:
78
+ async def get_daystat(self, *, year=None, month=None) -> dict:
77
79
  """Return daily stats for the given year & month.
78
80
 
79
81
  The return value is a dictionary of {day: time, ...}.
@@ -82,7 +84,7 @@ class Usage(Module):
82
84
  data = self._convert_stat_data(data["day_list"], entry_key="day")
83
85
  return data
84
86
 
85
- async def get_monthstat(self, *, year=None) -> Dict:
87
+ async def get_monthstat(self, *, year=None) -> dict:
86
88
  """Return monthly stats for the given year.
87
89
 
88
90
  The return value is a dictionary of {month: time, ...}.
@@ -95,7 +97,7 @@ class Usage(Module):
95
97
  """Erase all stats."""
96
98
  return await self.call("erase_runtime_stat")
97
99
 
98
- def _convert_stat_data(self, data, entry_key) -> Dict:
100
+ def _convert_stat_data(self, data, entry_key) -> dict:
99
101
  """Return usage information keyed with the day/month.
100
102
 
101
103
  The incoming data is a list of dictionaries::
kasa/iotprotocol.py CHANGED
@@ -1,15 +1,17 @@
1
1
  """Module for the IOT legacy IOT KASA protocol."""
2
+
3
+ from __future__ import annotations
4
+
2
5
  import asyncio
3
6
  import logging
4
- from typing import Dict, Optional, Union
5
7
 
6
8
  from .deviceconfig import DeviceConfig
7
9
  from .exceptions import (
8
- AuthenticationException,
9
- ConnectionException,
10
- RetryableException,
11
- SmartDeviceException,
12
- TimeoutException,
10
+ AuthenticationError,
11
+ KasaException,
12
+ TimeoutError,
13
+ _ConnectionError,
14
+ _RetryableError,
13
15
  )
14
16
  from .json import dumps as json_dumps
15
17
  from .protocol import BaseProtocol, BaseTransport
@@ -33,7 +35,7 @@ class IotProtocol(BaseProtocol):
33
35
 
34
36
  self._query_lock = asyncio.Lock()
35
37
 
36
- async def query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
38
+ async def query(self, request: str | dict, retry_count: int = 3) -> dict:
37
39
  """Query the device retrying for retry_count on failure."""
38
40
  if isinstance(request, dict):
39
41
  request = json_dumps(request)
@@ -42,35 +44,35 @@ class IotProtocol(BaseProtocol):
42
44
  async with self._query_lock:
43
45
  return await self._query(request, retry_count)
44
46
 
45
- async def _query(self, request: str, retry_count: int = 3) -> Dict:
47
+ async def _query(self, request: str, retry_count: int = 3) -> dict:
46
48
  for retry in range(retry_count + 1):
47
49
  try:
48
50
  return await self._execute_query(request, retry)
49
- except ConnectionException as sdex:
51
+ except _ConnectionError as sdex:
50
52
  if retry >= retry_count:
51
53
  _LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
52
54
  raise sdex
53
55
  continue
54
- except AuthenticationException as auex:
56
+ except AuthenticationError as auex:
55
57
  await self._transport.reset()
56
58
  _LOGGER.debug(
57
59
  "Unable to authenticate with %s, not retrying", self._host
58
60
  )
59
61
  raise auex
60
- except RetryableException as ex:
62
+ except _RetryableError as ex:
61
63
  await self._transport.reset()
62
64
  if retry >= retry_count:
63
65
  _LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
64
66
  raise ex
65
67
  continue
66
- except TimeoutException as ex:
68
+ except TimeoutError as ex:
67
69
  await self._transport.reset()
68
70
  if retry >= retry_count:
69
71
  _LOGGER.debug("Giving up on %s after %s retries", self._host, retry)
70
72
  raise ex
71
73
  await asyncio.sleep(self.BACKOFF_SECONDS_AFTER_TIMEOUT)
72
74
  continue
73
- except SmartDeviceException as ex:
75
+ except KasaException as ex:
74
76
  await self._transport.reset()
75
77
  _LOGGER.debug(
76
78
  "Unable to query the device: %s, not retrying: %s",
@@ -80,9 +82,9 @@ class IotProtocol(BaseProtocol):
80
82
  raise ex
81
83
 
82
84
  # make mypy happy, this should never be reached..
83
- raise SmartDeviceException("Query reached somehow to unreachable")
85
+ raise KasaException("Query reached somehow to unreachable")
84
86
 
85
- async def _execute_query(self, request: str, retry_count: int) -> Dict:
87
+ async def _execute_query(self, request: str, retry_count: int) -> dict:
86
88
  return await self._transport.send(request)
87
89
 
88
90
  async def close(self) -> None:
@@ -93,15 +95,15 @@ class IotProtocol(BaseProtocol):
93
95
  class _deprecated_TPLinkSmartHomeProtocol(IotProtocol):
94
96
  def __init__(
95
97
  self,
96
- host: Optional[str] = None,
98
+ host: str | None = None,
97
99
  *,
98
- port: Optional[int] = None,
99
- timeout: Optional[int] = None,
100
- transport: Optional[BaseTransport] = None,
100
+ port: int | None = None,
101
+ timeout: int | None = None,
102
+ transport: BaseTransport | None = None,
101
103
  ) -> None:
102
104
  """Create a protocol object."""
103
105
  if not host and not transport:
104
- raise SmartDeviceException("host or transport must be supplied")
106
+ raise KasaException("host or transport must be supplied")
105
107
  if not transport:
106
108
  config = DeviceConfig(
107
109
  host=host, # type: ignore[arg-type]
kasa/klaptransport.py CHANGED
@@ -40,6 +40,8 @@ https://github.com/python-kasa/python-kasa/pull/117
40
40
 
41
41
  """
42
42
 
43
+ from __future__ import annotations
44
+
43
45
  import asyncio
44
46
  import base64
45
47
  import datetime
@@ -49,7 +51,7 @@ import secrets
49
51
  import struct
50
52
  import time
51
53
  from pprint import pformat as pf
52
- from typing import Any, Dict, Optional, Tuple, cast
54
+ from typing import Any, cast
53
55
 
54
56
  from cryptography.hazmat.primitives import padding
55
57
  from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
@@ -57,7 +59,7 @@ from yarl import URL
57
59
 
58
60
  from .credentials import Credentials
59
61
  from .deviceconfig import DeviceConfig
60
- from .exceptions import AuthenticationException, SmartDeviceException
62
+ from .exceptions import AuthenticationError, KasaException, _RetryableError
61
63
  from .httpclient import HttpClient
62
64
  from .json import loads as json_loads
63
65
  from .protocol import DEFAULT_CREDENTIALS, BaseTransport, get_default_credentials, md5
@@ -99,7 +101,7 @@ class KlapTransport(BaseTransport):
99
101
  super().__init__(config=config)
100
102
 
101
103
  self._http_client = HttpClient(config)
102
- self._local_seed: Optional[bytes] = None
104
+ self._local_seed: bytes | None = None
103
105
  if (
104
106
  not self._credentials or self._credentials.username is None
105
107
  ) and not self._credentials_hash:
@@ -109,19 +111,19 @@ class KlapTransport(BaseTransport):
109
111
  self._local_auth_owner = self.generate_owner_hash(self._credentials).hex()
110
112
  else:
111
113
  self._local_auth_hash = base64.b64decode(self._credentials_hash.encode()) # type: ignore[union-attr]
112
- self._default_credentials_auth_hash: Dict[str, bytes] = {}
114
+ self._default_credentials_auth_hash: dict[str, bytes] = {}
113
115
  self._blank_auth_hash = None
114
116
  self._handshake_lock = asyncio.Lock()
115
117
  self._query_lock = asyncio.Lock()
116
118
  self._handshake_done = False
117
119
 
118
- self._encryption_session: Optional[KlapEncryptionSession] = None
119
- self._session_expire_at: Optional[float] = None
120
+ self._encryption_session: KlapEncryptionSession | None = None
121
+ self._session_expire_at: float | None = None
120
122
 
121
- self._session_cookie: Optional[Dict[str, Any]] = None
123
+ self._session_cookie: dict[str, Any] | None = None
122
124
 
123
125
  _LOGGER.debug("Created KLAP transport for %s", self._host)
124
- self._app_url = URL(f"http://{self._host}/app")
126
+ self._app_url = URL(f"http://{self._host}:{self._port}/app")
125
127
  self._request_url = self._app_url / "request"
126
128
 
127
129
  @property
@@ -134,7 +136,7 @@ class KlapTransport(BaseTransport):
134
136
  """The hashed credentials used by the transport."""
135
137
  return base64.b64encode(self._local_auth_hash).decode()
136
138
 
137
- async def perform_handshake1(self) -> Tuple[bytes, bytes, bytes]:
139
+ async def perform_handshake1(self) -> tuple[bytes, bytes, bytes]:
138
140
  """Perform handshake1."""
139
141
  local_seed: bytes = secrets.token_bytes(16)
140
142
 
@@ -159,7 +161,7 @@ class KlapTransport(BaseTransport):
159
161
  )
160
162
 
161
163
  if response_status != 200:
162
- raise AuthenticationException(
164
+ raise KasaException(
163
165
  f"Device {self._host} responded with {response_status} to handshake1"
164
166
  )
165
167
 
@@ -167,6 +169,12 @@ class KlapTransport(BaseTransport):
167
169
  remote_seed: bytes = response_data[0:16]
168
170
  server_hash = response_data[16:]
169
171
 
172
+ if len(server_hash) != 32:
173
+ raise KasaException(
174
+ f"Device {self._host} responded with unexpected klap response "
175
+ + f"{response_data!r} to handshake1"
176
+ )
177
+
170
178
  if _LOGGER.isEnabledFor(logging.DEBUG):
171
179
  _LOGGER.debug(
172
180
  "Handshake1 success at %s. Host is %s, "
@@ -230,11 +238,11 @@ class KlapTransport(BaseTransport):
230
238
 
231
239
  msg = f"Server response doesn't match our challenge on ip {self._host}"
232
240
  _LOGGER.debug(msg)
233
- raise AuthenticationException(msg)
241
+ raise AuthenticationError(msg)
234
242
 
235
243
  async def perform_handshake2(
236
244
  self, local_seed, remote_seed, auth_hash
237
- ) -> "KlapEncryptionSession":
245
+ ) -> KlapEncryptionSession:
238
246
  """Perform handshake2."""
239
247
  # Handshake 2 has the following payload:
240
248
  # sha256(serverBytes | authenticator)
@@ -260,7 +268,9 @@ class KlapTransport(BaseTransport):
260
268
  )
261
269
 
262
270
  if response_status != 200:
263
- raise AuthenticationException(
271
+ # This shouldn't be caused by incorrect
272
+ # credentials so don't raise AuthenticationError
273
+ raise KasaException(
264
274
  f"Device {self._host} responded with {response_status} to handshake2"
265
275
  )
266
276
 
@@ -329,12 +339,12 @@ class KlapTransport(BaseTransport):
329
339
  # If we failed with a security error, force a new handshake next time.
330
340
  if response_status == 403:
331
341
  self._handshake_done = False
332
- raise AuthenticationException(
342
+ raise _RetryableError(
333
343
  f"Got a security error from {self._host} after handshake "
334
344
  + "completed"
335
345
  )
336
346
  else:
337
- raise SmartDeviceException(
347
+ raise KasaException(
338
348
  f"Device {self._host} responded with {response_status} to"
339
349
  + f"request with seq {seq}"
340
350
  )
kasa/module.py ADDED
@@ -0,0 +1,136 @@
1
+ """Base class for all module implementations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ from abc import ABC, abstractmethod
7
+ from typing import (
8
+ TYPE_CHECKING,
9
+ Final,
10
+ TypeVar,
11
+ )
12
+
13
+ from .exceptions import KasaException
14
+ from .feature import Feature
15
+ from .modulemapping import ModuleName
16
+
17
+ if TYPE_CHECKING:
18
+ from . import interfaces
19
+ from .device import Device
20
+ from .iot import modules as iot
21
+ from .smart import modules as smart
22
+
23
+ _LOGGER = logging.getLogger(__name__)
24
+
25
+ ModuleT = TypeVar("ModuleT", bound="Module")
26
+
27
+
28
+ class Module(ABC):
29
+ """Base class implemention for all modules.
30
+
31
+ The base classes should implement `query` to return the query they want to be
32
+ executed during the regular update cycle.
33
+ """
34
+
35
+ # Common Modules
36
+ LightEffect: Final[ModuleName[interfaces.LightEffect]] = ModuleName("LightEffect")
37
+ Led: Final[ModuleName[interfaces.Led]] = ModuleName("Led")
38
+ Light: Final[ModuleName[interfaces.Light]] = ModuleName("Light")
39
+ LightPreset: Final[ModuleName[interfaces.LightPreset]] = ModuleName("LightPreset")
40
+
41
+ # IOT only Modules
42
+ IotAmbientLight: Final[ModuleName[iot.AmbientLight]] = ModuleName("ambient")
43
+ IotAntitheft: Final[ModuleName[iot.Antitheft]] = ModuleName("anti_theft")
44
+ IotCountdown: Final[ModuleName[iot.Countdown]] = ModuleName("countdown")
45
+ IotEmeter: Final[ModuleName[iot.Emeter]] = ModuleName("emeter")
46
+ IotMotion: Final[ModuleName[iot.Motion]] = ModuleName("motion")
47
+ IotSchedule: Final[ModuleName[iot.Schedule]] = ModuleName("schedule")
48
+ IotUsage: Final[ModuleName[iot.Usage]] = ModuleName("usage")
49
+ IotCloud: Final[ModuleName[iot.Cloud]] = ModuleName("cloud")
50
+ IotTime: Final[ModuleName[iot.Time]] = ModuleName("time")
51
+
52
+ # SMART only Modules
53
+ Alarm: Final[ModuleName[smart.Alarm]] = ModuleName("Alarm")
54
+ AutoOff: Final[ModuleName[smart.AutoOff]] = ModuleName("AutoOff")
55
+ BatterySensor: Final[ModuleName[smart.BatterySensor]] = ModuleName("BatterySensor")
56
+ Brightness: Final[ModuleName[smart.Brightness]] = ModuleName("Brightness")
57
+ ChildDevice: Final[ModuleName[smart.ChildDevice]] = ModuleName("ChildDevice")
58
+ Cloud: Final[ModuleName[smart.Cloud]] = ModuleName("Cloud")
59
+ Color: Final[ModuleName[smart.Color]] = ModuleName("Color")
60
+ ColorTemperature: Final[ModuleName[smart.ColorTemperature]] = ModuleName(
61
+ "ColorTemperature"
62
+ )
63
+ ContactSensor: Final[ModuleName[smart.ContactSensor]] = ModuleName("ContactSensor")
64
+ DeviceModule: Final[ModuleName[smart.DeviceModule]] = ModuleName("DeviceModule")
65
+ Energy: Final[ModuleName[smart.Energy]] = ModuleName("Energy")
66
+ Fan: Final[ModuleName[smart.Fan]] = ModuleName("Fan")
67
+ Firmware: Final[ModuleName[smart.Firmware]] = ModuleName("Firmware")
68
+ FrostProtection: Final[ModuleName[smart.FrostProtection]] = ModuleName(
69
+ "FrostProtection"
70
+ )
71
+ HumiditySensor: Final[ModuleName[smart.HumiditySensor]] = ModuleName(
72
+ "HumiditySensor"
73
+ )
74
+ LightTransition: Final[ModuleName[smart.LightTransition]] = ModuleName(
75
+ "LightTransition"
76
+ )
77
+ ReportMode: Final[ModuleName[smart.ReportMode]] = ModuleName("ReportMode")
78
+ TemperatureSensor: Final[ModuleName[smart.TemperatureSensor]] = ModuleName(
79
+ "TemperatureSensor"
80
+ )
81
+ TemperatureControl: Final[ModuleName[smart.TemperatureControl]] = ModuleName(
82
+ "TemperatureControl"
83
+ )
84
+ Time: Final[ModuleName[smart.Time]] = ModuleName("Time")
85
+ WaterleakSensor: Final[ModuleName[smart.WaterleakSensor]] = ModuleName(
86
+ "WaterleakSensor"
87
+ )
88
+
89
+ def __init__(self, device: Device, module: str):
90
+ self._device = device
91
+ self._module = module
92
+ self._module_features: dict[str, Feature] = {}
93
+
94
+ @abstractmethod
95
+ def query(self):
96
+ """Query to execute during the update cycle.
97
+
98
+ The inheriting modules implement this to include their wanted
99
+ queries to the query that gets executed when Device.update() gets called.
100
+ """
101
+
102
+ @property
103
+ @abstractmethod
104
+ def data(self):
105
+ """Return the module specific raw data from the last update."""
106
+
107
+ def _initialize_features(self): # noqa: B027
108
+ """Initialize features after the initial update.
109
+
110
+ This can be implemented if features depend on module query responses.
111
+ It will only be called once per module and will always be called
112
+ after *_post_update_hook* has been called for every device module and its
113
+ children's modules.
114
+ """
115
+
116
+ def _post_update_hook(self): # noqa: B027
117
+ """Perform actions after a device update.
118
+
119
+ This can be implemented if a module needs to perform actions each time
120
+ the device has updated like generating collections for property access.
121
+ It will be called after every update and will be called prior to
122
+ *_initialize_features* on the first update.
123
+ """
124
+
125
+ def _add_feature(self, feature: Feature):
126
+ """Add module feature."""
127
+ id_ = feature.id
128
+ if id_ in self._module_features:
129
+ raise KasaException("Duplicate id detected %s" % id_)
130
+ self._module_features[id_] = feature
131
+
132
+ def __repr__(self) -> str:
133
+ return (
134
+ f"<Module {self.__class__.__name__} ({self._module})"
135
+ f" for {self._device.host}>"
136
+ )
kasa/modulemapping.py ADDED
@@ -0,0 +1,25 @@
1
+ """Module for Implementation for ModuleMapping and ModuleName types.
2
+
3
+ Custom dict for getting typed modules from the module dict.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from typing import TYPE_CHECKING, Generic, TypeVar
9
+
10
+ if TYPE_CHECKING:
11
+ from .module import Module
12
+
13
+ _ModuleT = TypeVar("_ModuleT", bound="Module")
14
+
15
+
16
+ class ModuleName(str, Generic[_ModuleT]):
17
+ """Generic Module name type.
18
+
19
+ At runtime this is a generic subclass of str.
20
+ """
21
+
22
+ __slots__ = ()
23
+
24
+
25
+ ModuleMapping = dict
kasa/modulemapping.pyi ADDED
@@ -0,0 +1,96 @@
1
+ """Typing stub file for ModuleMapping."""
2
+
3
+ from abc import ABCMeta
4
+ from collections.abc import Mapping
5
+ from typing import Generic, TypeVar, overload
6
+
7
+ from .module import Module
8
+
9
+ __all__ = [
10
+ "ModuleMapping",
11
+ "ModuleName",
12
+ ]
13
+
14
+ _ModuleT = TypeVar("_ModuleT", bound=Module, covariant=True)
15
+ _ModuleBaseT = TypeVar("_ModuleBaseT", bound=Module, covariant=True)
16
+
17
+ class ModuleName(Generic[_ModuleT]):
18
+ """Class for typed Module names. At runtime delegated to str."""
19
+
20
+ def __init__(self, value: str, /) -> None: ...
21
+ def __len__(self) -> int: ...
22
+ def __hash__(self) -> int: ...
23
+ def __eq__(self, other: object) -> bool: ...
24
+ def __getitem__(self, index: int) -> str: ...
25
+
26
+ class ModuleMapping(
27
+ Mapping[ModuleName[_ModuleBaseT] | str, _ModuleBaseT], metaclass=ABCMeta
28
+ ):
29
+ """Custom dict type to provide better value type hints for Module key types."""
30
+
31
+ @overload
32
+ def __getitem__(self, key: ModuleName[_ModuleT], /) -> _ModuleT: ...
33
+ @overload
34
+ def __getitem__(self, key: str, /) -> _ModuleBaseT: ...
35
+ @overload
36
+ def __getitem__(
37
+ self, key: ModuleName[_ModuleT] | str, /
38
+ ) -> _ModuleT | _ModuleBaseT: ...
39
+ @overload # type: ignore[override]
40
+ def get(self, key: ModuleName[_ModuleT], /) -> _ModuleT | None: ...
41
+ @overload
42
+ def get(self, key: str, /) -> _ModuleBaseT | None: ...
43
+ @overload
44
+ def get(
45
+ self, key: ModuleName[_ModuleT] | str, /
46
+ ) -> _ModuleT | _ModuleBaseT | None: ...
47
+
48
+ def _test_module_mapping_typing() -> None:
49
+ """Test ModuleMapping overloads work as intended.
50
+
51
+ This is tested during the mypy run and needs to be in this file.
52
+ """
53
+ from typing import Any, NewType, cast
54
+
55
+ from typing_extensions import assert_type
56
+
57
+ from .iot.iotmodule import IotModule
58
+ from .module import Module
59
+ from .smart.smartmodule import SmartModule
60
+
61
+ NewCommonModule = NewType("NewCommonModule", Module)
62
+ NewIotModule = NewType("NewIotModule", IotModule)
63
+ NewSmartModule = NewType("NewSmartModule", SmartModule)
64
+ NotModule = NewType("NotModule", list)
65
+
66
+ NEW_COMMON_MODULE: ModuleName[NewCommonModule] = ModuleName("NewCommonModule")
67
+ NEW_IOT_MODULE: ModuleName[NewIotModule] = ModuleName("NewIotModule")
68
+ NEW_SMART_MODULE: ModuleName[NewSmartModule] = ModuleName("NewSmartModule")
69
+
70
+ # TODO Enable --warn-unused-ignores
71
+ NOT_MODULE: ModuleName[NotModule] = ModuleName("NotModule") # type: ignore[type-var] # noqa: F841
72
+ NOT_MODULE_2 = ModuleName[NotModule]("NotModule2") # type: ignore[type-var] # noqa: F841
73
+
74
+ device_modules: ModuleMapping[Module] = cast(ModuleMapping[Module], {})
75
+ assert_type(device_modules[NEW_COMMON_MODULE], NewCommonModule)
76
+ assert_type(device_modules[NEW_IOT_MODULE], NewIotModule)
77
+ assert_type(device_modules[NEW_SMART_MODULE], NewSmartModule)
78
+ assert_type(device_modules["foobar"], Module)
79
+ assert_type(device_modules[3], Any) # type: ignore[call-overload]
80
+
81
+ assert_type(device_modules.get(NEW_COMMON_MODULE), NewCommonModule | None)
82
+ assert_type(device_modules.get(NEW_IOT_MODULE), NewIotModule | None)
83
+ assert_type(device_modules.get(NEW_SMART_MODULE), NewSmartModule | None)
84
+ assert_type(device_modules.get(NEW_COMMON_MODULE, default=[1, 2]), Any) # type: ignore[call-overload]
85
+
86
+ iot_modules: ModuleMapping[IotModule] = cast(ModuleMapping[IotModule], {})
87
+ smart_modules: ModuleMapping[SmartModule] = cast(ModuleMapping[SmartModule], {})
88
+
89
+ assert_type(smart_modules["foobar"], SmartModule)
90
+ assert_type(iot_modules["foobar"], IotModule)
91
+
92
+ # Test for covariance
93
+ device_modules_2: ModuleMapping[Module] = iot_modules # noqa: F841
94
+ device_modules_3: ModuleMapping[Module] = smart_modules # noqa: F841
95
+ NEW_MODULE: ModuleName[Module] = NEW_SMART_MODULE # noqa: F841
96
+ NEW_MODULE_2: ModuleName[Module] = NEW_IOT_MODULE # noqa: F841
kasa/protocol.py CHANGED
@@ -9,13 +9,15 @@ https://github.com/softScheck/tplink-smartplug/
9
9
  which are licensed under the Apache License, Version 2.0
10
10
  http://www.apache.org/licenses/LICENSE-2.0
11
11
  """
12
+
13
+ from __future__ import annotations
14
+
12
15
  import base64
13
16
  import errno
14
17
  import hashlib
15
18
  import logging
16
19
  import struct
17
20
  from abc import ABC, abstractmethod
18
- from typing import Dict, Tuple, Union
19
21
 
20
22
  # When support for cpython older than 3.11 is dropped
21
23
  # async_timeout can be replaced with asyncio.timeout
@@ -61,7 +63,7 @@ class BaseTransport(ABC):
61
63
  """The hashed credentials used by the transport."""
62
64
 
63
65
  @abstractmethod
64
- async def send(self, request: str) -> Dict:
66
+ async def send(self, request: str) -> dict:
65
67
  """Send a message to the device and return a response."""
66
68
 
67
69
  @abstractmethod
@@ -94,7 +96,7 @@ class BaseProtocol(ABC):
94
96
  return self._transport._config
95
97
 
96
98
  @abstractmethod
97
- async def query(self, request: Union[str, Dict], retry_count: int = 3) -> Dict:
99
+ async def query(self, request: str | dict, retry_count: int = 3) -> dict:
98
100
  """Query the device for the protocol. Abstract method to be overriden."""
99
101
 
100
102
  @abstractmethod
@@ -102,7 +104,7 @@ class BaseProtocol(ABC):
102
104
  """Close the protocol. Abstract method to be overriden."""
103
105
 
104
106
 
105
- def get_default_credentials(tuple: Tuple[str, str]) -> Credentials:
107
+ def get_default_credentials(tuple: tuple[str, str]) -> Credentials:
106
108
  """Return decoded default credentials."""
107
109
  un = base64.b64decode(tuple[0].encode()).decode()
108
110
  pw = base64.b64decode(tuple[1].encode()).decode()
kasa/smart/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """Package for supporting tapo-branded and newer kasa devices."""
2
+
3
+ from .smartchilddevice import SmartChildDevice
4
+ from .smartdevice import SmartDevice
5
+
6
+ __all__ = ["SmartDevice", "SmartChildDevice"]