ha-atomberg-integration 1.1.1__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ratul BMG
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,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: ha-atomberg-integration
3
+ Version: 1.1.1
4
+ Summary: Async Python client for the Atomberg public cloud API (fans, water purifiers, smart locks)
5
+ Author: Ratul BMG
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ratulbmg/ha-atomberg-integration
8
+ Project-URL: Issues, https://github.com/ratulbmg/ha-atomberg-integration/issues
9
+ Keywords: atomberg,home-assistant,smart-home,iot
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: aiohttp>=3.9
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=8; extra == "test"
21
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ <p align="center"><img src="https://raw.githubusercontent.com/ratulbmg/ha-atomberg-integration/main/docs/logo.png" width="128" alt="ha-atomberg-integration logo"></p>
25
+
26
+ # ha-atomberg-integration
27
+
28
+ Async Python client for the [Atomberg public cloud API](https://developer.atomberg-iot.com/).
29
+ It supports Atomberg fans, water purifiers, and smart locks, and is used by the
30
+ Home Assistant `atomberg` integration.
31
+
32
+ This is an unofficial community library. It is not affiliated with or endorsed by Atomberg.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install ha-atomberg-integration
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ You need an API key and a refresh token, which you generate in the Atomberg Home app
43
+ (see the [developer portal](https://developer.atomberg-iot.com/)). Keep them private.
44
+
45
+ ```python
46
+ import asyncio
47
+
48
+ import aiohttp
49
+
50
+ from atomberg_api import AtombergClient
51
+
52
+
53
+ async def main() -> None:
54
+ async with aiohttp.ClientSession() as session:
55
+ client = AtombergClient(session, "YOUR_API_KEY", "YOUR_REFRESH_TOKEN")
56
+ for device in await client.async_get_devices():
57
+ print(device.name, device.device_type)
58
+ states = await client.async_get_states()
59
+ print(states)
60
+
61
+
62
+ asyncio.run(main())
63
+ ```
64
+
65
+ ## API limits
66
+
67
+ The public API allows 100 requests per day per account, shared with the Atomberg Home app
68
+ and any other tools using the same account. One call to `async_get_states()` returns the
69
+ state of every device.
70
+
71
+ ## Errors
72
+
73
+ - `AtombergAuthError`: the API key or refresh token was rejected.
74
+ - `AtombergConnectionError`: a network or server error.
75
+ - `AtombergError`: any other unexpected response. The two errors above inherit from it.
76
+
77
+ ## Development
78
+
79
+ ```bash
80
+ pip install -e ".[test]"
81
+ pytest
82
+ ```
83
+
84
+ ## License
85
+
86
+ MIT
@@ -0,0 +1,63 @@
1
+ <p align="center"><img src="https://raw.githubusercontent.com/ratulbmg/ha-atomberg-integration/main/docs/logo.png" width="128" alt="ha-atomberg-integration logo"></p>
2
+
3
+ # ha-atomberg-integration
4
+
5
+ Async Python client for the [Atomberg public cloud API](https://developer.atomberg-iot.com/).
6
+ It supports Atomberg fans, water purifiers, and smart locks, and is used by the
7
+ Home Assistant `atomberg` integration.
8
+
9
+ This is an unofficial community library. It is not affiliated with or endorsed by Atomberg.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install ha-atomberg-integration
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ You need an API key and a refresh token, which you generate in the Atomberg Home app
20
+ (see the [developer portal](https://developer.atomberg-iot.com/)). Keep them private.
21
+
22
+ ```python
23
+ import asyncio
24
+
25
+ import aiohttp
26
+
27
+ from atomberg_api import AtombergClient
28
+
29
+
30
+ async def main() -> None:
31
+ async with aiohttp.ClientSession() as session:
32
+ client = AtombergClient(session, "YOUR_API_KEY", "YOUR_REFRESH_TOKEN")
33
+ for device in await client.async_get_devices():
34
+ print(device.name, device.device_type)
35
+ states = await client.async_get_states()
36
+ print(states)
37
+
38
+
39
+ asyncio.run(main())
40
+ ```
41
+
42
+ ## API limits
43
+
44
+ The public API allows 100 requests per day per account, shared with the Atomberg Home app
45
+ and any other tools using the same account. One call to `async_get_states()` returns the
46
+ state of every device.
47
+
48
+ ## Errors
49
+
50
+ - `AtombergAuthError`: the API key or refresh token was rejected.
51
+ - `AtombergConnectionError`: a network or server error.
52
+ - `AtombergError`: any other unexpected response. The two errors above inherit from it.
53
+
54
+ ## Development
55
+
56
+ ```bash
57
+ pip install -e ".[test]"
58
+ pytest
59
+ ```
60
+
61
+ ## License
62
+
63
+ MIT
@@ -0,0 +1,39 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ha-atomberg-integration"
7
+ version = "1.1.1"
8
+ description = "Async Python client for the Atomberg public cloud API (fans, water purifiers, smart locks)"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.12"
13
+ authors = [{ name = "Ratul BMG" }]
14
+ keywords = ["atomberg", "home-assistant", "smart-home", "iot"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Framework :: AsyncIO",
18
+ "Intended Audience :: Developers",
19
+ "Programming Language :: Python :: 3",
20
+ "Typing :: Typed",
21
+ ]
22
+ dependencies = ["aiohttp>=3.9"]
23
+
24
+ [project.optional-dependencies]
25
+ test = ["pytest>=8", "pytest-asyncio>=0.23"]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/ratulbmg/ha-atomberg-integration"
29
+ Issues = "https://github.com/ratulbmg/ha-atomberg-integration/issues"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.setuptools.package-data]
35
+ atomberg_api = ["py.typed"]
36
+
37
+ [tool.pytest.ini_options]
38
+ asyncio_mode = "auto"
39
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,57 @@
1
+ """Async client for the Atomberg public cloud API."""
2
+
3
+ from .client import (
4
+ API_URL,
5
+ COMMAND_BRIGHTNESS,
6
+ COMMAND_FALLBACK_MODE,
7
+ COMMAND_IDLE_SLEEP,
8
+ COMMAND_LED,
9
+ COMMAND_LIGHT_MODE,
10
+ COMMAND_MODE,
11
+ COMMAND_POWER,
12
+ COMMAND_SLEEP,
13
+ COMMAND_SLEEP_WINDOW,
14
+ COMMAND_SPEED,
15
+ COMMAND_START_UTC,
16
+ COMMAND_STOP_UTC,
17
+ COMMAND_TDS_THRESHOLD,
18
+ COMMAND_TIMER,
19
+ DEFAULT_FAN_COMMANDS,
20
+ DEVICE_TYPE_FAN,
21
+ DEVICE_TYPE_LOCK,
22
+ DEVICE_TYPE_WATER_PURIFIER,
23
+ AtombergAuthError,
24
+ AtombergClient,
25
+ AtombergConnectionError,
26
+ AtombergDevice,
27
+ AtombergError,
28
+ parse_state,
29
+ )
30
+
31
+ __all__ = [
32
+ "API_URL",
33
+ "COMMAND_BRIGHTNESS",
34
+ "COMMAND_FALLBACK_MODE",
35
+ "COMMAND_IDLE_SLEEP",
36
+ "COMMAND_LED",
37
+ "COMMAND_LIGHT_MODE",
38
+ "COMMAND_MODE",
39
+ "COMMAND_POWER",
40
+ "COMMAND_SLEEP",
41
+ "COMMAND_SLEEP_WINDOW",
42
+ "COMMAND_SPEED",
43
+ "COMMAND_START_UTC",
44
+ "COMMAND_STOP_UTC",
45
+ "COMMAND_TDS_THRESHOLD",
46
+ "COMMAND_TIMER",
47
+ "DEFAULT_FAN_COMMANDS",
48
+ "DEVICE_TYPE_FAN",
49
+ "DEVICE_TYPE_LOCK",
50
+ "DEVICE_TYPE_WATER_PURIFIER",
51
+ "AtombergAuthError",
52
+ "AtombergClient",
53
+ "AtombergConnectionError",
54
+ "AtombergDevice",
55
+ "AtombergError",
56
+ "parse_state",
57
+ ]
@@ -0,0 +1,235 @@
1
+ """Async client for the Atomberg public cloud API."""
2
+
3
+ import asyncio
4
+ from dataclasses import dataclass
5
+ import json
6
+ import time
7
+ from typing import Any, Self
8
+
9
+ from aiohttp import ClientError, ClientSession, ClientTimeout
10
+
11
+ API_URL = "https://api.developer.atomberg-iot.com"
12
+ REQUEST_TIMEOUT = ClientTimeout(total=30)
13
+ ACCESS_TOKEN_LIFETIME = 23 * 60 * 60
14
+
15
+ DEVICE_TYPE_FAN = "fan"
16
+ DEVICE_TYPE_WATER_PURIFIER = "water_purifier"
17
+ DEVICE_TYPE_LOCK = "lock"
18
+
19
+ COMMAND_POWER = "power"
20
+ COMMAND_SPEED = "speed"
21
+ COMMAND_SLEEP = "sleep"
22
+ COMMAND_TIMER = "timer"
23
+ COMMAND_LED = "led"
24
+ COMMAND_BRIGHTNESS = "brightness"
25
+ COMMAND_LIGHT_MODE = "light_mode"
26
+
27
+ COMMAND_MODE = "mode"
28
+ COMMAND_FALLBACK_MODE = "fallback_mode"
29
+ COMMAND_TDS_THRESHOLD = "tds_threshold"
30
+ COMMAND_IDLE_SLEEP = "idle_sleep"
31
+ COMMAND_SLEEP_WINDOW = "sleep_mode"
32
+ COMMAND_START_UTC = "start_utc"
33
+ COMMAND_STOP_UTC = "stop_utc"
34
+
35
+ DEFAULT_FAN_COMMANDS = frozenset({COMMAND_POWER, COMMAND_SPEED})
36
+
37
+
38
+ class AtombergError(Exception):
39
+ """Base error for the Atomberg API."""
40
+
41
+
42
+ class AtombergConnectionError(AtombergError):
43
+ """Error talking to the Atomberg API."""
44
+
45
+
46
+ class AtombergAuthError(AtombergError):
47
+ """The API key or refresh token was rejected."""
48
+
49
+
50
+ @dataclass(frozen=True, slots=True)
51
+ class AtombergDevice:
52
+ """A device registered to the Atomberg account."""
53
+
54
+ device_id: str
55
+ name: str
56
+ model: str | None
57
+ series: str | None
58
+ color: str | None
59
+ device_type: str
60
+ supported_commands: frozenset[str]
61
+
62
+ @classmethod
63
+ def from_api(cls, data: dict[str, Any]) -> Self:
64
+ """Build a device from an entry of ``get_list_of_devices``."""
65
+ commands = frozenset(
66
+ command["command"] for command in data.get("supported_commands") or []
67
+ )
68
+ device_type = data.get("device_type", DEVICE_TYPE_FAN)
69
+ return cls(
70
+ device_id=data["device_id"],
71
+ name=data["name"],
72
+ model=data.get("model"),
73
+ series=data.get("series"),
74
+ color=data.get("color"),
75
+ device_type=device_type,
76
+ supported_commands=commands
77
+ or (
78
+ DEFAULT_FAN_COMMANDS if device_type == DEVICE_TYPE_FAN else frozenset()
79
+ ),
80
+ )
81
+
82
+
83
+ def parse_state(device: AtombergDevice, data: dict[str, Any]) -> dict[str, Any]:
84
+ """Map an entry of ``get_device_state`` to the keys used by the integration."""
85
+ if device.device_type in (DEVICE_TYPE_WATER_PURIFIER, DEVICE_TYPE_LOCK):
86
+ return {**data, "is_online": data.get("is_online", True)}
87
+ return {
88
+ "is_online": data.get("is_online", True),
89
+ COMMAND_POWER: data.get("power", False),
90
+ COMMAND_SPEED: data.get("last_recorded_speed"),
91
+ COMMAND_SLEEP: data.get("sleep_mode", False),
92
+ COMMAND_LED: data.get("led", False),
93
+ COMMAND_BRIGHTNESS: data.get("last_recorded_brightness"),
94
+ COMMAND_LIGHT_MODE: data.get("last_recorded_color"),
95
+ "timer_hours": data.get("timer_hours"),
96
+ }
97
+
98
+
99
+ class AtombergClient:
100
+ """Async client for the Atomberg Home public API."""
101
+
102
+ def __init__(
103
+ self, session: ClientSession, api_key: str, refresh_token: str
104
+ ) -> None:
105
+ """Initialize the client."""
106
+ self._session = session
107
+ self._api_key = api_key
108
+ self._refresh_token = refresh_token
109
+ self._access_token: str | None = None
110
+ self._access_token_expires = 0.0
111
+ self._token_lock = asyncio.Lock()
112
+
113
+ async def async_get_devices(self) -> list[AtombergDevice]:
114
+ """Return all devices on the account."""
115
+ message = await self._async_authorized_request("GET", "/v1/get_list_of_devices")
116
+ try:
117
+ return [
118
+ AtombergDevice.from_api(device) for device in message["devices_list"]
119
+ ]
120
+ except (KeyError, TypeError) as err:
121
+ raise AtombergError("Unexpected device list response") from err
122
+
123
+ async def async_get_states(self) -> dict[str, dict[str, Any]]:
124
+ """Return the raw state of every device, keyed by device ID, in one call."""
125
+ message = await self._async_authorized_request(
126
+ "GET", "/v1/get_device_state", params={"device_id": "all"}
127
+ )
128
+ try:
129
+ return {state["device_id"]: state for state in message["device_state"]}
130
+ except (KeyError, TypeError) as err:
131
+ raise AtombergError("Unexpected device state response") from err
132
+
133
+ async def async_send_command(self, device_id: str, command: dict[str, Any]) -> None:
134
+ """Send a command to a device."""
135
+ await self._async_authorized_request(
136
+ "POST",
137
+ "/v1/send_command",
138
+ json_body={"device_id": device_id, "command": command},
139
+ )
140
+
141
+ async def async_get_guest_pin(
142
+ self, device_id: str, start_time: int | None = None, end_time: int | None = None
143
+ ) -> dict[str, Any]:
144
+ """Generate a temporary guest PIN for a lock."""
145
+ body: dict[str, Any] = {"device_id": device_id}
146
+ if start_time is not None and end_time is not None:
147
+ body["start_time"] = start_time
148
+ body["end_time"] = end_time
149
+ message = await self._async_authorized_request(
150
+ "POST", "/v1/get_lock_dynamic_pin", json_body=body
151
+ )
152
+ try:
153
+ data: dict[str, Any] = message["data"]
154
+ except (KeyError, TypeError) as err:
155
+ raise AtombergError("Unexpected guest PIN response") from err
156
+ return data
157
+
158
+ async def _async_get_access_token(self) -> str:
159
+ async with self._token_lock:
160
+ if self._access_token and time.monotonic() < self._access_token_expires:
161
+ return self._access_token
162
+ message = await self._async_request(
163
+ "GET",
164
+ "/v1/get_access_token",
165
+ bearer=self._refresh_token,
166
+ auth_error_statuses=(401, 403),
167
+ )
168
+ try:
169
+ self._access_token = message["access_token"]
170
+ except (KeyError, TypeError) as err:
171
+ raise AtombergError("Unexpected access token response") from err
172
+ self._access_token_expires = time.monotonic() + ACCESS_TOKEN_LIFETIME
173
+ return self._access_token
174
+
175
+ async def _async_authorized_request(
176
+ self,
177
+ method: str,
178
+ path: str,
179
+ *,
180
+ params: dict[str, str] | None = None,
181
+ json_body: dict[str, Any] | None = None,
182
+ ) -> Any:
183
+ token = await self._async_get_access_token()
184
+ try:
185
+ return await self._async_request(
186
+ method, path, bearer=token, params=params, json_body=json_body
187
+ )
188
+ except AtombergAuthError:
189
+ self._access_token = None
190
+ token = await self._async_get_access_token()
191
+ return await self._async_request(
192
+ method, path, bearer=token, params=params, json_body=json_body
193
+ )
194
+
195
+ async def _async_request(
196
+ self,
197
+ method: str,
198
+ path: str,
199
+ *,
200
+ bearer: str,
201
+ params: dict[str, str] | None = None,
202
+ json_body: dict[str, Any] | None = None,
203
+ auth_error_statuses: tuple[int, ...] = (401,),
204
+ ) -> Any:
205
+ headers = {
206
+ "Accept": "application/json",
207
+ "Authorization": f"Bearer {bearer}",
208
+ "x-api-key": self._api_key,
209
+ }
210
+ try:
211
+ async with self._session.request(
212
+ method,
213
+ f"{API_URL}{path}",
214
+ headers=headers,
215
+ params=params,
216
+ json=json_body,
217
+ timeout=REQUEST_TIMEOUT,
218
+ ) as response:
219
+ status = response.status
220
+ body = await response.text()
221
+ except (ClientError, TimeoutError) as err:
222
+ raise AtombergConnectionError(str(err)) from err
223
+
224
+ if status in auth_error_statuses:
225
+ raise AtombergAuthError(f"HTTP {status}")
226
+ if status >= 400:
227
+ raise AtombergConnectionError(f"HTTP {status}: {body[:200]}")
228
+
229
+ try:
230
+ data = json.loads(body)
231
+ except ValueError as err:
232
+ raise AtombergError("Response was not valid JSON") from err
233
+ if not isinstance(data, dict) or data.get("status") != "Success":
234
+ raise AtombergError(f"API reported failure: {body[:200]}")
235
+ return data.get("message")
@@ -0,0 +1,86 @@
1
+ Metadata-Version: 2.4
2
+ Name: ha-atomberg-integration
3
+ Version: 1.1.1
4
+ Summary: Async Python client for the Atomberg public cloud API (fans, water purifiers, smart locks)
5
+ Author: Ratul BMG
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ratulbmg/ha-atomberg-integration
8
+ Project-URL: Issues, https://github.com/ratulbmg/ha-atomberg-integration/issues
9
+ Keywords: atomberg,home-assistant,smart-home,iot
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Framework :: AsyncIO
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.12
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Requires-Dist: aiohttp>=3.9
19
+ Provides-Extra: test
20
+ Requires-Dist: pytest>=8; extra == "test"
21
+ Requires-Dist: pytest-asyncio>=0.23; extra == "test"
22
+ Dynamic: license-file
23
+
24
+ <p align="center"><img src="https://raw.githubusercontent.com/ratulbmg/ha-atomberg-integration/main/docs/logo.png" width="128" alt="ha-atomberg-integration logo"></p>
25
+
26
+ # ha-atomberg-integration
27
+
28
+ Async Python client for the [Atomberg public cloud API](https://developer.atomberg-iot.com/).
29
+ It supports Atomberg fans, water purifiers, and smart locks, and is used by the
30
+ Home Assistant `atomberg` integration.
31
+
32
+ This is an unofficial community library. It is not affiliated with or endorsed by Atomberg.
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ pip install ha-atomberg-integration
38
+ ```
39
+
40
+ ## Usage
41
+
42
+ You need an API key and a refresh token, which you generate in the Atomberg Home app
43
+ (see the [developer portal](https://developer.atomberg-iot.com/)). Keep them private.
44
+
45
+ ```python
46
+ import asyncio
47
+
48
+ import aiohttp
49
+
50
+ from atomberg_api import AtombergClient
51
+
52
+
53
+ async def main() -> None:
54
+ async with aiohttp.ClientSession() as session:
55
+ client = AtombergClient(session, "YOUR_API_KEY", "YOUR_REFRESH_TOKEN")
56
+ for device in await client.async_get_devices():
57
+ print(device.name, device.device_type)
58
+ states = await client.async_get_states()
59
+ print(states)
60
+
61
+
62
+ asyncio.run(main())
63
+ ```
64
+
65
+ ## API limits
66
+
67
+ The public API allows 100 requests per day per account, shared with the Atomberg Home app
68
+ and any other tools using the same account. One call to `async_get_states()` returns the
69
+ state of every device.
70
+
71
+ ## Errors
72
+
73
+ - `AtombergAuthError`: the API key or refresh token was rejected.
74
+ - `AtombergConnectionError`: a network or server error.
75
+ - `AtombergError`: any other unexpected response. The two errors above inherit from it.
76
+
77
+ ## Development
78
+
79
+ ```bash
80
+ pip install -e ".[test]"
81
+ pytest
82
+ ```
83
+
84
+ ## License
85
+
86
+ MIT
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/atomberg_api/__init__.py
5
+ src/atomberg_api/client.py
6
+ src/atomberg_api/py.typed
7
+ src/ha_atomberg_integration.egg-info/PKG-INFO
8
+ src/ha_atomberg_integration.egg-info/SOURCES.txt
9
+ src/ha_atomberg_integration.egg-info/dependency_links.txt
10
+ src/ha_atomberg_integration.egg-info/requires.txt
11
+ src/ha_atomberg_integration.egg-info/top_level.txt
12
+ tests/test_client.py
@@ -0,0 +1,5 @@
1
+ aiohttp>=3.9
2
+
3
+ [test]
4
+ pytest>=8
5
+ pytest-asyncio>=0.23
@@ -0,0 +1,294 @@
1
+ """Tests for the Atomberg API client."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections import defaultdict
6
+ import json
7
+ from typing import Any
8
+
9
+ import aiohttp
10
+ import pytest
11
+
12
+ from atomberg_api import (
13
+ API_URL,
14
+ AtombergAuthError,
15
+ AtombergClient,
16
+ AtombergConnectionError,
17
+ AtombergDevice,
18
+ AtombergError,
19
+ )
20
+
21
+ TOKEN_URL = f"{API_URL}/v1/get_access_token"
22
+ DEVICES_URL = f"{API_URL}/v1/get_list_of_devices"
23
+ STATE_URL = f"{API_URL}/v1/get_device_state"
24
+ COMMAND_URL = f"{API_URL}/v1/send_command"
25
+ PIN_URL = f"{API_URL}/v1/get_lock_dynamic_pin"
26
+ TOKEN_RESPONSE = {"status": "Success", "message": {"access_token": "access-1"}}
27
+
28
+
29
+ class _Response:
30
+ def __init__(self, status: int, body: str) -> None:
31
+ self.status = status
32
+ self._body = body
33
+
34
+ async def __aenter__(self) -> _Response:
35
+ return self
36
+
37
+ async def __aexit__(self, *args: object) -> None:
38
+ return None
39
+
40
+ async def text(self) -> str:
41
+ return self._body
42
+
43
+
44
+ class FakeSession:
45
+ """Minimal stand-in for aiohttp.ClientSession."""
46
+
47
+ def __init__(self) -> None:
48
+ self._responses: dict[str, list[Any]] = defaultdict(list)
49
+ self.calls: dict[str, list[dict[str, Any]]] = defaultdict(list)
50
+
51
+ def add(
52
+ self,
53
+ url: str,
54
+ *,
55
+ payload: Any = None,
56
+ body: str | None = None,
57
+ status: int = 200,
58
+ exception: Exception | None = None,
59
+ repeat: bool = False,
60
+ ) -> None:
61
+ """Queue a response for a URL."""
62
+ text = body if body is not None else json.dumps(payload)
63
+ self._responses[url].append((status, text, exception, repeat))
64
+
65
+ def request(self, method: str, url: str, **kwargs: Any) -> _Response:
66
+ """Return the next queued response for the URL."""
67
+ self.calls[url].append({"method": method, **kwargs})
68
+ queue = self._responses[url]
69
+ status, text, exception, repeat = queue[0]
70
+ if not repeat and len(queue) > 1:
71
+ queue.pop(0)
72
+ if exception is not None:
73
+ raise exception
74
+ return _Response(status, text)
75
+
76
+
77
+ @pytest.fixture
78
+ def mocked() -> FakeSession:
79
+ """Return a fake session."""
80
+ return FakeSession()
81
+
82
+
83
+ @pytest.fixture
84
+ def client(mocked: FakeSession) -> AtombergClient:
85
+ """Return a client using the fake session."""
86
+ return AtombergClient(mocked, "key", "refresh") # type: ignore[arg-type]
87
+
88
+
89
+ def _calls(mocked: FakeSession, url: str) -> list[dict[str, Any]]:
90
+ return mocked.calls[url]
91
+
92
+
93
+ async def test_token_is_reused(mocked: FakeSession, client: AtombergClient) -> None:
94
+ """One token request serves several calls and headers are set."""
95
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
96
+ mocked.add(
97
+ DEVICES_URL,
98
+ payload={"status": "Success", "message": {"devices_list": []}},
99
+ repeat=True,
100
+ )
101
+
102
+ assert await client.async_get_devices() == []
103
+ await client.async_get_devices()
104
+
105
+ token_calls = _calls(mocked, TOKEN_URL)
106
+ assert len(token_calls) == 1
107
+ assert token_calls[0]["headers"]["Authorization"] == "Bearer refresh"
108
+ assert token_calls[0]["headers"]["x-api-key"] == "key"
109
+ device_calls = _calls(mocked, DEVICES_URL)
110
+ assert device_calls[0]["headers"]["Authorization"] == "Bearer access-1"
111
+
112
+
113
+ async def test_rejected_access_token_refreshes_once(
114
+ mocked: FakeSession, client: AtombergClient
115
+ ) -> None:
116
+ """A 401 triggers exactly one token refresh and retry before failing."""
117
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE, repeat=True)
118
+ mocked.add(DEVICES_URL, status=401, repeat=True)
119
+
120
+ with pytest.raises(AtombergAuthError):
121
+ await client.async_get_devices()
122
+
123
+ assert len(_calls(mocked, TOKEN_URL)) == 2
124
+ assert len(_calls(mocked, DEVICES_URL)) == 2
125
+
126
+
127
+ @pytest.mark.parametrize(
128
+ ("status", "exception"),
129
+ [
130
+ (401, AtombergAuthError),
131
+ (403, AtombergAuthError),
132
+ (500, AtombergConnectionError),
133
+ ],
134
+ )
135
+ async def test_token_request_errors(
136
+ mocked: FakeSession,
137
+ client: AtombergClient,
138
+ status: int,
139
+ exception: type[AtombergError],
140
+ ) -> None:
141
+ """Token endpoint errors map to the right exception."""
142
+ mocked.add(TOKEN_URL, status=status)
143
+
144
+ with pytest.raises(exception):
145
+ await client.async_get_devices()
146
+
147
+
148
+ async def test_connection_error(mocked: FakeSession, client: AtombergClient) -> None:
149
+ """A network failure maps to a connection error."""
150
+ mocked.add(TOKEN_URL, exception=TimeoutError())
151
+
152
+ with pytest.raises(AtombergConnectionError):
153
+ await client.async_get_devices()
154
+
155
+
156
+ async def test_bad_token_response(mocked: FakeSession, client: AtombergClient) -> None:
157
+ """A token response without a token raises."""
158
+ mocked.add(TOKEN_URL, payload={"status": "Success", "message": {}})
159
+
160
+ with pytest.raises(AtombergError):
161
+ await client.async_get_devices()
162
+
163
+
164
+ async def test_invalid_json(mocked: FakeSession, client: AtombergClient) -> None:
165
+ """A non-JSON body raises."""
166
+ mocked.add(TOKEN_URL, body="not json")
167
+
168
+ with pytest.raises(AtombergError):
169
+ await client.async_get_devices()
170
+
171
+
172
+ @pytest.mark.parametrize(
173
+ "body",
174
+ [
175
+ {"status": "Failure", "message": "nope"},
176
+ {"status": "Success", "message": {"unexpected": []}},
177
+ ],
178
+ )
179
+ async def test_bad_device_list(
180
+ mocked: FakeSession, client: AtombergClient, body: dict[str, Any]
181
+ ) -> None:
182
+ """Unexpected device list responses raise."""
183
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
184
+ mocked.add(DEVICES_URL, payload=body)
185
+
186
+ with pytest.raises(AtombergError):
187
+ await client.async_get_devices()
188
+
189
+
190
+ async def test_get_devices_parses(mocked: FakeSession, client: AtombergClient) -> None:
191
+ """Devices are parsed into AtombergDevice objects."""
192
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
193
+ mocked.add(
194
+ DEVICES_URL,
195
+ payload={
196
+ "status": "Success",
197
+ "message": {
198
+ "devices_list": [
199
+ {"device_id": "abc", "name": "Fan", "series": "I1", "model": "M"}
200
+ ]
201
+ },
202
+ },
203
+ )
204
+
205
+ devices = await client.async_get_devices()
206
+
207
+ assert len(devices) == 1
208
+ assert isinstance(devices[0], AtombergDevice)
209
+ assert devices[0].device_id == "abc"
210
+
211
+
212
+ async def test_get_states(mocked: FakeSession, client: AtombergClient) -> None:
213
+ """States are keyed by device ID."""
214
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
215
+ mocked.add(
216
+ STATE_URL,
217
+ payload={
218
+ "status": "Success",
219
+ "message": {"device_state": [{"device_id": "abc", "power": True}]},
220
+ },
221
+ )
222
+
223
+ assert await client.async_get_states() == {
224
+ "abc": {"device_id": "abc", "power": True}
225
+ }
226
+
227
+
228
+ async def test_bad_states(mocked: FakeSession, client: AtombergClient) -> None:
229
+ """Unexpected state responses raise."""
230
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
231
+ mocked.add(STATE_URL, payload={"status": "Success", "message": {}})
232
+
233
+ with pytest.raises(AtombergError):
234
+ await client.async_get_states()
235
+
236
+
237
+ async def test_send_command_payload(
238
+ mocked: FakeSession, client: AtombergClient
239
+ ) -> None:
240
+ """The command request body is correct."""
241
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
242
+ mocked.add(COMMAND_URL, payload={"status": "Success", "message": {}})
243
+
244
+ await client.async_send_command("abc", {"speed": 4})
245
+
246
+ assert _calls(mocked, COMMAND_URL)[0]["json"] == {
247
+ "device_id": "abc",
248
+ "command": {"speed": 4},
249
+ }
250
+
251
+
252
+ @pytest.mark.parametrize(
253
+ ("window", "expected_body"),
254
+ [
255
+ ((None, None), {"device_id": "abc"}),
256
+ ((10, 20), {"device_id": "abc", "start_time": 10, "end_time": 20}),
257
+ ],
258
+ )
259
+ async def test_guest_pin_request(
260
+ mocked: FakeSession,
261
+ client: AtombergClient,
262
+ window: tuple[int | None, int | None],
263
+ expected_body: dict[str, Any],
264
+ ) -> None:
265
+ """The guest PIN request body and response parsing."""
266
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
267
+ mocked.add(
268
+ PIN_URL,
269
+ payload={"status": "Success", "message": {"data": {"otp": "123456"}}},
270
+ )
271
+
272
+ pin = await client.async_get_guest_pin("abc", *window)
273
+
274
+ assert pin == {"otp": "123456"}
275
+ assert _calls(mocked, PIN_URL)[0]["json"] == expected_body
276
+
277
+
278
+ async def test_guest_pin_bad_response(
279
+ mocked: FakeSession, client: AtombergClient
280
+ ) -> None:
281
+ """A response without PIN data raises."""
282
+ mocked.add(TOKEN_URL, payload=TOKEN_RESPONSE)
283
+ mocked.add(PIN_URL, payload={"status": "Success", "message": {}})
284
+
285
+ with pytest.raises(AtombergError):
286
+ await client.async_get_guest_pin("abc")
287
+
288
+
289
+ async def test_client_error_maps(mocked: FakeSession, client: AtombergClient) -> None:
290
+ """An aiohttp client error maps to a connection error."""
291
+ mocked.add(TOKEN_URL, exception=aiohttp.ClientError("boom"))
292
+
293
+ with pytest.raises(AtombergConnectionError):
294
+ await client.async_get_devices()