python-tado 0.18.16__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.16/python_tado.egg-info → python_tado-0.18.17}/PKG-INFO +1 -1
  2. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/http.py +45 -14
  3. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/interface/interface.py +5 -0
  4. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/logger.py +2 -6
  5. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/zone/hops_zone.py +11 -34
  6. {python_tado-0.18.16 → python_tado-0.18.17}/pyproject.toml +2 -2
  7. {python_tado-0.18.16 → python_tado-0.18.17/python_tado.egg-info}/PKG-INFO +1 -1
  8. {python_tado-0.18.16 → python_tado-0.18.17}/tests/test_http.py +60 -0
  9. {python_tado-0.18.16 → python_tado-0.18.17}/AUTHORS +0 -0
  10. {python_tado-0.18.16 → python_tado-0.18.17}/LICENSE +0 -0
  11. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/__init__.py +0 -0
  12. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/__main__.py +0 -0
  13. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/const.py +0 -0
  14. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/exceptions.py +0 -0
  15. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/interface/__init__.py +0 -0
  16. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/interface/api/__init__.py +0 -0
  17. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/interface/api/hops_tado.py +0 -0
  18. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/interface/api/my_tado.py +0 -0
  19. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/zone/__init__.py +0 -0
  20. {python_tado-0.18.16 → python_tado-0.18.17}/PyTado/zone/my_zone.py +0 -0
  21. {python_tado-0.18.16 → python_tado-0.18.17}/README.md +0 -0
  22. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/SOURCES.txt +0 -0
  23. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/dependency_links.txt +0 -0
  24. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/entry_points.txt +0 -0
  25. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/not-zip-safe +0 -0
  26. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/requires.txt +0 -0
  27. {python_tado-0.18.16 → python_tado-0.18.17}/python_tado.egg-info/top_level.txt +0 -0
  28. {python_tado-0.18.16 → python_tado-0.18.17}/setup.cfg +0 -0
  29. {python_tado-0.18.16 → python_tado-0.18.17}/tests/test_hops_zone.py +0 -0
  30. {python_tado-0.18.16 → python_tado-0.18.17}/tests/test_my_tado.py +0 -0
  31. {python_tado-0.18.16 → python_tado-0.18.17}/tests/test_my_zone.py +0 -0
  32. {python_tado-0.18.16 → python_tado-0.18.17}/tests/test_tado_interface.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-tado
3
- Version: 0.18.16
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
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
@@ -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,7 @@ 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
199
206
 
200
207
  self._rate_limit: dict[str, str] = {}
201
208
 
@@ -323,23 +330,35 @@ class Http:
323
330
  raise TadoException(e) from e
324
331
 
325
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
+ )
326
342
  return {}
327
343
 
328
- # Retrieve the headers to update the rate limit info
329
- # They're stored in the object memory
330
- if response.headers.get("RateLimit-Policy") is not None:
331
- policy = response.headers["RateLimit-Policy"]
332
- rate_limit = response.headers["RateLimit"]
333
- # Example: RateLimit-Policy': '"perday";q=20000;w=86400'
334
- # Rate limit is stored as follows: 'RateLimit': '"perday";r=15211'
335
- self._rate_limit = {
336
- "per-day": policy.split(";")[1].split("=")[1],
337
- "window-seconds": policy.split(";")[2].split("=")[1],
338
- "remaining": rate_limit.split(";")[1].split("=")[1],
339
- }
344
+ self._store_rate_limit(response)
340
345
 
341
346
  return response.json()
342
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
+
343
362
  def _configure_url(self, request: TadoRequest) -> str:
344
363
  if request.endpoint == Endpoint.MOBILE:
345
364
  url = f"{request.endpoint}{request.command}"
@@ -385,6 +404,12 @@ class Http:
385
404
 
386
405
  self._save_token()
387
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
+
388
413
  return refresh_token
389
414
 
390
415
  def _load_token(self) -> bool:
@@ -599,9 +624,15 @@ class Http:
599
624
  request.action = Action.GET
600
625
  request.domain = Domain.ME
601
626
 
602
- 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}")
603
634
 
604
- return homes_[0]["id"]
635
+ return int(homes_[0]["id"])
605
636
 
606
637
  def _check_x_line_generation(self):
607
638
  # get home info
@@ -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
@@ -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,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "python-tado"
7
- version = "0.18.16"
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" },
@@ -46,7 +46,7 @@ platforms = ["any"]
46
46
  zip-safe = false
47
47
 
48
48
  [tool.black]
49
- line-length = 100
49
+ line-length = 120
50
50
  target-version = ["py311"]
51
51
 
52
52
  [tool.pytype]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-tado
3
- Version: 0.18.16
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
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
@@ -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