python-hotspring 5.0.0__py3-none-any.whl → 5.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/hotspring.py CHANGED
@@ -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
@@ -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
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-hotspring
3
- Version: 5.0.0
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
@@ -1,10 +1,11 @@
1
1
  hotspring/__init__.py,sha256=-aVuurySHa-uAcIzLJdsvyWmiqAzhd3zq1jncXodGdc,1628
2
2
  hotspring/const.py,sha256=GtzcIq6ZVsvQo6XiA7jDF0fRgOQZnExk1hEuecA0rxU,14908
3
3
  hotspring/exceptions.py,sha256=R8YwGfi6mXZ5DcHw4_fmtrRuvgkfOrLRCH-d3x6OUIw,1184
4
- hotspring/hotspring.py,sha256=RRCHinEBu9blpjhD9-IZZU--Yfe2hJGTkFj1O_bozaI,39542
4
+ hotspring/hotspring.py,sha256=3wg2fKrWa4CXtslnjP1p1wZPKnkwweQuIps6WaznNmI,40027
5
+ hotspring/json_recovery.py,sha256=853Mf3WHjGfj8YXjbwFcY8378Z25-yjID3HwfJfvZqo,2539
5
6
  hotspring/models.py,sha256=W5XQKQreC4ZzPeNVfctrk5t-25OsKdxjXoZIEM5WKEw,65388
6
7
  hotspring/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
- python_hotspring-5.0.0.dist-info/METADATA,sha256=txVID8YEeNqoxXAfMwQ8qP1z_wbJyOWEm5ZZR9Sb95I,7915
8
- python_hotspring-5.0.0.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
9
- python_hotspring-5.0.0.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
10
- python_hotspring-5.0.0.dist-info/RECORD,,
8
+ python_hotspring-5.0.1.dist-info/METADATA,sha256=VviDzWhcmDxKJ6mFaWOq8batQOQd0WpH-GrMWZxRN68,7915
9
+ python_hotspring-5.0.1.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
10
+ python_hotspring-5.0.1.dist-info/licenses/LICENSE,sha256=4n3vNP1aJ5r8xLfzCCjo5l0EK5-k2-7w9rgucn7WVFM,1080
11
+ python_hotspring-5.0.1.dist-info/RECORD,,