python-kasa 0.7.0.2__py3-none-any.whl → 0.7.0.4__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.
kasa/aestransport.py CHANGED
@@ -144,7 +144,9 @@ class AesTransport(BaseTransport):
144
144
  try:
145
145
  error_code = SmartErrorCode.from_int(error_code_raw)
146
146
  except ValueError:
147
- _LOGGER.warning("Received unknown error code: %s", error_code_raw)
147
+ _LOGGER.warning(
148
+ "Device %s received unknown error code: %s", self._host, error_code_raw
149
+ )
148
150
  error_code = SmartErrorCode.INTERNAL_UNKNOWN_ERROR
149
151
  if error_code is SmartErrorCode.SUCCESS:
150
152
  return
@@ -214,10 +216,18 @@ class AesTransport(BaseTransport):
214
216
  """Login to the device."""
215
217
  try:
216
218
  await self.try_login(self._login_params)
219
+ _LOGGER.debug(
220
+ "%s: logged in with provided credentials",
221
+ self._host,
222
+ )
217
223
  except AuthenticationError as aex:
218
224
  try:
219
225
  if aex.error_code is not SmartErrorCode.LOGIN_ERROR:
220
226
  raise aex
227
+ _LOGGER.debug(
228
+ "%s: trying login with default TAPO credentials",
229
+ self._host,
230
+ )
221
231
  if self._default_credentials is None:
222
232
  self._default_credentials = get_default_credentials(
223
233
  DEFAULT_CREDENTIALS["TAPO"]
@@ -225,7 +235,7 @@ class AesTransport(BaseTransport):
225
235
  await self.perform_handshake()
226
236
  await self.try_login(self._get_login_params(self._default_credentials))
227
237
  _LOGGER.debug(
228
- "%s: logged in with default credentials",
238
+ "%s: logged in with default TAPO credentials",
229
239
  self._host,
230
240
  )
231
241
  except (AuthenticationError, _ConnectionError, TimeoutError):
kasa/exceptions.py CHANGED
@@ -128,6 +128,8 @@ class SmartErrorCode(IntEnum):
128
128
 
129
129
  # Library internal for unknown error codes
130
130
  INTERNAL_UNKNOWN_ERROR = -100_000
131
+ # Library internal for query errors
132
+ INTERNAL_QUERY_ERROR = -100_001
131
133
 
132
134
 
133
135
  SMART_RETRYABLE_ERRORS = [
kasa/httpclient.py CHANGED
@@ -75,13 +75,21 @@ class HttpClient:
75
75
  now = time.time()
76
76
  gap = now - self._last_request_time
77
77
  if gap < self._wait_between_requests:
78
- await asyncio.sleep(self._wait_between_requests - gap)
78
+ sleep = self._wait_between_requests - gap
79
+ _LOGGER.debug(
80
+ "Device %s waiting %s seconds to send request",
81
+ self._config.host,
82
+ sleep,
83
+ )
84
+ await asyncio.sleep(sleep)
79
85
 
80
86
  _LOGGER.debug("Posting to %s", url)
81
87
  response_data = None
82
88
  self._last_url = url
83
89
  self.client.cookie_jar.clear()
84
90
  return_json = bool(json)
91
+ client_timeout = aiohttp.ClientTimeout(total=self._config.timeout)
92
+
85
93
  # If json is not a dict send as data.
86
94
  # This allows the json parameter to be used to pass other
87
95
  # types of data such as async_generator and still have json
@@ -95,9 +103,10 @@ class HttpClient:
95
103
  params=params,
96
104
  data=data,
97
105
  json=json,
98
- timeout=self._config.timeout,
106
+ timeout=client_timeout,
99
107
  cookies=cookies_dict,
100
108
  headers=headers,
109
+ ssl=False,
101
110
  )
102
111
  async with resp:
103
112
  if resp.status == 200:
@@ -106,9 +115,15 @@ class HttpClient:
106
115
  response_data = json_loads(response_data.decode())
107
116
 
108
117
  except (aiohttp.ServerDisconnectedError, aiohttp.ClientOSError) as ex:
109
- if isinstance(ex, aiohttp.ClientOSError):
118
+ if not self._wait_between_requests:
119
+ _LOGGER.debug(
120
+ "Device %s received an os error, "
121
+ "enabling sequential request delay: %s",
122
+ self._config.host,
123
+ ex,
124
+ )
110
125
  self._wait_between_requests = self.WAIT_BETWEEN_REQUESTS_ON_OSERROR
111
- self._last_request_time = time.time()
126
+ self._last_request_time = time.time()
112
127
  raise _ConnectionError(
113
128
  f"Device connection error: {self._config.host}: {ex}", ex
114
129
  ) from ex
@@ -19,12 +19,6 @@ class AutoOff(SmartModule):
19
19
 
20
20
  def _initialize_features(self):
21
21
  """Initialize features after the initial update."""
22
- if not isinstance(self.data, dict):
23
- _LOGGER.warning(
24
- "No data available for module, skipping %s: %s", self, self.data
25
- )
26
- return
27
-
28
22
  self._add_feature(
29
23
  Feature(
30
24
  self._device,
@@ -43,6 +43,10 @@ class BatterySensor(SmartModule):
43
43
  )
44
44
  )
45
45
 
46
+ def query(self) -> dict:
47
+ """Query to execute during the update cycle."""
48
+ return {}
49
+
46
50
  @property
47
51
  def battery(self):
48
52
  """Return battery level."""
@@ -4,7 +4,6 @@ from __future__ import annotations
4
4
 
5
5
  from typing import TYPE_CHECKING
6
6
 
7
- from ...exceptions import SmartErrorCode
8
7
  from ...feature import Feature
9
8
  from ..smartmodule import SmartModule
10
9
 
@@ -17,6 +16,14 @@ class Cloud(SmartModule):
17
16
 
18
17
  QUERY_GETTER_NAME = "get_connect_cloud_state"
19
18
  REQUIRED_COMPONENT = "cloud_connect"
19
+ MINIMUM_UPDATE_INTERVAL_SECS = 60
20
+
21
+ def _post_update_hook(self):
22
+ """Perform actions after a device update.
23
+
24
+ Overrides the default behaviour to disable a module if the query returns
25
+ an error because the logic here is to treat that as not connected.
26
+ """
20
27
 
21
28
  def __init__(self, device: SmartDevice, module: str):
22
29
  super().__init__(device, module)
@@ -37,6 +44,6 @@ class Cloud(SmartModule):
37
44
  @property
38
45
  def is_connected(self):
39
46
  """Return True if device is connected to the cloud."""
40
- if isinstance(self.data, SmartErrorCode):
47
+ if self._has_data_error():
41
48
  return False
42
49
  return self.data["status"] == 0
@@ -10,6 +10,13 @@ class DeviceModule(SmartModule):
10
10
 
11
11
  REQUIRED_COMPONENT = "device"
12
12
 
13
+ def _post_update_hook(self):
14
+ """Perform actions after a device update.
15
+
16
+ Overrides the default behaviour to disable a module if the query returns
17
+ an error because this module is critical.
18
+ """
19
+
13
20
  def query(self) -> dict:
14
21
  """Query to execute during the update cycle."""
15
22
  query = {
@@ -13,9 +13,8 @@ from typing import TYPE_CHECKING, Any, Callable, Optional
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 SmartErrorCode
17
16
  from ...feature import Feature
18
- from ..smartmodule import SmartModule
17
+ from ..smartmodule import SmartModule, allow_update_after
19
18
 
20
19
  if TYPE_CHECKING:
21
20
  from ..smartdevice import SmartDevice
@@ -67,6 +66,7 @@ class Firmware(SmartModule):
67
66
  """Implementation of firmware module."""
68
67
 
69
68
  REQUIRED_COMPONENT = "firmware"
69
+ MINIMUM_UPDATE_INTERVAL_SECS = 60 * 60 * 24
70
70
 
71
71
  def __init__(self, device: SmartDevice, module: str):
72
72
  super().__init__(device, module)
@@ -136,11 +136,11 @@ class Firmware(SmartModule):
136
136
  @property
137
137
  def firmware_update_info(self):
138
138
  """Return latest firmware information."""
139
- fw = self.data.get("get_latest_fw") or self.data
140
- if not self._device.is_cloud_connected or isinstance(fw, SmartErrorCode):
139
+ if not self._device.is_cloud_connected or self._has_data_error():
141
140
  # Error in response, probably disconnected from the cloud.
142
141
  return UpdateInfo(type=0, need_to_upgrade=False)
143
142
 
143
+ fw = self.data.get("get_latest_fw") or self.data
144
144
  return UpdateInfo.parse_obj(fw)
145
145
 
146
146
  @property
@@ -156,6 +156,7 @@ class Firmware(SmartModule):
156
156
  state = resp["get_fw_download_state"]
157
157
  return DownloadState(**state)
158
158
 
159
+ @allow_update_after
159
160
  async def update(
160
161
  self, progress_cb: Callable[[DownloadState], Coroutine] | None = None
161
162
  ):
@@ -213,6 +214,7 @@ class Firmware(SmartModule):
213
214
  and self.data["get_auto_update_info"]["enable"]
214
215
  )
215
216
 
217
+ @allow_update_after
216
218
  async def set_auto_update_enabled(self, enabled: bool):
217
219
  """Change autoupdate setting."""
218
220
  data = {**self.data["get_auto_update_info"], "enable": enabled}
@@ -14,6 +14,10 @@ class FrostProtection(SmartModule):
14
14
  REQUIRED_COMPONENT = "frost_protection"
15
15
  QUERY_GETTER_NAME = "get_frost_protection"
16
16
 
17
+ def query(self) -> dict:
18
+ """Query to execute during the update cycle."""
19
+ return {}
20
+
17
21
  @property
18
22
  def enabled(self) -> bool:
19
23
  """Return True if frost protection is on."""
@@ -45,6 +45,10 @@ class HumiditySensor(SmartModule):
45
45
  )
46
46
  )
47
47
 
48
+ def query(self) -> dict:
49
+ """Query to execute during the update cycle."""
50
+ return {}
51
+
48
52
  @property
49
53
  def humidity(self):
50
54
  """Return current humidity in percentage."""
kasa/smart/modules/led.py CHANGED
@@ -3,7 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  from ...interfaces.led import Led as LedInterface
6
- from ..smartmodule import SmartModule
6
+ from ..smartmodule import SmartModule, allow_update_after
7
7
 
8
8
 
9
9
  class Led(SmartModule, LedInterface):
@@ -11,6 +11,8 @@ class Led(SmartModule, LedInterface):
11
11
 
12
12
  REQUIRED_COMPONENT = "led"
13
13
  QUERY_GETTER_NAME = "get_led_info"
14
+ # Led queries can cause device to crash on P100
15
+ MINIMUM_UPDATE_INTERVAL_SECS = 60 * 60
14
16
 
15
17
  def query(self) -> dict:
16
18
  """Query to execute during the update cycle."""
@@ -29,6 +31,7 @@ class Led(SmartModule, LedInterface):
29
31
  """Return current led status."""
30
32
  return self.data["led_rule"] != "never"
31
33
 
34
+ @allow_update_after
32
35
  async def set_led(self, enable: bool):
33
36
  """Set led.
34
37
 
@@ -9,7 +9,7 @@ import copy
9
9
  from typing import Any
10
10
 
11
11
  from ..effects import SmartLightEffect
12
- from ..smartmodule import Module, SmartModule
12
+ from ..smartmodule import Module, SmartModule, allow_update_after
13
13
 
14
14
 
15
15
  class LightEffect(SmartModule, SmartLightEffect):
@@ -17,6 +17,7 @@ class LightEffect(SmartModule, SmartLightEffect):
17
17
 
18
18
  REQUIRED_COMPONENT = "light_effect"
19
19
  QUERY_GETTER_NAME = "get_dynamic_light_effect_rules"
20
+ MINIMUM_UPDATE_INTERVAL_SECS = 60
20
21
  AVAILABLE_BULB_EFFECTS = {
21
22
  "L1": "Party",
22
23
  "L2": "Relax",
@@ -130,6 +131,7 @@ class LightEffect(SmartModule, SmartLightEffect):
130
131
 
131
132
  return brightness
132
133
 
134
+ @allow_update_after
133
135
  async def set_brightness(
134
136
  self,
135
137
  brightness: int,
@@ -156,6 +158,7 @@ class LightEffect(SmartModule, SmartLightEffect):
156
158
 
157
159
  return await self.call("edit_dynamic_light_effect_rule", new_effect)
158
160
 
161
+ @allow_update_after
159
162
  async def set_custom_effect(
160
163
  self,
161
164
  effect_dict: dict,
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING
8
8
 
9
9
  from ...interfaces import LightPreset as LightPresetInterface
10
10
  from ...interfaces import LightState
11
- from ..smartmodule import SmartModule
11
+ from ..smartmodule import SmartModule, allow_update_after
12
12
 
13
13
  if TYPE_CHECKING:
14
14
  from ..smartdevice import SmartDevice
@@ -19,6 +19,7 @@ class LightPreset(SmartModule, LightPresetInterface):
19
19
 
20
20
  REQUIRED_COMPONENT = "preset"
21
21
  QUERY_GETTER_NAME = "get_preset_rules"
22
+ MINIMUM_UPDATE_INTERVAL_SECS = 60
22
23
 
23
24
  SYS_INFO_STATE_KEY = "preset_state"
24
25
 
@@ -113,6 +114,7 @@ class LightPreset(SmartModule, LightPresetInterface):
113
114
  raise ValueError(f"{preset_name} is not a valid preset: {self.preset_list}")
114
115
  await self._device.modules[SmartModule.Light].set_state(preset)
115
116
 
117
+ @allow_update_after
116
118
  async def save_preset(
117
119
  self,
118
120
  preset_name: str,
@@ -140,7 +142,7 @@ class LightPreset(SmartModule, LightPresetInterface):
140
142
  """Query to execute during the update cycle."""
141
143
  if self._state_in_sysinfo: # Child lights can have states in the child info
142
144
  return {}
143
- return {self.QUERY_GETTER_NAME: None}
145
+ return {self.QUERY_GETTER_NAME: {"start_index": 0}}
144
146
 
145
147
  async def _check_supported(self):
146
148
  """Additional check to see if the module is supported by the device.
@@ -5,7 +5,7 @@ from __future__ import annotations
5
5
  from typing import TYPE_CHECKING
6
6
 
7
7
  from ..effects import EFFECT_MAPPING, EFFECT_NAMES, SmartLightEffect
8
- from ..smartmodule import Module, SmartModule
8
+ from ..smartmodule import Module, SmartModule, allow_update_after
9
9
 
10
10
  if TYPE_CHECKING:
11
11
  from ..smartdevice import SmartDevice
@@ -84,6 +84,7 @@ class LightStripEffect(SmartModule, SmartLightEffect):
84
84
  """
85
85
  return self._effect_list
86
86
 
87
+ @allow_update_after
87
88
  async def set_effect(
88
89
  self,
89
90
  effect: str,
@@ -126,6 +127,7 @@ class LightStripEffect(SmartModule, SmartLightEffect):
126
127
 
127
128
  await self.set_custom_effect(effect_dict)
128
129
 
130
+ @allow_update_after
129
131
  async def set_custom_effect(
130
132
  self,
131
133
  effect_dict: dict,
@@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, TypedDict
6
6
 
7
7
  from ...exceptions import KasaException
8
8
  from ...feature import Feature
9
- from ..smartmodule import SmartModule
9
+ from ..smartmodule import SmartModule, allow_update_after
10
10
 
11
11
  if TYPE_CHECKING:
12
12
  from ..smartdevice import SmartDevice
@@ -23,6 +23,7 @@ class LightTransition(SmartModule):
23
23
 
24
24
  REQUIRED_COMPONENT = "on_off_gradually"
25
25
  QUERY_GETTER_NAME = "get_on_off_gradually_info"
26
+ MINIMUM_UPDATE_INTERVAL_SECS = 60
26
27
  MAXIMUM_DURATION = 60
27
28
 
28
29
  # Key in sysinfo that indicates state can be retrieved from there.
@@ -136,6 +137,7 @@ class LightTransition(SmartModule):
136
137
  "max_duration": off_max,
137
138
  }
138
139
 
140
+ @allow_update_after
139
141
  async def set_enabled(self, enable: bool):
140
142
  """Enable gradual on/off."""
141
143
  if not self._supports_on_and_off:
@@ -168,6 +170,7 @@ class LightTransition(SmartModule):
168
170
  # v3 added max_duration, we default to 60 when it's not available
169
171
  return self._on_state["max_duration"]
170
172
 
173
+ @allow_update_after
171
174
  async def set_turn_on_transition(self, seconds: int):
172
175
  """Set turn on transition in seconds.
173
176
 
@@ -203,6 +206,7 @@ class LightTransition(SmartModule):
203
206
  # v3 added max_duration, we default to 60 when it's not available
204
207
  return self._off_state["max_duration"]
205
208
 
209
+ @allow_update_after
206
210
  async def set_turn_off_transition(self, seconds: int):
207
211
  """Set turn on transition in seconds.
208
212
 
@@ -230,7 +234,7 @@ class LightTransition(SmartModule):
230
234
  if self._state_in_sysinfo:
231
235
  return {}
232
236
  else:
233
- return {self.QUERY_GETTER_NAME: None}
237
+ return {self.QUERY_GETTER_NAME: {}}
234
238
 
235
239
  async def _check_supported(self):
236
240
  """Additional check to see if the module is supported by the device."""
@@ -32,6 +32,10 @@ class ReportMode(SmartModule):
32
32
  )
33
33
  )
34
34
 
35
+ def query(self) -> dict:
36
+ """Query to execute during the update cycle."""
37
+ return {}
38
+
35
39
  @property
36
40
  def report_interval(self):
37
41
  """Reporting interval of a sensor device."""
@@ -4,15 +4,10 @@ from __future__ import annotations
4
4
 
5
5
  import logging
6
6
  from enum import Enum
7
- from typing import TYPE_CHECKING
8
7
 
9
8
  from ...feature import Feature
10
9
  from ..smartmodule import SmartModule
11
10
 
12
- if TYPE_CHECKING:
13
- from ..smartdevice import SmartDevice
14
-
15
-
16
11
  _LOGGER = logging.getLogger(__name__)
17
12
 
18
13
 
@@ -31,11 +26,11 @@ class TemperatureControl(SmartModule):
31
26
 
32
27
  REQUIRED_COMPONENT = "temp_control"
33
28
 
34
- def __init__(self, device: SmartDevice, module: str):
35
- super().__init__(device, module)
29
+ def _initialize_features(self):
30
+ """Initialize features after the initial update."""
36
31
  self._add_feature(
37
32
  Feature(
38
- device,
33
+ self._device,
39
34
  id="target_temperature",
40
35
  name="Target temperature",
41
36
  container=self,
@@ -50,7 +45,7 @@ class TemperatureControl(SmartModule):
50
45
  # TODO: this might belong into its own module, temperature_correction?
51
46
  self._add_feature(
52
47
  Feature(
53
- device,
48
+ self._device,
54
49
  id="temperature_offset",
55
50
  name="Temperature offset",
56
51
  container=self,
@@ -65,7 +60,7 @@ class TemperatureControl(SmartModule):
65
60
 
66
61
  self._add_feature(
67
62
  Feature(
68
- device,
63
+ self._device,
69
64
  id="state",
70
65
  name="State",
71
66
  container=self,
@@ -78,7 +73,7 @@ class TemperatureControl(SmartModule):
78
73
 
79
74
  self._add_feature(
80
75
  Feature(
81
- device,
76
+ self._device,
82
77
  id="thermostat_mode",
83
78
  name="Thermostat mode",
84
79
  container=self,
@@ -109,23 +104,24 @@ class TemperatureControl(SmartModule):
109
104
  if self._device.sys_info.get("frost_protection_on", False):
110
105
  return ThermostatState.Off
111
106
 
112
- states = self._device.sys_info["trv_states"]
107
+ states = self.states
113
108
 
114
109
  # If the states is empty, the device is idling
115
110
  if not states:
116
111
  return ThermostatState.Idle
117
112
 
113
+ # Discard known extra states, and report on unknown extra states
114
+ states.discard("low_battery")
118
115
  if len(states) > 1:
119
- _LOGGER.warning(
120
- "Got multiple states (%s), using the first one: %s", states, states[0]
121
- )
116
+ _LOGGER.warning("Got multiple states: %s", states)
122
117
 
123
- state = states[0]
124
- try:
125
- return ThermostatState(state)
126
- except: # noqa: E722
127
- _LOGGER.warning("Got unknown state: %s", state)
128
- return ThermostatState.Unknown
118
+ # Return the first known state
119
+ for state in ThermostatState:
120
+ if state.value in states:
121
+ return state
122
+
123
+ _LOGGER.warning("Got unknown state: %s", states)
124
+ return ThermostatState.Unknown
129
125
 
130
126
  @property
131
127
  def allowed_temperature_range(self) -> tuple[int, int]:
@@ -147,6 +143,11 @@ class TemperatureControl(SmartModule):
147
143
  """Return target temperature."""
148
144
  return self._device.sys_info["target_temp"]
149
145
 
146
+ @property
147
+ def states(self) -> set:
148
+ """Return thermostat states."""
149
+ return set(self._device.sys_info["trv_states"])
150
+
150
151
  async def set_target_temperature(self, target: float):
151
152
  """Set target temperature."""
152
153
  if (
@@ -58,6 +58,10 @@ class TemperatureSensor(SmartModule):
58
58
  )
59
59
  )
60
60
 
61
+ def query(self) -> dict:
62
+ """Query to execute during the update cycle."""
63
+ return {}
64
+
61
65
  @property
62
66
  def temperature(self):
63
67
  """Return current humidity in percentage."""
@@ -3,6 +3,7 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import logging
6
+ import time
6
7
  from typing import Any
7
8
 
8
9
  from ..device_type import DeviceType
@@ -46,6 +47,7 @@ class SmartChildDevice(SmartDevice):
46
47
  req.update(mod_query)
47
48
  if req:
48
49
  self._last_update = await self.protocol.query(req)
50
+ self._last_update_time = time.time()
49
51
 
50
52
  @classmethod
51
53
  async def create(cls, parent: SmartDevice, child_info, child_components):