python-hotspring 3.1.0__py3-none-any.whl → 4.0.1__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.
hotspring/const.py CHANGED
@@ -12,7 +12,6 @@ class HeatingMode(Enum):
12
12
  """
13
13
 
14
14
  UNKNOWN = "unknown"
15
- INVALID = "invalid"
16
15
  HEAT_SAVER = "heatSaver"
17
16
  HEAT_WITH_BOOST = "heatWithBoost"
18
17
  CHILL = "chill"
hotspring/hotspring.py CHANGED
@@ -5,6 +5,8 @@ from __future__ import annotations
5
5
  import asyncio
6
6
  import contextlib
7
7
  import json
8
+ import logging
9
+ import time
8
10
  from dataclasses import dataclass
9
11
  from typing import Self
10
12
 
@@ -36,6 +38,15 @@ from .models import (
36
38
  SpaInfo,
37
39
  )
38
40
 
41
+ _LOGGER = logging.getLogger(__name__)
42
+
43
+
44
+ def _describe_exception(exception: BaseException) -> str:
45
+ """Return the exception type, plus its message when it has one."""
46
+ if detail := str(exception):
47
+ return f"{type(exception).__name__}: {detail}"
48
+ return type(exception).__name__
49
+
39
50
 
40
51
  @dataclass
41
52
  class HotSpring: # pylint: disable=too-many-public-methods
@@ -97,8 +108,11 @@ class HotSpring: # pylint: disable=too-many-public-methods
97
108
  """
98
109
  url = URL.build(scheme="http", host=self.host, port=80, path=uri)
99
110
 
111
+ # The HNA's single HTTP worker should not be left holding an idle pooled
112
+ # socket from a shared session between polls.
100
113
  headers = {
101
114
  "Accept": "application/json, text/plain, */*",
115
+ "Connection": "close",
102
116
  }
103
117
 
104
118
  if self.session is None:
@@ -107,62 +121,90 @@ class HotSpring: # pylint: disable=too-many-public-methods
107
121
 
108
122
  attempts = 0
109
123
  while True:
124
+ started = time.monotonic()
110
125
  try:
111
- async with asyncio.timeout(self.request_timeout):
112
- response = await self.session.request(
126
+ # Bound the body read too: a stalled body would otherwise hold
127
+ # the HNA's single HTTP worker until the caller's session
128
+ # timeout. Exiting mid-body closes the connection, never pools it.
129
+ async with (
130
+ asyncio.timeout(self.request_timeout),
131
+ self.session.request(
113
132
  method,
114
133
  url,
115
134
  json=data,
116
135
  headers=headers,
117
- )
136
+ ) as response,
137
+ ):
138
+ if response.status // 100 in [4, 5]:
139
+ contents = await response.read()
140
+
141
+ try:
142
+ raise HotSpringError(
143
+ response.status,
144
+ json.loads(contents.decode("utf8")),
145
+ )
146
+ except json.JSONDecodeError:
147
+ raise HotSpringError(
148
+ response.status,
149
+ {"message": contents.decode("utf8")},
150
+ ) from None
151
+
152
+ # The spa returns JSON with text/html Content-Type,
153
+ # so always try JSON parsing first.
154
+ body = await response.text()
118
155
 
119
- if response.status // 100 in [4, 5]:
120
- contents = await response.read()
121
- response.close()
122
-
123
- try:
124
- raise HotSpringError(
125
- response.status,
126
- json.loads(contents.decode("utf8")),
127
- )
128
- except json.JSONDecodeError:
129
- raise HotSpringError(
130
- response.status,
131
- {"message": contents.decode("utf8")},
132
- ) from None
133
-
134
- # The spa returns JSON with text/html Content-Type,
135
- # so always try JSON parsing first.
136
- body = await response.text()
137
156
  try:
138
157
  response_data = json.loads(body)
139
- except json.JSONDecodeError as exc:
158
+ except json.JSONDecodeError as exception:
140
159
  msg = f"Invalid JSON response from {uri}: {body[:200]}"
141
- raise HotSpringError(msg) from exc
160
+ raise HotSpringError(msg) from exception
142
161
 
143
162
  if not isinstance(response_data, dict):
144
163
  msg = f"Unexpected response type from {uri}"
145
164
  raise HotSpringError(msg)
146
165
 
147
- except asyncio.TimeoutError as exception: # noqa: PERF203
166
+ except asyncio.TimeoutError as exception:
148
167
  attempts += 1
168
+ _LOGGER.debug(
169
+ "%s %s attempt %d timed out after %.2fs",
170
+ method,
171
+ uri,
172
+ attempts,
173
+ time.monotonic() - started,
174
+ )
149
175
  if attempts > self.request_retries:
150
176
  msg = (
151
177
  f"Timeout occurred while connecting to Hot Spring HNA at "
152
- f"{self.host}"
178
+ f"{self.host}: no response within {self.request_timeout}s"
153
179
  )
154
180
  raise HotSpringConnectionTimeoutError(msg) from exception
155
181
  await asyncio.sleep(0.5 * (2 ** (attempts - 1)))
156
182
  except aiohttp.ClientError as exception:
157
183
  attempts += 1
184
+ cause = _describe_exception(exception)
185
+ _LOGGER.debug(
186
+ "%s %s attempt %d failed after %.2fs: %s",
187
+ method,
188
+ uri,
189
+ attempts,
190
+ time.monotonic() - started,
191
+ cause,
192
+ )
158
193
  if attempts > self.request_retries:
159
194
  msg = (
160
195
  f"Error occurred while communicating with Hot Spring HNA at "
161
- f"{self.host}"
196
+ f"{self.host}: {cause}"
162
197
  )
163
198
  raise HotSpringConnectionError(msg) from exception
164
199
  await asyncio.sleep(0.5 * (2 ** (attempts - 1)))
165
200
  else:
201
+ _LOGGER.debug(
202
+ "%s %s -> %d in %.2fs",
203
+ method,
204
+ uri,
205
+ response.status,
206
+ time.monotonic() - started,
207
+ )
166
208
  return response_data
167
209
 
168
210
  async def _safe_request(self, uri: str) -> dict[str, object] | None:
hotspring/models.py CHANGED
@@ -138,6 +138,8 @@ class Spa:
138
138
  status if isinstance(status, dict) else {},
139
139
  existing=self.versions,
140
140
  )
141
+ if self._apply_fwiq_firmware_installed():
142
+ updated.add("freshwater_iq")
141
143
  updated.add("versions")
142
144
 
143
145
  return updated
@@ -211,7 +213,19 @@ class Spa:
211
213
  data: The JSON response from GET /getFWIQData.
212
214
 
213
215
  """
214
- self.freshwater_iq = FreshWaterIQ.from_dict(data)
216
+ self.freshwater_iq = FreshWaterIQ.from_dict(data, existing=self.freshwater_iq)
217
+ self._apply_fwiq_firmware_installed()
218
+
219
+ def _apply_fwiq_firmware_installed(self) -> bool:
220
+ """Ensure installed=True when FWIQFirmwareVersion is reported.
221
+
222
+ A non-empty FWIQFirmwareVersion takes priority over FWIQinstalled from
223
+ /getFWIQData so pre-sync responses cannot clear hardware presence.
224
+ """
225
+ if self.versions.fwiq and not self.freshwater_iq.installed:
226
+ self.freshwater_iq = replace(self.freshwater_iq, installed=True)
227
+ return True
228
+ return False
215
229
 
216
230
  @property
217
231
  def is_hna(self) -> bool:
@@ -847,14 +861,22 @@ class WaterCare: # pylint: disable=too-many-instance-attributes
847
861
 
848
862
  @dataclass
849
863
  class FreshWaterIQ:
850
- """FreshWater IQ water quality sensor data."""
864
+ """FreshWater IQ water quality sensor data.
851
865
 
852
- conductivity: int = 0
853
- orp: int = 0
854
- chlorine: float = 0.0
855
- ph: float = 0.0
856
- sensor_life_percentage: float = 0.0
866
+ Sensor reading fields are ``None`` when no valid measurement is available
867
+ (sensor not installed, ``-1`` firmware sentinel, or pre-sync all-zero state).
868
+ """
869
+
870
+ conductivity: int | None = None
871
+ orp: int | None = None
872
+ chlorine: float | None = None
873
+ ph: float | None = None
874
+ sensor_life_percentage: float | None = None
857
875
  installed: bool = False
876
+ system_enabled: bool = False
877
+ cl_calibration_factor: float | None = None
878
+ ph_calibration_factor: float | None = None
879
+ regional_cl_selection: str = ""
858
880
 
859
881
  @staticmethod
860
882
  def from_dict(
@@ -876,6 +898,8 @@ class FreshWaterIQ:
876
898
  A FreshWaterIQ instance.
877
899
 
878
900
  """
901
+ base = existing or FreshWaterIQ()
902
+
879
903
  # Handle the nested /getFWIQData format
880
904
  water_care = data.get("waterCare")
881
905
  fwiq = None
@@ -887,36 +911,10 @@ class FreshWaterIQ:
887
911
  fwiq = fwiq_status
888
912
 
889
913
  if fwiq is not None:
890
- return FreshWaterIQ(
891
- conductivity=int(fwiq.get("Conductivity", 0)),
892
- orp=int(fwiq.get("ORP", 0)),
893
- chlorine=float(fwiq.get("Chlorine", 0.0)),
894
- ph=float(fwiq.get("pH", 0.0)),
895
- sensor_life_percentage=float(fwiq.get("SensorLife", 0.0)),
896
- installed=fwiq.get("FWIQinstalled", "notinstalled") != "notinstalled",
897
- )
914
+ return replace(base, **_parse_fwiq_status(fwiq))
898
915
 
899
916
  # Handle the flat /status FWIQ_Parameters format
900
- kwargs: dict[str, object] = {}
901
- if "current_Current_CompConductivity" in data:
902
- kwargs["conductivity"] = int(
903
- data.get("current_Current_CompConductivity", 0)
904
- )
905
- if "current_ORP" in data:
906
- kwargs["orp"] = int(data.get("current_ORP", 0))
907
- if "current_chlorine" in data:
908
- kwargs["chlorine"] = float(data.get("current_chlorine", 0.0))
909
- if "current_pH" in data:
910
- kwargs["ph"] = float(data.get("current_pH", 0.0))
911
- if "current_SensorLife_Percentage" in data:
912
- kwargs["sensor_life_percentage"] = float(
913
- data.get("current_SensorLife_Percentage", 0.0)
914
- )
915
-
916
- if kwargs:
917
- kwargs["installed"] = True
918
-
919
- base = existing or FreshWaterIQ()
917
+ kwargs = _parse_fwiq_parameters(data)
920
918
  return replace(base, **kwargs)
921
919
 
922
920
 
@@ -1290,13 +1288,15 @@ def _parse_heater_status(status: dict[str, object]) -> dict[str, object]:
1290
1288
  kwargs["is_on"] = status.get("heater", "off") != "off"
1291
1289
  if "heaterLock" in status:
1292
1290
  kwargs["heater_lock"] = status.get("heaterLock", "off") != "off"
1293
- if "heatpumpInstalled" in status:
1294
- kwargs["heatpump_installed"] = (
1295
- status.get("heatpumpInstalled", "notinstalled") != "notinstalled"
1296
- )
1297
- if "heatingMode" in status:
1298
- mode = HeatingMode.build(status.get("heatingMode"))
1299
- if mode != HeatingMode.UNKNOWN:
1291
+ if (raw_hp := status.get("heatpumpInstalled")) is not None:
1292
+ kwargs["heatpump_installed"] = raw_hp != "notinstalled"
1293
+ if kwargs.get("heatpump_installed") is False:
1294
+ # At boot before UART sync, the HNA zero-initializes heater_mode to 0
1295
+ # ("heatWithBoost") even when no CoolZone heat pump is installed.
1296
+ kwargs["heating_mode"] = HeatingMode.UNKNOWN
1297
+ elif (raw_mode := status.get("heatingMode")) is not None:
1298
+ mode = HeatingMode.build(raw_mode)
1299
+ if mode != HeatingMode.UNKNOWN or str(raw_mode).strip().lower() == "invalid":
1300
1300
  kwargs["heating_mode"] = mode
1301
1301
  if "heaterCurrent" in status:
1302
1302
  # Motherboard current registers use Q8.8 fixed point in deciapps (0.1 A):
@@ -1548,3 +1548,75 @@ def _parse_energy_saving_control(control: dict[str, object]) -> dict[str, object
1548
1548
  with contextlib.suppress(ValueError, TypeError):
1549
1549
  kwargs["duration"] = int(str(control["duration"]))
1550
1550
  return kwargs
1551
+
1552
+
1553
+ _FWIQ_STATUS_READING_KEYS: tuple[tuple[str, str, type[int | float]], ...] = (
1554
+ ("Conductivity", "conductivity", int),
1555
+ ("ORP", "orp", int),
1556
+ ("Chlorine", "chlorine", float),
1557
+ ("pH", "ph", float),
1558
+ ("SensorLife", "sensor_life_percentage", float),
1559
+ )
1560
+
1561
+ _FWIQ_PARAMS_READING_KEYS: tuple[tuple[str, str, type[int | float]], ...] = (
1562
+ ("current_Current_CompConductivity", "conductivity", int),
1563
+ ("current_ORP", "orp", int),
1564
+ ("current_chlorine", "chlorine", float),
1565
+ ("current_pH", "ph", float),
1566
+ ("current_SensorLife_Percentage", "sensor_life_percentage", float),
1567
+ )
1568
+
1569
+
1570
+ _FWIQ_STATUS_META_KEYS: tuple[tuple[str, str, type[float | str]], ...] = (
1571
+ ("Cl_CalibrationFactor", "cl_calibration_factor", float),
1572
+ ("pH_CalibrationFactor", "ph_calibration_factor", float),
1573
+ ("Regional_Cl_Selection", "regional_cl_selection", str),
1574
+ )
1575
+
1576
+
1577
+ def _normalize_fwiq_readings(
1578
+ source: dict[str, object],
1579
+ key_specs: tuple[tuple[str, str, type[int | float]], ...],
1580
+ ) -> dict[str, int | float | None]:
1581
+ """Parse and normalize FWIQ sensor readings.
1582
+
1583
+ The HNA firmware initializes FWIQ registers to ``0`` at boot before the
1584
+ first UART packet arrives from the control box, and overwrites all five
1585
+ registers with ``-1`` / ``-1.0`` when FWIQ is not installed or no sensor
1586
+ readings are available. Negative values and payloads where no reading is
1587
+ positive are normalized to ``None``.
1588
+ """
1589
+ readings: dict[str, int | float | None] = {}
1590
+ for json_key, attr_name, converter in key_specs:
1591
+ if (raw := source.get(json_key)) is not None:
1592
+ val = converter(raw)
1593
+ readings[attr_name] = val if val >= 0 else None
1594
+
1595
+ if readings and not any(v is not None and v > 0 for v in readings.values()):
1596
+ return dict.fromkeys(readings, None)
1597
+ return readings
1598
+
1599
+
1600
+ def _parse_fwiq_status(fwiq: dict[str, object]) -> dict[str, object]:
1601
+ """Parse nested ``waterCare.status.FWIQstatus`` from GET /getFWIQData."""
1602
+ installed = fwiq.get("FWIQinstalled", "notinstalled") != "notinstalled"
1603
+ readings = _normalize_fwiq_readings(fwiq, _FWIQ_STATUS_READING_KEYS)
1604
+ if not installed:
1605
+ readings = dict.fromkeys(readings, None)
1606
+
1607
+ kwargs: dict[str, object] = {**readings, "installed": installed}
1608
+ if (raw_state := fwiq.get("SystemState")) is not None:
1609
+ kwargs["system_enabled"] = str(raw_state).strip().lower() == "enabled"
1610
+ for json_key, attr_name, converter in _FWIQ_STATUS_META_KEYS:
1611
+ if (raw_meta := fwiq.get(json_key)) is not None:
1612
+ kwargs[attr_name] = converter(raw_meta)
1613
+ return kwargs
1614
+
1615
+
1616
+ def _parse_fwiq_parameters(data: dict[str, object]) -> dict[str, object]:
1617
+ """Parse flat ``FWIQ_Parameters`` from GET /status."""
1618
+ readings = _normalize_fwiq_readings(data, _FWIQ_PARAMS_READING_KEYS)
1619
+ kwargs: dict[str, object] = dict(readings)
1620
+ if any(v is not None for v in readings.values()):
1621
+ kwargs["installed"] = True
1622
+ return kwargs
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-hotspring
3
- Version: 3.1.0
3
+ Version: 4.0.1
4
4
  Summary: Asynchronous Python client for Hot Spring Connected Spa Kit 2.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -22,8 +22,6 @@ Classifier: Programming Language :: Python :: 3.14
22
22
  Classifier: Programming Language :: Python :: 3.15
23
23
  Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
24
  Requires-Dist: aiohttp (>=3.0.0)
25
- Requires-Dist: awesomeversion (>=22.1.0)
26
- Requires-Dist: python-backoff (>=2.2.0)
27
25
  Requires-Dist: yarl (>=1.6.0)
28
26
  Project-URL: Bug Tracker, https://github.com/Moustachauve/python-hotspring/issues
29
27
  Project-URL: Changelog, https://github.com/Moustachauve/python-hotspring/releases
@@ -0,0 +1,10 @@
1
+ hotspring/__init__.py,sha256=wV3giZmeCl0qdz6zStvbQAYOBc6d5qdAFzEaHViYKkA,1560
2
+ hotspring/const.py,sha256=f1iopXr4KVgOAr67dKzI0ra5k965zbEcOzicGu_VzuA,14466
3
+ hotspring/exceptions.py,sha256=R8YwGfi6mXZ5DcHw4_fmtrRuvgkfOrLRCH-d3x6OUIw,1184
4
+ hotspring/hotspring.py,sha256=-sJT9dTmxIzYeJCvpHe8DDOXwPm4WHJr6FEbYL8WJ-Q,30568
5
+ hotspring/models.py,sha256=dCSZEL-GmnKIBk-u6Z-S-tivrMCUS6cP-06wBGDSy8A,56648
6
+ hotspring/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ python_hotspring-4.0.1.dist-info/METADATA,sha256=iky-CKQzfQylRKqZ6YnwZVCrGEN5DYbHLAtA2zXSur0,8037
8
+ python_hotspring-4.0.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
9
+ python_hotspring-4.0.1.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
10
+ python_hotspring-4.0.1.dist-info/RECORD,,
@@ -1,10 +0,0 @@
1
- hotspring/__init__.py,sha256=wV3giZmeCl0qdz6zStvbQAYOBc6d5qdAFzEaHViYKkA,1560
2
- hotspring/const.py,sha256=ggMcA7ng0pdfquOAQdM7gUoF48J7ha5diya-YkYqFaA,14490
3
- hotspring/exceptions.py,sha256=R8YwGfi6mXZ5DcHw4_fmtrRuvgkfOrLRCH-d3x6OUIw,1184
4
- hotspring/hotspring.py,sha256=uQHNk5hTxHGRIxmiWzn-eGv7DVd0wiGrLouXahIIqaE,28896
5
- hotspring/models.py,sha256=uiN7_VkHHLmKEagbRDBAa5xvYFLfZ98U_H93K-pkNd0,53465
6
- hotspring/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- python_hotspring-3.1.0.dist-info/METADATA,sha256=lq6FH-ct7qVgisgJ24M0mLvVkI6GyyIaQwWKngNq5s8,8118
8
- python_hotspring-3.1.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
9
- python_hotspring-3.1.0.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
10
- python_hotspring-3.1.0.dist-info/RECORD,,