karaca-connect-client 0.1.0a1__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.
- karaca_connect_client-0.1.0a1/LICENSE +21 -0
- karaca_connect_client-0.1.0a1/PKG-INFO +92 -0
- karaca_connect_client-0.1.0a1/README.md +68 -0
- karaca_connect_client-0.1.0a1/pyproject.toml +35 -0
- karaca_connect_client-0.1.0a1/setup.cfg +4 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client/__init__.py +18 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client/client.py +204 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client/exceptions.py +29 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client/py.typed +0 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client.egg-info/PKG-INFO +92 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client.egg-info/SOURCES.txt +15 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client.egg-info/dependency_links.txt +1 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client.egg-info/requires.txt +1 -0
- karaca_connect_client-0.1.0a1/src/karaca_connect_client.egg-info/top_level.txt +1 -0
- karaca_connect_client-0.1.0a1/tests/test_client.py +195 -0
- karaca_connect_client-0.1.0a1/tests/test_extra_contracts.py +112 -0
- karaca_connect_client-0.1.0a1/tests/test_release_safety.py +21 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 AzadGLR
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: karaca-connect-client
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Unofficial asynchronous client for the Karaca Connect cloud API
|
|
5
|
+
Author: AzadGLR
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Azadglr/karaca-connect-client
|
|
8
|
+
Project-URL: Repository, https://github.com/Azadglr/karaca-connect-client
|
|
9
|
+
Project-URL: Issues, https://github.com/Azadglr/karaca-connect-client/issues
|
|
10
|
+
Keywords: karaca,home-assistant,asyncio,tea-maker
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: aiohttp<4,>=3.9
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# Karaca Connect Client
|
|
26
|
+
|
|
27
|
+
Unofficial asynchronous Python client for the Karaca Connect cloud service.
|
|
28
|
+
|
|
29
|
+
> **Alpha** — This library is extracted from the community Home Assistant integration at
|
|
30
|
+
> [Azadglr/karaca-connect-unofficial](https://github.com/Azadglr/karaca-connect-unofficial).
|
|
31
|
+
> It has been tested with simulated API responses but has **not yet been independently
|
|
32
|
+
> authenticated against the live Karaca service** in this extracted form.
|
|
33
|
+
|
|
34
|
+
This project is not affiliated with or endorsed by Karaca. The service API is not publicly documented;
|
|
35
|
+
its behavior and availability can change without notice. Currently the original community integration
|
|
36
|
+
reports verified support for the Karaca Çaysever Robotea Pro Connect 4in1 only.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install karaca-connect-client
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Read-only example
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import asyncio
|
|
48
|
+
import getpass
|
|
49
|
+
from aiohttp import ClientSession
|
|
50
|
+
from karaca_connect_client import KaracaClient
|
|
51
|
+
|
|
52
|
+
async def main():
|
|
53
|
+
email = input("Karaca Connect email: ")
|
|
54
|
+
password = getpass.getpass("Karaca Connect password: ")
|
|
55
|
+
async with ClientSession() as session:
|
|
56
|
+
client = KaracaClient(session, email=email, password=password)
|
|
57
|
+
devices = await client.get_devices()
|
|
58
|
+
for device in devices:
|
|
59
|
+
print(device.get("id"), device.get("label"))
|
|
60
|
+
# In multi-device accounts, pass device_id=... explicitly.
|
|
61
|
+
# No device mode or settings are changed by this example.
|
|
62
|
+
|
|
63
|
+
asyncio.run(main())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The caller owns the `aiohttp.ClientSession` and is responsible for securing account credentials.
|
|
67
|
+
Please do not paste credentials, tokens, or device details into public issues.
|
|
68
|
+
|
|
69
|
+
## Functions
|
|
70
|
+
|
|
71
|
+
- Authenticate and renew tokens when the cloud API rejects expired authorization
|
|
72
|
+
- List devices, retrieve device details and notification settings
|
|
73
|
+
- Set device modes and notification settings (optional; supported capabilities may differ by model)
|
|
74
|
+
- Distinguish authentication, connectivity, rate-limit, cloud availability and API errors
|
|
75
|
+
- Refuse to silently select a device when more than one device is present
|
|
76
|
+
|
|
77
|
+
## Development
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
python -m pip install -e . pytest
|
|
81
|
+
python -m pytest tests
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Release policy
|
|
85
|
+
|
|
86
|
+
Source code and GitHub release tags are public. Publishing to PyPI is performed solely
|
|
87
|
+
by the `publish.yml` GitHub Actions workflow using PyPI Trusted Publishing. The version
|
|
88
|
+
in `pyproject.toml` must match the release tag without its leading `v`.
|
|
89
|
+
|
|
90
|
+
**Initial alpha release:** `v0.1.0a1`. No credentials or API tokens are stored in this repository.
|
|
91
|
+
|
|
92
|
+
License: MIT.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
# Karaca Connect Client
|
|
2
|
+
|
|
3
|
+
Unofficial asynchronous Python client for the Karaca Connect cloud service.
|
|
4
|
+
|
|
5
|
+
> **Alpha** — This library is extracted from the community Home Assistant integration at
|
|
6
|
+
> [Azadglr/karaca-connect-unofficial](https://github.com/Azadglr/karaca-connect-unofficial).
|
|
7
|
+
> It has been tested with simulated API responses but has **not yet been independently
|
|
8
|
+
> authenticated against the live Karaca service** in this extracted form.
|
|
9
|
+
|
|
10
|
+
This project is not affiliated with or endorsed by Karaca. The service API is not publicly documented;
|
|
11
|
+
its behavior and availability can change without notice. Currently the original community integration
|
|
12
|
+
reports verified support for the Karaca Çaysever Robotea Pro Connect 4in1 only.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
pip install karaca-connect-client
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Read-only example
|
|
21
|
+
|
|
22
|
+
```python
|
|
23
|
+
import asyncio
|
|
24
|
+
import getpass
|
|
25
|
+
from aiohttp import ClientSession
|
|
26
|
+
from karaca_connect_client import KaracaClient
|
|
27
|
+
|
|
28
|
+
async def main():
|
|
29
|
+
email = input("Karaca Connect email: ")
|
|
30
|
+
password = getpass.getpass("Karaca Connect password: ")
|
|
31
|
+
async with ClientSession() as session:
|
|
32
|
+
client = KaracaClient(session, email=email, password=password)
|
|
33
|
+
devices = await client.get_devices()
|
|
34
|
+
for device in devices:
|
|
35
|
+
print(device.get("id"), device.get("label"))
|
|
36
|
+
# In multi-device accounts, pass device_id=... explicitly.
|
|
37
|
+
# No device mode or settings are changed by this example.
|
|
38
|
+
|
|
39
|
+
asyncio.run(main())
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The caller owns the `aiohttp.ClientSession` and is responsible for securing account credentials.
|
|
43
|
+
Please do not paste credentials, tokens, or device details into public issues.
|
|
44
|
+
|
|
45
|
+
## Functions
|
|
46
|
+
|
|
47
|
+
- Authenticate and renew tokens when the cloud API rejects expired authorization
|
|
48
|
+
- List devices, retrieve device details and notification settings
|
|
49
|
+
- Set device modes and notification settings (optional; supported capabilities may differ by model)
|
|
50
|
+
- Distinguish authentication, connectivity, rate-limit, cloud availability and API errors
|
|
51
|
+
- Refuse to silently select a device when more than one device is present
|
|
52
|
+
|
|
53
|
+
## Development
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
python -m pip install -e . pytest
|
|
57
|
+
python -m pytest tests
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Release policy
|
|
61
|
+
|
|
62
|
+
Source code and GitHub release tags are public. Publishing to PyPI is performed solely
|
|
63
|
+
by the `publish.yml` GitHub Actions workflow using PyPI Trusted Publishing. The version
|
|
64
|
+
in `pyproject.toml` must match the release tag without its leading `v`.
|
|
65
|
+
|
|
66
|
+
**Initial alpha release:** `v0.1.0a1`. No credentials or API tokens are stored in this repository.
|
|
67
|
+
|
|
68
|
+
License: MIT.
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=69", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "karaca-connect-client"
|
|
7
|
+
version = "0.1.0a1"
|
|
8
|
+
description = "Unofficial asynchronous client for the Karaca Connect cloud API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.12"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{name = "AzadGLR"}]
|
|
13
|
+
keywords = ["karaca", "home-assistant", "asyncio", "tea-maker"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 3 - Alpha",
|
|
16
|
+
"Framework :: AsyncIO",
|
|
17
|
+
"Programming Language :: Python :: 3",
|
|
18
|
+
"Programming Language :: Python :: 3.12",
|
|
19
|
+
"Programming Language :: Python :: 3.13",
|
|
20
|
+
"Programming Language :: Python :: 3.14",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Topic :: Home Automation",
|
|
23
|
+
]
|
|
24
|
+
dependencies = ["aiohttp>=3.9,<4"]
|
|
25
|
+
|
|
26
|
+
[project.urls]
|
|
27
|
+
Homepage = "https://github.com/Azadglr/karaca-connect-client"
|
|
28
|
+
Repository = "https://github.com/Azadglr/karaca-connect-client"
|
|
29
|
+
Issues = "https://github.com/Azadglr/karaca-connect-client/issues"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools.packages.find]
|
|
32
|
+
where = ["src"]
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.package-data]
|
|
35
|
+
karaca_connect_client = ["py.typed"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Unofficial asynchronous Karaca Connect cloud API client."""
|
|
2
|
+
|
|
3
|
+
from .client import KaracaClient
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
KaracaApiError,
|
|
6
|
+
KaracaAuthError,
|
|
7
|
+
KaracaConnectionError,
|
|
8
|
+
KaracaDeviceNotFound,
|
|
9
|
+
KaracaError,
|
|
10
|
+
KaracaRateLimitError,
|
|
11
|
+
KaracaServiceError,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
__all__ = [
|
|
15
|
+
"KaracaClient", "KaracaApiError", "KaracaAuthError",
|
|
16
|
+
"KaracaConnectionError", "KaracaDeviceNotFound", "KaracaError",
|
|
17
|
+
"KaracaRateLimitError", "KaracaServiceError",
|
|
18
|
+
]
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
"""Pre-release client adapted from the existing public integration's API shape.
|
|
2
|
+
|
|
3
|
+
No Karaca credentials or requests have been used to live-test this code.
|
|
4
|
+
Endpoint paths are reverse-engineered / undocumented and may change.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import asyncio
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
from aiohttp import ClientError, ClientSession, ClientTimeout
|
|
14
|
+
|
|
15
|
+
from .exceptions import (
|
|
16
|
+
KaracaApiError,
|
|
17
|
+
KaracaAuthError,
|
|
18
|
+
KaracaConnectionError,
|
|
19
|
+
KaracaDeviceNotFound,
|
|
20
|
+
KaracaRateLimitError,
|
|
21
|
+
KaracaServiceError,
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
DEFAULT_BASE_URL = "https://karacaconnectapi.krc.com.tr"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class KaracaClient:
|
|
28
|
+
"""Asynchronous cloud client. The caller owns the aiohttp session."""
|
|
29
|
+
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
session: ClientSession,
|
|
33
|
+
*,
|
|
34
|
+
email: str,
|
|
35
|
+
password: str,
|
|
36
|
+
device_id: str | None = None,
|
|
37
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
38
|
+
timeout_seconds: float = 20.0,
|
|
39
|
+
) -> None:
|
|
40
|
+
if not email or not password:
|
|
41
|
+
raise ValueError("Email and password must be provided")
|
|
42
|
+
if timeout_seconds <= 0:
|
|
43
|
+
raise ValueError("timeout_seconds must be greater than zero")
|
|
44
|
+
self._session = session
|
|
45
|
+
self._email = email
|
|
46
|
+
self._password = password
|
|
47
|
+
self._device_id = str(device_id) if device_id else None
|
|
48
|
+
self._base_url = base_url.rstrip("/")
|
|
49
|
+
self._timeout = ClientTimeout(total=timeout_seconds)
|
|
50
|
+
self._token: str | None = None
|
|
51
|
+
self._auth_lock = asyncio.Lock()
|
|
52
|
+
|
|
53
|
+
@property
|
|
54
|
+
def device_id(self) -> str | None:
|
|
55
|
+
return self._device_id
|
|
56
|
+
|
|
57
|
+
async def _send(
|
|
58
|
+
self,
|
|
59
|
+
method: str,
|
|
60
|
+
path: str,
|
|
61
|
+
*,
|
|
62
|
+
payload: Mapping[str, Any] | None = None,
|
|
63
|
+
token: str | None = None,
|
|
64
|
+
) -> tuple[int, Mapping[str, Any]]:
|
|
65
|
+
headers = {
|
|
66
|
+
"Accept": "application/json",
|
|
67
|
+
"Content-Type": "application/json",
|
|
68
|
+
"User-Agent": "KaracaConnectClient/0.1.0a1",
|
|
69
|
+
}
|
|
70
|
+
if token:
|
|
71
|
+
headers["Authorization"] = f"Bearer {token}"
|
|
72
|
+
try:
|
|
73
|
+
async with self._session.request(
|
|
74
|
+
method,
|
|
75
|
+
f"{self._base_url}{path}",
|
|
76
|
+
headers=headers,
|
|
77
|
+
json=dict(payload) if payload is not None else None,
|
|
78
|
+
timeout=self._timeout,
|
|
79
|
+
) as response:
|
|
80
|
+
status = response.status
|
|
81
|
+
try:
|
|
82
|
+
data = await response.json(content_type=None)
|
|
83
|
+
except (ValueError, ClientError, TypeError) as exc:
|
|
84
|
+
# Error pages can be HTML or empty: retain the HTTP status
|
|
85
|
+
# so callers can distinguish auth, throttling and outages.
|
|
86
|
+
if status >= 400:
|
|
87
|
+
data = {}
|
|
88
|
+
else:
|
|
89
|
+
raise KaracaConnectionError("Invalid cloud API response") from exc
|
|
90
|
+
except (ClientError, TimeoutError, asyncio.TimeoutError) as exc:
|
|
91
|
+
raise KaracaConnectionError("Unable to reach Karaca cloud service") from exc
|
|
92
|
+
if not isinstance(data, Mapping):
|
|
93
|
+
if status >= 400:
|
|
94
|
+
data = {}
|
|
95
|
+
else:
|
|
96
|
+
raise KaracaConnectionError("Unexpected cloud API response type")
|
|
97
|
+
return status, data
|
|
98
|
+
|
|
99
|
+
@staticmethod
|
|
100
|
+
def _check(status: int, data: Mapping[str, Any]) -> None:
|
|
101
|
+
if status in (401, 403):
|
|
102
|
+
raise KaracaAuthError("Karaca authentication or authorization failed")
|
|
103
|
+
if status == 429:
|
|
104
|
+
raise KaracaRateLimitError("Karaca cloud rate limit reached")
|
|
105
|
+
if status >= 500:
|
|
106
|
+
raise KaracaServiceError("Karaca cloud service unavailable")
|
|
107
|
+
if not 200 <= status < 300 or data.get("succeeded") is False:
|
|
108
|
+
raise KaracaApiError("Karaca cloud request rejected")
|
|
109
|
+
|
|
110
|
+
async def login(self, *, force: bool = False) -> None:
|
|
111
|
+
async with self._auth_lock:
|
|
112
|
+
if self._token and not force:
|
|
113
|
+
return
|
|
114
|
+
status, data = await self._send(
|
|
115
|
+
"POST",
|
|
116
|
+
"/api/auth/signin",
|
|
117
|
+
payload={"email": self._email, "password": self._password},
|
|
118
|
+
)
|
|
119
|
+
# A service outage / throttle must not become "invalid password".
|
|
120
|
+
if status in (401, 403) or (
|
|
121
|
+
200 <= status < 300 and data.get("succeeded") is False
|
|
122
|
+
):
|
|
123
|
+
raise KaracaAuthError("Karaca credentials were rejected")
|
|
124
|
+
self._check(status, data)
|
|
125
|
+
payload = data.get("data")
|
|
126
|
+
token = payload.get("jwToken") if isinstance(payload, Mapping) else None
|
|
127
|
+
if not isinstance(token, str) or not token:
|
|
128
|
+
raise KaracaAuthError("Cloud response did not include a token")
|
|
129
|
+
self._token = token
|
|
130
|
+
|
|
131
|
+
async def _request(
|
|
132
|
+
self,
|
|
133
|
+
method: str,
|
|
134
|
+
path: str,
|
|
135
|
+
*,
|
|
136
|
+
payload: Mapping[str, Any] | None = None,
|
|
137
|
+
) -> Mapping[str, Any]:
|
|
138
|
+
await self.login()
|
|
139
|
+
token = self._token
|
|
140
|
+
status, data = await self._send(method, path, payload=payload, token=token)
|
|
141
|
+
if status == 401:
|
|
142
|
+
# Another coroutine may already have refreshed the expired token.
|
|
143
|
+
if self._token == token:
|
|
144
|
+
self._token = None
|
|
145
|
+
await self.login()
|
|
146
|
+
status, data = await self._send(
|
|
147
|
+
method, path, payload=payload, token=self._token
|
|
148
|
+
)
|
|
149
|
+
self._check(status, data)
|
|
150
|
+
return data
|
|
151
|
+
|
|
152
|
+
async def get_devices(self) -> list[dict[str, Any]]:
|
|
153
|
+
data = await self._request("GET", "/api/v1/devices/me")
|
|
154
|
+
devices = data.get("data")
|
|
155
|
+
if not isinstance(devices, list) or not all(isinstance(d, dict) for d in devices):
|
|
156
|
+
raise KaracaConnectionError("Malformed device list")
|
|
157
|
+
return devices
|
|
158
|
+
|
|
159
|
+
async def resolve_device_id(self) -> str:
|
|
160
|
+
if self._device_id:
|
|
161
|
+
return self._device_id
|
|
162
|
+
devices = await self.get_devices()
|
|
163
|
+
# Never guess which device to control from a multi-device account.
|
|
164
|
+
# The Home Assistant config flow selects and stores a device explicitly.
|
|
165
|
+
if len(devices) != 1 or not devices[0].get("id"):
|
|
166
|
+
raise KaracaDeviceNotFound(
|
|
167
|
+
"Select a device ID explicitly; automatic selection requires exactly one device"
|
|
168
|
+
)
|
|
169
|
+
self._device_id = str(devices[0]["id"])
|
|
170
|
+
return self._device_id
|
|
171
|
+
|
|
172
|
+
async def get_detail(self) -> dict[str, Any]:
|
|
173
|
+
device_id = await self.resolve_device_id()
|
|
174
|
+
response = await self._request("GET", f"/api/v1/devices/{device_id}")
|
|
175
|
+
data = response.get("data")
|
|
176
|
+
if not isinstance(data, dict):
|
|
177
|
+
raise KaracaConnectionError("Malformed device detail response")
|
|
178
|
+
return data
|
|
179
|
+
|
|
180
|
+
async def get_settings(self) -> list[dict[str, Any]]:
|
|
181
|
+
device_id = await self.resolve_device_id()
|
|
182
|
+
response = await self._request("GET", f"/api/v1/devices/{device_id}/settings")
|
|
183
|
+
data = response.get("data")
|
|
184
|
+
settings = data.get("notifications") if isinstance(data, dict) else None
|
|
185
|
+
if not isinstance(settings, list):
|
|
186
|
+
raise KaracaConnectionError("Malformed settings response")
|
|
187
|
+
return settings
|
|
188
|
+
|
|
189
|
+
async def set_mode(self, mode_id: int, active: bool = True) -> None:
|
|
190
|
+
device_id = await self.resolve_device_id()
|
|
191
|
+
await self._request(
|
|
192
|
+
"PUT", f"/api/v1/devices/{device_id}/modes/{mode_id}",
|
|
193
|
+
payload={"active": active},
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
async def set_setting(self, setting_id: int, value: bool) -> None:
|
|
197
|
+
device_id = await self.resolve_device_id()
|
|
198
|
+
path = f"/api/v1/devices/{device_id}/settings/{setting_id}"
|
|
199
|
+
try:
|
|
200
|
+
await self._request("PUT", path, payload={"value": value})
|
|
201
|
+
except KaracaApiError:
|
|
202
|
+
# Existing integration uses this fallback; compatibility must be
|
|
203
|
+
# confirmed against the live API before any public release.
|
|
204
|
+
await self._request("PUT", path, payload={"active": value})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Public client exceptions. Never include credentials or response bodies."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class KaracaError(Exception):
|
|
5
|
+
"""Base error for Karaca cloud requests."""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class KaracaAuthError(KaracaError):
|
|
9
|
+
"""Authentication failed or credentials need attention."""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class KaracaConnectionError(KaracaError):
|
|
13
|
+
"""Connection or response format failed."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class KaracaServiceError(KaracaError):
|
|
17
|
+
"""The service is temporarily unavailable."""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class KaracaRateLimitError(KaracaServiceError):
|
|
21
|
+
"""Cloud API request frequency was limited."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class KaracaDeviceNotFound(KaracaError):
|
|
25
|
+
"""No matching device was found."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class KaracaApiError(KaracaError):
|
|
29
|
+
"""Cloud API rejected the request."""
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: karaca-connect-client
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Unofficial asynchronous client for the Karaca Connect cloud API
|
|
5
|
+
Author: AzadGLR
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Azadglr/karaca-connect-client
|
|
8
|
+
Project-URL: Repository, https://github.com/Azadglr/karaca-connect-client
|
|
9
|
+
Project-URL: Issues, https://github.com/Azadglr/karaca-connect-client/issues
|
|
10
|
+
Keywords: karaca,home-assistant,asyncio,tea-maker
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Home Automation
|
|
19
|
+
Requires-Python: >=3.12
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
License-File: LICENSE
|
|
22
|
+
Requires-Dist: aiohttp<4,>=3.9
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
|
|
25
|
+
# Karaca Connect Client
|
|
26
|
+
|
|
27
|
+
Unofficial asynchronous Python client for the Karaca Connect cloud service.
|
|
28
|
+
|
|
29
|
+
> **Alpha** — This library is extracted from the community Home Assistant integration at
|
|
30
|
+
> [Azadglr/karaca-connect-unofficial](https://github.com/Azadglr/karaca-connect-unofficial).
|
|
31
|
+
> It has been tested with simulated API responses but has **not yet been independently
|
|
32
|
+
> authenticated against the live Karaca service** in this extracted form.
|
|
33
|
+
|
|
34
|
+
This project is not affiliated with or endorsed by Karaca. The service API is not publicly documented;
|
|
35
|
+
its behavior and availability can change without notice. Currently the original community integration
|
|
36
|
+
reports verified support for the Karaca Çaysever Robotea Pro Connect 4in1 only.
|
|
37
|
+
|
|
38
|
+
## Installation
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
pip install karaca-connect-client
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## Read-only example
|
|
45
|
+
|
|
46
|
+
```python
|
|
47
|
+
import asyncio
|
|
48
|
+
import getpass
|
|
49
|
+
from aiohttp import ClientSession
|
|
50
|
+
from karaca_connect_client import KaracaClient
|
|
51
|
+
|
|
52
|
+
async def main():
|
|
53
|
+
email = input("Karaca Connect email: ")
|
|
54
|
+
password = getpass.getpass("Karaca Connect password: ")
|
|
55
|
+
async with ClientSession() as session:
|
|
56
|
+
client = KaracaClient(session, email=email, password=password)
|
|
57
|
+
devices = await client.get_devices()
|
|
58
|
+
for device in devices:
|
|
59
|
+
print(device.get("id"), device.get("label"))
|
|
60
|
+
# In multi-device accounts, pass device_id=... explicitly.
|
|
61
|
+
# No device mode or settings are changed by this example.
|
|
62
|
+
|
|
63
|
+
asyncio.run(main())
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
The caller owns the `aiohttp.ClientSession` and is responsible for securing account credentials.
|
|
67
|
+
Please do not paste credentials, tokens, or device details into public issues.
|
|
68
|
+
|
|
69
|
+
## Functions
|
|
70
|
+
|
|
71
|
+
- Authenticate and renew tokens when the cloud API rejects expired authorization
|
|
72
|
+
- List devices, retrieve device details and notification settings
|
|
73
|
+
- Set device modes and notification settings (optional; supported capabilities may differ by model)
|
|
74
|
+
- Distinguish authentication, connectivity, rate-limit, cloud availability and API errors
|
|
75
|
+
- Refuse to silently select a device when more than one device is present
|
|
76
|
+
|
|
77
|
+
## Development
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
python -m pip install -e . pytest
|
|
81
|
+
python -m pytest tests
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Release policy
|
|
85
|
+
|
|
86
|
+
Source code and GitHub release tags are public. Publishing to PyPI is performed solely
|
|
87
|
+
by the `publish.yml` GitHub Actions workflow using PyPI Trusted Publishing. The version
|
|
88
|
+
in `pyproject.toml` must match the release tag without its leading `v`.
|
|
89
|
+
|
|
90
|
+
**Initial alpha release:** `v0.1.0a1`. No credentials or API tokens are stored in this repository.
|
|
91
|
+
|
|
92
|
+
License: MIT.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/karaca_connect_client/__init__.py
|
|
5
|
+
src/karaca_connect_client/client.py
|
|
6
|
+
src/karaca_connect_client/exceptions.py
|
|
7
|
+
src/karaca_connect_client/py.typed
|
|
8
|
+
src/karaca_connect_client.egg-info/PKG-INFO
|
|
9
|
+
src/karaca_connect_client.egg-info/SOURCES.txt
|
|
10
|
+
src/karaca_connect_client.egg-info/dependency_links.txt
|
|
11
|
+
src/karaca_connect_client.egg-info/requires.txt
|
|
12
|
+
src/karaca_connect_client.egg-info/top_level.txt
|
|
13
|
+
tests/test_client.py
|
|
14
|
+
tests/test_extra_contracts.py
|
|
15
|
+
tests/test_release_safety.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
aiohttp<4,>=3.9
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
karaca_connect_client
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Entirely offline simulations of the cloud API."""
|
|
2
|
+
|
|
3
|
+
import unittest
|
|
4
|
+
import asyncio
|
|
5
|
+
from aiohttp import ClientConnectionError
|
|
6
|
+
from collections import deque
|
|
7
|
+
|
|
8
|
+
from karaca_connect_client import (
|
|
9
|
+
KaracaApiError,
|
|
10
|
+
KaracaAuthError,
|
|
11
|
+
KaracaClient,
|
|
12
|
+
KaracaConnectionError,
|
|
13
|
+
KaracaDeviceNotFound,
|
|
14
|
+
KaracaRateLimitError,
|
|
15
|
+
KaracaServiceError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class FakeResponse:
|
|
20
|
+
def __init__(self, status, data):
|
|
21
|
+
self.status = status
|
|
22
|
+
self.data = data
|
|
23
|
+
|
|
24
|
+
async def __aenter__(self):
|
|
25
|
+
return self
|
|
26
|
+
|
|
27
|
+
async def __aexit__(self, *args):
|
|
28
|
+
return False
|
|
29
|
+
|
|
30
|
+
async def json(self, **kwargs):
|
|
31
|
+
return self.data
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class FakeSession:
|
|
35
|
+
def __init__(self, *responses):
|
|
36
|
+
self.responses = deque(responses)
|
|
37
|
+
self.calls = []
|
|
38
|
+
|
|
39
|
+
def request(self, method, url, **kwargs):
|
|
40
|
+
self.calls.append((method, url, kwargs))
|
|
41
|
+
return self.responses.popleft()
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ok_login(token="private-test-token"):
|
|
45
|
+
return FakeResponse(200, {"succeeded": True, "data": {"jwToken": token}})
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class KaracaClientTests(unittest.IsolatedAsyncioTestCase):
|
|
49
|
+
async def test_successful_login_and_detail(self):
|
|
50
|
+
session = FakeSession(ok_login(), FakeResponse(200, {"data": {"detail": {"mode": 6}, "meta": {"connected": True}}}))
|
|
51
|
+
client = KaracaClient(session, email="test@example.invalid", password="test", device_id="dev123")
|
|
52
|
+
self.assertEqual((await client.get_detail())["detail"]["mode"], 6)
|
|
53
|
+
self.assertEqual(session.calls[-1][2]["headers"]["Authorization"], "Bearer private-test-token")
|
|
54
|
+
|
|
55
|
+
async def test_device_selection(self):
|
|
56
|
+
session = FakeSession(ok_login(), FakeResponse(200, {"data": [{"id": 234, "label": "Test"}]}))
|
|
57
|
+
client = KaracaClient(session, email="t", password="t")
|
|
58
|
+
self.assertEqual(await client.resolve_device_id(), "234")
|
|
59
|
+
|
|
60
|
+
async def test_no_devices(self):
|
|
61
|
+
session = FakeSession(ok_login(), FakeResponse(200, {"data": []}))
|
|
62
|
+
client = KaracaClient(session, email="t", password="t")
|
|
63
|
+
with self.assertRaises(KaracaDeviceNotFound):
|
|
64
|
+
await client.resolve_device_id()
|
|
65
|
+
|
|
66
|
+
async def test_login_failure_never_includes_response_body(self):
|
|
67
|
+
session = FakeSession(FakeResponse(401, {"raw": "sensitive-upstream-response"}))
|
|
68
|
+
client = KaracaClient(session, email="t", password="bad")
|
|
69
|
+
with self.assertRaises(KaracaAuthError) as error:
|
|
70
|
+
await client.login()
|
|
71
|
+
self.assertNotIn("sensitive", str(error.exception))
|
|
72
|
+
|
|
73
|
+
async def test_missing_token(self):
|
|
74
|
+
client = KaracaClient(FakeSession(FakeResponse(200, {"data": {}})), email="t", password="t")
|
|
75
|
+
with self.assertRaises(KaracaAuthError):
|
|
76
|
+
await client.login()
|
|
77
|
+
|
|
78
|
+
async def test_token_refresh_on_401(self):
|
|
79
|
+
session = FakeSession(ok_login("old-token"), FakeResponse(401, {}), ok_login("new-token"), FakeResponse(200, {"data": {"detail": {"mode": 9}}}))
|
|
80
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
81
|
+
self.assertEqual((await client.get_detail())["detail"]["mode"], 9)
|
|
82
|
+
self.assertEqual(session.calls[-1][2]["headers"]["Authorization"], "Bearer new-token")
|
|
83
|
+
|
|
84
|
+
async def test_second_401_raises_without_infinite_retry(self):
|
|
85
|
+
session = FakeSession(ok_login("old"), FakeResponse(401, {}), ok_login("new"), FakeResponse(401, {}))
|
|
86
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
87
|
+
with self.assertRaises(KaracaAuthError):
|
|
88
|
+
await client.get_detail()
|
|
89
|
+
self.assertEqual(len(session.calls), 4)
|
|
90
|
+
|
|
91
|
+
async def test_429_rate_limit(self):
|
|
92
|
+
client = KaracaClient(FakeSession(ok_login(), FakeResponse(429, {})), email="t", password="t", device_id="dev")
|
|
93
|
+
with self.assertRaises(KaracaRateLimitError):
|
|
94
|
+
await client.get_detail()
|
|
95
|
+
|
|
96
|
+
async def test_503_service_unavailable(self):
|
|
97
|
+
client = KaracaClient(FakeSession(ok_login(), FakeResponse(503, {})), email="t", password="t", device_id="dev")
|
|
98
|
+
with self.assertRaises(KaracaServiceError):
|
|
99
|
+
await client.get_detail()
|
|
100
|
+
|
|
101
|
+
async def test_malformed_data(self):
|
|
102
|
+
client = KaracaClient(FakeSession(ok_login(), FakeResponse(200, {"data": None})), email="t", password="t", device_id="dev")
|
|
103
|
+
with self.assertRaises(KaracaConnectionError):
|
|
104
|
+
await client.get_detail()
|
|
105
|
+
|
|
106
|
+
async def test_mode_command(self):
|
|
107
|
+
session = FakeSession(ok_login(), FakeResponse(200, {"succeeded": True}))
|
|
108
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
109
|
+
await client.set_mode(9)
|
|
110
|
+
self.assertEqual(session.calls[-1][0], "PUT")
|
|
111
|
+
self.assertEqual(session.calls[-1][2]["json"], {"active": True})
|
|
112
|
+
|
|
113
|
+
async def test_settings_fallback(self):
|
|
114
|
+
session = FakeSession(ok_login(), FakeResponse(400, {"succeeded": False}), FakeResponse(200, {"succeeded": True}))
|
|
115
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
116
|
+
await client.set_setting(3, False)
|
|
117
|
+
self.assertEqual(session.calls[-1][2]["json"], {"active": False})
|
|
118
|
+
|
|
119
|
+
async def test_api_error_does_not_leak_payload(self):
|
|
120
|
+
client = KaracaClient(FakeSession(ok_login(), FakeResponse(400, {"raw": "secret-value", "succeeded": False})), email="t", password="t", device_id="dev")
|
|
121
|
+
with self.assertRaises(KaracaApiError) as error:
|
|
122
|
+
await client.get_detail()
|
|
123
|
+
self.assertNotIn("secret-value", str(error.exception))
|
|
124
|
+
|
|
125
|
+
async def test_get_settings(self):
|
|
126
|
+
client = KaracaClient(FakeSession(ok_login(), FakeResponse(200, {"data": {"notifications": [{"id": 3, "value": True}]}})), email="t", password="t", device_id="dev")
|
|
127
|
+
self.assertEqual((await client.get_settings())[0]["id"], 3)
|
|
128
|
+
|
|
129
|
+
async def test_service_error_with_html_response(self):
|
|
130
|
+
session = FakeSession(ok_login(), FakeResponse(503, None))
|
|
131
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
132
|
+
with self.assertRaises(KaracaServiceError):
|
|
133
|
+
await client.get_detail()
|
|
134
|
+
|
|
135
|
+
async def test_rate_limit_with_non_json_response(self):
|
|
136
|
+
session = FakeSession(ok_login(), FakeResponse(429, "Too Many Requests"))
|
|
137
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
138
|
+
with self.assertRaises(KaracaRateLimitError):
|
|
139
|
+
await client.get_detail()
|
|
140
|
+
|
|
141
|
+
async def test_service_error_during_login_is_not_auth_failure(self):
|
|
142
|
+
session = FakeSession(FakeResponse(503, {"succeeded": False}))
|
|
143
|
+
client = KaracaClient(session, email="t", password="t")
|
|
144
|
+
with self.assertRaises(KaracaServiceError):
|
|
145
|
+
await client.login()
|
|
146
|
+
|
|
147
|
+
async def test_login_rate_limit_is_not_invalid_credentials(self):
|
|
148
|
+
session = FakeSession(FakeResponse(429, {}))
|
|
149
|
+
client = KaracaClient(session, email="t", password="t")
|
|
150
|
+
with self.assertRaises(KaracaRateLimitError):
|
|
151
|
+
await client.login()
|
|
152
|
+
|
|
153
|
+
async def test_403_forbidden(self):
|
|
154
|
+
session = FakeSession(ok_login(), FakeResponse(403, {"raw": "secret"}))
|
|
155
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
156
|
+
with self.assertRaises(KaracaAuthError) as error:
|
|
157
|
+
await client.get_detail()
|
|
158
|
+
self.assertNotIn("secret", str(error.exception))
|
|
159
|
+
|
|
160
|
+
async def test_network_error_is_sanitized(self):
|
|
161
|
+
class OfflineSession:
|
|
162
|
+
def request(self, *_args, **_kwargs):
|
|
163
|
+
raise ClientConnectionError("upstream-user-secret")
|
|
164
|
+
client = KaracaClient(OfflineSession(), email="t", password="t")
|
|
165
|
+
with self.assertRaises(KaracaConnectionError) as error:
|
|
166
|
+
await client.login()
|
|
167
|
+
self.assertNotIn("upstream-user-secret", str(error.exception))
|
|
168
|
+
|
|
169
|
+
async def test_login_is_shared_across_concurrent_requests(self):
|
|
170
|
+
session = FakeSession(
|
|
171
|
+
ok_login(),
|
|
172
|
+
FakeResponse(200, {"data": []}),
|
|
173
|
+
FakeResponse(200, {"data": []}),
|
|
174
|
+
)
|
|
175
|
+
client = KaracaClient(session, email="t", password="t")
|
|
176
|
+
result = await asyncio.gather(client.get_devices(), client.get_devices())
|
|
177
|
+
self.assertEqual(result, [[], []])
|
|
178
|
+
self.assertEqual(sum(1 for call in session.calls if call[1].endswith("/api/auth/signin")), 1)
|
|
179
|
+
|
|
180
|
+
async def test_malformed_device_list(self):
|
|
181
|
+
session = FakeSession(ok_login(), FakeResponse(200, {"data": [1, 2]}))
|
|
182
|
+
client = KaracaClient(session, email="t", password="t")
|
|
183
|
+
with self.assertRaises(KaracaConnectionError):
|
|
184
|
+
await client.get_devices()
|
|
185
|
+
|
|
186
|
+
async def test_setting_fallback_does_not_trigger_for_rate_limit(self):
|
|
187
|
+
session = FakeSession(ok_login(), FakeResponse(429, {}))
|
|
188
|
+
client = KaracaClient(session, email="t", password="t", device_id="dev")
|
|
189
|
+
with self.assertRaises(KaracaRateLimitError):
|
|
190
|
+
await client.set_setting(3, False)
|
|
191
|
+
self.assertEqual(len(session.calls), 2)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
if __name__ == "__main__":
|
|
195
|
+
unittest.main()
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Additional purely offline contract and safety checks."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import unittest
|
|
5
|
+
from collections import deque
|
|
6
|
+
|
|
7
|
+
from karaca_connect_client import (
|
|
8
|
+
KaracaApiError,
|
|
9
|
+
KaracaAuthError,
|
|
10
|
+
KaracaClient,
|
|
11
|
+
KaracaConnectionError,
|
|
12
|
+
KaracaDeviceNotFound,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Response:
|
|
17
|
+
def __init__(self, status, body):
|
|
18
|
+
self.status, self.body = status, body
|
|
19
|
+
|
|
20
|
+
async def __aenter__(self):
|
|
21
|
+
return self
|
|
22
|
+
|
|
23
|
+
async def __aexit__(self, *_args):
|
|
24
|
+
return False
|
|
25
|
+
|
|
26
|
+
async def json(self, **_kwargs):
|
|
27
|
+
return self.body
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Session:
|
|
31
|
+
def __init__(self, *responses):
|
|
32
|
+
self.responses = deque(responses)
|
|
33
|
+
self.calls = []
|
|
34
|
+
|
|
35
|
+
def request(self, method, url, **kwargs):
|
|
36
|
+
self.calls.append((method, url, kwargs))
|
|
37
|
+
return self.responses.popleft()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def signed_in(token='token-1'):
|
|
41
|
+
return Response(200, {'data': {'jwToken': token}})
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ClientExtraTests(unittest.IsolatedAsyncioTestCase):
|
|
45
|
+
async def test_login_rejection_is_not_reported_as_connection_failure(self):
|
|
46
|
+
client = KaracaClient(Session(Response(200, {'succeeded': False, 'messages': ['invalid']})), email='u', password='p')
|
|
47
|
+
with self.assertRaises(KaracaAuthError):
|
|
48
|
+
await client.login()
|
|
49
|
+
|
|
50
|
+
async def test_bad_json_type_does_not_pass_as_valid_device_data(self):
|
|
51
|
+
client = KaracaClient(Session(signed_in(), Response(200, ['not-object'])), email='u', password='p')
|
|
52
|
+
with self.assertRaises(KaracaConnectionError):
|
|
53
|
+
await client.get_devices()
|
|
54
|
+
|
|
55
|
+
async def test_invalid_first_device_id_is_not_selected(self):
|
|
56
|
+
client = KaracaClient(Session(signed_in(), Response(200, {'data': [{'name': 'Unnamed'}]})), email='u', password='p')
|
|
57
|
+
with self.assertRaises(KaracaDeviceNotFound):
|
|
58
|
+
await client.resolve_device_id()
|
|
59
|
+
|
|
60
|
+
async def test_multiple_devices_without_selection_is_rejected(self):
|
|
61
|
+
session = Session(
|
|
62
|
+
signed_in(),
|
|
63
|
+
Response(200, {"data": [{"id": "dev-a"}, {"id": "dev-b"}]}),
|
|
64
|
+
)
|
|
65
|
+
client = KaracaClient(session, email="u", password="p")
|
|
66
|
+
with self.assertRaises(KaracaDeviceNotFound):
|
|
67
|
+
await client.resolve_device_id()
|
|
68
|
+
self.assertIsNone(client.device_id)
|
|
69
|
+
self.assertTrue(all(call[0] != "PUT" for call in session.calls))
|
|
70
|
+
|
|
71
|
+
async def test_explicit_selection_does_not_guess_or_fetch_device_list(self):
|
|
72
|
+
client = KaracaClient(Session(), email="u", password="p", device_id="dev-b")
|
|
73
|
+
self.assertEqual(await client.resolve_device_id(), "dev-b")
|
|
74
|
+
|
|
75
|
+
async def test_duplicate_device_id_and_invalid_first_device_is_not_used(self):
|
|
76
|
+
session = Session(
|
|
77
|
+
signed_in(),
|
|
78
|
+
Response(200, {"data": [{"label": "unknown"}, {"id": "valid"}]}),
|
|
79
|
+
)
|
|
80
|
+
client = KaracaClient(session, email="u", password="p")
|
|
81
|
+
with self.assertRaises(KaracaDeviceNotFound):
|
|
82
|
+
await client.resolve_device_id()
|
|
83
|
+
|
|
84
|
+
async def test_raw_password_not_present_in_client_repr(self):
|
|
85
|
+
client = KaracaClient(Session(), email='private@example.invalid', password='opaque-super-secret')
|
|
86
|
+
self.assertNotIn('opaque-super-secret', repr(client))
|
|
87
|
+
self.assertNotIn('private@example.invalid', repr(client))
|
|
88
|
+
|
|
89
|
+
async def test_failed_command_cannot_be_retried_with_different_payload_implicitly(self):
|
|
90
|
+
session = Session(signed_in(), Response(400, {'succeeded': False, 'raw': 'upstream-private'}))
|
|
91
|
+
client = KaracaClient(session, email='u', password='p', device_id='dev-1')
|
|
92
|
+
with self.assertRaises(KaracaApiError) as error:
|
|
93
|
+
await client.set_mode(6, True)
|
|
94
|
+
self.assertNotIn('upstream-private', str(error.exception))
|
|
95
|
+
self.assertEqual(len(session.calls), 2)
|
|
96
|
+
|
|
97
|
+
async def test_explicit_device_ids_are_kept_as_strings(self):
|
|
98
|
+
client = KaracaClient(Session(), email='u', password='p', device_id=123)
|
|
99
|
+
self.assertEqual(await client.resolve_device_id(), '123')
|
|
100
|
+
|
|
101
|
+
async def test_two_clients_do_not_share_tokens(self):
|
|
102
|
+
one = Session(signed_in('first-token'), Response(200, {'data': []}))
|
|
103
|
+
two = Session(signed_in('second-token'), Response(200, {'data': []}))
|
|
104
|
+
client_one = KaracaClient(one, email='one', password='one')
|
|
105
|
+
client_two = KaracaClient(two, email='two', password='two')
|
|
106
|
+
await asyncio.gather(client_one.get_devices(), client_two.get_devices())
|
|
107
|
+
self.assertEqual(one.calls[1][2]['headers']['Authorization'], 'Bearer first-token')
|
|
108
|
+
self.assertEqual(two.calls[1][2]['headers']['Authorization'], 'Bearer second-token')
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
if __name__ == '__main__':
|
|
112
|
+
unittest.main()
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Test basic safety preconditions without contacting a real Karaca account."""
|
|
2
|
+
|
|
3
|
+
import unittest
|
|
4
|
+
|
|
5
|
+
from karaca_connect_client import KaracaClient
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class ClientSafetyTests(unittest.TestCase):
|
|
9
|
+
def test_empty_credentials_rejected(self):
|
|
10
|
+
with self.assertRaises(ValueError):
|
|
11
|
+
KaracaClient(object(), email="", password="something")
|
|
12
|
+
|
|
13
|
+
def test_nonpositive_timeout_rejected(self):
|
|
14
|
+
for seconds in (0, -1, -10):
|
|
15
|
+
with self.subTest(seconds=seconds), self.assertRaises(ValueError):
|
|
16
|
+
KaracaClient(object(), email="test", password="secret", timeout_seconds=seconds)
|
|
17
|
+
|
|
18
|
+
def test_no_public_password_or_token_properties(self):
|
|
19
|
+
c = KaracaClient(object(), email="test", password="not-real")
|
|
20
|
+
self.assertFalse(hasattr(c, "password"))
|
|
21
|
+
self.assertFalse(hasattr(c, "token"))
|