prana-api-client 0.2.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.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.4
2
+ Name: prana-api-client
3
+ Version: 0.2.0
4
+ Summary: Async API client for Prana heat recovery ventilator.
5
+ Author-email: Prana Developer <devprana18@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/YourUsername/prana-api-client
8
+ Keywords: prana,ventilator,api,async
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ Requires-Dist: aiohttp>=3.9.0
13
+ Dynamic: license-file
14
+
15
+ # Prana Local API Client
16
+
17
+ Prana Local API Client is a small asynchronous Python library to interact with a local HTTP API exposed by a Prana device. It uses aiohttp and provides a simple interface to read device state and send control commands.
18
+
19
+ ## Requirements
20
+ - Python 3.9+
21
+ - aiohttp
22
+
23
+ Install dependencies:
24
+ ```bash
25
+ pip install aiohttp
26
+ ```
27
+
28
+ ## Overview
29
+ Primary class: `PranaLocalApiClient`
30
+
31
+ Constructor:
32
+ - `PranaLocalApiClient(host: str, port: int = 80)`
33
+
34
+ Behavior summary:
35
+ - Uses an aiohttp ClientSession. You can provide/retain a session by using the client as an async context manager (`async with`) or let the client create and close a temporary session for each call.
36
+ - Requests use a total timeout of 10 seconds.
37
+ - Non-200 HTTP responses raise `PranaApiUpdateFailed`.
38
+ - Network errors and timeouts raise `PranaApiCommunicationError`.
39
+
40
+ ## API (async)
41
+
42
+ - `async def get_state() -> dict[str, Any] | None`
43
+ - GET /getState
44
+ - Returns parsed JSON when the server responds with `application/json`. Returns `None` for responses without JSON body.
45
+
46
+ - `async def set_speed(speed: int, fan_type: str) -> None`
47
+ - POST /setSpeed
48
+ - JSON body: `{"speed": speed, "fanType": fan_type}`
49
+
50
+ - `async def set_switch(switch_type: str, value: bool) -> None`
51
+ - POST /setSwitch
52
+ - JSON body: `{"switchType": switch_type, "value": value}`
53
+
54
+ - `async def set_brightness(brightness: int) -> None`
55
+ - POST /setBrightness
56
+ - JSON body: `{"brightness": brightness}`
57
+
58
+ Notes:
59
+ - All methods call a shared internal `_async_request` which handles creating/closing sessions when needed, error handling and JSON parsing.
60
+
61
+ ## Exceptions
62
+ The library exposes a small exception hierarchy in `prana_local_api_client.exceptions`:
63
+
64
+ - `PranaApiClientException` — base exception class.
65
+ - `PranaApiCommunicationError` — network-level issues (wrapping aiohttp ClientError / timeout).
66
+ - `PranaApiUpdateFailed(status: int)` — HTTP request completed but device returned non-200 status.
67
+
68
+ Example of catching errors:
69
+ ```python
70
+ from prana_local_api_client.exceptions import PranaApiCommunicationError, PranaApiUpdateFailed
71
+
72
+ try:
73
+ state = await client.get_state()
74
+ except PranaApiUpdateFailed as e:
75
+ # HTTP-level error (server returned non-200)
76
+ print("Device returned error status:", getattr(e, "status", None))
77
+ except PranaApiCommunicationError as e:
78
+ # Network/timeout/etc.
79
+ print("Communication error:", e)
80
+ ```
81
+
82
+ ## Usage examples
83
+
84
+ Using the client as a context manager (recommended when performing multiple requests):
85
+ ```python
86
+ import asyncio
87
+ from prana_local_api_client.prana_api_client import PranaLocalApiClient
88
+
89
+ async def main():
90
+ async with PranaLocalApiClient("192.168.1.100", 80) as client:
91
+ state = await client.get_state()
92
+ await client.set_speed(3, fan_type="main")
93
+ await client.set_switch("power", True)
94
+ await client.set_brightness(70)
95
+
96
+ asyncio.run(main())
97
+ ```
98
+
99
+ Using the client without context manager (client will create and close a session per call):
100
+ ```python
101
+ from prana_local_api_client.prana_api_client import PranaLocalApiClient
102
+ import asyncio
103
+
104
+ async def short_run():
105
+ client = PranaLocalApiClient("192.168.1.100")
106
+ # session will be created internally for each call and closed afterwards
107
+ state = await client.get_state()
108
+ print(state)
109
+
110
+ asyncio.run(short_run())
111
+ ```
112
+
113
+ ## Logging and debugging
114
+ The module uses a logger under its package name. Enable debugging in your application to see detailed logs:
115
+ ```python
116
+ import logging
117
+ logging.basicConfig(level=logging.DEBUG)
118
+ ```
119
+
120
+ ## Timeouts and retries
121
+ - Default request timeout is 10 seconds (ClientTimeout(total=10)).
122
+ - This library does not implement automatic retries. If you need retries, implement them in your caller code (e.g., with tenacity) or wrap calls in retry logic.
123
+
124
+ ## Type hints
125
+ The client uses Python 3.9+ type hints (`dict[str, Any]`). Adjust your type checks accordingly.
126
+
127
+ ## Contributing
@@ -0,0 +1,8 @@
1
+ prana_api_client-0.2.0.dist-info/licenses/LICENSE,sha256=fdQp8T4oJpuKtyeC6YaWNT8RJiwuhq-w0d9EPWusNIM,1065
2
+ prana_local_api_client/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ prana_local_api_client/exceptions.py,sha256=5al7XgeQtsP7TNG93fUKZNLBYPe9wf5N5bCjRU2p7jY,489
4
+ prana_local_api_client/prana_api_client.py,sha256=KYYofyIOlJUHpnxixi-a_9UQ9oigEiUgSOTODLHlztk,3441
5
+ prana_api_client-0.2.0.dist-info/METADATA,sha256=ym5B9FK3AJuham-2J3ccfSJF3GjCJAsodDi-9e0xfFo,4336
6
+ prana_api_client-0.2.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
7
+ prana_api_client-0.2.0.dist-info/top_level.txt,sha256=XLDnI49eWpdBNyEPZu9j95GcgKjMuTEz4Dt0fqNXbsc,23
8
+ prana_api_client-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Delly LTD
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 @@
1
+ prana_local_api_client
File without changes
@@ -0,0 +1,11 @@
1
+ class PranaApiClientException(Exception):
2
+ """Base exception for the Prana API client library."""
3
+
4
+ class PranaApiCommunicationError(PranaApiClientException):
5
+ """Network communication error (e.g., ClientError, TimeoutError)."""
6
+
7
+ class PranaApiUpdateFailed(PranaApiClientException):
8
+ """HTTP request failed (e.g., status code not 200)."""
9
+ def __init__(self, status: int, message: str = "HTTP error"):
10
+ super().__init__(f"{message} {status}")
11
+ self.status = status
@@ -0,0 +1,89 @@
1
+ from aiohttp import ClientSession, ClientError, ClientTimeout
2
+ from typing import Any
3
+ import json
4
+ import logging
5
+ from .exceptions import PranaApiUpdateFailed, PranaApiCommunicationError
6
+
7
+ _LOGGER = logging.getLogger(__name__)
8
+
9
+
10
+ class PranaLocalApiClient:
11
+ """Client for interacting with the Prana device API."""
12
+
13
+ def __init__(self, host: str, port: int = 80) -> None:
14
+ """Initialize the API client."""
15
+ self.base_url = f"http://{host}:{port}"
16
+ self.session = None # Session is created externally or on first request
17
+
18
+ async def __aenter__(self):
19
+ """Context manager entry for ClientSession."""
20
+ self.session = ClientSession()
21
+ return self
22
+
23
+ async def __aexit__(self, exc_type, exc_val, exc_tb):
24
+ """Closing the ClientSession."""
25
+ await self.session.close()
26
+ self.session = None
27
+
28
+ # --- HTTP Methods, extracted from Coordinator and async_get_state ---
29
+
30
+ async def get_state(self) -> dict[str, Any]:
31
+ """Performs a GET to retrieve the raw device state."""
32
+ url = f"{self.base_url}/getState"
33
+ return await self._async_request("GET", url)
34
+
35
+ async def set_speed(self, speed: int, fan_type: str) -> None:
36
+ """Sends the speed change command."""
37
+ url = f"{self.base_url}/setSpeed"
38
+ data = {"speed": speed, "fanType": fan_type}
39
+ await self._async_request("POST", url, json_data=data)
40
+
41
+ async def set_switch(self, switch_type: str, value: bool) -> None:
42
+ """Sends the switch state change command."""
43
+ url = f"{self.base_url}/setSwitch"
44
+ data = {"switchType": switch_type, "value": value}
45
+ await self._async_request("POST", url, json_data=data)
46
+
47
+ async def set_brightness(self, brightness: int) -> None:
48
+ """Sends the brightness change command."""
49
+ url = f"{self.base_url}/setBrightness"
50
+ data = {"brightness": brightness}
51
+ await self._async_request("POST", url, json_data=data)
52
+
53
+ # --- General method for executing requests ---
54
+
55
+ async def _async_request(
56
+ self,
57
+ method: str,
58
+ url: str,
59
+ json_data: dict[str, Any] | None = None,
60
+ ) -> dict[str, Any] | None:
61
+ """Base async method for HTTP requests, handles errors."""
62
+
63
+ # Check if a session needs to be created internally
64
+ session_was_created = False
65
+ if not self.session:
66
+ self.session = ClientSession()
67
+ session_was_created = True
68
+
69
+ try:
70
+ async with self.session.request(
71
+ method, url, json=json_data, timeout=ClientTimeout(total=10)
72
+ ) as resp:
73
+ if resp.status != 200:
74
+ _LOGGER.error("Request failed: %s %s with status %s", method, url, resp.status)
75
+ raise PranaApiUpdateFailed(resp.status, "HTTP error from device")
76
+
77
+ if resp.content_type == "application/json":
78
+ return await resp.json()
79
+
80
+ return None # For POST requests that don't return JSON
81
+
82
+ except (ClientError, ClientTimeout) as err:
83
+ _LOGGER.error("Network or timeout error: %s", err)
84
+ raise PranaApiCommunicationError(f"Network error: {err}") from err
85
+ finally:
86
+ # Close the session if it was created internally by this method
87
+ if session_was_created:
88
+ await self.session.close()
89
+ self.session = None