aiopoolcop 1.0.0__py3-none-any.whl

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.
aiopoolcop/__init__.py ADDED
@@ -0,0 +1,96 @@
1
+ """Asynchronous Python client for the PoolCop Client API."""
2
+
3
+ from .client import PoolCopClientAPI, PoolCopCloudAPI
4
+ from .exceptions import (
5
+ PoolCopClientAuthError,
6
+ PoolCopClientConnectionError,
7
+ PoolCopClientError,
8
+ PoolCopClientNotFoundError,
9
+ PoolCopClientRateLimitError,
10
+ PoolCopCloudAuthError,
11
+ PoolCopCloudConnectionError,
12
+ PoolCopCloudError,
13
+ PoolCopCloudNotFoundError,
14
+ PoolCopCloudRateLimitError,
15
+ )
16
+ from .models import (
17
+ AcoSettings,
18
+ AuxSettings,
19
+ AuxTimer,
20
+ DeviceHistory,
21
+ DeviceMinimalistic,
22
+ DeviceSettings,
23
+ DeviceState,
24
+ DisinfectionSettings,
25
+ ElectrolyserSettings,
26
+ EquipmentsInfo,
27
+ FacSettings,
28
+ FcSettings,
29
+ FiltrationSettings,
30
+ FiltrationTimer,
31
+ FlowVisInfo,
32
+ JetStreamInfo,
33
+ OrpSettings,
34
+ PhSettings,
35
+ Pool,
36
+ PoolCopAuxiliary,
37
+ PoolCopCommand,
38
+ PoolCopDevice,
39
+ PoolCopState,
40
+ PoolCoverInfo,
41
+ PoolSettings,
42
+ PumpInfo,
43
+ RemnantSettings,
44
+ SuctionValveSettings,
45
+ TcSettings,
46
+ VersionInfo,
47
+ WaterLevelInfo,
48
+ WaterLevelSettings,
49
+ )
50
+
51
+ __all__ = [
52
+ "AcoSettings",
53
+ "AuxSettings",
54
+ "AuxTimer",
55
+ "DeviceHistory",
56
+ "DeviceMinimalistic",
57
+ "DeviceSettings",
58
+ "DeviceState",
59
+ "DisinfectionSettings",
60
+ "ElectrolyserSettings",
61
+ "EquipmentsInfo",
62
+ "FacSettings",
63
+ "FcSettings",
64
+ "FiltrationSettings",
65
+ "FiltrationTimer",
66
+ "FlowVisInfo",
67
+ "JetStreamInfo",
68
+ "OrpSettings",
69
+ "PhSettings",
70
+ "Pool",
71
+ "PoolCopAuxiliary",
72
+ "PoolCopClientAPI",
73
+ "PoolCopClientAuthError",
74
+ "PoolCopClientConnectionError",
75
+ "PoolCopClientError",
76
+ "PoolCopClientNotFoundError",
77
+ "PoolCopClientRateLimitError",
78
+ "PoolCopCloudAPI",
79
+ "PoolCopCloudAuthError",
80
+ "PoolCopCloudConnectionError",
81
+ "PoolCopCloudError",
82
+ "PoolCopCloudNotFoundError",
83
+ "PoolCopCloudRateLimitError",
84
+ "PoolCopCommand",
85
+ "PoolCopDevice",
86
+ "PoolCopState",
87
+ "PoolCoverInfo",
88
+ "PoolSettings",
89
+ "PumpInfo",
90
+ "RemnantSettings",
91
+ "SuctionValveSettings",
92
+ "TcSettings",
93
+ "VersionInfo",
94
+ "WaterLevelInfo",
95
+ "WaterLevelSettings",
96
+ ]
aiopoolcop/client.py ADDED
@@ -0,0 +1,294 @@
1
+ """Asynchronous client for the PoolCop Client API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import socket
8
+ from dataclasses import dataclass, field
9
+ from http import HTTPStatus
10
+ from typing import Any, Self
11
+
12
+ from aiohttp.client import ClientError, ClientSession
13
+ from yarl import URL
14
+
15
+ from .const import API_BASE_PATH, API_HOST, USER_AGENT
16
+ from .exceptions import (
17
+ PoolCopClientAuthError,
18
+ PoolCopClientConnectionError,
19
+ PoolCopClientError,
20
+ PoolCopClientNotFoundError,
21
+ PoolCopClientRateLimitError,
22
+ )
23
+ from .models import (
24
+ Pool,
25
+ PoolCopCommand,
26
+ PoolCopDevice,
27
+ )
28
+
29
+
30
+ @dataclass
31
+ class PoolCopClientAPI:
32
+ """Asynchronous client for the PoolCop Client API.
33
+
34
+ Uses x-api-key header authentication.
35
+ Rate limits: 1s between queries, 10s between queries on same entity.
36
+ """
37
+
38
+ api_key: str
39
+ session: ClientSession | None = None
40
+ request_timeout: float = 15.0
41
+
42
+ _close_session: bool = field(default=False, init=False, repr=False)
43
+
44
+ def _build_url(self, path: str) -> URL:
45
+ """Build a full API URL."""
46
+ return URL.build(
47
+ scheme="https",
48
+ host=API_HOST,
49
+ path=f"{API_BASE_PATH}/{path.lstrip('/')}",
50
+ )
51
+
52
+ def _headers(self) -> dict[str, str]:
53
+ """Return request headers."""
54
+ return {
55
+ "Accept": "application/json",
56
+ "User-Agent": USER_AGENT,
57
+ "x-api-key": self.api_key,
58
+ }
59
+
60
+ async def _request(
61
+ self,
62
+ method: str,
63
+ path: str,
64
+ *,
65
+ params: dict[str, Any] | None = None,
66
+ return_json: bool = True,
67
+ ) -> Any:
68
+ """Make an API request."""
69
+ if self.session is None:
70
+ self.session = ClientSession()
71
+ self._close_session = True
72
+
73
+ url = self._build_url(path)
74
+ headers = self._headers()
75
+
76
+ try:
77
+ async with asyncio.timeout(self.request_timeout):
78
+ response = await self.session.request(
79
+ method,
80
+ url,
81
+ headers=headers,
82
+ params=params,
83
+ )
84
+ except TimeoutError as err:
85
+ msg = "Timeout connecting to PoolCop Client API"
86
+ raise PoolCopClientConnectionError(msg) from err
87
+ except (ClientError, socket.gaierror) as err:
88
+ msg = f"Error connecting to PoolCop Client API: {err}"
89
+ raise PoolCopClientConnectionError(msg) from err
90
+
91
+ self._handle_error_status(response)
92
+
93
+ if not return_json:
94
+ return None
95
+
96
+ content_type = response.headers.get("Content-Type", "")
97
+ if "application/json" not in content_type:
98
+ text = await response.text()
99
+ msg = f"Unexpected content type: {content_type}: {text}"
100
+ raise PoolCopClientError(msg)
101
+
102
+ return await response.json()
103
+
104
+ @staticmethod
105
+ def _handle_error_status(response: Any) -> None:
106
+ """Raise typed exception for error HTTP status codes."""
107
+ status = response.status
108
+ if status == HTTPStatus.UNAUTHORIZED or status == HTTPStatus.FORBIDDEN:
109
+ msg = f"Authentication failed ({status})"
110
+ raise PoolCopClientAuthError(msg)
111
+ if status == HTTPStatus.NOT_FOUND:
112
+ msg = "Resource not found"
113
+ raise PoolCopClientNotFoundError(msg)
114
+ if status == HTTPStatus.TOO_MANY_REQUESTS:
115
+ retry_after = None
116
+ with contextlib.suppress(Exception):
117
+ data = response.headers.get("Retry-After")
118
+ if data:
119
+ retry_after = int(data)
120
+ msg = "Rate limit exceeded"
121
+ raise PoolCopClientRateLimitError(msg, retry_after=retry_after)
122
+ if status >= HTTPStatus.INTERNAL_SERVER_ERROR:
123
+ msg = f"Server error ({status})"
124
+ raise PoolCopClientError(msg)
125
+ if status >= HTTPStatus.BAD_REQUEST:
126
+ msg = f"Client error ({status})"
127
+ raise PoolCopClientError(msg)
128
+
129
+ # ------------------------------------------------------------------
130
+ # Pool endpoints
131
+ # ------------------------------------------------------------------
132
+
133
+ async def get_pools(self) -> list[Pool]:
134
+ """Get all pools the API key has access to."""
135
+ data = await self._request("GET", "/pools")
136
+ # Paginated response: {data: [...], currentPage, totalPages, ...}
137
+ items = data.get("data", []) if isinstance(data, dict) else []
138
+ return [Pool.from_dict(p) for p in items]
139
+
140
+ async def get_pool(self, pool_id: int) -> Pool:
141
+ """Get a specific pool by ID."""
142
+ data = await self._request("GET", f"/pools/{pool_id}")
143
+ return Pool.from_dict(data)
144
+
145
+ # ------------------------------------------------------------------
146
+ # Device endpoints
147
+ # ------------------------------------------------------------------
148
+
149
+ async def get_devices(self, *, page: int = 1) -> list[PoolCopDevice]:
150
+ """Get all devices the API key has access to (paginated)."""
151
+ data = await self._request("GET", "/devices", params={"page": page})
152
+ items = data.get("data", []) if isinstance(data, dict) else []
153
+ return [PoolCopDevice.from_dict(d) for d in items]
154
+
155
+ async def get_device(self, device_id: int) -> PoolCopDevice:
156
+ """Get a device with full state, settings, history, and equipments."""
157
+ data = await self._request("GET", f"/devices/{device_id}")
158
+ return PoolCopDevice.from_dict(data)
159
+
160
+ async def get_commands(self, device_id: int) -> list[PoolCopCommand]:
161
+ """Get command history for a device."""
162
+ data = await self._request("GET", f"/devices/{device_id}/commands")
163
+ items = data.get("data", []) if isinstance(data, dict) else []
164
+ return [PoolCopCommand.from_dict(c) for c in items]
165
+
166
+ # ------------------------------------------------------------------
167
+ # Device interaction endpoints
168
+ # ------------------------------------------------------------------
169
+
170
+ async def set_pump(self, device_id: int, *, on: bool, pump_id: int = 0) -> None:
171
+ """Turn pump on or off."""
172
+ await self._request(
173
+ "POST",
174
+ f"/devices/{device_id}/interactions/pumpstate",
175
+ params={"pumpState": str(on).lower(), "pumpId": pump_id},
176
+ return_json=False,
177
+ )
178
+
179
+ async def set_pump_speed(
180
+ self, device_id: int, speed: str, *, pump_id: int = 0
181
+ ) -> None:
182
+ """Set pump speed (None, Speed1-Speed8)."""
183
+ await self._request(
184
+ "POST",
185
+ f"/devices/{device_id}/interactions/pumpspeed",
186
+ params={"speed": speed, "pumpId": pump_id},
187
+ return_json=False,
188
+ )
189
+
190
+ async def set_pump_forced(
191
+ self, device_id: int, mode: str, *, pump_id: int = 0
192
+ ) -> None:
193
+ """Set forced filtration mode (NotForced, Forced24H, Forced48H, Forced72H)."""
194
+ await self._request(
195
+ "POST",
196
+ f"/devices/{device_id}/interactions/pumpforced",
197
+ params={"forcedMode": mode, "pumpId": pump_id},
198
+ return_json=False,
199
+ )
200
+
201
+ async def set_valve_position(
202
+ self, device_id: int, position: str, *, filter_id: int = 0
203
+ ) -> None:
204
+ """Set valve position (Filter, Waste, Closed, Backwash, Bypass, Rinse)."""
205
+ await self._request(
206
+ "POST",
207
+ f"/devices/{device_id}/interactions/valveposition",
208
+ params={"valvePosition": position, "filterId": filter_id},
209
+ return_json=False,
210
+ )
211
+
212
+ async def set_auxiliary(
213
+ self,
214
+ device_id: int,
215
+ module: str,
216
+ aux_id: int,
217
+ *,
218
+ on: bool,
219
+ ) -> None:
220
+ """Set an auxiliary output on or off."""
221
+ await self._request(
222
+ "POST",
223
+ f"/devices/{device_id}/interactions/auxstate",
224
+ params={
225
+ "auxState": str(on).lower(),
226
+ "auxId": aux_id,
227
+ "module": module,
228
+ },
229
+ return_json=False,
230
+ )
231
+
232
+ async def set_heating_setpoint(
233
+ self,
234
+ device_id: int,
235
+ setpoint: float,
236
+ aux_id: int,
237
+ module: str = "None",
238
+ ) -> None:
239
+ """Set heating setpoint for an auxiliary."""
240
+ await self._request(
241
+ "POST",
242
+ f"/devices/{device_id}/interactions/heatingsetpoint",
243
+ params={
244
+ "heatingSetpoint": setpoint,
245
+ "auxId": aux_id,
246
+ "module": module,
247
+ },
248
+ return_json=False,
249
+ )
250
+
251
+ async def set_jet_stream(self, device_id: int, *, on: bool) -> None:
252
+ """Turn the jet stream on or off."""
253
+ await self._request(
254
+ "POST",
255
+ f"/devices/{device_id}/interactions/jetstreamstate",
256
+ params={"jetStreamState": str(on).lower()},
257
+ return_json=False,
258
+ )
259
+
260
+ async def clear_alarm(self, device_id: int, alarm_code: str) -> None:
261
+ """Clear a specific alarm by code."""
262
+ await self._request(
263
+ "DELETE",
264
+ f"/devices/{device_id}/interactions/clearalarm",
265
+ params={"alarmCode": alarm_code},
266
+ return_json=False,
267
+ )
268
+
269
+ async def clear_all_alarms(self, device_id: int) -> None:
270
+ """Clear all active alarms."""
271
+ await self._request(
272
+ "DELETE",
273
+ f"/devices/{device_id}/interactions/clearalarms",
274
+ return_json=False,
275
+ )
276
+
277
+ # ------------------------------------------------------------------
278
+ # Session management
279
+ # ------------------------------------------------------------------
280
+
281
+ async def close(self) -> None:
282
+ """Close the client session if we created it."""
283
+ if self.session and self._close_session:
284
+ await self.session.close()
285
+
286
+ async def __aenter__(self) -> Self:
287
+ return self
288
+
289
+ async def __aexit__(self, *_exc_info: Any) -> None:
290
+ await self.close()
291
+
292
+
293
+ # Backwards-compatible alias
294
+ PoolCopCloudAPI = PoolCopClientAPI
aiopoolcop/const.py ADDED
@@ -0,0 +1,8 @@
1
+ """Constants for PoolCop Client API."""
2
+
3
+ from importlib import metadata
4
+ from typing import Final
5
+
6
+ API_HOST: Final = "client-api.poolcop.net"
7
+ API_BASE_PATH: Final = ""
8
+ USER_AGENT: Final = f"python-aiopoolcop/{metadata.version(__package__)}"
@@ -0,0 +1,35 @@
1
+ """Exceptions for PoolCop Client API."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class PoolCopClientError(Exception):
7
+ """Generic PoolCop Client API exception."""
8
+
9
+
10
+ class PoolCopClientConnectionError(PoolCopClientError):
11
+ """PoolCop Client API connection error."""
12
+
13
+
14
+ class PoolCopClientAuthError(PoolCopClientError):
15
+ """PoolCop Client API authentication error (invalid API key)."""
16
+
17
+
18
+ class PoolCopClientNotFoundError(PoolCopClientError):
19
+ """PoolCop Client API resource not found."""
20
+
21
+
22
+ class PoolCopClientRateLimitError(PoolCopClientError):
23
+ """PoolCop Client API rate limit exceeded."""
24
+
25
+ def __init__(self, message: str, *, retry_after: int | None = None) -> None:
26
+ super().__init__(message)
27
+ self.retry_after = retry_after
28
+
29
+
30
+ # Backwards-compatible aliases for existing integrations
31
+ PoolCopCloudError = PoolCopClientError
32
+ PoolCopCloudConnectionError = PoolCopClientConnectionError
33
+ PoolCopCloudAuthError = PoolCopClientAuthError
34
+ PoolCopCloudNotFoundError = PoolCopClientNotFoundError
35
+ PoolCopCloudRateLimitError = PoolCopClientRateLimitError