python-tado 0.19.4__tar.gz → 1.0.1rc1__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 (49) hide show
  1. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PKG-INFO +39 -2
  2. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/factory/initializer.py +14 -2
  3. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/http.py +165 -89
  4. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/api/base_tado.py +17 -7
  5. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/api/hops_tado.py +6 -0
  6. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/api/my_tado.py +2 -1
  7. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/interface.py +6 -0
  8. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/util.py +1 -1
  9. python_tado-1.0.1rc1/PyTado/token_manager/__init__.py +15 -0
  10. python_tado-1.0.1rc1/PyTado/token_manager/can_manage_device_activation.py +35 -0
  11. python_tado-1.0.1rc1/PyTado/token_manager/device_token_manager.py +177 -0
  12. python_tado-1.0.1rc1/PyTado/token_manager/dummy_device_manager.py +21 -0
  13. python_tado-1.0.1rc1/PyTado/token_manager/file_token_manager.py +105 -0
  14. python_tado-1.0.1rc1/PyTado/token_manager/token_manager_interface.py +20 -0
  15. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/zone/base_zone.py +1 -1
  16. {python_tado-0.19.4 → python_tado-1.0.1rc1}/README.md +35 -0
  17. {python_tado-0.19.4 → python_tado-1.0.1rc1}/pyproject.toml +6 -2
  18. {python_tado-0.19.4 → python_tado-1.0.1rc1}/AUTHORS +0 -0
  19. {python_tado-0.19.4 → python_tado-1.0.1rc1}/LICENSE +0 -0
  20. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/__init__.py +0 -0
  21. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/__main__.py +0 -0
  22. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/const.py +0 -0
  23. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/exceptions.py +0 -0
  24. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/factory/__init__.py +0 -0
  25. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/__init__.py +0 -0
  26. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/interface/api/__init__.py +0 -0
  27. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/logger.py +0 -0
  28. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/__init__.py +0 -0
  29. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/common/__init__.py +0 -0
  30. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/common/schedule.py +0 -0
  31. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/historic.py +0 -0
  32. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/home.py +0 -0
  33. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/line_x/__init__.py +0 -0
  34. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/line_x/device.py +0 -0
  35. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/line_x/installation.py +0 -0
  36. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/line_x/room.py +0 -0
  37. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/line_x/schedule.py +0 -0
  38. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/__init__.py +0 -0
  39. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/boiler.py +0 -0
  40. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/device.py +0 -0
  41. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/flow_temperature_optimization.py +0 -0
  42. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/home.py +0 -0
  43. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/schedule.py +0 -0
  44. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/pre_line_x/zone.py +0 -0
  45. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/models/return_models.py +0 -0
  46. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/types.py +0 -0
  47. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/zone/__init__.py +0 -0
  48. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/zone/hops_zone.py +0 -0
  49. {python_tado-0.19.4 → python_tado-1.0.1rc1}/PyTado/zone/my_zone.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-tado
3
- Version: 0.19.4
3
+ Version: 1.0.1rc1
4
4
  Summary: PyTado from chrism0dwk, modified by w.malgadey, diplix, michaelarnauts, LenhartStephan, splifter, syssi, andersonshatch, Yippy, p0thi, Coffee2CodeNL, chiefdragon, FilBr, nikilase, albertomontesg, Moritz-Schmidt, palazzem
5
5
  License: GPL-3.0-or-later
6
6
  License-File: AUTHORS
@@ -9,7 +9,7 @@ Keywords: tado
9
9
  Author: Chris Jewell
10
10
  Author-email: chrism0dwk@gmail.com
11
11
  Requires-Python: >=3.11
12
- Classifier: Development Status :: 4 - Beta
12
+ Classifier: Development Status :: 5 - Production/Stable
13
13
  Classifier: Intended Audience :: Developers
14
14
  Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
15
15
  Classifier: License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)
@@ -37,8 +37,10 @@ Requires-Dist: pytype ; extra == "dev" or extra == "all"
37
37
  Requires-Dist: requests
38
38
  Requires-Dist: responses ; extra == "test" or extra == "all"
39
39
  Requires-Dist: types-requests ; extra == "dev" or extra == "all"
40
+ Project-URL: Changelog, https://github.com/wmalgadey/PyTado/releases
40
41
  Project-URL: Documentation, https://wmalgadey.github.io/PyTado/
41
42
  Project-URL: Homepage, https://github.com/wmalgadey/PyTado
43
+ Project-URL: Migration guide, https://github.com/wmalgadey/PyTado/blob/master/MigrationV1.0.0.md
42
44
  Project-URL: Repository, https://github.com/wmalgadey/PyTado
43
45
  Description-Content-Type: text/markdown
44
46
 
@@ -73,6 +75,26 @@ otherwise) from Tado, and have no business interest with them. This software is
73
75
  the GNU Public License version 3, and should therefore not be used where it may endanger life, financial stakes, or
74
76
  cause discomfort and inconvenience to others.
75
77
 
78
+ ## Versions
79
+
80
+ | Line | API | Status | Branch |
81
+ | ---- | --- | ------ | ------ |
82
+ | **1.x** (from 1.0.1) | New typed API: pydantic models instead of `dict`, separate clients for tado v2/v3/v3+ (`Tado`) and tado X (`TadoX`), `TadoClientInitializer`, token managers that share one login between processes. Needs `pydantic` 2. | Under active development | `master` |
83
+ | **0.18.x** | Old API: methods return plain `dict`/`list`, one `Tado` class for all devices. | Maintained, bug fixes and backports | `support/0.18` |
84
+ | **0.19.x** | Same old API as 0.18.x (0.19.0 brought the OAuth device flow, child lock and flow temperature optimization, which were all backported to 0.18.x). | Frozen, use 0.18.x | `support/0.19` |
85
+
86
+ The 1.x API is not compatible with 0.x. See the [migration guide](https://github.com/wmalgadey/PyTado/blob/master/MigrationV1.0.0.md).
87
+
88
+ Pin the line you need, e.g. `python-tado~=0.18.17` for the old API or `python-tado>=1.0.1,<2` for the new one. Until 1.0.1 final is out, the new API is only available as a release candidate: `pip install --pre "python-tado>=1.0.1rc1,<2"`.
89
+
90
+ ### Releases to avoid
91
+
92
+ - **0.19.4** contains the 1.x API by mistake, even though its version number says 0.19. It is yanked on PyPI (since 2026-11-30). Use 0.19.5 (old API) or 1.0.1 or later (new API) instead.
93
+ - **1.0.0** was uploaded to PyPI by mistake (from the 0.19.3 tag) and then deleted. PyPI never accepts a version number twice, so the first stable 1.x release is **1.0.1**.
94
+ - **0.19.3** was never published to PyPI.
95
+
96
+ Release notes for every version are on the [GitHub releases page](https://github.com/wmalgadey/PyTado/releases).
97
+
76
98
  ## Usage
77
99
 
78
100
  As of the 15th of March 2025, Tado has updated their OAuth2 authentication flow. It will now use the device flow, instead of a username/password flow. This means that the user will have to authenticate the device using a browser, and then enter the code that is displayed on the browser into the terminal.
@@ -124,6 +146,21 @@ else:
124
146
  print(f"Login status is {status}")
125
147
  ```
126
148
 
149
+ ### Sharing the login between several processes
150
+
151
+ If several processes on one machine use PyTado (e.g. a service and a CLI), use the
152
+ `DeviceTokenManager`. It stores the refresh token in a per-user data directory (or in
153
+ `data_dir`) and shares a running device activation: the processes show the same code
154
+ instead of each asking tado for a new one, and they pick up the token once one of them
155
+ is activated.
156
+
157
+ ```python
158
+ from PyTado.interface.interface import Tado
159
+ from PyTado.token_manager import DeviceTokenManager
160
+
161
+ tado = Tado(token_manager=DeviceTokenManager())
162
+ ```
163
+
127
164
  ## Example code
128
165
 
129
166
  ```python
@@ -2,13 +2,14 @@
2
2
  PyTado API factory to use app.tado.com or hops.tado.com
3
3
  """
4
4
 
5
- from typing import Self
5
+ from typing import Callable, Self
6
6
 
7
7
  import requests
8
8
 
9
9
  import PyTado.interface.api as API
10
10
  from PyTado.exceptions import TadoException
11
11
  from PyTado.http import DeviceActivationStatus, Http
12
+ from PyTado.token_manager import TokenManagerInterface
12
13
 
13
14
 
14
15
  class TadoClientInitializer:
@@ -26,7 +27,12 @@ class TadoClientInitializer:
26
27
  saved_refresh_token: str | None = None,
27
28
  http_session: requests.Session | None = None,
28
29
  debug: bool = False,
30
+ user_agent: str | None = None,
31
+ client_id: str | None = None,
32
+ token_update_callback: Callable[[str], None] | None = None,
33
+ token_manager: TokenManagerInterface | None = None,
29
34
  ):
35
+ """Takes the same login options as PyTado.interface.Tado."""
30
36
  self.token_file_path = token_file_path
31
37
  self.saved_refresh_token = saved_refresh_token
32
38
  self.http_session = http_session
@@ -36,6 +42,10 @@ class TadoClientInitializer:
36
42
  saved_refresh_token=saved_refresh_token,
37
43
  http_session=http_session,
38
44
  debug=debug,
45
+ user_agent=user_agent,
46
+ client_id=client_id,
47
+ token_update_callback=token_update_callback,
48
+ token_manager=token_manager,
39
49
  )
40
50
 
41
51
  def get_verification_url(self) -> str | None:
@@ -77,8 +87,10 @@ class TadoClientInitializer:
77
87
 
78
88
  self.device_activation()
79
89
 
90
+ # device_activation() changes the status; mypy narrows it too eagerly
80
91
  if (
81
- self.http.device_activation_status == DeviceActivationStatus.COMPLETED
92
+ self.http.device_activation_status # type: ignore[comparison-overlap]
93
+ == DeviceActivationStatus.COMPLETED
82
94
  ): # pyright: ignore[reportUnnecessaryComparison]
83
95
  print("Device activation completed successfully.")
84
96
  else:
@@ -5,16 +5,12 @@ Do all the API HTTP heavy lifting in this file
5
5
  import enum
6
6
  import json
7
7
  import logging
8
- import os
9
8
  import pprint
10
9
  import threading
11
10
  import time
12
11
  from collections.abc import Callable
13
12
  from dataclasses import dataclass
14
13
  from datetime import datetime, timedelta, timezone
15
- from json import dump as json_dump
16
- from json import load as json_load
17
- from pathlib import Path
18
14
  from typing import Any
19
15
  from urllib.parse import urlencode
20
16
 
@@ -31,6 +27,12 @@ from PyTado.exceptions import (
31
27
  TadoWrongCredentialsException,
32
28
  )
33
29
  from PyTado.logger import Logger
30
+ from PyTado.token_manager import (
31
+ CanManageDeviceActivation,
32
+ DummyDeviceManager,
33
+ FileTokenManager,
34
+ TokenManagerInterface,
35
+ )
34
36
 
35
37
  _LOGGER = Logger(__name__)
36
38
 
@@ -106,7 +108,7 @@ class TadoXRequest(TadoRequest):
106
108
  def __post_init__(self) -> None:
107
109
  self._action = self.action
108
110
 
109
- @property # type: ignore
111
+ @property # type: ignore[misc]
110
112
  def action(self) -> Action | str:
111
113
  """Get request action for Tado X"""
112
114
  if self._action == Action.CHANGE:
@@ -114,7 +116,7 @@ class TadoXRequest(TadoRequest):
114
116
  return self._action
115
117
 
116
118
  @action.setter
117
- def action(self, value: Action | str) -> None: # type: ignore
119
+ def action(self, value: Action | str) -> None:
118
120
  """Set request action"""
119
121
  self._action = value
120
122
 
@@ -139,7 +141,6 @@ class Http:
139
141
  _username: str
140
142
  _password: str
141
143
  _id: int
142
- _token_refresh: str | None = None
143
144
  _x_api: bool | None = None
144
145
  _user_code: str | None = None
145
146
  _device_verification_url: str | None = None
@@ -157,6 +158,7 @@ class Http:
157
158
  user_agent: str | None = None,
158
159
  client_id: str | None = None,
159
160
  token_update_callback: Callable[[str], None] | None = None,
161
+ token_manager: TokenManagerInterface | None = None,
160
162
  ) -> None:
161
163
  """
162
164
  Initialize the HTTP client for interacting with the Tado API.
@@ -182,6 +184,11 @@ class Http:
182
184
  None
183
185
  """
184
186
 
187
+ if token_manager is not None and (token_file_path or saved_refresh_token):
188
+ raise ValueError(
189
+ "Cannot provide both token_manager and token_file_path/saved_refresh_token."
190
+ )
191
+
185
192
  if debug:
186
193
  _LOGGER.setLevel(logging.DEBUG)
187
194
  else:
@@ -216,20 +223,30 @@ class Http:
216
223
  self._device_activation_status = DeviceActivationStatus.NOT_STARTED
217
224
  self._expires_at: datetime | None = None
218
225
 
219
- self._id: int | None = None
220
- self._token_refresh: str | None = None
226
+ self._id = None # type: ignore[assignment] # set during login
221
227
  self._rate_limit: dict[str, str] = {}
222
228
  self._x_api: bool | None = None
223
- self._token_file_path = token_file_path
229
+ self._token_manager: TokenManagerInterface = (
230
+ FileTokenManager(token_file_path, saved_refresh_token)
231
+ if token_manager is None
232
+ else token_manager
233
+ )
234
+ # Sharing a device activation needs support from the token manager.
235
+ self._device_manager: CanManageDeviceActivation = (
236
+ self._token_manager
237
+ if isinstance(self._token_manager, CanManageDeviceActivation)
238
+ else DummyDeviceManager()
239
+ )
224
240
  self._client_id = client_id or CLIENT_ID_DEVICE
225
241
  self._token_update_callback = token_update_callback
226
242
 
227
243
  self._session.mount("https://", self._http_adapter)
228
244
  self._session.mount("http://", self._http_adapter)
229
245
 
230
- if saved_refresh_token or self._load_token():
246
+ stored_refresh_token = self._token_manager.get_token()
247
+ if stored_refresh_token:
231
248
  if self._refresh_token(
232
- refresh_token=saved_refresh_token, force_refresh=True
249
+ refresh_token=stored_refresh_token, force_refresh=True
233
250
  ):
234
251
  # The refresh worked, so the token is good. If /me fails now (rate
235
252
  # limit, server error) the error is raised and the freshly rotated
@@ -291,7 +308,7 @@ class Http:
291
308
  Returns:
292
309
  str | None: The current refresh token, or None if not available.
293
310
  """
294
- return self._token_refresh
311
+ return self._token_manager.get_token()
295
312
 
296
313
  @property
297
314
  def rate_limit(self) -> dict[str, str]:
@@ -460,7 +477,6 @@ class Http:
460
477
  expires_in = float(data["expires_in"])
461
478
  refresh_token = data["refresh_token"]
462
479
 
463
- self._token_refresh = refresh_token
464
480
  self._refresh_at = datetime.now(timezone.utc)
465
481
  self._refresh_at = self._refresh_at + timedelta(seconds=expires_in)
466
482
  # We subtract 30 seconds from the correct refresh time.
@@ -469,7 +485,7 @@ class Http:
469
485
 
470
486
  self._headers["Authorization"] = f"Bearer {access_token}"
471
487
 
472
- self._save_token()
488
+ self._token_manager.set_oauth_data(data)
473
489
 
474
490
  if self._token_update_callback is not None:
475
491
  try:
@@ -479,24 +495,6 @@ class Http:
479
495
 
480
496
  return str(refresh_token)
481
497
 
482
- def _load_token(self) -> bool:
483
- """Load the refresh token from a file."""
484
-
485
- if not self._token_file_path or not os.path.exists(self._token_file_path):
486
- return False
487
-
488
- try:
489
- with open(self._token_file_path, encoding="utf-8") as f:
490
- data = json_load(f)
491
- self._token_refresh = data.get("refresh_token")
492
-
493
- _LOGGER.debug("Refresh token loaded from %s", self._token_file_path)
494
-
495
- return True
496
- except (OSError, json.JSONDecodeError) as e:
497
- _LOGGER.error("Failed to load refresh token: %s", e)
498
- raise TadoException(e) from e
499
-
500
498
  def _refresh_token(
501
499
  self, refresh_token: str | None = None, force_refresh: bool = False
502
500
  ) -> bool:
@@ -522,8 +520,12 @@ class Http:
522
520
  # The expiry check runs again under the lock, so the threads that waited
523
521
  # use the token the first thread got instead of refreshing with the
524
522
  # refresh token it just used up (tado answers that with HTTP 400).
525
- with self._refresh_lock:
526
- return self._refresh_token_locked(refresh_token, force_refresh)
523
+ # Clients in other processes that share the token are kept apart by the
524
+ # device manager's lock (always taken first, so the order is the same
525
+ # everywhere). It may already be held by this thread.
526
+ with self._device_manager.lock_device_activation():
527
+ with self._refresh_lock:
528
+ return self._refresh_token_locked(refresh_token, force_refresh)
527
529
 
528
530
  def _refresh_token_locked(
529
531
  self, refresh_token: str | None, force_refresh: bool
@@ -536,7 +538,9 @@ class Http:
536
538
  data = {
537
539
  "client_id": self._client_id,
538
540
  "grant_type": "refresh_token",
539
- "refresh_token": refresh_token or self._token_refresh,
541
+ # Read again: a client in another process may have rotated the token
542
+ # while this one waited for the lock.
543
+ "refresh_token": self._token_manager.get_token() or refresh_token,
540
544
  }
541
545
  self._session.close()
542
546
  self._session = self._create_session()
@@ -581,33 +585,51 @@ class Http:
581
585
 
582
586
  return True
583
587
 
584
- def _save_token(self) -> None:
585
- """Save the refresh token to a file."""
586
- if not self._token_file_path or not self._token_refresh:
587
- return
588
-
589
- try:
590
- token_dir = os.path.dirname(self._token_file_path)
591
- if token_dir and not os.path.exists(token_dir):
592
- Path(token_dir).mkdir(parents=True, exist_ok=True)
593
-
594
- with open(self._token_file_path, "w", encoding="utf-8") as f:
595
- json_dump(
596
- {"refresh_token": self._token_refresh},
597
- f,
598
- )
599
-
600
- _LOGGER.debug("Refresh token saved to %s", self._token_file_path)
601
- except Exception as e:
602
- _LOGGER.error("Failed to save refresh token: %s", e)
603
- raise TadoException(e) from e
604
-
605
588
  def _login_device_flow(self) -> DeviceActivationStatus:
606
589
  """Start the login to the API using the device flow"""
607
590
 
608
591
  if self._device_activation_status != DeviceActivationStatus.NOT_STARTED:
609
592
  raise TadoException("The device has been started already")
610
593
 
594
+ # Hold the lock until the new activation is stored, so that clients starting
595
+ # at the same moment find it instead of each requesting their own.
596
+ with self._device_manager.lock_device_activation():
597
+ device_flow_data = self._get_pending_device_data()
598
+ if device_flow_data is None:
599
+ device_flow_data = self._request_device_authorization()
600
+ self._device_manager.set_pending_device_data(device_flow_data)
601
+
602
+ return self._set_device_flow_data(device_flow_data)
603
+
604
+ def _get_pending_device_data(self) -> dict[str, Any] | None:
605
+ """Return the shared device activation, if there is one that has not expired."""
606
+ device_flow_data = self._device_manager.get_pending_device_data()
607
+ if not device_flow_data:
608
+ return None
609
+
610
+ try:
611
+ expires_at = datetime.fromisoformat(device_flow_data["expires_at"])
612
+ usable = all(
613
+ isinstance(device_flow_data.get(key), str) and device_flow_data[key]
614
+ for key in ("device_code", "user_code", "verification_uri")
615
+ ) and isinstance(device_flow_data.get("interval", 0), (int, float))
616
+ except (KeyError, TypeError, ValueError):
617
+ usable = False
618
+
619
+ if not usable:
620
+ _LOGGER.warning("Ignoring unusable pending device data")
621
+ return None
622
+
623
+ if expires_at.tzinfo is None:
624
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
625
+ if expires_at <= datetime.now(timezone.utc):
626
+ return None
627
+
628
+ _LOGGER.debug("Using the pending device activation of another client")
629
+ return device_flow_data
630
+
631
+ def _request_device_authorization(self) -> dict[str, Any]:
632
+ """Ask tado for a new device activation."""
611
633
  url = "https://login.tado.com/oauth2/device_authorize"
612
634
  data = {
613
635
  "client_id": self._client_id,
@@ -633,12 +655,26 @@ class Http:
633
655
  f"Login failed. Status code: {response.status_code} and reason: {response.reason}"
634
656
  )
635
657
 
636
- self._device_flow_data = response.json()
637
- _LOGGER.debug("Device flow response: %s", self._device_flow_data)
658
+ device_flow_data: dict[str, Any] = response.json()
659
+ _LOGGER.debug("Device flow response: %s", device_flow_data)
638
660
 
639
- self._user_code = self._device_flow_data["user_code"]
661
+ # Stored as an absolute time, so a client that reads it later knows when it ends.
662
+ device_flow_data["expires_at"] = (
663
+ datetime.now(timezone.utc)
664
+ + timedelta(seconds=device_flow_data["expires_in"])
665
+ ).isoformat()
666
+
667
+ return device_flow_data
668
+
669
+ def _set_device_flow_data(
670
+ self, device_flow_data: dict[str, Any]
671
+ ) -> DeviceActivationStatus:
672
+ """Remember the device activation to wait for."""
673
+ self._device_flow_data = device_flow_data
674
+
675
+ self._user_code = device_flow_data["user_code"]
640
676
  visit_url = (
641
- self._device_flow_data["verification_uri"]
677
+ device_flow_data["verification_uri"]
642
678
  + "?"
643
679
  + urlencode({"user_code": self._user_code, "client_id": self._client_id})
644
680
  )
@@ -646,10 +682,9 @@ class Http:
646
682
 
647
683
  _LOGGER.info("Please visit the following URL: %s", visit_url)
648
684
 
649
- expires_in_seconds = self._device_flow_data["expires_in"]
650
- self._expires_at = datetime.now(timezone.utc) + timedelta(
651
- seconds=expires_in_seconds
652
- )
685
+ self._expires_at = datetime.fromisoformat(device_flow_data["expires_at"])
686
+ if self._expires_at.tzinfo is None:
687
+ self._expires_at = self._expires_at.replace(tzinfo=timezone.utc)
653
688
 
654
689
  _LOGGER.info(
655
690
  "Waiting for user to authorize the device. Expires at %s",
@@ -662,39 +697,80 @@ class Http:
662
697
  if self._expires_at is not None and datetime.timestamp(
663
698
  datetime.now(timezone.utc)
664
699
  ) > datetime.timestamp(self._expires_at):
700
+ # Another client may have finished this activation in the meantime.
701
+ with self._device_manager.lock_device_activation():
702
+ if self._use_token_of_other_client():
703
+ return True
704
+ self._clear_own_pending_device_data()
665
705
  raise TadoException("User took too long to enter key")
666
706
 
667
- # Await the desired interval, before polling the API again
707
+ # Await the desired interval, before polling the API again. This is done
708
+ # outside the lock, so other clients are not blocked while this one sleeps.
668
709
  time.sleep(self._device_flow_data.get("interval", 0))
669
710
 
670
- try:
671
- token_response = self._session.request(
672
- method="post",
673
- url="https://login.tado.com/oauth2/token",
674
- params={
675
- "client_id": self._client_id,
676
- "device_code": self._device_flow_data["device_code"],
677
- "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
678
- },
679
- )
680
- except requests.exceptions.ConnectionError as e:
681
- raise TadoException(e) from e
711
+ # A device code can be exchanged once and the refresh token it returns is
712
+ # stored right away. Doing both under the lock means a client that comes
713
+ # second always finds the token of the first one.
714
+ with self._device_manager.lock_device_activation():
715
+ try:
716
+ token_response = self._session.request(
717
+ method="post",
718
+ url="https://login.tado.com/oauth2/token",
719
+ params={
720
+ "client_id": self._client_id,
721
+ "device_code": self._device_flow_data["device_code"],
722
+ "grant_type": "urn:ietf:params:oauth:grant-type:device_code",
723
+ },
724
+ )
725
+ except requests.exceptions.ConnectionError as e:
726
+ raise TadoException(e) from e
727
+
728
+ if token_response.status_code == 200:
729
+ self._set_oauth_header(token_response.json())
730
+ self._clear_own_pending_device_data()
731
+ return True
732
+
733
+ # The user has not yet authorized the device, let's continue
734
+ if (
735
+ token_response.status_code == 400
736
+ and token_response.json()["error"] == "authorization_pending"
737
+ ):
738
+ _LOGGER.info(
739
+ "Authorization pending, waiting for user to authorize. Continue polling."
740
+ )
741
+ return False
682
742
 
683
- if token_response.status_code == 200:
684
- self._set_oauth_header(token_response.json())
685
- return True
743
+ # If another client sharing this activation got there first, it stored
744
+ # a refresh token we can use.
745
+ if self._use_token_of_other_client():
746
+ return True
747
+
748
+ self._clear_own_pending_device_data()
749
+ raise TadoException(f"Login failed. Reason: {token_response.reason}")
750
+
751
+ def _clear_own_pending_device_data(self) -> None:
752
+ """Forget the shared activation, unless another client replaced it.
686
753
 
687
- # The user has not yet authorized the device, let's continue
688
- if (
689
- token_response.status_code == 400
690
- and token_response.json()["error"] == "authorization_pending"
754
+ The caller holds the device activation lock.
755
+ """
756
+ pending = self._device_manager.get_pending_device_data()
757
+ if pending and pending.get("device_code") == self._device_flow_data.get(
758
+ "device_code"
691
759
  ):
692
- _LOGGER.info(
693
- "Authorization pending, waiting for user to authorize. Continue polling."
694
- )
760
+ self._device_manager.set_pending_device_data(None)
761
+
762
+ def _use_token_of_other_client(self) -> bool:
763
+ """Finish the activation with the token another client stored.
764
+
765
+ The caller holds the device activation lock.
766
+ """
767
+ if not isinstance(self._token_manager, CanManageDeviceActivation):
695
768
  return False
696
769
 
697
- raise TadoException(f"Login failed. Reason: {token_response.reason}")
770
+ token = self._token_manager.get_token()
771
+ return bool(token) and self._refresh_token(
772
+ refresh_token=token, force_refresh=True
773
+ )
698
774
 
699
775
  def device_activation(self) -> None:
700
776
  """Activate the device and get the refresh token"""
@@ -254,7 +254,7 @@ class TadoBase(metaclass=ABCMeta):
254
254
  request.command = "presenceLock"
255
255
  request.action = Action.RESET
256
256
 
257
- return self._http.request(request)
257
+ self._http.request(request)
258
258
  else:
259
259
  raise TadoNotSupportedException("Auto mode is not known to be supported.")
260
260
 
@@ -295,10 +295,12 @@ class TadoBase(metaclass=ABCMeta):
295
295
  for device in self._http.request(request)
296
296
  ]
297
297
 
298
- def get_running_times(self, from_date: date = date.today()) -> RunningTimes:
298
+ def get_running_times(self, from_date: date | None = None) -> RunningTimes:
299
299
  """
300
- Get the running times from the Minder API
300
+ Get the running times from the Minder API (from_date defaults to today)
301
301
  """
302
+ if from_date is None:
303
+ from_date = date.today()
302
304
 
303
305
  request = TadoRequest()
304
306
  request.command = "runningTimes"
@@ -523,11 +525,14 @@ class TadoBase(metaclass=ABCMeta):
523
525
  ]
524
526
 
525
527
  def set_eiq_meter_readings(
526
- self, reading_date: date = date.today(), reading: int = 0
528
+ self, reading_date: date | None = None, reading: int = 0
527
529
  ) -> SuccessResult | None:
528
530
  """
529
531
  Send Meter Readings to Tado, reading is without decimals
532
+ (reading_date defaults to today)
530
533
  """
534
+ if reading_date is None:
535
+ reading_date = date.today()
531
536
 
532
537
  request = TadoRequest()
533
538
  request.command = "meterReadings"
@@ -542,8 +547,8 @@ class TadoBase(metaclass=ABCMeta):
542
547
 
543
548
  def set_eiq_tariff(
544
549
  self,
545
- from_date: date = date.today(),
546
- to_date: date = date.today(),
550
+ from_date: date | None = None,
551
+ to_date: date | None = None,
547
552
  tariff: float = 0,
548
553
  unit: str = "m3",
549
554
  is_period: bool = False,
@@ -552,7 +557,12 @@ class TadoBase(metaclass=ABCMeta):
552
557
  Send Tariffs to Tado,
553
558
  tariff is with decimals, unit is either m3 or kWh,
554
559
  set is_period to true to set a period of price
560
+ (from_date and to_date default to today)
555
561
  """
562
+ if from_date is None:
563
+ from_date = date.today()
564
+ if to_date is None:
565
+ to_date = date.today()
556
566
 
557
567
  tariff_in_cents = tariff * 100
558
568
 
@@ -589,7 +599,7 @@ class TadoBase(metaclass=ABCMeta):
589
599
  Included is check to ignore request to less than 100 meters
590
600
  """
591
601
  if meters < 100:
592
- return
602
+ return None
593
603
 
594
604
  request = TadoRequest()
595
605
  request.action = Action.CHANGE
@@ -404,6 +404,12 @@ class TadoX(TadoBase):
404
404
  if isinstance(result, str) and result.isdigit():
405
405
  return int(result)
406
406
 
407
+ # Error statuses already raise in the HTTP layer. The API answers a
408
+ # successful request with HTTP 204 (reported as {"success": True}), an
409
+ # empty HTTP 200 (reported as {}) or {"success": true}.
410
+ if isinstance(result, dict) and result.get("success", True):
411
+ return 0
412
+
407
413
  raise TadoNotSupportedException("Unexpected response from set_manual_control")
408
414
 
409
415
  def get_installation(self) -> Installation:
@@ -6,7 +6,7 @@ from typing import Any, final
6
6
 
7
7
  from PyTado.exceptions import TadoException
8
8
  from PyTado.http import Action, Domain, Mode, TadoRequest
9
- from PyTado.interface.api.base_tado import TadoBase, Timetable
9
+ from PyTado.interface.api.base_tado import TadoBase
10
10
  from PyTado.models import pre_line_x
11
11
  from PyTado.models.home import AirComfort
12
12
  from PyTado.models.pre_line_x.boiler import MaxOutputTemp, WiringInstallationState
@@ -21,6 +21,7 @@ from PyTado.models.pre_line_x.zone import (
21
21
  ZoneState,
22
22
  )
23
23
  from PyTado.models.return_models import SuccessResult, TemperatureOffset
24
+ from PyTado.types import Timetable
24
25
  from PyTado.zone.my_zone import TadoZone
25
26
 
26
27
 
@@ -11,6 +11,7 @@ import requests
11
11
  import PyTado.interface.api as API
12
12
  from PyTado.exceptions import TadoException
13
13
  from PyTado.http import DeviceActivationStatus, Http
14
+ from PyTado.token_manager import TokenManagerInterface
14
15
 
15
16
  F = TypeVar("F", bound=Callable[..., Any]) # Type variable for function
16
17
 
@@ -60,6 +61,7 @@ class Tado:
60
61
  user_agent: str | None = None,
61
62
  client_id: str | None = None,
62
63
  token_update_callback: Callable[[str], None] | None = None,
64
+ token_manager: TokenManagerInterface | None = None,
63
65
  ):
64
66
  """
65
67
  Initializes the interface class.
@@ -78,6 +80,9 @@ class Tado:
78
80
  from PyTado.const. Pass a custom value instead of patching the module global.
79
81
  token_update_callback (Callable[[str], None] | None): Called with the new refresh
80
82
  token every time tado rotates it, so callers can store it at once.
83
+ token_manager (TokenManagerInterface | None): Custom way to store and load the
84
+ refresh token. Can't be used together with token_file_path or
85
+ saved_refresh_token.
81
86
  """
82
87
 
83
88
  self._http = Http(
@@ -88,6 +93,7 @@ class Tado:
88
93
  user_agent=user_agent,
89
94
  client_id=client_id,
90
95
  token_update_callback=token_update_callback,
96
+ token_manager=token_manager,
91
97
  )
92
98
  self._api: API.Tado | API.TadoX | None = None
93
99
  self._debug = debug
@@ -83,7 +83,7 @@ class Base(BaseModel):
83
83
  "Model %s has extra key: %s with value %r", cls, key, value
84
84
  )
85
85
 
86
- unused_keys = model.model_fields.keys() - model.model_fields_set
86
+ unused_keys = type(model).model_fields.keys() - model.model_fields_set
87
87
  if unused_keys:
88
88
  LOGGER.debug("Model %s has unused keys: %r", cls, unused_keys)
89
89
 
@@ -0,0 +1,15 @@
1
+ """Persistence of the OAuth refresh token and of a pending device activation."""
2
+
3
+ from .can_manage_device_activation import CanManageDeviceActivation
4
+ from .device_token_manager import DeviceTokenManager
5
+ from .dummy_device_manager import DummyDeviceManager
6
+ from .file_token_manager import FileTokenManager
7
+ from .token_manager_interface import TokenManagerInterface
8
+
9
+ __all__ = [
10
+ "CanManageDeviceActivation",
11
+ "DeviceTokenManager",
12
+ "DummyDeviceManager",
13
+ "FileTokenManager",
14
+ "TokenManagerInterface",
15
+ ]
@@ -0,0 +1,35 @@
1
+ """Interface for sharing a running device activation between clients/processes."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from contextlib import AbstractContextManager
5
+ from typing import Any
6
+
7
+
8
+ class CanManageDeviceActivation(ABC):
9
+ """A token manager that can also share a pending device activation.
10
+
11
+ tado allows only a few open device activations. Several clients (or processes)
12
+ that start up at the same time can share one instead of each asking for a new
13
+ code: the first one stores the device data it got from tado, the others read it
14
+ and wait for the same user confirmation.
15
+ """
16
+
17
+ @abstractmethod
18
+ def lock_device_activation(self) -> AbstractContextManager[None]:
19
+ """Return a context manager that holds an exclusive lock while it is entered.
20
+
21
+ Used around "check for pending data, otherwise request a new activation",
22
+ so that two clients can't both request one, and around every refresh of the
23
+ token, so that two processes don't use the same single-use refresh token.
24
+ Must block until the lock is free, and must be re-entrant for the thread that
25
+ holds it (the client refreshes the token while it holds the lock to finish an
26
+ activation).
27
+ """
28
+
29
+ @abstractmethod
30
+ def get_pending_device_data(self) -> dict[str, Any] | None:
31
+ """Return the stored data of the pending device activation, or None."""
32
+
33
+ @abstractmethod
34
+ def set_pending_device_data(self, device_data: dict[str, Any] | None) -> None:
35
+ """Store the data of the pending device activation. None clears it."""
@@ -0,0 +1,177 @@
1
+ """Token manager that several processes on one machine can share."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import sys
7
+ import tempfile
8
+ import threading
9
+ import time
10
+ from collections.abc import Generator
11
+ from contextlib import contextmanager
12
+ from typing import Any
13
+
14
+ from PyTado.exceptions import TadoException
15
+ from PyTado.token_manager.can_manage_device_activation import CanManageDeviceActivation
16
+ from PyTado.token_manager.file_token_manager import FileTokenManager
17
+
18
+ _LOGGER = logging.getLogger(__name__)
19
+
20
+ _APP_NAME = "PyTado"
21
+
22
+
23
+ def default_data_dir() -> str:
24
+ """Per-user directory for data of the current platform."""
25
+ home = os.path.expanduser("~")
26
+ if sys.platform == "win32": # pragma: no cover
27
+ base = os.environ.get("LOCALAPPDATA") or os.path.join(home, "AppData", "Local")
28
+ elif sys.platform == "darwin": # pragma: no cover
29
+ base = os.path.join(home, "Library", "Application Support")
30
+ else:
31
+ base = os.environ.get("XDG_DATA_HOME") or os.path.join(home, ".local", "share")
32
+ return os.path.join(base, _APP_NAME)
33
+
34
+
35
+ @contextmanager
36
+ def _exclusive_lock(path: str) -> Generator[None, None, None]:
37
+ """Hold an exclusive lock on a file until the block ends; blocks until it is free."""
38
+ with open(path, "a+b") as f:
39
+ if sys.platform == "win32": # pragma: no cover
40
+ import msvcrt # only here, so importing PyTado needs no lock backend
41
+
42
+ f.seek(0)
43
+ while True:
44
+ try:
45
+ msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
46
+ break
47
+ except OSError:
48
+ time.sleep(0.1)
49
+ try:
50
+ yield
51
+ finally:
52
+ f.seek(0)
53
+ msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
54
+ else:
55
+ import fcntl # only here, so importing PyTado needs no lock backend
56
+
57
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
58
+ try:
59
+ yield
60
+ finally:
61
+ fcntl.flock(f.fileno(), fcntl.LOCK_UN)
62
+
63
+
64
+ class DeviceTokenManager(FileTokenManager, CanManageDeviceActivation):
65
+ """Stores the refresh token and a pending device activation in a per-user directory.
66
+
67
+ Every process that uses the same directory shares them: while one process waits for
68
+ the user to confirm the device, the others show the same code instead of asking
69
+ tado for another one, and they find the refresh token once it is stored.
70
+
71
+ The data lives in three files, so writing one kind of data never touches another:
72
+ ``device_token.json`` (the refresh token), ``pending_device.json`` (the running
73
+ device activation) and ``device.lock`` (the lock).
74
+ """
75
+
76
+ def __init__(
77
+ self,
78
+ data_dir: str | None = None,
79
+ saved_refresh_token: str | None = None,
80
+ ) -> None:
81
+ """
82
+ Args:
83
+ data_dir (str | None): Directory for the files. If None, a directory in the
84
+ per-user data directory of the platform is used.
85
+ saved_refresh_token (str | None): A refresh token to use instead of the
86
+ stored one, until tado rotates it.
87
+ """
88
+ self._data_dir = data_dir or default_data_dir()
89
+ super().__init__(
90
+ token_file_path=os.path.join(self._data_dir, "device_token.json"),
91
+ saved_refresh_token=saved_refresh_token,
92
+ )
93
+ self._pending_file_path = os.path.join(self._data_dir, "pending_device.json")
94
+ self._lock_file_path = os.path.join(self._data_dir, "device.lock")
95
+ self._lock_state = threading.local()
96
+
97
+ _LOGGER.debug("Using data directory %s", self._data_dir)
98
+
99
+ @contextmanager
100
+ def lock_device_activation(self) -> Generator[None, None, None]:
101
+ # A file lock blocks even the thread that holds it, so the thread that
102
+ # already holds it just goes on (the client refreshes the token while it
103
+ # holds the lock to finish an activation).
104
+ if getattr(self._lock_state, "held", False):
105
+ yield
106
+ return
107
+
108
+ os.makedirs(self._data_dir, mode=0o700, exist_ok=True)
109
+ with _exclusive_lock(self._lock_file_path):
110
+ self._lock_state.held = True
111
+ try:
112
+ yield
113
+ finally:
114
+ self._lock_state.held = False
115
+
116
+ def get_pending_device_data(self) -> dict[str, Any] | None:
117
+ try:
118
+ with open(self._pending_file_path, encoding="utf-8") as f:
119
+ data = json.load(f)
120
+ except FileNotFoundError:
121
+ return None
122
+ except (OSError, json.JSONDecodeError) as e:
123
+ _LOGGER.error("Failed to load pending device data: %s", e)
124
+ return None
125
+
126
+ return data if isinstance(data, dict) else None
127
+
128
+ def set_pending_device_data(self, device_data: dict[str, Any] | None) -> None:
129
+ if not device_data:
130
+ try:
131
+ os.remove(self._pending_file_path)
132
+ except FileNotFoundError:
133
+ pass
134
+ except OSError as e:
135
+ raise TadoException(f"Failed to clear pending device data: {e}") from e
136
+ return
137
+
138
+ try:
139
+ self._write_private_json(self._pending_file_path, device_data)
140
+ except OSError as e:
141
+ _LOGGER.error("Failed to save pending device data: %s", e)
142
+ raise TadoException(f"Failed to save pending device data: {e}") from e
143
+
144
+ def _save_token(self) -> None:
145
+ """Save the refresh token readable for this user only, replacing the file at once."""
146
+ if not self._token:
147
+ return
148
+
149
+ try:
150
+ self._known_mtime = self._write_private_json(
151
+ self._token_file_path or "", {"refresh_token": self._token}
152
+ )
153
+ _LOGGER.debug("Refresh token saved to %s", self._token_file_path)
154
+ except OSError as e:
155
+ _LOGGER.error("Failed to save refresh token: %s", e)
156
+ raise TadoException(f"Failed to save refresh token: {e}") from e
157
+
158
+ def _write_private_json(self, path: str, data: dict[str, Any]) -> int:
159
+ """Write a file only this user can read, and replace the old one in one step.
160
+
161
+ A reader sees either the old or the new file, never half of one. Returns the
162
+ modification time of the file that was written.
163
+ """
164
+ os.makedirs(self._data_dir, mode=0o700, exist_ok=True)
165
+ # mkstemp creates the file with mode 0600
166
+ fd, tmp_path = tempfile.mkstemp(dir=self._data_dir, prefix="tmp_")
167
+ try:
168
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
169
+ json.dump(data, f)
170
+ f.flush()
171
+ mtime = os.fstat(f.fileno()).st_mtime_ns
172
+ os.replace(tmp_path, path)
173
+ except BaseException:
174
+ if os.path.exists(tmp_path):
175
+ os.remove(tmp_path)
176
+ raise
177
+ return mtime
@@ -0,0 +1,21 @@
1
+ """Fallback for token managers that can't share a device activation."""
2
+
3
+ from collections.abc import Generator
4
+ from contextlib import contextmanager
5
+ from typing import Any
6
+
7
+ from PyTado.token_manager.can_manage_device_activation import CanManageDeviceActivation
8
+
9
+
10
+ class DummyDeviceManager(CanManageDeviceActivation):
11
+ """Shares nothing: every client does its own device activation."""
12
+
13
+ @contextmanager
14
+ def lock_device_activation(self) -> Generator[None, None, None]:
15
+ yield
16
+
17
+ def get_pending_device_data(self) -> dict[str, Any] | None:
18
+ return None
19
+
20
+ def set_pending_device_data(self, device_data: dict[str, Any] | None) -> None:
21
+ return None
@@ -0,0 +1,105 @@
1
+ """Token manager that keeps the refresh token in memory and optionally in a file."""
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from PyTado.exceptions import TadoException
10
+ from PyTado.token_manager.token_manager_interface import TokenManagerInterface
11
+
12
+ _LOGGER = logging.getLogger(__name__)
13
+
14
+
15
+ class FileTokenManager(TokenManagerInterface):
16
+ """Keeps the refresh token in memory and, if a path is given, in a JSON file."""
17
+
18
+ def __init__(
19
+ self,
20
+ token_file_path: str | None = None,
21
+ saved_refresh_token: str | None = None,
22
+ ) -> None:
23
+ """
24
+ Args:
25
+ token_file_path (str | None): File to persist the refresh token in.
26
+ If None, the token is only kept in memory.
27
+ saved_refresh_token (str | None): A refresh token to use instead of
28
+ the one in the file, until tado rotates it.
29
+ """
30
+ self._token_file_path = token_file_path
31
+ self._token: str | None = saved_refresh_token or None
32
+ # A given token wins over what is in the file now, but not over what another
33
+ # process writes into the file later.
34
+ self._known_mtime = self._file_mtime()
35
+
36
+ def get_token(self) -> str | None:
37
+ # The in-memory token is the newest one this process knows. The file is only
38
+ # read when there is none, or when another process has written to it since:
39
+ # tado refresh tokens are single use, so that process holds the valid one.
40
+ mtime = self._file_mtime()
41
+ if self._token is None or mtime != self._known_mtime:
42
+ token = self._load_token()
43
+ # Only remember the file version once it was read successfully, so an
44
+ # unreadable file is tried again on the next call.
45
+ self._known_mtime = mtime
46
+ if token:
47
+ self._token = token
48
+ return self._token
49
+
50
+ def set_oauth_data(self, oauth_data: dict[str, Any]) -> None:
51
+ refresh_token = oauth_data.get("refresh_token")
52
+ if not refresh_token:
53
+ return
54
+
55
+ self._token = str(refresh_token)
56
+ self._save_token()
57
+
58
+ def _mtime_of(self, f: Any) -> int | None:
59
+ try:
60
+ return os.fstat(f.fileno()).st_mtime_ns
61
+ except (OSError, ValueError, AttributeError):
62
+ return self._file_mtime()
63
+
64
+ def _file_mtime(self) -> int | None:
65
+ if not self._token_file_path:
66
+ return None
67
+ try:
68
+ return os.stat(self._token_file_path).st_mtime_ns
69
+ except OSError:
70
+ return None
71
+
72
+ def _load_token(self) -> str | None:
73
+ if not self._token_file_path or not os.path.exists(self._token_file_path):
74
+ return None
75
+
76
+ try:
77
+ with open(self._token_file_path, encoding="utf-8") as f:
78
+ data = json.load(f)
79
+ except (OSError, json.JSONDecodeError) as e:
80
+ _LOGGER.error("Failed to load refresh token: %s", e)
81
+ raise TadoException(e) from e
82
+
83
+ _LOGGER.debug("Refresh token loaded from %s", self._token_file_path)
84
+ token = data.get("refresh_token") if isinstance(data, dict) else None
85
+ return str(token) if token else None
86
+
87
+ def _save_token(self) -> None:
88
+ if not self._token_file_path or not self._token:
89
+ return
90
+
91
+ try:
92
+ token_dir = os.path.dirname(self._token_file_path)
93
+ if token_dir and not os.path.exists(token_dir):
94
+ Path(token_dir).mkdir(parents=True, exist_ok=True)
95
+
96
+ with open(self._token_file_path, "w", encoding="utf-8") as f:
97
+ json.dump({"refresh_token": self._token}, f)
98
+ f.flush()
99
+ # The version of the file we just wrote, taken from the open file: a
100
+ # stat by path could already see a write of another process.
101
+ self._known_mtime = self._mtime_of(f)
102
+ _LOGGER.debug("Refresh token saved to %s", self._token_file_path)
103
+ except Exception as e:
104
+ _LOGGER.error("Failed to save refresh token: %s", e)
105
+ raise TadoException(e) from e
@@ -0,0 +1,20 @@
1
+ """Interface for objects that persist the OAuth refresh token."""
2
+
3
+ from abc import ABC, abstractmethod
4
+ from typing import Any
5
+
6
+
7
+ class TokenManagerInterface(ABC):
8
+ """Persists the OAuth refresh token between runs (or between processes).
9
+
10
+ The refresh expiry of the access token stays with the HTTP client; a
11
+ token manager only stores and returns the refresh token.
12
+ """
13
+
14
+ @abstractmethod
15
+ def get_token(self) -> str | None:
16
+ """Return the stored refresh token, or None if there is none."""
17
+
18
+ @abstractmethod
19
+ def set_oauth_data(self, oauth_data: dict[str, Any]) -> None:
20
+ """Store the OAuth data (``access_token``, ``refresh_token``, ...) tado returned."""
@@ -76,7 +76,7 @@ class BaseZone:
76
76
  id: The unique identifier of the zone/room
77
77
  """
78
78
  self._home = home
79
- self._http = home._http # type: ignore
79
+ self._http = home._http
80
80
  self._id = id
81
81
 
82
82
  def update(self) -> None:
@@ -29,6 +29,26 @@ otherwise) from Tado, and have no business interest with them. This software is
29
29
  the GNU Public License version 3, and should therefore not be used where it may endanger life, financial stakes, or
30
30
  cause discomfort and inconvenience to others.
31
31
 
32
+ ## Versions
33
+
34
+ | Line | API | Status | Branch |
35
+ | ---- | --- | ------ | ------ |
36
+ | **1.x** (from 1.0.1) | New typed API: pydantic models instead of `dict`, separate clients for tado v2/v3/v3+ (`Tado`) and tado X (`TadoX`), `TadoClientInitializer`, token managers that share one login between processes. Needs `pydantic` 2. | Under active development | `master` |
37
+ | **0.18.x** | Old API: methods return plain `dict`/`list`, one `Tado` class for all devices. | Maintained, bug fixes and backports | `support/0.18` |
38
+ | **0.19.x** | Same old API as 0.18.x (0.19.0 brought the OAuth device flow, child lock and flow temperature optimization, which were all backported to 0.18.x). | Frozen, use 0.18.x | `support/0.19` |
39
+
40
+ The 1.x API is not compatible with 0.x. See the [migration guide](https://github.com/wmalgadey/PyTado/blob/master/MigrationV1.0.0.md).
41
+
42
+ Pin the line you need, e.g. `python-tado~=0.18.17` for the old API or `python-tado>=1.0.1,<2` for the new one. Until 1.0.1 final is out, the new API is only available as a release candidate: `pip install --pre "python-tado>=1.0.1rc1,<2"`.
43
+
44
+ ### Releases to avoid
45
+
46
+ - **0.19.4** contains the 1.x API by mistake, even though its version number says 0.19. It is yanked on PyPI (since 2026-11-30). Use 0.19.5 (old API) or 1.0.1 or later (new API) instead.
47
+ - **1.0.0** was uploaded to PyPI by mistake (from the 0.19.3 tag) and then deleted. PyPI never accepts a version number twice, so the first stable 1.x release is **1.0.1**.
48
+ - **0.19.3** was never published to PyPI.
49
+
50
+ Release notes for every version are on the [GitHub releases page](https://github.com/wmalgadey/PyTado/releases).
51
+
32
52
  ## Usage
33
53
 
34
54
  As of the 15th of March 2025, Tado has updated their OAuth2 authentication flow. It will now use the device flow, instead of a username/password flow. This means that the user will have to authenticate the device using a browser, and then enter the code that is displayed on the browser into the terminal.
@@ -80,6 +100,21 @@ else:
80
100
  print(f"Login status is {status}")
81
101
  ```
82
102
 
103
+ ### Sharing the login between several processes
104
+
105
+ If several processes on one machine use PyTado (e.g. a service and a CLI), use the
106
+ `DeviceTokenManager`. It stores the refresh token in a per-user data directory (or in
107
+ `data_dir`) and shares a running device activation: the processes show the same code
108
+ instead of each asking tado for a new one, and they pick up the token once one of them
109
+ is activated.
110
+
111
+ ```python
112
+ from PyTado.interface.interface import Tado
113
+ from PyTado.token_manager import DeviceTokenManager
114
+
115
+ tado = Tado(token_manager=DeviceTokenManager())
116
+ ```
117
+
83
118
  ## Example code
84
119
 
85
120
  ```python
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
4
4
 
5
5
  [tool.poetry]
6
6
  name = "python-tado"
7
- version = "0.19.4"
7
+ version = "1.0.1rc1"
8
8
  description = "PyTado from chrism0dwk, modified by w.malgadey, diplix, michaelarnauts, LenhartStephan, splifter, syssi, andersonshatch, Yippy, p0thi, Coffee2CodeNL, chiefdragon, FilBr, nikilase, albertomontesg, Moritz-Schmidt, palazzem"
9
9
  authors = [
10
10
  "Chris Jewell <chrism0dwk@gmail.com>",
@@ -13,7 +13,7 @@ authors = [
13
13
  "Erwin Douna <e.douna@gmail.com>"
14
14
  ]
15
15
  classifiers = [
16
- "Development Status :: 4 - Beta",
16
+ "Development Status :: 5 - Production/Stable",
17
17
  "Topic :: Home Automation",
18
18
  "Intended Audience :: Developers",
19
19
  "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
@@ -30,6 +30,10 @@ documentation = "https://wmalgadey.github.io/PyTado/"
30
30
  homepage = "https://github.com/wmalgadey/PyTado"
31
31
  repository = "https://github.com/wmalgadey/PyTado"
32
32
 
33
+ [tool.poetry.urls]
34
+ "Changelog" = "https://github.com/wmalgadey/PyTado/releases"
35
+ "Migration guide" = "https://github.com/wmalgadey/PyTado/blob/master/MigrationV1.0.0.md"
36
+
33
37
  [tool.poetry.dependencies]
34
38
  python = ">=3.11"
35
39
  requests = "*"
File without changes
File without changes