From 4b6a0b3670455c0a51df67349b9acd5b73213f9b Mon Sep 17 00:00:00 2001 From: tis24dev Date: Wed, 11 Nov 2026 22:00:31 +0100 Subject: [PATCH 01/10] fix(statistics): a maintenance answer carrying an error is discarded, the last cleaning counters kept On 2026-11-11 a v5.29.0 dump of an HQD washer showed /maintenance-cycle answering, at alternate polls, a 200 with resultCode "1", errorCode "1003", errorDescription "SQL error: " and no cleaning map: merged as it came, the cleaning binaries went unknown and the error keys entered the statistics. The app never checks it and is saved by a store that merges (apk2/analysis/issue138-beta3/21). --- custom_components/addhon/CHANGELOG.md | 5 + .../addhon/client/engine/appliance.py | 102 +++++++- .../addhon/client/engine/cycle_log.py | 7 +- custom_components/addhon/diagnostics.py | 10 +- tests/test_statistics_endpoint.py | 224 +++++++++++++++++- 5 files changed, 330 insertions(+), 18 deletions(-) diff --git a/custom_components/addhon/CHANGELOG.md b/custom_components/addhon/CHANGELOG.md index 876478d..dfaf672 100644 --- a/custom_components/addhon/CHANGELOG.md +++ b/custom_components/addhon/CHANGELOG.md @@ -11,6 +11,11 @@ the notes were generated automatically carry a link to their diff instead of a s **Changes** +- **A maintenance answer carrying an error is discarded and the last cleaning counters + kept** (#138): the cloud answered the maintenance service with a 200 that carried an + error code and no cleaning counters at alternate polls, the drum, filter and drawer + cleaning binary sensors went unknown and the error fields entered the statistics. The + diagnostics file says `maintenance_rejected` and the cycle timeline gets a row. - **The Laundry Centre is supported, read-only** (#124): a Haier washer and dryer under one appliance is set up as one device with a Washer and a Dryer child device. Sensors: state, remaining time, programme name, phase, errors, totals and energy; binary sensors: remote diff --git a/custom_components/addhon/client/engine/appliance.py b/custom_components/addhon/client/engine/appliance.py index 96cc68a..3386c16 100644 --- a/custom_components/addhon/client/engine/appliance.py +++ b/custom_components/addhon/client/engine/appliance.py @@ -106,6 +106,45 @@ def _blank(value: Any) -> bool: return value is None or (isinstance(value, str) and not value.strip()) +# A `/maintenance-cycle` answer carrying one of these with a value, or a `resultCode` +# other than zero, is an error body and not the cleaning counters: on 2026-11-11 a +# v5.29.0 dump of an HQD washer showed the cloud answering a 200 whose payload was +# `resultCode "1"`, `errorCode "1003"`, `errorDescription "SQL error: "` and no cleaning +# map, at alternate polls. Merged as it came, the cleaning binaries went unknown and the +# three keys entered the statistics. The app checks none of them and is saved by its +# store, which merges the payload over the maps it holds (`STORE_MAINTENANCE`, apk2 +# decomp.txt @1346088-1346113; `apk2/analysis/issue138-beta3/21`); here the answer is +# discarded and the last good one merged in its place. +_MAINTENANCE_ERROR_KEYS = ("errorCode", "errorDescription", "errorMessage", "errorType") + + +def _maintenance_error(answer: Mapping[str, Any]) -> Optional[str]: + """Why `answer` is an error body and not the cleaning counters, None when it is + not: `maintenance_` when that is a bare name the dump can print (64 + characters, `diagnostics._statistics_reason`), `maintenance` otherwise. + + A `resultCode` that is null or blank says nothing, and neither does an error field + that is; "0", 0 and "0.0" are all the zero of a good answer.""" + code = answer.get("resultCode") + failed = not _blank(code) and not _zero(code) + if not failed and all(_blank(answer.get(key)) for key in _MAINTENANCE_ERROR_KEYS): + return None + error = answer.get("errorCode") + if isinstance(error, (str, int)) and not isinstance(error, bool): + reason = f"maintenance_{str(error).strip()}" + if reason.isidentifier() and len(reason) <= 64: + return reason + return "maintenance" + + +def _zero(value: Any) -> bool: + """Whether a `resultCode` reads as zero, as text or as a number.""" + try: + return float(str(value).strip()) == 0 + except (TypeError, ValueError): + return False + + def _statistics_shaped(answer: Mapping[str, Any]) -> bool: """Whether `answer` carries at least one statistics key with a value of its shape.""" for key, shapes in _STATISTICS_SHAPES.items(): @@ -229,6 +268,11 @@ def __init__( # returned. self._statistics_kept: dict[str, Any] = {} self._statistics_v1_only = False + # The last `/maintenance-cycle` answer taken, as it came, {} before one: what is + # merged when the answer is an error body (`_read_maintenance`); and why the + # last answer was discarded, None once a good one came (`statistics_source`). + self._maintenance_kept: dict[str, Any] = {} + self._maintenance_rejected: Optional[str] = None self._attributes: dict[str, Any] = {} self._zone = zone self._additional_data: dict[str, Any] = {} @@ -446,9 +490,14 @@ def statistics_source(self) -> Optional[dict[str, Any]]: """`{"version": "v2" | "v1", "fallback": None | reason}` of the last statistics read (issue #138): the reason is `"empty"`, `"shape"` or the class name of what v2 raised. A v2 answer discarded as an error body adds `"rejected"`, its - `errorType` or `"error"`, until the next answer taken. None before the first - read. Read by the diagnostics dump only.""" - return self._statistics_source + `errorType` or `"error"`, until the next answer taken; a `/maintenance-cycle` + answer discarded as one adds `"maintenance_rejected"`, `maintenance_` + or `"maintenance"`, until the next good one. None before the first read. Read + by the diagnostics dump only.""" + source = self._statistics_source + if source is None or self._maintenance_rejected is None: + return source + return {**source, "maintenance_rejected": self._maintenance_rejected} @property def info(self) -> dict[str, Any]: @@ -1267,11 +1316,47 @@ async def load_statistics(self) -> None: self._statistics = await self._read_statistics() # The statistics half as it came, before the merge writes into it. statistics = dict(self._statistics) if isinstance(self._statistics, dict) else {} - maintenance = await self.api.load_maintenance(self) + maintenance = await self._read_maintenance() self._statistics |= maintenance if self._cycle_log is not None: self._log_statistics(self._cycle_log, statistics, maintenance) + async def _read_maintenance(self) -> dict[str, Any]: + """The `/maintenance-cycle` payload to merge over the statistics. + + An answer that is an error body (`_maintenance_error`: seen at alternate polls + with no cleaning map, dump of 2026-11-11) is discarded: the last good answer is + handed back ({} before one), so the cleaning counters stay and the error keys + never enter the statistics; `statistics_source` says `maintenance_rejected` and + the cycle log gets a row. A good answer is kept and clears that. An empty one + is merged as it is and changes neither. + """ + answer = await self.api.load_maintenance(self) + if not isinstance(answer, Mapping) or not answer: + return answer + rejected = _maintenance_error(answer) + if rejected is None: + self._maintenance_kept = dict(answer) + self._maintenance_rejected = None + return answer + _LOGGER.debug( + "Maintenance answered an error body for %s (%s): kept the last", + self.appliance_type, + rejected, + ) + self._maintenance_rejected = rejected + self._log_rejected(rejected) + return dict(self._maintenance_kept) + + def _log_rejected(self, reason: str) -> None: + """A statistics or maintenance answer discarded, in the cycle log. Never raises.""" + if self._cycle_log is None: + return + try: + self._cycle_log.statistics_rejected(reason=reason) + except Exception: # noqa: BLE001 - the log must never cost the poll + _LOGGER.debug("Cycle log failed", exc_info=True) + def _log_statistics( self, log: _cycle_log.CycleLog, statistics: Any, maintenance: Any ) -> None: @@ -1280,7 +1365,8 @@ def _log_statistics( of this object seeds the comparison silently. An empty answer is no read: both halves empty log nothing, and one half empty beside a full one leaves that half's keys last seen in the comparison (the next read is compared with the last - that said something). Never raises.""" + that said something). A discarded maintenance answer comes here as the last + good one, so its cleaning maps do not move. Never raises.""" try: if statistics: self._statistics_half_logged = dict(statistics) @@ -1334,11 +1420,7 @@ async def _read_statistics(self) -> dict[str, Any]: self._statistics_source = { "version": "v2", "fallback": None, "rejected": rejected, } - if self._cycle_log is not None: - try: - self._cycle_log.statistics_rejected(reason=rejected) - except Exception: # noqa: BLE001 - the log must never cost the poll - _LOGGER.debug("Cycle log failed", exc_info=True) + self._log_rejected(rejected) return dict(self._statistics_kept) if _statistics_shaped(answer): self._statistics_source = {"version": "v2", "fallback": None} diff --git a/custom_components/addhon/client/engine/cycle_log.py b/custom_components/addhon/client/engine/cycle_log.py index b3cd8f5..983ec44 100644 --- a/custom_components/addhon/client/engine/cycle_log.py +++ b/custom_components/addhon/client/engine/cycle_log.py @@ -34,7 +34,8 @@ one cycle each) and the scalars that changed, a map's own one level down (`temperatureUsage.temp40`); the first read of an appliance object only seeds; or a v2 answer discarded as an error body (`rejected`, its `errorType`), the statistics - held unchanged; + held unchanged, or a `/maintenance-cycle` answer discarded as one (`rejected`, + `maintenance_` or `maintenance`), the cleaning counters held unchanged; - `entity`: a state one of the entities that show a cycle's options, phase, programme or machine state published (`key`, the unique_id's suffix), `unknown` and `unavailable` kept as the text they are; Home Assistant's listener feeds it (`__init__.py`); @@ -581,7 +582,9 @@ def statistics( def statistics_rejected(self, *, reason: str) -> None: """A poll whose `/statistics` answer was an error body and was discarded, the - statistics held unchanged: `reason` is its `errorType` or `error`.""" + statistics held unchanged: `reason` is its `errorType` or `error`. Or one whose + `/maintenance-cycle` answer was, the cleaning counters held unchanged: `reason` + is `maintenance_` or `maintenance`.""" now = self._clock() fields = {"rejected": _text(reason)} with self._lock: diff --git a/custom_components/addhon/diagnostics.py b/custom_components/addhon/diagnostics.py index 6f455d3..4cfab24 100644 --- a/custom_components/addhon/diagnostics.py +++ b/custom_components/addhon/diagnostics.py @@ -1587,8 +1587,9 @@ def _statistics_source(appliance) -> dict | None: issue #138), rebuilt: the version only from the two the engine writes, the fallback only as `empty`, `shape` or a bare exception class name; anything else prints as null. `rejected`, printed only when the engine wrote it (a v2 error body discarded), - takes the same rule as the fallback. None for an engine without the property or - before its first read.""" + takes the same rule as the fallback, and so does `maintenance_rejected` (a + `/maintenance-cycle` error body discarded, the last cleaning counters kept). None + for an engine without the property or before its first read.""" source = getattr(appliance, "statistics_source", None) if not isinstance(source, Mapping): return None @@ -1597,8 +1598,9 @@ def _statistics_source(appliance) -> dict | None: "version": version if type(version) is str and version in _STATISTICS_VERSIONS else None, "fallback": _statistics_reason(source.get("fallback")), } - if "rejected" in source: - printed["rejected"] = _statistics_reason(source.get("rejected")) + for key in ("rejected", "maintenance_rejected"): + if key in source: + printed[key] = _statistics_reason(source.get(key)) return printed diff --git a/tests/test_statistics_endpoint.py b/tests/test_statistics_endpoint.py index 0e1881e..ba3f12f 100644 --- a/tests/test_statistics_endpoint.py +++ b/tests/test_statistics_endpoint.py @@ -19,6 +19,15 @@ swung 39<->37 every minute, the cleaning binaries went unknown at alternate polls and the cycle log filled with the swings. Such a body is discarded, the last good statistics kept, the version unchanged (no v1 fallback) and the cycle log told (`rejected`). + +The cleaning counters come from a second read, `GET /commands/v1/maintenance-cycle`, merged +over the statistics. On 2026-11-11 a v5.29.0 dump of an HQD washer showed it answering a +200 whose payload was `{"resultCode": "1", "errorCode": "1003", "errorDescription": "SQL +error: "}`, without the three cleaning maps, at alternate polls: merged as it came, the +cleaning binaries went unknown and the error keys entered the statistics. The app never +checks it and is saved by its store, which merges (apk2 decomp.txt @1346088-1346113; +`apk2/analysis/issue138-beta3/21`). Such an answer is discarded and the last good +maintenance answer merged in its place. """ from __future__ import annotations @@ -47,8 +56,11 @@ def _run(coro): class _Api: """An engine-facing API double: v2 and v1 answer what the test sets, calls are kept.""" - def __init__(self, v2=None, v1=None, v2_error: Exception | None = None) -> None: + def __init__( + self, v2=None, v1=None, v2_error: Exception | None = None, maintenance=None + ) -> None: self.v2, self.v1, self.v2_error = v2, v1, v2_error + self.maintenance = {} if maintenance is None else maintenance self.calls: list[str] = [] async def load_statistics_v2(self, appliance): @@ -63,7 +75,8 @@ async def load_statistics(self, appliance): async def load_maintenance(self, appliance): self.calls.append("maintenance") - return {} + # A new map each poll, as the cloud's. + return dict(self.maintenance) class _V1OnlyApi(_Api): @@ -106,6 +119,44 @@ def _error_body(): _REJECTED = {"version": "v2", "fallback": None, "rejected": "AttributeError"} +def _statistics_only(counter=41): + """A v2 answer without the cleaning maps, which come from `/maintenance-cycle`. It + carries a `resultCode` of its own: the first key of the merged map in the dump of + 2026-11-11, where the maintenance one overwrote it.""" + return { + "resultCode": "0", + "programsCounter": counter, + "loadingPercentage": [ + {"current": 5, "max": 9, "date": "2026-11-09T16:05:30Z"}, + ], + "temperatureUsage": {"tempUsageStatistics": {"temp40": 56}}, + } + + +_CLEANING = {"tot": "100", "count": "40", "remaining": "60", "percentage": "40"} +_CLEANING_MAPS = ("filterCleaning", "drumCleaning", "drawerCleaning") + + +def _good_maintenance(): + """A `/maintenance-cycle` answer as the cloud gives it when it works (v5.29.0 dump + of 2026-11-11).""" + return { + "resultCode": "0", + **{name: dict(_CLEANING) for name in _CLEANING_MAPS}, + "lastCheckup": None, + } + + +def _maintenance_error(): + """The 200 `/maintenance-cycle` answered at alternate polls on 2026-11-11.""" + return {"resultCode": "1", "errorCode": "1003", "errorDescription": "SQL error: "} + + +_MAINTENANCE_REJECTED = { + "version": "v2", "fallback": None, "maintenance_rejected": "maintenance_1003", +} + + def _appliance(api, kind="WM"): return factory._native_engine_appliance_cls()( api, {"applianceTypeName": kind, "applianceModelId": 1, "macAddress": "aa"}, zone=0 @@ -534,5 +585,174 @@ def test_a_source_outside_the_vocabulary_is_dropped(self) -> None: self.assertEqual({"version": None, "fallback": None}, block["statistics_source"]) +class MaintenanceTest(unittest.TestCase): + """A `/maintenance-cycle` answer carrying an error is discarded and the last good one + merged in its place (decision of 2026-11-11, `apk2/analysis/issue138-beta3/21`).""" + + def setUp(self) -> None: + from custom_components.addhon.client.engine import cycle_log + + cycle_log.forget_all() + # The log is per appliance id and every test here uses the same one. + self.addCleanup(cycle_log.forget_all) + + @staticmethod + def _events(app): + return [e for e in app.cycle_log.snapshot()["events"] if e["kind"] == "statistics"] + + def test_a_maintenance_error_is_discarded_and_the_last_cleaning_counters_kept(self) -> None: + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + self.assertEqual({"version": "v2", "fallback": None}, app.statistics_source) + api.maintenance = _maintenance_error() + _run(app.load_statistics()) + self.assertEqual(["v2", "maintenance"] * 2, api.calls) + for name in _CLEANING_MAPS: + self.assertEqual(_CLEANING, app.statistics[name]) + self.assertNotIn("errorCode", app.statistics) + self.assertNotIn("errorDescription", app.statistics) + # "0" twice over: the v2 answer carries one, the last good maintenance another. + self.assertEqual("0", app.statistics["resultCode"]) + self.assertEqual(41, app.statistics["programsCounter"]) + self.assertEqual(_MAINTENANCE_REJECTED, app.statistics_source) + [event] = self._events(app) + self.assertEqual("maintenance_1003", event["rejected"]) + self.assertNotIn("changed", event) + self.assertNotIn("new_rows", event) + + def test_the_next_good_maintenance_clears_the_rejection(self) -> None: + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + api.maintenance = _maintenance_error() + _run(app.load_statistics()) + api.maintenance = dict(_good_maintenance(), drumCleaning=dict(_CLEANING, count="41")) + _run(app.load_statistics()) + self.assertEqual({"version": "v2", "fallback": None}, app.statistics_source) + self.assertEqual("41", app.statistics["drumCleaning"]["count"]) + rejected, changed = self._events(app) + self.assertEqual("maintenance_1003", rejected["rejected"]) + self.assertEqual( + {"drumCleaning.count": {"before": "40", "after": "41"}}, changed["changed"] + ) + + def test_a_maintenance_error_at_the_first_read_merges_nothing(self) -> None: + api = _Api(v2=_statistics_only(), maintenance=_maintenance_error()) + app = _appliance(api) + _run(app.load_statistics()) + self.assertEqual(_statistics_only(), app.statistics) + self.assertEqual(_MAINTENANCE_REJECTED, app.statistics_source) + [event] = self._events(app) + self.assertEqual("maintenance_1003", event["rejected"]) + + def test_a_zero_result_code_with_blank_error_fields_is_a_good_answer(self) -> None: + for extra in ( + {}, + {"errorCode": None}, + {"errorCode": "", "errorDescription": " "}, + {"resultCode": 0}, + {"resultCode": "0.0", "errorMessage": None, "errorType": ""}, + {"resultCode": None}, + {"resultCode": " "}, + ): + with self.subTest(extra=extra): + answer = _good_maintenance() | extra + api = _Api(v2=_statistics_only(), maintenance=answer) + app = _appliance(api) + _run(app.load_statistics()) + self.assertEqual(_CLEANING, app.statistics["filterCleaning"]) + self.assertEqual({"version": "v2", "fallback": None}, app.statistics_source) + self.assertEqual([], self._events(app)) + + def test_each_sign_of_an_error_alone_discards_the_answer(self) -> None: + for extra, reason in ( + ({"resultCode": "1"}, "maintenance"), + ({"resultCode": 1}, "maintenance"), + ({"resultCode": "KO"}, "maintenance"), + ({"errorCode": "1003"}, "maintenance_1003"), + ({"errorCode": 1003}, "maintenance_1003"), + ({"errorCode": "E_SQL"}, "maintenance_E_SQL"), + ({"errorCode": "SQL error!"}, "maintenance"), + ({"errorCode": "9" * 64}, "maintenance"), + ({"errorDescription": "SQL error: "}, "maintenance"), + ({"errorMessage": "boom"}, "maintenance"), + ({"errorType": "AttributeError"}, "maintenance"), + ): + with self.subTest(extra=extra): + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + api.maintenance = dict( + _good_maintenance() | extra, drumCleaning=dict(_CLEANING, count="99") + ) + _run(app.load_statistics()) + self.assertEqual("40", app.statistics["drumCleaning"]["count"]) + self.assertEqual(reason, app.statistics_source["maintenance_rejected"]) + for key in extra: + if key != "resultCode": + self.assertNotIn(key, app.statistics) + + def test_an_empty_maintenance_answer_neither_sets_nor_clears_the_rejection(self) -> None: + api = _Api(v2=_statistics_only()) + app = _appliance(api) + _run(app.load_statistics()) + self.assertEqual({"version": "v2", "fallback": None}, app.statistics_source) + api.maintenance = _maintenance_error() + _run(app.load_statistics()) + api.maintenance = {} + _run(app.load_statistics()) + self.assertEqual(_MAINTENANCE_REJECTED, app.statistics_source) + self.assertNotIn("filterCleaning", app.statistics) + + def test_the_rejection_stands_beside_a_statistics_one_and_on_v1(self) -> None: + api = _Api(v2=_good_answer(), maintenance=_maintenance_error()) + app = _appliance(api) + _run(app.load_statistics()) + api.v2 = _error_body() + _run(app.load_statistics()) + self.assertEqual( + dict(_REJECTED, maintenance_rejected="maintenance_1003"), app.statistics_source + ) + api = _Api(v1=_statistics_only(), maintenance=_maintenance_error()) + app = _appliance(api, "AC") + _run(app.load_statistics()) + _run(app.load_statistics()) + self.assertEqual( + {"version": "v1", "fallback": None, "maintenance_rejected": "maintenance_1003"}, + app.statistics_source, + ) + self.assertNotIn("errorCode", app.statistics) + api.maintenance = _good_maintenance() + _run(app.load_statistics()) + self.assertEqual({"version": "v1", "fallback": None}, app.statistics_source) + + def test_a_rejected_maintenance_is_printed_in_the_dump(self) -> None: + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + api.maintenance = _maintenance_error() + _run(app.load_statistics()) + data = {"type": "WM", "appliance": app, "name": "W", "attributes": {}, "statistics": app.statistics} + block = diagnostics._appliance_block("wm1", data) + self.assertEqual(_MAINTENANCE_REJECTED, block["statistics_source"]) + self.assertEqual(_CLEANING, block["statistics"]["drumCleaning"]) + [event] = [e for e in block["cycle_log"]["events"] if e["kind"] == "statistics"] + self.assertEqual("maintenance_1003", event["rejected"]) + json.dumps(block) + + def test_a_maintenance_rejection_outside_the_vocabulary_prints_null(self) -> None: + app = _appliance(_Api(v2={"programsCounter": 3})) + app._statistics_source = { + "version": "v2", "fallback": None, "maintenance_rejected": "