python-hotspring 4.0.2__tar.gz → 5.0.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-hotspring
3
- Version: 4.0.2
3
+ Version: 5.0.1
4
4
  Summary: Asynchronous Python client for Hot Spring Connected Spa Kit 2.
5
5
  License: MIT
6
6
  License-File: LICENSE
@@ -45,10 +45,6 @@ Asynchronous Python client for Hot Spring Connected Spa Kit 2.
45
45
  > This library is currently in heavy development. Not all features might work
46
46
  > perfectly, and some features may not be fully tested as they depend on the
47
47
  > physical hardware available for testing.
48
- >
49
- > The spa's energy consumption estimates (watts, power draw) are not accurate
50
- > and are most likely incorrect, as the power calculation registers have not
51
- > been fully reverse-engineered.
52
48
 
53
49
  ## About
54
50
 
@@ -69,9 +65,11 @@ It is primarily designed to be used as the communication layer for an official
69
65
  plus the logo light
70
66
  - **Water care** — Monitor FreshWater IQ salt system metrics (pH, chlorine,
71
67
  ORP, sensor life)
72
- - **Diagnostics & Test Metrics** — Read raw hardware test point currents, line voltages,
73
- sensor flow/switch states, and failure diagnostics
74
- - **Runtime Tracking** — Cumulative heater runtime and individual jet pump runtime in hours
68
+ - **Power & Diagnostics**: Read per-circuit power and current metrics (on spas equipped
69
+ with current-sensing hardware), filter cycle durations, sensor flow/switch states, and
70
+ failure diagnostics
71
+ - **Runtime Tracking**: System uptime and cumulative runtime for supported jet pumps and
72
+ blower in hours
75
73
  - **Connection monitoring** — Check LoRA bridge and cloud connectivity status
76
74
  - **Energy saving schedules** — View configured energy saving time windows
77
75
  - **Clean cycle** — Start or stop the 10-minute clean cycle
@@ -13,10 +13,6 @@ Asynchronous Python client for Hot Spring Connected Spa Kit 2.
13
13
  > This library is currently in heavy development. Not all features might work
14
14
  > perfectly, and some features may not be fully tested as they depend on the
15
15
  > physical hardware available for testing.
16
- >
17
- > The spa's energy consumption estimates (watts, power draw) are not accurate
18
- > and are most likely incorrect, as the power calculation registers have not
19
- > been fully reverse-engineered.
20
16
 
21
17
  ## About
22
18
 
@@ -37,9 +33,11 @@ It is primarily designed to be used as the communication layer for an official
37
33
  plus the logo light
38
34
  - **Water care** — Monitor FreshWater IQ salt system metrics (pH, chlorine,
39
35
  ORP, sensor life)
40
- - **Diagnostics & Test Metrics** — Read raw hardware test point currents, line voltages,
41
- sensor flow/switch states, and failure diagnostics
42
- - **Runtime Tracking** — Cumulative heater runtime and individual jet pump runtime in hours
36
+ - **Power & Diagnostics**: Read per-circuit power and current metrics (on spas equipped
37
+ with current-sensing hardware), filter cycle durations, sensor flow/switch states, and
38
+ failure diagnostics
39
+ - **Runtime Tracking**: System uptime and cumulative runtime for supported jet pumps and
40
+ blower in hours
43
41
  - **Connection monitoring** — Check LoRA bridge and cloud connectivity status
44
42
  - **Energy saving schedules** — View configured energy saving time windows
45
43
  - **Clean cycle** — Start or stop the 10-minute clean cycle
@@ -23,7 +23,7 @@ packages = [
23
23
  readme = "README.md"
24
24
  repository = "https://github.com/Moustachauve/python-hotspring"
25
25
  # The CI/CD and GitHub Actions release workflows are responsible for setting the version tag
26
- version = "4.0.2"
26
+ version = "5.0.1"
27
27
 
28
28
  [tool.poetry.dependencies]
29
29
  aiohttp = ">=3.0.0"
@@ -35,6 +35,7 @@ from .models import (
35
35
  Jet,
36
36
  LightZone,
37
37
  LogoLight,
38
+ PowerMetrics,
38
39
  Spa,
39
40
  SpaInfo,
40
41
  SpaLock,
@@ -71,6 +72,7 @@ __all__ = [
71
72
  "LightWheelMode",
72
73
  "LightZone",
73
74
  "LogoLight",
75
+ "PowerMetrics",
74
76
  "Spa",
75
77
  "SpaBrand",
76
78
  "SpaFailureState",
@@ -32,6 +32,7 @@ from .exceptions import (
32
32
  HotSpringNotReadyError,
33
33
  HotSpringSNADetectedError,
34
34
  )
35
+ from .json_recovery import recover_truncated_json
35
36
  from .models import (
36
37
  ConnectionStatus,
37
38
  Diagnostics,
@@ -63,6 +64,30 @@ def _parsing(uri: str) -> Iterator[None]:
63
64
  raise HotSpringError(msg) from exception
64
65
 
65
66
 
67
+ def _parse_response_json(uri: str, body: str) -> dict[str, object]:
68
+ """Parse a JSON object body, recovering truncated /status responses."""
69
+ try:
70
+ response_data = json.loads(body)
71
+ except json.JSONDecodeError as exception:
72
+ if (
73
+ uri != Endpoint.STATUS
74
+ or (recovered := recover_truncated_json(body)) is None
75
+ ):
76
+ msg = f"Invalid JSON response from {uri}: {body[:200]}"
77
+ raise HotSpringError(msg) from exception
78
+ _LOGGER.debug(
79
+ "Recovered truncated %d-byte JSON payload from %s",
80
+ len(body),
81
+ uri,
82
+ )
83
+ return recovered
84
+
85
+ if not isinstance(response_data, dict):
86
+ msg = f"Unexpected response type from {uri}"
87
+ raise HotSpringError(msg)
88
+ return response_data
89
+
90
+
66
91
  @dataclass
67
92
  class HotSpring: # pylint: disable=too-many-public-methods
68
93
  """Main class for handling connections with a Hot Spring Spa.
@@ -168,15 +193,7 @@ class HotSpring: # pylint: disable=too-many-public-methods
168
193
  # so always try JSON parsing first.
169
194
  body = await response.text()
170
195
 
171
- try:
172
- response_data = json.loads(body)
173
- except json.JSONDecodeError as exception:
174
- msg = f"Invalid JSON response from {uri}: {body[:200]}"
175
- raise HotSpringError(msg) from exception
176
-
177
- if not isinstance(response_data, dict):
178
- msg = f"Unexpected response type from {uri}"
179
- raise HotSpringError(msg)
196
+ response_data = _parse_response_json(uri, body)
180
197
 
181
198
  except asyncio.TimeoutError as exception:
182
199
  attempts += 1
@@ -258,7 +275,9 @@ class HotSpring: # pylint: disable=too-many-public-methods
258
275
 
259
276
  On subsequent routine polling cycles, it queries /status and /spaConnectStatus
260
277
  sequentially, avoiding redundant radio (LoRA) queries for static identity data
261
- while keeping telemetry and connection status fresh.
278
+ while keeping telemetry and connection status fresh. When power monitoring is
279
+ supported and /addDebugData is needed for initial baseline current or active
280
+ loads, it is also fetched opportunistically.
262
281
 
263
282
  Args:
264
283
  ----
@@ -314,6 +333,7 @@ class HotSpring: # pylint: disable=too-many-public-methods
314
333
  )
315
334
  raise HotSpringSNADetectedError(msg)
316
335
 
336
+ await self._refresh_power_diagnostics(self.spa)
317
337
  self._identity_loaded = True
318
338
  return self.spa
319
339
 
@@ -334,8 +354,19 @@ class HotSpring: # pylint: disable=too-many-public-methods
334
354
  ):
335
355
  self.spa.connection_status.spa_connected = True
336
356
 
357
+ await self._refresh_power_diagnostics(self.spa)
337
358
  return self.spa
338
359
 
360
+ async def _refresh_power_diagnostics(self, spa: Spa) -> None:
361
+ """Fetch /addDebugData when needed for baseline current or active loads."""
362
+ if (
363
+ not spa.connection_status.spa_connected
364
+ or not spa.needs_diagnostics_for_power
365
+ ):
366
+ return
367
+ with contextlib.suppress(HotSpringError):
368
+ await self._fetch(Endpoint.DEBUG_DATA, spa.update_diagnostics)
369
+
339
370
  async def get_device_info(self) -> SpaInfo:
340
371
  """Fetch lightweight device identity directly from /startup.
341
372
 
@@ -0,0 +1,70 @@
1
+ """Helpers for recovering buffer-truncated JSON payloads from the HNA.
2
+
3
+ The HNA firmware serializes GET /status into a fixed 3,072-byte (0xc00)
4
+ buffer and null-terminates at index 3,071, returning HTTP 200 with truncated
5
+ JSON when a spa's payload exceeds that capacity.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+
13
+ # Match one JSON token at a time: a complete double-quoted string, a structural
14
+ # character, or a bare scalar run. An unterminated string at EOF fails to match
15
+ # and exits the loop cleanly.
16
+ _JSON_TOKEN_RE = re.compile(r'\s*(?P<tok>"(?:\\.|[^"\\])*"|[{}\[\]:,]|[^"\s{}\[\]:,]+)')
17
+ _CONTAINER_CLOSERS: dict[str, str] = {"{": "}", "[": "]"}
18
+ _SCALAR_DELIMITERS = frozenset(" \t\r\n,}]")
19
+
20
+
21
+ def _find_truncated_json_cut(body: str) -> tuple[int, str] | None:
22
+ """Return the cut index and closing delimiters after the last complete value."""
23
+ stack: list[str] = []
24
+ expect_value = False
25
+ safe_state: tuple[int, str] | None = None
26
+ pos = 0
27
+ end = len(body)
28
+
29
+ while (match := _JSON_TOKEN_RE.match(body, pos)) is not None:
30
+ tok = match.group("tok")
31
+ pos = match.end()
32
+ if (closer := _CONTAINER_CLOSERS.get(tok)) is not None:
33
+ stack.append(closer)
34
+ expect_value = tok == "["
35
+ elif tok in "}]":
36
+ if not stack or stack[-1] != tok:
37
+ return None
38
+ stack.pop()
39
+ safe_state = (pos, "".join(reversed(stack)))
40
+ expect_value = bool(stack) and stack[-1] == "]"
41
+ elif tok in ":,":
42
+ expect_value = tok == ":" or (bool(stack) and stack[-1] == "]")
43
+ elif tok.startswith('"'):
44
+ if expect_value and len(stack) == 1:
45
+ safe_state = (pos, "".join(reversed(stack)))
46
+ expect_value = False
47
+ elif expect_value and pos == end:
48
+ break
49
+ elif expect_value and body[pos] in _SCALAR_DELIMITERS:
50
+ if len(stack) == 1:
51
+ safe_state = (pos, "".join(reversed(stack)))
52
+ expect_value = False
53
+ else:
54
+ return None
55
+
56
+ return safe_state
57
+
58
+
59
+ def recover_truncated_json(body: str) -> dict[str, object] | None:
60
+ """Recover a valid JSON object prefix from a buffer-truncated response."""
61
+ if (cut := _find_truncated_json_cut(body)) is None:
62
+ return None
63
+ cut_pos, closers = cut
64
+ try:
65
+ parsed = json.loads(body[:cut_pos] + closers)
66
+ except json.JSONDecodeError:
67
+ return None
68
+ if isinstance(parsed, dict) and parsed:
69
+ return parsed
70
+ return None
@@ -9,6 +9,7 @@
9
9
  from __future__ import annotations
10
10
 
11
11
  import contextlib
12
+ import itertools
12
13
  from dataclasses import dataclass, replace
13
14
  from typing import TYPE_CHECKING, NamedTuple
14
15
 
@@ -30,6 +31,14 @@ from .const import (
30
31
  if TYPE_CHECKING:
31
32
  from collections.abc import Callable
32
33
 
34
+ type _WordBlock = tuple[int | None, ...]
35
+ type _PumpBlowerState = tuple[JetSpeed, JetSpeed, bool] | None
36
+ type _CircuitStates = tuple[bool, bool, _PumpBlowerState]
37
+
38
+ _NO_HEAD_WORDS: _WordBlock = (None, None, None)
39
+ _NO_STATUS_WORDS: _WordBlock = (None, None, None, None)
40
+ _NO_TAIL_WORDS: _WordBlock = (None, None)
41
+
33
42
 
34
43
  class Spa:
35
44
  """Object holding all information from a Hot Spring Spa.
@@ -53,6 +62,9 @@ class Spa:
53
62
  connection_status: ConnectionStatus
54
63
  diagnostics: Diagnostics
55
64
  test_metrics: SpaTestData
65
+ power: PowerMetrics
66
+ system_uptime_seconds: int | None
67
+ _pending_status_words: _WordBlock
56
68
 
57
69
  def __init__(self, data: dict[str, object]) -> None:
58
70
  """Initialize a Spa from the API response.
@@ -72,11 +84,14 @@ class Spa:
72
84
  self.water_care = WaterCare()
73
85
  self.freshwater_iq = FreshWaterIQ()
74
86
  self.test_metrics = SpaTestData()
87
+ self.power = PowerMetrics()
88
+ self.system_uptime_seconds = None
75
89
  self.energy_savings = {}
76
90
  self.versions = Versions()
77
91
  self.info = SpaInfo()
78
92
  self.connection_status = ConnectionStatus()
79
93
  self.diagnostics = Diagnostics()
94
+ self._pending_status_words = _NO_STATUS_WORDS
80
95
  if data:
81
96
  self.update_from_dict(data)
82
97
 
@@ -93,6 +108,9 @@ class Spa:
93
108
 
94
109
  """
95
110
  updated: set[str] = set()
111
+ prior_states = self._circuit_states
112
+ previous_power = self.power
113
+ previous_uptime = self.system_uptime_seconds
96
114
 
97
115
  for section in _SECTION_PARSERS:
98
116
  if section.json_key in data and isinstance(data[section.json_key], dict):
@@ -142,8 +160,38 @@ class Spa:
142
160
  updated.add("freshwater_iq")
143
161
  updated.add("versions")
144
162
 
163
+ self._apply_shifted_runtimes(data, updated)
164
+ if self.system_uptime_seconds != previous_uptime:
165
+ updated.add("system_uptime_seconds")
166
+
167
+ self._update_power_from_status(data, prior_states)
168
+ if self.power != previous_power:
169
+ updated.add("power")
170
+
145
171
  return updated
146
172
 
173
+ def _update_power_from_status(
174
+ self, data: dict[str, object], prior_states: _CircuitStates
175
+ ) -> None:
176
+ """Update power metrics and pending words from a /status or echo dict."""
177
+ status_words = _extract_status_words(data)
178
+ if status_words is None:
179
+ if self._circuit_states == prior_states:
180
+ return
181
+ self._pending_status_words = _NO_STATUS_WORDS
182
+ self._apply_power_words({}, prior_states=prior_states)
183
+ return
184
+
185
+ fresh_power = _decode_registers(_NO_HEAD_WORDS, status_words, _NO_TAIL_WORDS)
186
+ if fresh_power["small_loads_power"] <= 0:
187
+ self.power = PowerMetrics()
188
+ self._pending_status_words = _NO_STATUS_WORDS
189
+ return
190
+
191
+ self._pending_status_words = status_words
192
+ self.power = replace(self.power, supported=True)
193
+ self._apply_power_words(fresh_power, prior_states=prior_states)
194
+
147
195
  def update_info(self, data: dict[str, object]) -> None:
148
196
  """Update spa identity from /startup and /spamodel responses.
149
197
 
@@ -196,14 +244,26 @@ class Spa:
196
244
  self.connection_status = ConnectionStatus.from_dict(data)
197
245
 
198
246
  def update_diagnostics(self, data: dict[str, object]) -> None:
199
- """Update diagnostics from /addDebugData response.
247
+ """Update diagnostics and power metrics from /addDebugData response.
200
248
 
201
249
  Args:
202
250
  ----
203
251
  data: The JSON response from GET /addDebugData.
204
252
 
205
253
  """
206
- self.diagnostics = Diagnostics.from_dict(data)
254
+ self.diagnostics, debug_integers = _parse_diagnostics_and_electrical(
255
+ data, existing=self.diagnostics
256
+ )
257
+ if debug_integers is None:
258
+ return
259
+ status_words = self._pending_status_words
260
+ self._pending_status_words = _NO_STATUS_WORDS
261
+ fresh_power = _decode_registers(
262
+ tuple(debug_integers.get(key) for key in _DEBUG_HEAD_KEYS),
263
+ status_words,
264
+ tuple(debug_integers.get(key) for key in _DEBUG_TAIL_KEYS),
265
+ )
266
+ self._apply_power_words(fresh_power, prior_states=self._circuit_states)
207
267
 
208
268
  def update_freshwater_iq(self, data: dict[str, object]) -> None:
209
269
  """Update FreshWater IQ data from /getFWIQData response.
@@ -227,6 +287,95 @@ class Spa:
227
287
  return True
228
288
  return False
229
289
 
290
+ def _apply_shifted_runtimes(
291
+ self, data: dict[str, object], updated: set[str]
292
+ ) -> None:
293
+ """Route misaligned 24-bit runtime fields to their actual components."""
294
+ decoded = {
295
+ target: _decode_runtime_seconds(raw)
296
+ for path, target in _RUNTIME_ROUTES
297
+ if (raw := _dig(data, path)) is not None
298
+ }
299
+ if not decoded:
300
+ return
301
+ if not (
302
+ self.versions.control_box
303
+ or self.system_uptime_seconds is not None
304
+ or any(decoded.values())
305
+ ):
306
+ return
307
+
308
+ if "uptime" in decoded:
309
+ self.system_uptime_seconds = decoded["uptime"]
310
+ if (blower_seconds := decoded.get("blower")) is not None and (
311
+ self.blower.on_seconds != blower_seconds
312
+ ):
313
+ self.blower = replace(self.blower, on_seconds=blower_seconds)
314
+ updated.add("blower")
315
+ for target, jet_id in (("jet1", 1), ("jet3", 3)):
316
+ if (
317
+ (seconds := decoded.get(target)) is not None
318
+ and jet_id in self.jets
319
+ and self.jets[jet_id].on_seconds != seconds
320
+ ):
321
+ self.jets[jet_id] = replace(self.jets[jet_id], on_seconds=seconds)
322
+ updated.add("jets")
323
+
324
+ def _apply_power_words(
325
+ self,
326
+ fresh: dict[str, int],
327
+ *,
328
+ prior_states: _CircuitStates,
329
+ ) -> None:
330
+ """Merge freshly decoded power/current words and apply circuit gating."""
331
+ if not self.power.supported:
332
+ return
333
+
334
+ updates: dict[str, int | None] = dict(fresh)
335
+ for state, before, fields in zip(
336
+ self._circuit_states, prior_states, _CIRCUIT_FIELDS, strict=True
337
+ ):
338
+ if not state:
339
+ updates.update(dict.fromkeys(fields, 0))
340
+ elif state != before:
341
+ for field in fields:
342
+ updates[field] = fresh.get(field)
343
+ self.power = replace(self.power, **updates)
344
+
345
+ @property
346
+ def _circuit_states(self) -> _CircuitStates:
347
+ """Return active-state snapshot for (heater, jet3, jet1+jet2+blower)."""
348
+ return (self.heater.is_on, self._is_jet3_on, self._pump_blower_state)
349
+
350
+ @property
351
+ def _is_jet3_on(self) -> bool:
352
+ """Return True if an enabled Jet 3 is currently running."""
353
+ return bool((jet3 := self.jets.get(3)) and jet3.is_enabled and jet3.is_on)
354
+
355
+ @property
356
+ def _pump_blower_state(self) -> _PumpBlowerState:
357
+ """Return normalized active state of (Jet 1, Jet 2, Blower), or None if off."""
358
+ jet1 = self.jets.get(1)
359
+ jet2 = self.jets.get(2)
360
+ state = (
361
+ jet1.speed if jet1 is not None and jet1.is_on else JetSpeed.OFF,
362
+ jet2.speed if jet2 is not None and jet2.is_on else JetSpeed.OFF,
363
+ self.blower.is_on,
364
+ )
365
+ return None if state == (JetSpeed.OFF, JetSpeed.OFF, False) else state
366
+
367
+ @property
368
+ def system_uptime_hours(self) -> float | None:
369
+ """Return system uptime in hours when available."""
370
+ return _seconds_to_hours(self.system_uptime_seconds)
371
+
372
+ @property
373
+ def needs_diagnostics_for_power(self) -> bool:
374
+ """Return True when /addDebugData is needed for power or current readings."""
375
+ return self.power.supported and (
376
+ self.power.small_loads_current is None or any(self._circuit_states)
377
+ )
378
+
230
379
  @property
231
380
  def is_hna(self) -> bool:
232
381
  """Return True if this device is the Home Network Adapter (HNA)."""
@@ -361,24 +510,17 @@ class SpaInfo:
361
510
 
362
511
 
363
512
  @dataclass
364
- class Heater: # pylint: disable=too-many-instance-attributes
513
+ class Heater:
365
514
  """Heater status and configuration."""
366
515
 
367
516
  is_on: bool = False
368
517
  heater_lock: bool = False
369
518
  heatpump_installed: bool = False
370
519
  heating_mode: HeatingMode = HeatingMode.UNKNOWN
371
- heater_current: float = 0.0
372
- heater_on_seconds: int = 0
373
520
  set_temperature: float | None = None
374
521
  current_temperature: float | None = None
375
522
  temperature_unit: TemperatureUnit = TemperatureUnit.UNKNOWN
376
523
 
377
- @property
378
- def heater_on_hours(self) -> float:
379
- """Return cumulative heater runtime in hours."""
380
- return round(self.heater_on_seconds / 3600.0, 2)
381
-
382
524
  @staticmethod
383
525
  def from_dict(data: dict[str, object], existing: Heater | None = None) -> Heater:
384
526
  """Create a Heater from API response data.
@@ -415,8 +557,7 @@ class Jet:
415
557
  speed_type: JetSpeedType = JetSpeedType.UNKNOWN
416
558
  is_enabled: bool = True
417
559
  concurrent_mode: bool = False
418
- current: float = 0.0
419
- on_seconds: int = 0
560
+ on_seconds: int | None = None
420
561
 
421
562
  @property
422
563
  def is_available(self) -> bool:
@@ -448,9 +589,9 @@ class Jet:
448
589
  return [JetSpeed.OFF, JetSpeed.HIGH_SPEED]
449
590
 
450
591
  @property
451
- def on_hours(self) -> float:
452
- """Return cumulative jet runtime in hours."""
453
- return round(self.on_seconds / 3600.0, 2)
592
+ def on_hours(self) -> float | None:
593
+ """Return cumulative jet runtime in hours when available."""
594
+ return _seconds_to_hours(self.on_seconds)
454
595
 
455
596
  @staticmethod
456
597
  def from_dict(
@@ -486,22 +627,8 @@ class Jet:
486
627
  )
487
628
 
488
629
  status = data.get("status")
489
- if isinstance(status, dict):
490
- if "speed" in status:
491
- kwargs["speed"] = JetSpeed.build(status.get("speed"))
492
- if "current" in status:
493
- kwargs["current"] = int(status.get("current", 0)) / 2560.0
494
- on_sec_key = f"jet_{jet_id}_ON_sec"
495
- if on_sec_key in status:
496
- # The ESP32 firmware tracks runtime using an unsigned 32-bit counter
497
- # in units of 1/256 seconds (Q24.8 fixed-point), but formats it as a
498
- # signed 32-bit integer (`%d`) in the JSON output. Once runtime
499
- # exceeds 2^31 ticks (~97.1 days), it overflows into a negative value.
500
- # Masking with `& 0xFFFFFFFF` restores the true unsigned 32-bit counter
501
- # before dividing by 256 to convert to whole elapsed seconds.
502
- kwargs["on_seconds"] = (
503
- int(status.get(on_sec_key, 0)) & 0xFFFFFFFF
504
- ) // 256
630
+ if isinstance(status, dict) and "speed" in status:
631
+ kwargs["speed"] = JetSpeed.build(status["speed"])
505
632
 
506
633
  control = data.get("control")
507
634
  if isinstance(control, str):
@@ -509,7 +636,7 @@ class Jet:
509
636
  if speed != JetSpeed.UNKNOWN:
510
637
  kwargs["speed"] = speed
511
638
  elif isinstance(control, dict) and "speed" in control:
512
- speed = JetSpeed.build(control.get("speed"))
639
+ speed = JetSpeed.build(control["speed"])
513
640
  if speed != JetSpeed.UNKNOWN:
514
641
  kwargs["speed"] = speed
515
642
 
@@ -555,6 +682,12 @@ class Blower:
555
682
 
556
683
  is_enabled: bool = False
557
684
  is_on: bool = False
685
+ on_seconds: int | None = None
686
+
687
+ @property
688
+ def on_hours(self) -> float | None:
689
+ """Return cumulative blower runtime in hours when available."""
690
+ return _seconds_to_hours(self.on_seconds)
558
691
 
559
692
  @staticmethod
560
693
  def from_dict(data: dict[str, object], existing: Blower | None = None) -> Blower:
@@ -573,17 +706,17 @@ class Blower:
573
706
  kwargs: dict[str, object] = {}
574
707
  config = data.get("config")
575
708
  if isinstance(config, dict) and "blower" in config:
576
- kwargs["is_enabled"] = config.get("blower", "disable") != "disable"
709
+ kwargs["is_enabled"] = config["blower"] != "disable"
577
710
 
578
711
  status = data.get("status")
579
712
  if isinstance(status, dict) and "blower" in status:
580
- kwargs["is_on"] = status.get("blower", "off") not in ("off", "disable")
713
+ kwargs["is_on"] = status["blower"] not in ("off", "disable")
581
714
 
582
715
  control = data.get("control")
583
716
  if isinstance(control, str):
584
717
  kwargs["is_on"] = _is_truthy(control)
585
718
  elif isinstance(control, dict) and "blower" in control:
586
- raw_blower = control.get("blower")
719
+ raw_blower = control["blower"]
587
720
  if raw_blower is not None:
588
721
  kwargs["is_on"] = _is_truthy(raw_blower)
589
722
 
@@ -1086,17 +1219,52 @@ class ConnectionStatus:
1086
1219
  return ConnectionStatus(spa_connected=connected)
1087
1220
 
1088
1221
 
1222
+ @dataclass
1223
+ class PowerMetrics: # pylint: disable=too-many-instance-attributes
1224
+ """Reconstructed electrical power and current telemetry.
1225
+
1226
+ On IQ2020/Eagle control boards equipped with current-sensing hardware,
1227
+ power readings reflect apparent power (``V_rms * I_rms`` in VA, equal to
1228
+ real Watts for the resistive heater and within ~1-25% of real Watts on
1229
+ pump motors depending on power factor), and ``*_current`` fields report
1230
+ whole Amps (``A``). ``small_loads_current`` is sampled at initial baseline
1231
+ and refreshed while heater or pump loads are active. On entry-level
1232
+ control boards without current sensors or before initial controller sync,
1233
+ ``supported`` is ``False`` and all reading fields remain ``None``.
1234
+ """
1235
+
1236
+ supported: bool = False
1237
+ small_loads_power: int | None = None
1238
+ jet1_jet2_blower_power: int | None = None
1239
+ heater_power: int | None = None
1240
+ jet3_power: int | None = None
1241
+ jet1_jet2_blower_current: int | None = None
1242
+ small_loads_current: int | None = None
1243
+ heater_current: int | None = None
1244
+ jet3_current: int | None = None
1245
+
1246
+ @property
1247
+ def total_power(self) -> int | None:
1248
+ """Return combined power across all four spa circuits when known."""
1249
+ parts = (
1250
+ self.small_loads_power,
1251
+ self.jet1_jet2_blower_power,
1252
+ self.heater_power,
1253
+ self.jet3_power,
1254
+ )
1255
+ if None in parts:
1256
+ return None
1257
+ # Filter narrows int | None for mypy.
1258
+ return sum(part for part in parts if part is not None)
1259
+
1260
+
1089
1261
  @dataclass
1090
1262
  class SpaTestData:
1091
- """Test data metrics from the spa, including raw current readings."""
1263
+ """Factory calibration and test-status values from the spa."""
1092
1264
 
1093
1265
  heater_test_status: str = "off"
1094
1266
  temp_offset: float = 0.0
1095
1267
  vsense_cal: float = 0.0
1096
- jet1_jet2_blower_current: float = 0.0
1097
- small_loads_current: float = 0.0
1098
- heater_current: float = 0.0
1099
- jet3_current: float = 0.0
1100
1268
 
1101
1269
  @staticmethod
1102
1270
  def from_dict(
@@ -1118,28 +1286,11 @@ class SpaTestData:
1118
1286
  status = data.get("status")
1119
1287
  if isinstance(status, dict):
1120
1288
  if "heaterTestStatus" in status:
1121
- kwargs["heater_test_status"] = str(
1122
- status.get("heaterTestStatus", "off")
1123
- )
1289
+ kwargs["heater_test_status"] = str(status["heaterTestStatus"])
1124
1290
  if "tempOffset" in status:
1125
- kwargs["temp_offset"] = float(status.get("tempOffset", 0.0))
1291
+ kwargs["temp_offset"] = float(status["tempOffset"])
1126
1292
  if "VsenseCal" in status:
1127
- kwargs["vsense_cal"] = float(status.get("VsenseCal", 0.0))
1128
- # Current metrics are encoded in Q8.8 fixed-point deciapps (0.1 A units
1129
- # left-shifted by 8 bits / multiplied by 256).
1130
- # Dividing by 2560.0 (256 * 10) scales the raw integer to Amperes (A).
1131
- if "jet1+jet2+blowerCurrent" in status:
1132
- kwargs["jet1_jet2_blower_current"] = (
1133
- int(status.get("jet1+jet2+blowerCurrent", 0)) / 2560.0
1134
- )
1135
- if "smallLoadsCurrent" in status:
1136
- kwargs["small_loads_current"] = (
1137
- int(status.get("smallLoadsCurrent", 0)) / 2560.0
1138
- )
1139
- if "heaterCurrent" in status:
1140
- kwargs["heater_current"] = int(status.get("heaterCurrent", 0)) / 2560.0
1141
- if "jet3Current" in status:
1142
- kwargs["jet3_current"] = int(status.get("jet3Current", 0)) / 2560.0
1293
+ kwargs["vsense_cal"] = float(status["VsenseCal"])
1143
1294
 
1144
1295
  base = existing or SpaTestData()
1145
1296
  return replace(base, **kwargs)
@@ -1147,12 +1298,7 @@ class SpaTestData:
1147
1298
 
1148
1299
  @dataclass
1149
1300
  class Diagnostics: # pylint: disable=too-many-instance-attributes
1150
- """Diagnostic and power metrics from the spa.
1151
-
1152
- Availability depends on the spa model and whether the main control
1153
- board (IQ2020/Eagle) is equipped with current-sensing transformers.
1154
- Values may be ``0`` if sensors are not installed.
1155
- """
1301
+ """Hardware diagnostic status flags and filter settings from /addDebugData."""
1156
1302
 
1157
1303
  spa_failure_state: SpaFailureState = SpaFailureState.UNKNOWN
1158
1304
  heater_error: str = "0"
@@ -1161,70 +1307,192 @@ class Diagnostics: # pylint: disable=too-many-instance-attributes
1161
1307
  circulation_pump_flow_status: str = "0"
1162
1308
  regulation_thermistor_temp_status: str = "0"
1163
1309
  limit_thermistor_status: str = "0"
1164
- l1_n_volts: float = 0.0
1165
- l2_n_volts: float = 0.0
1166
- heater_volts: float = 0.0
1167
- jet3_volts: float = 0.0
1168
- jet1_jet2_blower_power: str = "0"
1169
- small_loads_power: str = "0"
1170
- heater_power: str = "0"
1171
- jet3_power: str = "0"
1310
+ jet3_volts: int | None = None
1311
+ daily_clean_cycle: int | None = None
1312
+ filter_1_minutes: int | None = None
1313
+ filter_2_minutes: int | None = None
1172
1314
 
1173
1315
  @staticmethod
1174
- def from_dict(data: dict[str, object]) -> Diagnostics:
1175
- """Create a Diagnostics from API response data.
1316
+ def from_dict(
1317
+ data: dict[str, object], existing: Diagnostics | None = None
1318
+ ) -> Diagnostics:
1319
+ """Create a Diagnostics instance from a GET /addDebugData response."""
1320
+ diagnostics, _ = _parse_diagnostics_and_electrical(data, existing=existing)
1321
+ return diagnostics
1322
+
1323
+
1324
+ _STATUS_ELECTRICAL_KEYS: tuple[str, ...] = (
1325
+ "jet1+jet2+blowerCurrent",
1326
+ "smallLoadsCurrent",
1327
+ "heaterCurrent",
1328
+ "jet3Current",
1329
+ )
1176
1330
 
1177
- Args:
1178
- ----
1179
- data: The JSON response from GET /addDebugData, or an empty
1180
- dict for default values.
1331
+ _DEBUG_HEAD_KEYS: tuple[str, ...] = (
1332
+ "L2_N_Volts",
1333
+ "Heater_Volts",
1334
+ "jet3_Volts",
1335
+ )
1181
1336
 
1182
- Returns:
1183
- -------
1184
- A Diagnostics instance.
1337
+ _DEBUG_TAIL_KEYS: tuple[str, ...] = (
1338
+ "jet1_jet2_blowerPower",
1339
+ "smallLoadsPower",
1340
+ )
1185
1341
 
1186
- """
1187
- debug_data = data.get("debugData")
1188
- if not isinstance(debug_data, dict):
1189
- return Diagnostics()
1190
-
1191
- debug = debug_data.get("status")
1192
- if not isinstance(debug, dict) or not debug:
1193
- return Diagnostics()
1194
-
1195
- volt_keys = {
1196
- "L1_N_Volts": "l1_n_volts",
1197
- "L2_N_Volts": "l2_n_volts",
1198
- "Heater_Volts": "heater_volts",
1199
- "jet3_Volts": "jet3_volts",
1200
- }
1201
- str_keys = {
1202
- "heaterError": "heater_error",
1203
- "powerFrequency": "power_frequency",
1204
- "pressureSwitchStatus": "pressure_switch_status",
1205
- "circulationPumpFlowStatus": "circulation_pump_flow_status",
1206
- "regulationThermistorTempStatus": "regulation_thermistor_temp_status",
1207
- "limitThermistorStatus": "limit_thermistor_status",
1208
- "jet1_jet2_blowerPower": "jet1_jet2_blower_power",
1209
- "smallLoadsPower": "small_loads_power",
1210
- "heaterPower": "heater_power",
1211
- "jet3Power": "jet3_power",
1212
- }
1213
- kwargs: dict[str, object] = {}
1214
- if "spaFailureState" in debug:
1215
- kwargs["spa_failure_state"] = SpaFailureState.build(
1216
- debug.get("spaFailureState")
1217
- )
1218
- for json_key, attr in str_keys.items():
1219
- if json_key in debug:
1220
- kwargs[attr] = str(debug[json_key])
1221
- # Voltage registers use Q11.5 fixed-point format (1/32 V resolution).
1222
- # Dividing raw integer by 32.0 converts to Volts.
1223
- for json_key, attr in volt_keys.items():
1224
- if json_key in debug:
1225
- kwargs[attr] = int(debug.get(json_key) or 0) / 32.0
1342
+ # HNA JSON is one byte out of phase with the controller register block.
1343
+ # Together, 3 debug head words + 4 /status test_data words + 2 debug tail words
1344
+ # form one 9-word sequence whose adjacent pairs yield these 8 registers.
1345
+ _REGISTER_NAMES: tuple[str, ...] = (
1346
+ "jet1_jet2_blower_current",
1347
+ "small_loads_current",
1348
+ "heater_current",
1349
+ "jet3_current",
1350
+ "jet1_jet2_blower_power",
1351
+ "small_loads_power",
1352
+ "heater_power",
1353
+ "jet3_power",
1354
+ )
1355
+
1356
+ _CIRCUIT_FIELDS: tuple[tuple[str, str], ...] = (
1357
+ ("heater_power", "heater_current"),
1358
+ ("jet3_power", "jet3_current"),
1359
+ ("jet1_jet2_blower_power", "jet1_jet2_blower_current"),
1360
+ )
1226
1361
 
1227
- return replace(Diagnostics(), **kwargs)
1362
+ _RUNTIME_ROUTES: tuple[tuple[tuple[str, ...], str], ...] = (
1363
+ # HNA shifts each 24-bit runtime counter into its neighboring JSON field.
1364
+ (("heater", "status", "heaterHours"), "jet1"),
1365
+ (("JET", "JET1", "status", "jet_1_ON_sec"), "uptime"),
1366
+ (("JET", "JET2", "status", "jet_2_ON_sec"), "jet3"),
1367
+ (("JET", "JET3", "status", "jet_3_ON_sec"), "blower"),
1368
+ )
1369
+
1370
+ _DEBUG_STRING_KEYS: dict[str, str] = {
1371
+ "heaterError": "heater_error",
1372
+ "powerFrequency": "power_frequency",
1373
+ "pressureSwitchStatus": "pressure_switch_status",
1374
+ "circulationPumpFlowStatus": "circulation_pump_flow_status",
1375
+ "regulationThermistorTempStatus": "regulation_thermistor_temp_status",
1376
+ "limitThermistorStatus": "limit_thermistor_status",
1377
+ }
1378
+
1379
+ _DEBUG_INTEGER_KEYS: tuple[str, ...] = (
1380
+ "L1_N_Volts",
1381
+ *_DEBUG_HEAD_KEYS,
1382
+ *_DEBUG_TAIL_KEYS,
1383
+ "heaterPower",
1384
+ "jet3Power",
1385
+ )
1386
+
1387
+
1388
+ def _seconds_to_hours(seconds: int | None) -> float | None:
1389
+ """Convert elapsed seconds to rounded hours, preserving None."""
1390
+ if seconds is None:
1391
+ return None
1392
+ return round(seconds / 3600.0, 2)
1393
+
1394
+
1395
+ def _dig(data: dict[str, object], path: tuple[str, ...]) -> object:
1396
+ """Return nested dict value along ``path``, or ``None`` if absent."""
1397
+ cursor: object = data
1398
+ for key in path:
1399
+ if not isinstance(cursor, dict) or key not in cursor:
1400
+ return None
1401
+ cursor = cursor[key]
1402
+ return cursor
1403
+
1404
+
1405
+ def _reconstruct_uint16(low_byte_word: int, high_byte_word: int) -> int:
1406
+ """Reconstruct a 16-bit register split across two adjacent misaligned words."""
1407
+ return ((high_byte_word & 0xFF) << 8) | ((low_byte_word >> 8) & 0xFF)
1408
+
1409
+
1410
+ def _decode_registers(
1411
+ head: _WordBlock, status: _WordBlock, tail: _WordBlock
1412
+ ) -> dict[str, int]:
1413
+ """Reconstruct 16-bit registers across the contiguous 9-word API stream."""
1414
+ words = (*head, *status, *tail)
1415
+ return {
1416
+ name: _reconstruct_uint16(low_word, high_word)
1417
+ for name, (low_word, high_word) in zip(
1418
+ _REGISTER_NAMES, itertools.pairwise(words), strict=True
1419
+ )
1420
+ if low_word is not None and high_word is not None
1421
+ }
1422
+
1423
+
1424
+ def _decode_runtime_seconds(raw: object) -> int:
1425
+ """Decode a 24-bit runtime counter shifted by 8 bits into signed 32-bit JSON.
1426
+
1427
+ Runtime counters are left-shifted by 8 bits and formatted as signed 32-bit
1428
+ integers, wrapping negative past ~97.1 days. Masking with ``0xFFFFFFFF``
1429
+ and shifting right by 8 recovers elapsed whole seconds.
1430
+ """
1431
+ raw_value: int = int(raw)
1432
+ return (raw_value & 0xFFFFFFFF) >> 8
1433
+
1434
+
1435
+ def _extract_status_words(data: dict[str, object]) -> _WordBlock | None:
1436
+ """Extract the 4 contiguous electrical words from /status when complete."""
1437
+ test_data = data.get("test_data")
1438
+ if not isinstance(test_data, dict):
1439
+ return None
1440
+ test_data_status = test_data.get("status")
1441
+ if not isinstance(test_data_status, dict) or not all(
1442
+ key in test_data_status for key in _STATUS_ELECTRICAL_KEYS
1443
+ ):
1444
+ return None
1445
+ return tuple(int(test_data_status[key]) for key in _STATUS_ELECTRICAL_KEYS)
1446
+
1447
+
1448
+ def _parse_diagnostics_and_electrical(
1449
+ data: dict[str, object],
1450
+ existing: Diagnostics | None = None,
1451
+ ) -> tuple[Diagnostics, dict[str, int] | None]:
1452
+ """Parse /addDebugData into Diagnostics and raw integer electrical words."""
1453
+ base = existing or Diagnostics()
1454
+ debug_data = data.get("debugData")
1455
+ if not isinstance(debug_data, dict):
1456
+ return base, None
1457
+
1458
+ debug = debug_data.get("status")
1459
+ if not isinstance(debug, dict) or not debug:
1460
+ return base, None
1461
+
1462
+ string_fields = {
1463
+ attribute_name: str(debug[json_key])
1464
+ for json_key, attribute_name in _DEBUG_STRING_KEYS.items()
1465
+ if json_key in debug
1466
+ }
1467
+ parsed_integers = {
1468
+ json_key: int(debug[json_key])
1469
+ for json_key in _DEBUG_INTEGER_KEYS
1470
+ if json_key in debug
1471
+ }
1472
+
1473
+ raw_failure = debug.get("spaFailureState")
1474
+ if not (
1475
+ (raw_failure is not None and str(raw_failure) not in ("", "Spa_Ok"))
1476
+ or any(value != "0" for value in string_fields.values())
1477
+ or any(value != 0 for value in parsed_integers.values())
1478
+ ):
1479
+ return base, None
1480
+
1481
+ kwargs: dict[str, object] = dict(string_fields)
1482
+ if "spaFailureState" in debug:
1483
+ kwargs["spa_failure_state"] = SpaFailureState.build(raw_failure)
1484
+ if (l1_volts := parsed_integers.get("L1_N_Volts")) is not None and (
1485
+ l2_volts := parsed_integers.get("L2_N_Volts")
1486
+ ) is not None:
1487
+ kwargs["jet3_volts"] = _reconstruct_uint16(l1_volts, l2_volts)
1488
+ if "smallLoadsPower" in parsed_integers:
1489
+ kwargs["daily_clean_cycle"] = (parsed_integers["smallLoadsPower"] >> 8) & 0xFF
1490
+ if "heaterPower" in parsed_integers:
1491
+ kwargs["filter_1_minutes"] = parsed_integers["heaterPower"]
1492
+ if "jet3Power" in parsed_integers:
1493
+ kwargs["filter_2_minutes"] = parsed_integers["jet3Power"]
1494
+
1495
+ return replace(base, **kwargs), parsed_integers
1228
1496
 
1229
1497
 
1230
1498
  class _SectionParser(NamedTuple):
@@ -1298,17 +1566,6 @@ def _parse_heater_status(status: dict[str, object]) -> dict[str, object]:
1298
1566
  mode = HeatingMode.build(raw_mode)
1299
1567
  if mode != HeatingMode.UNKNOWN or str(raw_mode).strip().lower() == "invalid":
1300
1568
  kwargs["heating_mode"] = mode
1301
- if "heaterCurrent" in status:
1302
- # Motherboard current registers use Q8.8 fixed point in deciapps (0.1 A):
1303
- # raw / 256 / 10.0 = raw / 2560.0 Amperes.
1304
- kwargs["heater_current"] = int(status.get("heaterCurrent", 0)) / 2560.0
1305
- if "heaterHours" in status:
1306
- # Like jet runtime counters, `heaterHours` is an unsigned 32-bit counter
1307
- # in 1/256 seconds (Q24.8) formatted as signed `%d` in ESP32 JSON.
1308
- # Mask with `& 0xFFFFFFFF` to handle 32-bit integer overflow and divide by 256.
1309
- kwargs["heater_on_seconds"] = (
1310
- int(status.get("heaterHours", 0)) & 0xFFFFFFFF
1311
- ) // 256
1312
1569
  kwargs.update(_parse_heater_temperatures(status))
1313
1570
  return kwargs
1314
1571