python-kasa 0.7.1__py3-none-any.whl → 0.7.3__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 (193) hide show
  1. kasa/aestransport.py +12 -4
  2. kasa/device_factory.py +5 -2
  3. kasa/deviceconfig.py +11 -2
  4. kasa/discover.py +1 -1
  5. kasa/emeterstatus.py +1 -1
  6. kasa/feature.py +3 -2
  7. kasa/iot/iotbulb.py +9 -3
  8. kasa/iot/iotdevice.py +3 -14
  9. kasa/iot/iotdimmer.py +8 -8
  10. kasa/iot/iotmodule.py +9 -8
  11. kasa/klaptransport.py +14 -14
  12. kasa/smart/modules/alarm.py +7 -5
  13. kasa/smart/modules/color.py +11 -5
  14. kasa/smart/modules/firmware.py +51 -24
  15. kasa/smart/modules/lighteffect.py +1 -1
  16. kasa/smart/smartmodule.py +1 -1
  17. kasa/smartprotocol.py +3 -2
  18. {python_kasa-0.7.1.dist-info → python_kasa-0.7.3.dist-info}/METADATA +30 -26
  19. python_kasa-0.7.3.dist-info/RECORD +104 -0
  20. {python_kasa-0.7.1.dist-info → python_kasa-0.7.3.dist-info}/WHEEL +1 -1
  21. python_kasa-0.7.3.dist-info/entry_points.txt +2 -0
  22. kasa/tests/__init__.py +0 -0
  23. kasa/tests/conftest.py +0 -107
  24. kasa/tests/device_fixtures.py +0 -473
  25. kasa/tests/discovery_fixtures.py +0 -256
  26. kasa/tests/fakeprotocol_iot.py +0 -459
  27. kasa/tests/fakeprotocol_smart.py +0 -409
  28. kasa/tests/fixtureinfo.py +0 -172
  29. kasa/tests/fixtures/EP10(US)_1.0_1.0.2.json +0 -32
  30. kasa/tests/fixtures/EP40(US)_1.0_1.0.2.json +0 -45
  31. kasa/tests/fixtures/ES20M(US)_1.0_1.0.8.json +0 -126
  32. kasa/tests/fixtures/HS100(UK)_1.0_1.2.6.json +0 -28
  33. kasa/tests/fixtures/HS100(UK)_4.1_1.1.0.json +0 -47
  34. kasa/tests/fixtures/HS100(US)_1.0_1.2.5.json +0 -44
  35. kasa/tests/fixtures/HS100(US)_2.0_1.5.6.json +0 -49
  36. kasa/tests/fixtures/HS103(US)_1.0_1.5.7.json +0 -52
  37. kasa/tests/fixtures/HS103(US)_2.1_1.1.2.json +0 -47
  38. kasa/tests/fixtures/HS103(US)_2.1_1.1.4.json +0 -31
  39. kasa/tests/fixtures/HS105(US)_1.0_1.5.6.json +0 -49
  40. kasa/tests/fixtures/HS107(US)_1.0_1.0.8.json +0 -59
  41. kasa/tests/fixtures/HS110(EU)_1.0_1.2.5.json +0 -37
  42. kasa/tests/fixtures/HS110(EU)_4.0_1.0.4.json +0 -40
  43. kasa/tests/fixtures/HS110(US)_1.0_1.2.6.json +0 -37
  44. kasa/tests/fixtures/HS200(US)_2.0_1.5.7.json +0 -49
  45. kasa/tests/fixtures/HS200(US)_5.0_1.0.2.json +0 -31
  46. kasa/tests/fixtures/HS210(US)_1.0_1.5.8.json +0 -50
  47. kasa/tests/fixtures/HS220(US)_1.0_1.5.7.json +0 -76
  48. kasa/tests/fixtures/HS220(US)_2.0_1.0.3.json +0 -64
  49. kasa/tests/fixtures/HS300(US)_1.0_1.0.10.json +0 -100
  50. kasa/tests/fixtures/HS300(US)_1.0_1.0.21.json +0 -89
  51. kasa/tests/fixtures/HS300(US)_2.0_1.0.12.json +0 -90
  52. kasa/tests/fixtures/HS300(US)_2.0_1.0.3.json +0 -90
  53. kasa/tests/fixtures/KL110(US)_1.0_1.8.11.json +0 -89
  54. kasa/tests/fixtures/KL120(US)_1.0_1.8.11.json +0 -85
  55. kasa/tests/fixtures/KL120(US)_1.0_1.8.6.json +0 -93
  56. kasa/tests/fixtures/KL125(US)_1.20_1.0.5.json +0 -88
  57. kasa/tests/fixtures/KL125(US)_2.0_1.0.7.json +0 -92
  58. kasa/tests/fixtures/KL125(US)_4.0_1.0.5.json +0 -93
  59. kasa/tests/fixtures/KL130(EU)_1.0_1.8.8.json +0 -85
  60. kasa/tests/fixtures/KL130(US)_1.0_1.8.11.json +0 -89
  61. kasa/tests/fixtures/KL135(US)_1.0_1.0.6.json +0 -89
  62. kasa/tests/fixtures/KL400L5(US)_1.0_1.0.5.json +0 -57
  63. kasa/tests/fixtures/KL400L5(US)_1.0_1.0.8.json +0 -57
  64. kasa/tests/fixtures/KL420L5(US)_1.0_1.0.2.json +0 -57
  65. kasa/tests/fixtures/KL430(UN)_2.0_1.0.8.json +0 -90
  66. kasa/tests/fixtures/KL430(US)_1.0_1.0.10.json +0 -109
  67. kasa/tests/fixtures/KL430(US)_2.0_1.0.11.json +0 -59
  68. kasa/tests/fixtures/KL430(US)_2.0_1.0.8.json +0 -59
  69. kasa/tests/fixtures/KL430(US)_2.0_1.0.9.json +0 -57
  70. kasa/tests/fixtures/KL50(US)_1.0_1.1.13.json +0 -90
  71. kasa/tests/fixtures/KL60(UN)_1.0_1.1.4.json +0 -102
  72. kasa/tests/fixtures/KL60(US)_1.0_1.1.13.json +0 -90
  73. kasa/tests/fixtures/KP100(US)_3.0_1.0.1.json +0 -31
  74. kasa/tests/fixtures/KP105(UK)_1.0_1.0.5.json +0 -36
  75. kasa/tests/fixtures/KP105(UK)_1.0_1.0.7.json +0 -33
  76. kasa/tests/fixtures/KP115(EU)_1.0_1.0.16.json +0 -42
  77. kasa/tests/fixtures/KP115(US)_1.0_1.0.17.json +0 -42
  78. kasa/tests/fixtures/KP115(US)_1.0_1.0.21.json +0 -42
  79. kasa/tests/fixtures/KP125(US)_1.0_1.0.6.json +0 -42
  80. kasa/tests/fixtures/KP200(US)_3.0_1.0.3.json +0 -46
  81. kasa/tests/fixtures/KP303(UK)_1.0_1.0.3.json +0 -54
  82. kasa/tests/fixtures/KP303(US)_2.0_1.0.3.json +0 -54
  83. kasa/tests/fixtures/KP400(US)_1.0_1.0.10.json +0 -63
  84. kasa/tests/fixtures/KP400(US)_2.0_1.0.6.json +0 -45
  85. kasa/tests/fixtures/KP400(US)_3.0_1.0.3.json +0 -45
  86. kasa/tests/fixtures/KP400(US)_3.0_1.0.4.json +0 -46
  87. kasa/tests/fixtures/KP401(US)_1.0_1.0.0.json +0 -32
  88. kasa/tests/fixtures/KP405(US)_1.0_1.0.5.json +0 -65
  89. kasa/tests/fixtures/KP405(US)_1.0_1.0.6.json +0 -65
  90. kasa/tests/fixtures/KS200M(US)_1.0_1.0.11.json +0 -96
  91. kasa/tests/fixtures/KS200M(US)_1.0_1.0.8.json +0 -95
  92. kasa/tests/fixtures/KS220M(US)_1.0_1.0.4.json +0 -126
  93. kasa/tests/fixtures/KS230(US)_1.0_1.0.14.json +0 -64
  94. kasa/tests/fixtures/LB110(US)_1.0_1.8.11.json +0 -89
  95. kasa/tests/fixtures/smart/EP25(US)_2.6_1.0.1.json +0 -457
  96. kasa/tests/fixtures/smart/EP25(US)_2.6_1.0.2.json +0 -414
  97. kasa/tests/fixtures/smart/H100(EU)_1.0_1.2.3.json +0 -221
  98. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.10.json +0 -547
  99. kasa/tests/fixtures/smart/H100(EU)_1.0_1.5.5.json +0 -391
  100. kasa/tests/fixtures/smart/HS220(US)_3.26_1.0.1.json +0 -371
  101. kasa/tests/fixtures/smart/KH100(UK)_1.0_1.5.6.json +0 -1557
  102. kasa/tests/fixtures/smart/KP125M(US)_1.0_1.1.3.json +0 -175
  103. kasa/tests/fixtures/smart/KS205(US)_1.0_1.0.2.json +0 -243
  104. kasa/tests/fixtures/smart/KS205(US)_1.0_1.1.0.json +0 -298
  105. kasa/tests/fixtures/smart/KS225(US)_1.0_1.0.2.json +0 -269
  106. kasa/tests/fixtures/smart/KS225(US)_1.0_1.1.0.json +0 -332
  107. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.4.json +0 -899
  108. kasa/tests/fixtures/smart/KS240(US)_1.0_1.0.5.json +0 -479
  109. kasa/tests/fixtures/smart/L510B(EU)_3.0_1.0.5.json +0 -263
  110. kasa/tests/fixtures/smart/L510E(US)_3.0_1.0.5.json +0 -303
  111. kasa/tests/fixtures/smart/L510E(US)_3.0_1.1.2.json +0 -267
  112. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.0.6.json +0 -425
  113. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.0.json +0 -440
  114. kasa/tests/fixtures/smart/L530E(EU)_3.0_1.1.6.json +0 -449
  115. kasa/tests/fixtures/smart/L530E(US)_2.0_1.1.0.json +0 -439
  116. kasa/tests/fixtures/smart/L900-10(EU)_1.0_1.0.17.json +0 -441
  117. kasa/tests/fixtures/smart/L900-10(US)_1.0_1.0.11.json +0 -428
  118. kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.0.17.json +0 -384
  119. kasa/tests/fixtures/smart/L900-5(EU)_1.0_1.1.0.json +0 -390
  120. kasa/tests/fixtures/smart/L920-5(EU)_1.0_1.0.7.json +0 -350
  121. kasa/tests/fixtures/smart/L920-5(EU)_1.0_1.1.3.json +0 -1085
  122. kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.0.json +0 -397
  123. kasa/tests/fixtures/smart/L920-5(US)_1.0_1.1.3.json +0 -415
  124. kasa/tests/fixtures/smart/L930-5(US)_1.0_1.1.2.json +0 -429
  125. kasa/tests/fixtures/smart/P100_1.0.0_1.1.3.json +0 -173
  126. kasa/tests/fixtures/smart/P100_1.0.0_1.3.7.json +0 -197
  127. kasa/tests/fixtures/smart/P100_1.0.0_1.4.0.json +0 -204
  128. kasa/tests/fixtures/smart/P110(EU)_1.0_1.0.7.json +0 -566
  129. kasa/tests/fixtures/smart/P110(EU)_1.0_1.2.3.json +0 -399
  130. kasa/tests/fixtures/smart/P110(UK)_1.0_1.3.0.json +0 -447
  131. kasa/tests/fixtures/smart/P115(EU)_1.0_1.2.3.json +0 -386
  132. kasa/tests/fixtures/smart/P125M(US)_1.0_1.1.0.json +0 -243
  133. kasa/tests/fixtures/smart/P135(US)_1.0_1.0.5.json +0 -317
  134. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.13.json +0 -510
  135. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.15.json +0 -966
  136. kasa/tests/fixtures/smart/P300(EU)_1.0_1.0.7.json +0 -512
  137. kasa/tests/fixtures/smart/S500D(US)_1.0_1.0.5.json +0 -317
  138. kasa/tests/fixtures/smart/S505(US)_1.0_1.0.2.json +0 -309
  139. kasa/tests/fixtures/smart/S505D(US)_1.0_1.1.0.json +0 -262
  140. kasa/tests/fixtures/smart/TP15(US)_1.0_1.0.3.json +0 -295
  141. kasa/tests/fixtures/smart/TP25(US)_1.0_1.0.2.json +0 -423
  142. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.4.0.json +0 -170
  143. kasa/tests/fixtures/smart/child/KE100(EU)_1.0_2.8.0.json +0 -171
  144. kasa/tests/fixtures/smart/child/KE100(UK)_1.0_2.8.0.json +0 -171
  145. kasa/tests/fixtures/smart/child/T100(EU)_1.0_1.12.0.json +0 -537
  146. kasa/tests/fixtures/smart/child/T110(EU)_1.0_1.8.0.json +0 -526
  147. kasa/tests/fixtures/smart/child/T300(EU)_1.0_1.7.0.json +0 -533
  148. kasa/tests/fixtures/smart/child/T310(EU)_1.0_1.5.0.json +0 -530
  149. kasa/tests/fixtures/smart/child/T315(EU)_1.0_1.7.0.json +0 -537
  150. kasa/tests/smart/__init__.py +0 -0
  151. kasa/tests/smart/features/__init__.py +0 -0
  152. kasa/tests/smart/features/test_brightness.py +0 -55
  153. kasa/tests/smart/features/test_colortemp.py +0 -30
  154. kasa/tests/smart/modules/__init__.py +0 -0
  155. kasa/tests/smart/modules/test_autooff.py +0 -103
  156. kasa/tests/smart/modules/test_contact.py +0 -28
  157. kasa/tests/smart/modules/test_fan.py +0 -83
  158. kasa/tests/smart/modules/test_firmware.py +0 -119
  159. kasa/tests/smart/modules/test_humidity.py +0 -28
  160. kasa/tests/smart/modules/test_light_effect.py +0 -83
  161. kasa/tests/smart/modules/test_light_strip_effect.py +0 -98
  162. kasa/tests/smart/modules/test_lighttransition.py +0 -80
  163. kasa/tests/smart/modules/test_motionsensor.py +0 -28
  164. kasa/tests/smart/modules/test_temperature.py +0 -47
  165. kasa/tests/smart/modules/test_temperaturecontrol.py +0 -145
  166. kasa/tests/smart/modules/test_waterleak.py +0 -42
  167. kasa/tests/test_aestransport.py +0 -510
  168. kasa/tests/test_bulb.py +0 -422
  169. kasa/tests/test_childdevice.py +0 -122
  170. kasa/tests/test_cli.py +0 -1051
  171. kasa/tests/test_common_modules.py +0 -323
  172. kasa/tests/test_device.py +0 -299
  173. kasa/tests/test_device_factory.py +0 -193
  174. kasa/tests/test_device_type.py +0 -23
  175. kasa/tests/test_deviceconfig.py +0 -74
  176. kasa/tests/test_dimmer.py +0 -143
  177. kasa/tests/test_discovery.py +0 -603
  178. kasa/tests/test_emeter.py +0 -203
  179. kasa/tests/test_feature.py +0 -209
  180. kasa/tests/test_httpclient.py +0 -100
  181. kasa/tests/test_iotdevice.py +0 -294
  182. kasa/tests/test_klapprotocol.py +0 -563
  183. kasa/tests/test_lightstrip.py +0 -77
  184. kasa/tests/test_plug.py +0 -83
  185. kasa/tests/test_protocol.py +0 -745
  186. kasa/tests/test_readme_examples.py +0 -203
  187. kasa/tests/test_smartdevice.py +0 -432
  188. kasa/tests/test_smartprotocol.py +0 -446
  189. kasa/tests/test_strip.py +0 -162
  190. kasa/tests/test_usage.py +0 -85
  191. python_kasa-0.7.1.dist-info/RECORD +0 -273
  192. python_kasa-0.7.1.dist-info/entry_points.txt +0 -3
  193. {python_kasa-0.7.1.dist-info → python_kasa-0.7.3.dist-info/licenses}/LICENSE +0 -0
kasa/aestransport.py CHANGED
@@ -106,6 +106,9 @@ class AesTransport(BaseTransport):
106
106
  self._session_cookie: dict[str, str] | None = None
107
107
 
108
108
  self._key_pair: KeyPair | None = None
109
+ if config.aes_keys:
110
+ aes_keys = config.aes_keys
111
+ self._key_pair = KeyPair(aes_keys["private"], aes_keys["public"])
109
112
  self._app_url = URL(f"http://{self._host}:{self._port}/app")
110
113
  self._token_url: URL | None = None
111
114
 
@@ -271,23 +274,28 @@ class AesTransport(BaseTransport):
271
274
  can be made to the device.
272
275
  """
273
276
  _LOGGER.debug("Generating keypair")
274
- self._key_pair = KeyPair.create_key_pair()
277
+ if not self._key_pair:
278
+ kp = KeyPair.create_key_pair()
279
+ self._config.aes_keys = {
280
+ "private": kp.get_private_key(),
281
+ "public": kp.get_public_key(),
282
+ }
283
+ self._key_pair = kp
284
+
275
285
  pub_key = (
276
286
  "-----BEGIN PUBLIC KEY-----\n"
277
287
  + self._key_pair.get_public_key() # type: ignore[union-attr]
278
288
  + "\n-----END PUBLIC KEY-----\n"
279
289
  )
280
290
  handshake_params = {"key": pub_key}
281
- _LOGGER.debug(f"Handshake params: {handshake_params}")
282
291
  request_body = {"method": "handshake", "params": handshake_params}
283
- _LOGGER.debug(f"Request {request_body}")
292
+ _LOGGER.debug("Handshake request: %s", request_body)
284
293
  yield json_dumps(request_body).encode()
285
294
 
286
295
  async def perform_handshake(self) -> None:
287
296
  """Perform the handshake."""
288
297
  _LOGGER.debug("Will perform handshaking...")
289
298
 
290
- self._key_pair = None
291
299
  self._token_url = None
292
300
  self._session_expire_at = None
293
301
  self._session_cookie = None
kasa/device_factory.py CHANGED
@@ -84,8 +84,11 @@ async def _connect(config: DeviceConfig, protocol: BaseProtocol) -> Device:
84
84
  if debug_enabled:
85
85
  end_time = time.perf_counter()
86
86
  _LOGGER.debug(
87
- f"Device {config.host} with connection params {has_params} "
88
- + f"took {end_time - start_time:.2f} seconds to {perf_type}",
87
+ "Device %s with connection params %s took %.2f seconds to %s",
88
+ config.host,
89
+ has_params,
90
+ end_time - start_time,
91
+ perf_type,
89
92
  )
90
93
  start_time = time.perf_counter()
91
94
 
kasa/deviceconfig.py CHANGED
@@ -34,7 +34,7 @@ Living Room Bulb
34
34
  import logging
35
35
  from dataclasses import asdict, dataclass, field, fields, is_dataclass
36
36
  from enum import Enum
37
- from typing import TYPE_CHECKING, Dict, Optional, Union
37
+ from typing import TYPE_CHECKING, Dict, Optional, TypedDict, Union
38
38
 
39
39
  from .credentials import Credentials
40
40
  from .exceptions import KasaException
@@ -45,6 +45,13 @@ if TYPE_CHECKING:
45
45
  _LOGGER = logging.getLogger(__name__)
46
46
 
47
47
 
48
+ class KeyPairDict(TypedDict):
49
+ """Class to represent a public/private key pair."""
50
+
51
+ private: str
52
+ public: str
53
+
54
+
48
55
  class DeviceEncryptionType(Enum):
49
56
  """Encrypt type enum."""
50
57
 
@@ -182,7 +189,7 @@ class DeviceConfig:
182
189
  #: The batch size for protoools supporting multiple request batches.
183
190
  connection_type: DeviceConnectionParameters = field(
184
191
  default_factory=lambda: DeviceConnectionParameters(
185
- DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor, 1
192
+ DeviceFamily.IotSmartPlugSwitch, DeviceEncryptionType.Xor
186
193
  )
187
194
  )
188
195
  #: True if the device uses http. Consumers should retrieve rather than set this
@@ -193,6 +200,8 @@ class DeviceConfig:
193
200
  #: Set a custom http_client for the device to use.
194
201
  http_client: Optional["ClientSession"] = field(default=None, compare=False)
195
202
 
203
+ aes_keys: Optional[KeyPairDict] = None
204
+
196
205
  def __post_init__(self):
197
206
  if self.connection_type is None:
198
207
  self.connection_type = DeviceConnectionParameters(
kasa/discover.py CHANGED
@@ -262,7 +262,7 @@ class _DiscoverProtocol(asyncio.DatagramProtocol):
262
262
  self._handle_discovered_event()
263
263
  return
264
264
  except KasaException as ex:
265
- _LOGGER.debug(f"[DISCOVERY] Unable to find device type for {ip}: {ex}")
265
+ _LOGGER.debug("[DISCOVERY] Unable to find device type for %s: %s", ip, ex)
266
266
  self.invalid_device_exceptions[ip] = ex
267
267
  self._handle_discovered_event()
268
268
  return
kasa/emeterstatus.py CHANGED
@@ -87,5 +87,5 @@ class EmeterStatus(dict):
87
87
  ):
88
88
  return value / 1000
89
89
 
90
- _LOGGER.debug(f"Unable to find value for '{item}'")
90
+ _LOGGER.debug("Unable to find value for '%s'", item)
91
91
  return None
kasa/feature.py CHANGED
@@ -31,9 +31,10 @@ Cloud connection (cloud_connection): True
31
31
  HSV (hsv): HSV(hue=0, saturation=100, value=100)
32
32
  Color temperature (color_temperature): 2700
33
33
  Auto update enabled (auto_update_enabled): False
34
- Update available (update_available): False
34
+ Update available (update_available): None
35
35
  Current firmware version (current_firmware_version): 1.1.6 Build 240130 Rel.173828
36
- Available firmware version (available_firmware_version): 1.1.6 Build 240130 Rel.173828
36
+ Available firmware version (available_firmware_version): None
37
+ Check latest firmware (check_latest_firmware): <Action>
37
38
  Light effect (light_effect): Off
38
39
  Light preset (light_preset): Not set
39
40
  Smooth transition on (smooth_transition_on): 2
kasa/iot/iotbulb.py CHANGED
@@ -388,10 +388,14 @@ class IotBulb(IotDevice):
388
388
  if not self._is_color:
389
389
  raise KasaException("Bulb does not support color.")
390
390
 
391
- if not isinstance(hue, int) or not (0 <= hue <= 360):
391
+ if not isinstance(hue, int):
392
+ raise TypeError("Hue must be an integer.")
393
+ if not (0 <= hue <= 360):
392
394
  raise ValueError(f"Invalid hue value: {hue} (valid range: 0-360)")
393
395
 
394
- if not isinstance(saturation, int) or not (0 <= saturation <= 100):
396
+ if not isinstance(saturation, int):
397
+ raise TypeError("Saturation must be an integer.")
398
+ if not (0 <= saturation <= 100):
395
399
  raise ValueError(
396
400
  f"Invalid saturation value: {saturation} (valid range: 0-100%)"
397
401
  )
@@ -445,7 +449,9 @@ class IotBulb(IotDevice):
445
449
  return await self._set_light_state(light_state, transition=transition)
446
450
 
447
451
  def _raise_for_invalid_brightness(self, value):
448
- if not isinstance(value, int) or not (0 <= value <= 100):
452
+ if not isinstance(value, int):
453
+ raise TypeError("Brightness must be an integer")
454
+ if not (0 <= value <= 100):
449
455
  raise ValueError(f"Invalid brightness value: {value} (valid range: 0-100%)")
450
456
 
451
457
  @property # type: ignore
kasa/iot/iotdevice.py CHANGED
@@ -14,7 +14,6 @@ http://www.apache.org/licenses/LICENSE-2.0
14
14
 
15
15
  from __future__ import annotations
16
16
 
17
- import collections.abc
18
17
  import functools
19
18
  import inspect
20
19
  import logging
@@ -29,22 +28,12 @@ from ..feature import Feature
29
28
  from ..module import Module
30
29
  from ..modulemapping import ModuleMapping, ModuleName
31
30
  from ..protocol import BaseProtocol
32
- from .iotmodule import IotModule
31
+ from .iotmodule import IotModule, merge
33
32
  from .modules import Emeter
34
33
 
35
34
  _LOGGER = logging.getLogger(__name__)
36
35
 
37
36
 
38
- def merge(d, u):
39
- """Update dict recursively."""
40
- for k, v in u.items():
41
- if isinstance(v, collections.abc.Mapping):
42
- d[k] = merge(d.get(k, {}), v)
43
- else:
44
- d[k] = v
45
- return d
46
-
47
-
48
37
  def requires_update(f):
49
38
  """Indicate that `update` should be called before accessing this method.""" # noqa: D202
50
39
  if inspect.iscoroutinefunction(f):
@@ -209,7 +198,7 @@ class IotDevice(Device):
209
198
  def add_module(self, name: str | ModuleName[Module], module: IotModule):
210
199
  """Register a module."""
211
200
  if name in self._modules:
212
- _LOGGER.debug("Module %s already registered, ignoring..." % name)
201
+ _LOGGER.debug("Module %s already registered, ignoring...", name)
213
202
  return
214
203
 
215
204
  _LOGGER.debug("Adding module %s", module)
@@ -382,7 +371,7 @@ class IotDevice(Device):
382
371
  est_response_size = 1024 if "system" in req else 0
383
372
  for module in self._modules.values():
384
373
  if not module.is_supported:
385
- _LOGGER.debug("Module %s not supported, skipping" % module)
374
+ _LOGGER.debug("Module %s not supported, skipping", module)
386
375
  continue
387
376
 
388
377
  est_response_size += module.estimated_query_response_size
kasa/iot/iotdimmer.py CHANGED
@@ -118,7 +118,9 @@ class IotDimmer(IotPlug):
118
118
  )
119
119
 
120
120
  if not 0 <= brightness <= 100:
121
- raise ValueError("Brightness value %s is not valid." % brightness)
121
+ raise ValueError(
122
+ f"Invalid brightness value: {brightness} (valid range: 0-100%)"
123
+ )
122
124
 
123
125
  # Dimmers do not support a brightness of 0, but bulbs do.
124
126
  # Coerce 0 to 1 to maintain the same interface between dimmers and bulbs.
@@ -161,20 +163,18 @@ class IotDimmer(IotPlug):
161
163
  A brightness value of 0 will turn off the dimmer.
162
164
  """
163
165
  if not isinstance(brightness, int):
164
- raise ValueError(
165
- "Brightness must be integer, " "not of %s.", type(brightness)
166
- )
166
+ raise TypeError(f"Brightness must be an integer, not {type(brightness)}.")
167
167
 
168
168
  if not 0 <= brightness <= 100:
169
- raise ValueError("Brightness value %s is not valid." % brightness)
169
+ raise ValueError(
170
+ f"Invalid brightness value: {brightness} (valid range: 0-100%)"
171
+ )
170
172
 
171
173
  # If zero set to 1 millisecond
172
174
  if transition == 0:
173
175
  transition = 1
174
176
  if not isinstance(transition, int):
175
- raise ValueError(
176
- "Transition must be integer, " "not of %s.", type(transition)
177
- )
177
+ raise TypeError(f"Transition must be integer, not of {type(transition)}.")
178
178
  if transition <= 0:
179
179
  raise ValueError("Transition value %s is not valid." % transition)
180
180
 
kasa/iot/iotmodule.py CHANGED
@@ -1,6 +1,5 @@
1
1
  """Base class for IOT module implementations."""
2
2
 
3
- import collections
4
3
  import logging
5
4
 
6
5
  from ..exceptions import KasaException
@@ -9,15 +8,17 @@ from ..module import Module
9
8
  _LOGGER = logging.getLogger(__name__)
10
9
 
11
10
 
12
- # TODO: This is used for query constructing, check for a better place
13
- def merge(d, u):
11
+ def _merge_dict(dest: dict, source: dict) -> dict:
14
12
  """Update dict recursively."""
15
- for k, v in u.items():
16
- if isinstance(v, collections.abc.Mapping):
17
- d[k] = merge(d.get(k, {}), v)
13
+ for k, v in source.items():
14
+ if k in dest and type(v) is dict: # noqa: E721 - only accepts `dict` type
15
+ _merge_dict(dest[k], v)
18
16
  else:
19
- d[k] = v
20
- return d
17
+ dest[k] = v
18
+ return dest
19
+
20
+
21
+ merge = _merge_dict
21
22
 
22
23
 
23
24
  class IotModule(Module):
kasa/klaptransport.py CHANGED
@@ -153,8 +153,8 @@ class KlapTransport(BaseTransport):
153
153
 
154
154
  if _LOGGER.isEnabledFor(logging.DEBUG):
155
155
  _LOGGER.debug(
156
- "Handshake1 posted at %s. Host is %s, Response"
157
- + "status is %s, Request was %s",
156
+ "Handshake1 posted at %s. Host is %s, "
157
+ "Response status is %s, Request was %s",
158
158
  datetime.datetime.now(),
159
159
  self._host,
160
160
  response_status,
@@ -179,7 +179,7 @@ class KlapTransport(BaseTransport):
179
179
  if _LOGGER.isEnabledFor(logging.DEBUG):
180
180
  _LOGGER.debug(
181
181
  "Handshake1 success at %s. Host is %s, "
182
- + "Server remote_seed is: %s, server hash is: %s",
182
+ "Server remote_seed is: %s, server hash is: %s",
183
183
  datetime.datetime.now(),
184
184
  self._host,
185
185
  remote_seed.hex(),
@@ -211,9 +211,10 @@ class KlapTransport(BaseTransport):
211
211
 
212
212
  if default_credentials_seed_auth_hash == server_hash:
213
213
  _LOGGER.debug(
214
- "Server response doesn't match our expected hash on ip %s"
215
- + f" but an authentication with {key} default credentials matched",
214
+ "Server response doesn't match our expected hash on ip %s, "
215
+ "but an authentication with %s default credentials matched",
216
216
  self._host,
217
+ key,
217
218
  )
218
219
  return local_seed, remote_seed, self._default_credentials_auth_hash[key] # type: ignore
219
220
 
@@ -231,8 +232,8 @@ class KlapTransport(BaseTransport):
231
232
 
232
233
  if blank_seed_auth_hash == server_hash:
233
234
  _LOGGER.debug(
234
- "Server response doesn't match our expected hash on ip %s"
235
- + " but an authentication with blank credentials matched",
235
+ "Server response doesn't match our expected hash on ip %s, "
236
+ "but an authentication with blank credentials matched",
236
237
  self._host,
237
238
  )
238
239
  return local_seed, remote_seed, self._blank_auth_hash # type: ignore
@@ -260,8 +261,8 @@ class KlapTransport(BaseTransport):
260
261
 
261
262
  if _LOGGER.isEnabledFor(logging.DEBUG):
262
263
  _LOGGER.debug(
263
- "Handshake2 posted %s. Host is %s, Response status is %s, "
264
- + "Request was %s",
264
+ "Handshake2 posted %s. Host is %s, "
265
+ "Response status is %s, Request was %s",
265
266
  datetime.datetime.now(),
266
267
  self._host,
267
268
  response_status,
@@ -338,18 +339,17 @@ class KlapTransport(BaseTransport):
338
339
  + f"Response status is {response_status}, Request was {request}"
339
340
  )
340
341
  if response_status != 200:
341
- _LOGGER.error("Query failed after successful authentication " + msg)
342
+ _LOGGER.error("Query failed after successful authentication: %s", msg)
342
343
  # If we failed with a security error, force a new handshake next time.
343
344
  if response_status == 403:
344
345
  self._handshake_done = False
345
346
  raise _RetryableError(
346
- f"Got a security error from {self._host} after handshake "
347
- + "completed"
347
+ "Got a security error from %s after handshake completed", self._host
348
348
  )
349
349
  else:
350
350
  raise KasaException(
351
- f"Device {self._host} responded with {response_status} to"
352
- + f"request with seq {seq}"
351
+ f"Device {self._host} responded with {response_status} to "
352
+ f"request with seq {seq}"
353
353
  )
354
354
  else:
355
355
  _LOGGER.debug("Device %s query posted %s", self._host, msg)
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from typing import Literal
6
+
5
7
  from ...feature import Feature
6
8
  from ..smartmodule import SmartModule
7
9
 
@@ -94,7 +96,7 @@ class Alarm(SmartModule):
94
96
  )
95
97
 
96
98
  @property
97
- def alarm_sound(self):
99
+ def alarm_sound(self) -> str:
98
100
  """Return current alarm sound."""
99
101
  return self.data["get_alarm_configure"]["type"]
100
102
 
@@ -113,11 +115,11 @@ class Alarm(SmartModule):
113
115
  return self.data["get_support_alarm_type_list"]["alarm_type_list"]
114
116
 
115
117
  @property
116
- def alarm_volume(self):
118
+ def alarm_volume(self) -> Literal["low", "normal", "high"]:
117
119
  """Return alarm volume."""
118
120
  return self.data["get_alarm_configure"]["volume"]
119
121
 
120
- async def set_alarm_volume(self, volume: str):
122
+ async def set_alarm_volume(self, volume: Literal["low", "normal", "high"]):
121
123
  """Set alarm volume."""
122
124
  payload = self.data["get_alarm_configure"].copy()
123
125
  payload["volume"] = volume
@@ -134,10 +136,10 @@ class Alarm(SmartModule):
134
136
  src = self._device.sys_info["in_alarm_source"]
135
137
  return src if src else None
136
138
 
137
- async def play(self):
139
+ async def play(self) -> dict:
138
140
  """Play alarm."""
139
141
  return await self.call("play_alarm")
140
142
 
141
- async def stop(self):
143
+ async def stop(self) -> dict:
142
144
  """Stop alarm."""
143
145
  return await self.call("stop_alarm")
@@ -51,10 +51,12 @@ class Color(SmartModule):
51
51
 
52
52
  return HSV(hue=h, saturation=s, value=v)
53
53
 
54
- def _raise_for_invalid_brightness(self, value: int):
54
+ def _raise_for_invalid_brightness(self, value):
55
55
  """Raise error on invalid brightness value."""
56
- if not isinstance(value, int) or not (1 <= value <= 100):
57
- raise ValueError(f"Invalid brightness value: {value} (valid range: 1-100%)")
56
+ if not isinstance(value, int):
57
+ raise TypeError("Brightness must be an integer")
58
+ if not (0 <= value <= 100):
59
+ raise ValueError(f"Invalid brightness value: {value} (valid range: 0-100%)")
58
60
 
59
61
  async def set_hsv(
60
62
  self,
@@ -73,10 +75,14 @@ class Color(SmartModule):
73
75
  :param int value: value in percentage [0, 100]
74
76
  :param int transition: transition in milliseconds.
75
77
  """
76
- if not isinstance(hue, int) or not (0 <= hue <= 360):
78
+ if not isinstance(hue, int):
79
+ raise TypeError("Hue must be an integer")
80
+ if not (0 <= hue <= 360):
77
81
  raise ValueError(f"Invalid hue value: {hue} (valid range: 0-360)")
78
82
 
79
- if not isinstance(saturation, int) or not (0 <= saturation <= 100):
83
+ if not isinstance(saturation, int):
84
+ raise TypeError("Saturation must be an integer")
85
+ if not (0 <= saturation <= 100):
80
86
  raise ValueError(
81
87
  f"Invalid saturation value: {saturation} (valid range: 0-100%)"
82
88
  )
@@ -6,13 +6,14 @@ import asyncio
6
6
  import logging
7
7
  from collections.abc import Coroutine
8
8
  from datetime import date
9
- from typing import TYPE_CHECKING, Any, Callable, Optional
9
+ from typing import TYPE_CHECKING, Callable, Optional
10
10
 
11
11
  # When support for cpython older than 3.11 is dropped
12
12
  # async_timeout can be replaced with asyncio.timeout
13
13
  from async_timeout import timeout as asyncio_timeout
14
14
  from pydantic.v1 import BaseModel, Field, validator
15
15
 
16
+ from ...exceptions import KasaException
16
17
  from ...feature import Feature
17
18
  from ..smartmodule import SmartModule, allow_update_after
18
19
 
@@ -70,6 +71,11 @@ class Firmware(SmartModule):
70
71
 
71
72
  def __init__(self, device: SmartDevice, module: str):
72
73
  super().__init__(device, module)
74
+ self._firmware_update_info: UpdateInfo | None = None
75
+
76
+ def _initialize_features(self):
77
+ """Initialize features."""
78
+ device = self._device
73
79
  if self.supported_version > 1:
74
80
  self._add_feature(
75
81
  Feature(
@@ -115,13 +121,34 @@ class Firmware(SmartModule):
115
121
  type=Feature.Type.Sensor,
116
122
  )
117
123
  )
124
+ self._add_feature(
125
+ Feature(
126
+ device,
127
+ id="check_latest_firmware",
128
+ name="Check latest firmware",
129
+ container=self,
130
+ attribute_setter="check_latest_firmware",
131
+ category=Feature.Category.Info,
132
+ type=Feature.Type.Action,
133
+ )
134
+ )
118
135
 
119
136
  def query(self) -> dict:
120
137
  """Query to execute during the update cycle."""
121
- req: dict[str, Any] = {"get_latest_fw": None}
122
138
  if self.supported_version > 1:
123
- req["get_auto_update_info"] = None
124
- return req
139
+ return {"get_auto_update_info": None}
140
+ return {}
141
+
142
+ async def check_latest_firmware(self) -> UpdateInfo | None:
143
+ """Check for the latest firmware for the device."""
144
+ try:
145
+ fw = await self.call("get_latest_fw")
146
+ self._firmware_update_info = UpdateInfo.parse_obj(fw["get_latest_fw"])
147
+ return self._firmware_update_info
148
+ except Exception:
149
+ _LOGGER.exception("Error getting latest firmware for %s:", self._device)
150
+ self._firmware_update_info = None
151
+ return None
125
152
 
126
153
  @property
127
154
  def current_firmware(self) -> str:
@@ -129,26 +156,23 @@ class Firmware(SmartModule):
129
156
  return self._device.hw_info["sw_ver"]
130
157
 
131
158
  @property
132
- def latest_firmware(self) -> str:
159
+ def latest_firmware(self) -> str | None:
133
160
  """Return the latest firmware version."""
134
- return self.firmware_update_info.version
161
+ if not self._firmware_update_info:
162
+ return None
163
+ return self._firmware_update_info.version
135
164
 
136
165
  @property
137
- def firmware_update_info(self):
166
+ def firmware_update_info(self) -> UpdateInfo | None:
138
167
  """Return latest firmware information."""
139
- if not self._device.is_cloud_connected or self._has_data_error():
140
- # Error in response, probably disconnected from the cloud.
141
- return UpdateInfo(type=0, need_to_upgrade=False)
142
-
143
- fw = self.data.get("get_latest_fw") or self.data
144
- return UpdateInfo.parse_obj(fw)
168
+ return self._firmware_update_info
145
169
 
146
170
  @property
147
171
  def update_available(self) -> bool | None:
148
172
  """Return True if update is available."""
149
- if not self._device.is_cloud_connected:
173
+ if not self._device.is_cloud_connected or not self._firmware_update_info:
150
174
  return None
151
- return self.firmware_update_info.update_available
175
+ return self._firmware_update_info.update_available
152
176
 
153
177
  async def get_update_state(self) -> DownloadState:
154
178
  """Return update state."""
@@ -161,11 +185,17 @@ class Firmware(SmartModule):
161
185
  self, progress_cb: Callable[[DownloadState], Coroutine] | None = None
162
186
  ):
163
187
  """Update the device firmware."""
188
+ if not self._firmware_update_info:
189
+ raise KasaException(
190
+ "You must call check_latest_firmware before calling update"
191
+ )
192
+ if not self.update_available:
193
+ raise KasaException("A new update must be available to call update")
164
194
  current_fw = self.current_firmware
165
195
  _LOGGER.info(
166
196
  "Going to upgrade from %s to %s",
167
197
  current_fw,
168
- self.firmware_update_info.version,
198
+ self._firmware_update_info.version,
169
199
  )
170
200
  await self.call("fw_download")
171
201
 
@@ -181,14 +211,14 @@ class Firmware(SmartModule):
181
211
  )
182
212
  continue
183
213
 
184
- _LOGGER.debug("Update state: %s" % state)
214
+ _LOGGER.debug("Update state: %s", state)
185
215
  if progress_cb is not None:
186
216
  asyncio.create_task(progress_cb(state))
187
217
 
188
218
  if state.status == 0:
189
219
  _LOGGER.info(
190
220
  "Update idle, hopefully updated to %s",
191
- self.firmware_update_info.version,
221
+ self._firmware_update_info.version,
192
222
  )
193
223
  break
194
224
  elif state.status == 2:
@@ -207,15 +237,12 @@ class Firmware(SmartModule):
207
237
  _LOGGER.warning("Unhandled state code: %s", state)
208
238
 
209
239
  @property
210
- def auto_update_enabled(self):
240
+ def auto_update_enabled(self) -> bool:
211
241
  """Return True if autoupdate is enabled."""
212
- return (
213
- "get_auto_update_info" in self.data
214
- and self.data["get_auto_update_info"]["enable"]
215
- )
242
+ return "enable" in self.data and self.data["enable"]
216
243
 
217
244
  @allow_update_after
218
245
  async def set_auto_update_enabled(self, enabled: bool):
219
246
  """Change autoupdate setting."""
220
- data = {**self.data["get_auto_update_info"], "enable": enabled}
247
+ data = {**self.data, "enable": enabled}
221
248
  await self.call("set_auto_update_info", data)
@@ -90,7 +90,7 @@ class LightEffect(SmartModule, SmartLightEffect):
90
90
  """
91
91
  if effect != self.LIGHT_EFFECTS_OFF and effect not in self._scenes_names_to_id:
92
92
  raise ValueError(
93
- f"Cannot set light effect to {effect}, possible values "
93
+ f"The effect {effect} is not a built in effect. Possible values "
94
94
  f"are: {self.LIGHT_EFFECTS_OFF} "
95
95
  f"{' '.join(self._scenes_names_to_id.keys())}"
96
96
  )
kasa/smart/smartmodule.py CHANGED
@@ -77,7 +77,7 @@ class SmartModule(Module):
77
77
 
78
78
  def __init_subclass__(cls, **kwargs):
79
79
  name = getattr(cls, "NAME", cls.__name__)
80
- _LOGGER.debug("Registering %s" % cls)
80
+ _LOGGER.debug("Registering %s", cls)
81
81
  cls.REGISTERED_MODULES[name] = cls
82
82
 
83
83
  def _set_error(self, err: Exception | None):
kasa/smartprotocol.py CHANGED
@@ -309,8 +309,9 @@ class SmartProtocol(BaseProtocol):
309
309
  # In case the device returns empty lists avoid infinite looping
310
310
  if not next_batch[response_list_name]:
311
311
  _LOGGER.error(
312
- f"Device {self._host} returned empty "
313
- + f"results list for method {method}"
312
+ "Device %s returned empty results list for method %s",
313
+ self._host,
314
+ method,
314
315
  )
315
316
  break
316
317
  response_result[response_list_name].extend(next_batch[response_list_name])