python-tado 0.18.15__tar.gz → 0.18.17__tar.gz

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 (32) hide show
  1. {python_tado-0.18.15/python_tado.egg-info → python_tado-0.18.17}/PKG-INFO +2 -2
  2. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/http.py +53 -2
  3. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/interface/api/my_tado.py +2 -2
  4. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/interface/interface.py +9 -0
  5. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/logger.py +2 -6
  6. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/zone/hops_zone.py +11 -34
  7. {python_tado-0.18.15 → python_tado-0.18.17}/pyproject.toml +3 -2
  8. {python_tado-0.18.15 → python_tado-0.18.17/python_tado.egg-info}/PKG-INFO +2 -2
  9. {python_tado-0.18.15 → python_tado-0.18.17}/tests/test_http.py +60 -0
  10. {python_tado-0.18.15 → python_tado-0.18.17}/AUTHORS +0 -0
  11. {python_tado-0.18.15 → python_tado-0.18.17}/LICENSE +0 -0
  12. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/__init__.py +0 -0
  13. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/__main__.py +0 -0
  14. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/const.py +0 -0
  15. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/exceptions.py +0 -0
  16. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/interface/__init__.py +0 -0
  17. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/interface/api/__init__.py +0 -0
  18. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/interface/api/hops_tado.py +0 -0
  19. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/zone/__init__.py +0 -0
  20. {python_tado-0.18.15 → python_tado-0.18.17}/PyTado/zone/my_zone.py +0 -0
  21. {python_tado-0.18.15 → python_tado-0.18.17}/README.md +0 -0
  22. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/SOURCES.txt +0 -0
  23. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/dependency_links.txt +0 -0
  24. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/entry_points.txt +0 -0
  25. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/not-zip-safe +0 -0
  26. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/requires.txt +0 -0
  27. {python_tado-0.18.15 → python_tado-0.18.17}/python_tado.egg-info/top_level.txt +0 -0
  28. {python_tado-0.18.15 → python_tado-0.18.17}/setup.cfg +0 -0
  29. {python_tado-0.18.15 → python_tado-0.18.17}/tests/test_hops_zone.py +0 -0
  30. {python_tado-0.18.15 → python_tado-0.18.17}/tests/test_my_tado.py +0 -0
  31. {python_tado-0.18.15 → python_tado-0.18.17}/tests/test_my_zone.py +0 -0
  32. {python_tado-0.18.15 → python_tado-0.18.17}/tests/test_tado_interface.py +0 -0
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-tado
3
- Version: 0.18.15
3
+ Version: 0.18.17
4
4
  Summary: PyTado from chrism0dwk, modfied by w.malgadey, diplix, michaelarnauts, LenhartStephan, splifter, syssi, andersonshatch, Yippy, p0thi, Coffee2CodeNL, chiefdragon, FilBr, nikilase, albertomontesg, Moritz-Schmidt, palazzem
5
- Author-email: Chris Jewell <chrism0dwk@gmail.com>, "w.malgadey" <w.malgadey@gmail.com>, FilBr <filippo.barba@protonmail.com>
5
+ Author-email: Chris Jewell <chrism0dwk@gmail.com>, "w.malgadey" <w.malgadey@gmail.com>, FilBr <filippo.barba@protonmail.com>, Erwin Douna <e.douna@gmail.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
7
7
  Version 3, 29 June 2007
8
8
 
@@ -9,6 +9,7 @@ import os
9
9
  import pprint
10
10
  import threading
11
11
  import time
12
+ from collections.abc import Callable
12
13
  from datetime import datetime, timedelta, timezone
13
14
  from json import dump as json_dump
14
15
  from json import load as json_load
@@ -158,6 +159,7 @@ class Http:
158
159
  http_session: requests.Session | None = None,
159
160
  debug: bool = False,
160
161
  user_agent: str | None = None,
162
+ token_update_callback: Callable[[str], None] | None = None,
161
163
  ) -> None:
162
164
  """
163
165
  Initialize the HTTP client for interacting with the Tado API.
@@ -172,6 +174,10 @@ class Http:
172
174
  debug (bool): If True, enables debug logging. Defaults to False.
173
175
  user_agent (str | None): Optional user-agent header to use for the HTTP requests.
174
176
  If None, a default user-agent PyTado/<PyTado-version> will be used.
177
+ token_update_callback (Callable[[str], None] | None): Called with the new
178
+ refresh token whenever tado rotates it. tado refresh tokens are single
179
+ use, so a caller that stores the token itself (instead of using
180
+ token_file_path) should save it here, not only after its own calls succeed.
175
181
 
176
182
  Returns:
177
183
  None
@@ -196,6 +202,9 @@ class Http:
196
202
  self._token_refresh: str | None = None
197
203
  self._x_api: bool | None = None
198
204
  self._token_file_path = token_file_path
205
+ self._token_update_callback = token_update_callback
206
+
207
+ self._rate_limit: dict[str, str] = {}
199
208
 
200
209
  if (saved_refresh_token or self._load_token()) and self._refresh_token(
201
210
  refresh_token=saved_refresh_token, force_refresh=True
@@ -256,6 +265,11 @@ class Http:
256
265
  """
257
266
  return self._token_refresh
258
267
 
268
+ @property
269
+ def rate_limit(self) -> dict[str, str]:
270
+ """Retrieve the current rate limit information."""
271
+ return self._rate_limit
272
+
259
273
  def _create_session(self) -> requests.Session:
260
274
  session = requests.Session()
261
275
  session.hooks["response"].append(self._log_response)
@@ -316,10 +330,35 @@ class Http:
316
330
  raise TadoException(e) from e
317
331
 
318
332
  if response.text is None or response.text == "":
333
+ if response.status_code == 429:
334
+ # Rate-limited responses carry an empty body; capture the
335
+ # quota headers and fail loudly so callers can back off.
336
+ self._store_rate_limit(response)
337
+ rate_limit = response.headers.get("RateLimit", "unknown")
338
+ raise requests.exceptions.HTTPError(
339
+ f"Tado API rate limit reached ({rate_limit})",
340
+ response=response,
341
+ )
319
342
  return {}
320
343
 
344
+ self._store_rate_limit(response)
345
+
321
346
  return response.json()
322
347
 
348
+ def _store_rate_limit(self, response: requests.Response) -> None:
349
+ """Store the quota headers of a response in the object memory."""
350
+ policy = response.headers.get("RateLimit-Policy")
351
+ rate_limit = response.headers.get("RateLimit")
352
+ if policy is None or rate_limit is None:
353
+ return
354
+ # Example: RateLimit-Policy': '"perday";q=20000;w=86400'
355
+ # Rate limit is stored as follows: 'RateLimit': '"perday";r=15211'
356
+ self._rate_limit = {
357
+ "per-day": policy.split(";")[1].split("=")[1],
358
+ "window-seconds": policy.split(";")[2].split("=")[1],
359
+ "remaining": rate_limit.split(";")[1].split("=")[1],
360
+ }
361
+
323
362
  def _configure_url(self, request: TadoRequest) -> str:
324
363
  if request.endpoint == Endpoint.MOBILE:
325
364
  url = f"{request.endpoint}{request.command}"
@@ -365,6 +404,12 @@ class Http:
365
404
 
366
405
  self._save_token()
367
406
 
407
+ if self._token_update_callback is not None:
408
+ try:
409
+ self._token_update_callback(str(refresh_token))
410
+ except Exception: # pylint: disable=broad-exception-caught
411
+ _LOGGER.exception("Token update callback failed")
412
+
368
413
  return refresh_token
369
414
 
370
415
  def _load_token(self) -> bool:
@@ -579,9 +624,15 @@ class Http:
579
624
  request.action = Action.GET
580
625
  request.domain = Domain.ME
581
626
 
582
- homes_ = self.request(request)["homes"]
627
+ response = self.request(request)
628
+ if isinstance(response, dict) and "homes" in response:
629
+ homes_ = response["homes"]
630
+ elif isinstance(response, list):
631
+ homes_ = response
632
+ else:
633
+ raise TadoException(f"Unexpected response from the /me endpoint: {response}")
583
634
 
584
- return homes_[0]["id"]
635
+ return int(homes_[0]["id"])
585
636
 
586
637
  def _check_x_line_generation(self):
587
638
  # get home info
@@ -231,7 +231,7 @@ class Tado:
231
231
  request.command = f"zones/{zone:d}/schedule/activeTimetable"
232
232
  request.action = Action.CHANGE
233
233
  request.payload = {"id": timetable}
234
- request.mode = Mode.PLAIN
234
+ request.mode = Mode.OBJECT
235
235
 
236
236
  self._http.request(request)
237
237
 
@@ -258,7 +258,7 @@ class Tado:
258
258
  request.command = f"zones/{zone:d}/schedule/timetables/{timetable:d}/blocks/{day}"
259
259
  request.action = Action.CHANGE
260
260
  request.payload = data
261
- request.mode = Mode.PLAIN
261
+ request.mode = Mode.OBJECT
262
262
 
263
263
  return self._http.request(request)
264
264
 
@@ -5,6 +5,7 @@ PyTado interface abstraction to use app.tado.com or hops.tado.com
5
5
  import datetime
6
6
  import functools
7
7
  import warnings
8
+ from collections.abc import Callable
8
9
 
9
10
  import requests
10
11
 
@@ -56,6 +57,7 @@ class Tado:
56
57
  http_session: requests.Session | None = None,
57
58
  debug: bool = False,
58
59
  user_agent: str | None = None,
60
+ token_update_callback: Callable[[str], None] | None = None,
59
61
  ):
60
62
  """
61
63
  Initializes the interface class.
@@ -71,6 +73,8 @@ class Tado:
71
73
  debug (bool, optional): Flag to enable or disable debug mode. Defaults to False.
72
74
  user_agent (str | None): Optional user-agent header to use for the HTTP requests.
73
75
  If None, a default user-agent PyTado/<PyTado-version> will be used.
76
+ token_update_callback (Callable[[str], None] | None): Called with the new refresh
77
+ token every time tado rotates it, so callers can store it at once.
74
78
  """
75
79
 
76
80
  self._http = Http(
@@ -79,6 +83,7 @@ class Tado:
79
83
  http_session=http_session,
80
84
  debug=debug,
81
85
  user_agent=user_agent,
86
+ token_update_callback=token_update_callback,
82
87
  )
83
88
  self._api: API.Tado | API.TadoX | None = None
84
89
  self._debug = debug
@@ -94,6 +99,10 @@ class Tado:
94
99
  """Returns the URL for device verification."""
95
100
  return self._http.device_verification_url
96
101
 
102
+ def rate_limit_info(self) -> dict[str, str]:
103
+ """Retrieve the current rate limit information."""
104
+ return self._http.rate_limit
105
+
97
106
  def device_activation_status(self) -> DeviceActivationStatus:
98
107
  """Returns the status of the device activation."""
99
108
  return self._http.device_activation_status
@@ -35,16 +35,12 @@ class Logger(logging.Logger):
35
35
  """
36
36
  Do the actual filtering
37
37
  """
38
- original = logging.Formatter.format(
39
- self, record
40
- ) # call parent method
38
+ original = logging.Formatter.format(self, record) # call parent method
41
39
  return self._filter(original)
42
40
 
43
41
  def __init__(self, name: str, level=logging.NOTSET):
44
42
  super().__init__(name)
45
43
  log_sh = logging.StreamHandler()
46
- log_fmt = self.SensitiveFormatter(
47
- fmt="%(name)s :: %(levelname)-8s :: %(message)s"
48
- )
44
+ log_fmt = self.SensitiveFormatter(fmt="%(name)s :: %(levelname)-8s :: %(message)s")
49
45
  log_sh.setFormatter(log_fmt)
50
46
  self.addHandler(log_sh)
@@ -46,15 +46,11 @@ class TadoXZone(TadoZone):
46
46
  kwargs["current_temp"] = float(inside_temp["value"])
47
47
  kwargs["current_temp_timestamp"] = None
48
48
  if "precision" in sensor_data["insideTemperature"]:
49
- kwargs["precision"] = sensor_data["insideTemperature"][
50
- "precision"
51
- ]["celsius"]
49
+ kwargs["precision"] = sensor_data["insideTemperature"]["precision"]["celsius"]
52
50
 
53
51
  # X-specific humidity parsing
54
52
  if "humidity" in sensor_data:
55
- kwargs["current_humidity"] = float(
56
- sensor_data["humidity"]["percentage"]
57
- )
53
+ kwargs["current_humidity"] = float(sensor_data["humidity"]["percentage"])
58
54
  kwargs["current_humidity_timestamp"] = None
59
55
 
60
56
  # Tado mode processing
@@ -74,13 +70,8 @@ class TadoXZone(TadoZone):
74
70
  # Setting processing
75
71
  if "setting" in data:
76
72
  # X-specific temperature setting
77
- if (
78
- "temperature" in data["setting"]
79
- and data["setting"]["temperature"] is not None
80
- ):
81
- kwargs["target_temp"] = float(
82
- data["setting"]["temperature"]["value"]
83
- )
73
+ if "temperature" in data["setting"] and data["setting"]["temperature"] is not None:
74
+ kwargs["target_temp"] = float(data["setting"]["temperature"]["value"])
84
75
 
85
76
  setting = data["setting"]
86
77
 
@@ -106,9 +97,7 @@ class TadoXZone(TadoZone):
106
97
  else:
107
98
  kwargs["current_hvac_action"] = CONST_HVAC_HEAT
108
99
 
109
- kwargs["heating_power_percentage"] = data["heatingPower"][
110
- "percentage"
111
- ]
100
+ kwargs["heating_power_percentage"] = data["heatingPower"]["percentage"]
112
101
  else:
113
102
  kwargs["heating_power_percentage"] = 0
114
103
  kwargs["current_hvac_action"] = CONST_HVAC_OFF
@@ -117,15 +106,9 @@ class TadoXZone(TadoZone):
117
106
  if "manualControlTermination" in data:
118
107
  manual_termination = data["manualControlTermination"]
119
108
  if manual_termination:
120
- kwargs["current_hvac_mode"] = (
121
- CONST_MODE_HEAT if power == "ON" else CONST_MODE_OFF
122
- )
123
- kwargs["overlay_termination_type"] = manual_termination[
124
- "type"
125
- ]
126
- kwargs["overlay_termination_timestamp"] = (
127
- manual_termination["projectedExpiry"]
128
- )
109
+ kwargs["current_hvac_mode"] = CONST_MODE_HEAT if power == "ON" else CONST_MODE_OFF
110
+ kwargs["overlay_termination_type"] = manual_termination["type"]
111
+ kwargs["overlay_termination_timestamp"] = manual_termination["projectedExpiry"]
129
112
  else:
130
113
  kwargs["current_hvac_mode"] = CONST_MODE_SMART_SCHEDULE
131
114
  kwargs["overlay_termination_type"] = None
@@ -133,17 +116,11 @@ class TadoXZone(TadoZone):
133
116
  else:
134
117
  kwargs["current_hvac_mode"] = CONST_MODE_SMART_SCHEDULE
135
118
 
136
- kwargs["available"] = (
137
- kwargs.get("connection") != CONST_CONNECTION_OFFLINE
138
- )
119
+ kwargs["available"] = kwargs.get("connection") != CONST_CONNECTION_OFFLINE
139
120
 
140
121
  # Termination conditions
141
122
  if "terminationCondition" in data:
142
- kwargs["default_overlay_termination_type"] = data[
143
- "terminationCondition"
144
- ].get("type", None)
145
- kwargs["default_overlay_termination_duration"] = data[
146
- "terminationCondition"
147
- ].get("durationInSeconds", None)
123
+ kwargs["default_overlay_termination_type"] = data["terminationCondition"].get("type", None)
124
+ kwargs["default_overlay_termination_duration"] = data["terminationCondition"].get("durationInSeconds", None)
148
125
 
149
126
  return cls(zone_id=zone_id, **kwargs)
@@ -4,12 +4,13 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-tado"
7
- version = "0.18.15"
7
+ version = "0.18.17"
8
8
  description = "PyTado from chrism0dwk, modfied by w.malgadey, diplix, michaelarnauts, LenhartStephan, splifter, syssi, andersonshatch, Yippy, p0thi, Coffee2CodeNL, chiefdragon, FilBr, nikilase, albertomontesg, Moritz-Schmidt, palazzem"
9
9
  authors = [
10
10
  { name = "Chris Jewell", email = "chrism0dwk@gmail.com" },
11
11
  { name = "w.malgadey", email = "w.malgadey@gmail.com" },
12
12
  { name = "FilBr", email = "filippo.barba@protonmail.com" },
13
+ { name = "Erwin Douna", email = "e.douna@gmail.com" },
13
14
  ]
14
15
  dependencies = ["requests"]
15
16
  requires-python = ">=3.11"
@@ -45,7 +46,7 @@ platforms = ["any"]
45
46
  zip-safe = false
46
47
 
47
48
  [tool.black]
48
- line-length = 100
49
+ line-length = 120
49
50
  target-version = ["py311"]
50
51
 
51
52
  [tool.pytype]
@@ -1,8 +1,8 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-tado
3
- Version: 0.18.15
3
+ Version: 0.18.17
4
4
  Summary: PyTado from chrism0dwk, modfied by w.malgadey, diplix, michaelarnauts, LenhartStephan, splifter, syssi, andersonshatch, Yippy, p0thi, Coffee2CodeNL, chiefdragon, FilBr, nikilase, albertomontesg, Moritz-Schmidt, palazzem
5
- Author-email: Chris Jewell <chrism0dwk@gmail.com>, "w.malgadey" <w.malgadey@gmail.com>, FilBr <filippo.barba@protonmail.com>
5
+ Author-email: Chris Jewell <chrism0dwk@gmail.com>, "w.malgadey" <w.malgadey@gmail.com>, FilBr <filippo.barba@protonmail.com>, Erwin Douna <e.douna@gmail.com>
6
6
  License: GNU GENERAL PUBLIC LICENSE
7
7
  Version 3, 29 June 2007
8
8
 
@@ -5,6 +5,7 @@ import io
5
5
  import json
6
6
  import unittest
7
7
  from unittest import mock
8
+ import requests
8
9
  import responses
9
10
 
10
11
  from PyTado.const import CLIENT_ID_DEVICE
@@ -248,6 +249,33 @@ class TestHttp(unittest.TestCase):
248
249
  self.assertTrue(result)
249
250
  mock_sleep.assert_called_once_with(5)
250
251
 
252
+ @responses.activate
253
+ def test_token_update_callback_gets_every_rotated_token(self):
254
+ """The callback sees each new refresh token, including the first one."""
255
+ seen: list[str] = []
256
+ instance = Http(saved_refresh_token="saved", token_update_callback=seen.append)
257
+ self.assertEqual(seen, ["another_value"])
258
+
259
+ responses.replace(
260
+ responses.POST,
261
+ "https://login.tado.com/oauth2/token",
262
+ json={"access_token": "a2", "expires_in": 600, "refresh_token": "r2"},
263
+ status=200,
264
+ )
265
+ instance._refresh_at = datetime.now(timezone.utc) - timedelta(seconds=1)
266
+ instance._refresh_token()
267
+ self.assertEqual(seen, ["another_value", "r2"])
268
+
269
+ @responses.activate
270
+ def test_token_update_callback_error_is_logged_not_raised(self):
271
+ """A broken callback must not break authentication."""
272
+
273
+ def broken(token: str) -> None:
274
+ raise RuntimeError("storage full")
275
+
276
+ instance = Http(saved_refresh_token="saved", token_update_callback=broken)
277
+ self.assertEqual(instance.device_activation_status, "COMPLETED")
278
+
251
279
  @responses.activate
252
280
  def test_save_refresh_token(self):
253
281
  """Test if refresh token is saved."""
@@ -304,3 +332,35 @@ class TestHttp(unittest.TestCase):
304
332
  mock_device_ready.assert_called_once()
305
333
  mock_load_token.assert_not_called()
306
334
  mock_login_device_flow.assert_not_called()
335
+
336
+ @responses.activate
337
+ def test_request_rate_limited_empty_body(self):
338
+ """A 429 with an empty body raises HTTPError and stores quota headers."""
339
+ responses.replace(
340
+ responses.GET,
341
+ "https://my.tado.com/api/v2/me",
342
+ body="",
343
+ status=429,
344
+ headers={
345
+ "RateLimit-Policy": '"perday";q=20000;w=86400',
346
+ "RateLimit": '"perday";r=0',
347
+ },
348
+ )
349
+ http = Http()
350
+ request = TadoRequest(domain=Domain.ME)
351
+ with self.assertRaises(requests.exceptions.HTTPError):
352
+ http.request(request)
353
+ self.assertEqual(http._rate_limit["remaining"], "0")
354
+ self.assertEqual(http._rate_limit["per-day"], "20000")
355
+
356
+ @responses.activate
357
+ def test_get_id_list_response(self):
358
+ """_get_id accepts a bare list of homes in the /me response."""
359
+ responses.replace(
360
+ responses.GET,
361
+ "https://my.tado.com/api/v2/me",
362
+ json=[{"id": 4321}],
363
+ status=200,
364
+ )
365
+ http = Http()
366
+ self.assertEqual(http._get_id(), 4321)
File without changes
File without changes
File without changes
File without changes