prana-api-client 0.2.0__tar.gz → 0.6.0__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prana-api-client
3
- Version: 0.2.0
3
+ Version: 0.6.0
4
4
  Summary: Async API client for Prana heat recovery ventilator.
5
5
  Author-email: Prana Developer <devprana18@gmail.com>
6
6
  License: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prana-api-client
3
- Version: 0.2.0
3
+ Version: 0.6.0
4
4
  Summary: Async API client for Prana heat recovery ventilator.
5
5
  Author-email: Prana Developer <devprana18@gmail.com>
6
6
  License: MIT
@@ -8,4 +8,5 @@ prana_api_client.egg-info/requires.txt
8
8
  prana_api_client.egg-info/top_level.txt
9
9
  prana_local_api_client/__init__.py
10
10
  prana_local_api_client/exceptions.py
11
- prana_local_api_client/prana_api_client.py
11
+ prana_local_api_client/prana_api_client.py
12
+ prana_local_api_client/state_normalizer.py
@@ -8,4 +8,9 @@ class PranaApiUpdateFailed(PranaApiClientException):
8
8
  """HTTP request failed (e.g., status code not 200)."""
9
9
  def __init__(self, status: int, message: str = "HTTP error"):
10
10
  super().__init__(f"{message} {status}")
11
- self.status = status
11
+ self.status = status
12
+
13
+ class UpdateFailed(PranaApiClientException):
14
+ """Raised when updating/fetching state fails (wrapper used by higher-level logic)."""
15
+ def __init__(self, message: str):
16
+ super().__init__(message)
@@ -2,7 +2,8 @@ from aiohttp import ClientSession, ClientError, ClientTimeout
2
2
  from typing import Any
3
3
  import json
4
4
  import logging
5
- from .exceptions import PranaApiUpdateFailed, PranaApiCommunicationError
5
+ from .exceptions import PranaApiUpdateFailed, PranaApiCommunicationError, UpdateFailed
6
+ from .state_normalizer import fetch_and_normalize_state
6
7
 
7
8
  _LOGGER = logging.getLogger(__name__)
8
9
 
@@ -28,7 +29,12 @@ class PranaLocalApiClient:
28
29
  # --- HTTP Methods, extracted from Coordinator and async_get_state ---
29
30
 
30
31
  async def get_state(self) -> dict[str, Any]:
31
- """Performs a GET to retrieve the raw device state."""
32
+ """Return the normalized device state by delegating to the state normalizer."""
33
+ state, _max_speed = await fetch_and_normalize_state(self)
34
+ return state
35
+
36
+ async def _get_raw_state(self) -> dict[str, Any] | None:
37
+ """Internal helper to fetch raw state JSON (used by state_normalizer)."""
32
38
  url = f"{self.base_url}/getState"
33
39
  return await self._async_request("GET", url)
34
40
 
@@ -50,6 +56,12 @@ class PranaLocalApiClient:
50
56
  data = {"brightness": brightness}
51
57
  await self._async_request("POST", url, json_data=data)
52
58
 
59
+ async def set_speed_is_on(self, speed_is_on: bool, fan_type: str) -> None:
60
+ """Sends the speed is on/off change command."""
61
+ url = f"{self.base_url}/setSpeedIsOn"
62
+ data = {"value": speed_is_on, "fanType": fan_type}
63
+ await self._async_request("POST", url, json_data=data)
64
+
53
65
  # --- General method for executing requests ---
54
66
 
55
67
  async def _async_request(
@@ -70,6 +82,7 @@ class PranaLocalApiClient:
70
82
  async with self.session.request(
71
83
  method, url, json=json_data, timeout=ClientTimeout(total=10)
72
84
  ) as resp:
85
+ print(resp.json())
73
86
  if resp.status != 200:
74
87
  _LOGGER.error("Request failed: %s %s with status %s", method, url, resp.status)
75
88
  raise PranaApiUpdateFailed(resp.status, "HTTP error from device")
@@ -80,6 +93,7 @@ class PranaLocalApiClient:
80
93
  return None # For POST requests that don't return JSON
81
94
 
82
95
  except (ClientError, ClientTimeout) as err:
96
+ print(err)
83
97
  _LOGGER.error("Network or timeout error: %s", err)
84
98
  raise PranaApiCommunicationError(f"Network error: {err}") from err
85
99
  finally:
@@ -0,0 +1,100 @@
1
+ import logging
2
+ from enum import Enum
3
+ from typing import Any, Dict, Optional, Tuple
4
+
5
+ from .exceptions import (
6
+ PranaApiUpdateFailed,
7
+ PranaApiCommunicationError,
8
+ UpdateFailed,
9
+ )
10
+
11
+ _LOGGER = logging.getLogger(__name__)
12
+
13
+ class PranaFanType(str, Enum):
14
+ BOUNDED = "bounded"
15
+ SUPPLY = "supply"
16
+ EXTRACT = "extract"
17
+
18
+ class PranaSensorType(str, Enum):
19
+ INSIDE_TEMPERATURE = "inside_temperature"
20
+ OUTSIDE_TEMPERATURE = "outside_temperature"
21
+ INSIDE_TEMPERATURE_2 = "inside_temperature_2"
22
+ OUTSIDE_TEMPERATURE_2 = "outside_temperature_2"
23
+
24
+ def normalize_state(raw_state: Dict[str, Any]) -> Dict[str, Any]:
25
+ """Normalize a raw state dict in-place and return it."""
26
+ state = dict(raw_state) if isinstance(raw_state, dict) else {}
27
+ # Compute normalized max_speed from extract fan if present
28
+ max_speed: Optional[int] = None
29
+ try:
30
+ extract = state.get(PranaFanType.EXTRACT.value)
31
+ if isinstance(extract, dict) and "max_speed" in extract:
32
+ raw_val = extract.get("max_speed")
33
+ if isinstance(raw_val, (int, float)):
34
+ max_speed = int(raw_val) // 10
35
+ except Exception:
36
+ _LOGGER.exception("Error computing max_speed from state")
37
+
38
+ if max_speed is not None:
39
+ for fan in (PranaFanType.BOUNDED.value, PranaFanType.SUPPLY.value, PranaFanType.EXTRACT.value):
40
+ if fan in state and isinstance(state[fan], dict):
41
+ state[fan]["max_speed"] = max_speed
42
+
43
+ for temp_key in (
44
+ PranaSensorType.INSIDE_TEMPERATURE.value,
45
+ PranaSensorType.OUTSIDE_TEMPERATURE.value,
46
+ PranaSensorType.INSIDE_TEMPERATURE_2.value,
47
+ PranaSensorType.OUTSIDE_TEMPERATURE_2.value,
48
+ ):
49
+ if temp_key in state and isinstance(state[temp_key], (int, float)):
50
+ try:
51
+ state[temp_key] = state[temp_key] / 10
52
+ except Exception:
53
+ _LOGGER.exception("Error converting temperature for key %s", temp_key)
54
+
55
+ return state
56
+
57
+ async def fetch_and_normalize_state(api_client) -> Tuple[Dict[str, Any], Optional[int]]:
58
+ """
59
+ Fetch state from api_client and normalize it:
60
+ - map errors to UpdateFailed
61
+ - compute and propagate max_speed
62
+ - convert temperature sensors from tenths of °C -> °C
63
+ Returns (state, max_speed) where max_speed may be None if not available.
64
+ """
65
+ _LOGGER.debug("Fetching data from Prana device")
66
+
67
+ try:
68
+ # Prefer an internal raw fetcher to avoid recursion; fallback to get_state if not available
69
+ raw_fetch = getattr(api_client, "_get_raw_state", None)
70
+ if raw_fetch is None:
71
+ # fallback (may raise or cause recursion if client.get_state delegates here)
72
+ raw = await api_client.get_state()
73
+ else:
74
+ print("Using internal raw fetcher")
75
+ raw = await raw_fetch()
76
+ except PranaApiUpdateFailed as err:
77
+ raise UpdateFailed(f"HTTP error communicating with device: {err}") from err
78
+ except PranaApiCommunicationError as err:
79
+ raise UpdateFailed(f"Network error communicating with device: {err}") from err
80
+ except Exception as err:
81
+ raise UpdateFailed(f"Unexpected error updating device: {err}") from err
82
+
83
+ if not isinstance(raw, dict):
84
+ _LOGGER.debug("Received non-dict state: %s", raw)
85
+ return {}, None
86
+
87
+ # Normalize and compute max_speed
88
+ normalized = normalize_state(raw)
89
+ max_speed = None
90
+ try:
91
+ extract = raw.get(PranaFanType.EXTRACT.value)
92
+ if isinstance(extract, dict) and "max_speed" in extract:
93
+ raw_val = extract.get("max_speed")
94
+ if isinstance(raw_val, (int, float)):
95
+ max_speed = int(raw_val) // 10
96
+ except Exception:
97
+ _LOGGER.exception("Error computing max_speed from state")
98
+
99
+ _LOGGER.debug("Fetched state: %s", normalized)
100
+ return normalized, max_speed
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "prana-api-client"
7
- version = "0.2.0"
7
+ version = "0.6.0"
8
8
  authors = [
9
9
  { name="Prana Developer", email="devprana18@gmail.com" },
10
10
  ]