diff --git a/custom_components/addhon/CHANGELOG.md b/custom_components/addhon/CHANGELOG.md index 876478d..5239183 100644 --- a/custom_components/addhon/CHANGELOG.md +++ b/custom_components/addhon/CHANGELOG.md @@ -11,6 +11,33 @@ the notes were generated automatically carry a link to their diff instead of a s **Changes** +- **The air conditioner energy sensor reads the counter in Wh; its value drops 1000 times** + (#147): the appliances that meter report watt-hours and the sensor declared them as kWh, + 1000 times too much. It still shows kWh. **Existing installations:** at the update the + value falls to a thousandth, Home Assistant's statistics read that as a meter reset, and + the energy recorded before the update stays 1000 times too high. To correct the past + figures use Developer tools → Statistics on that sensor (adjust the sum). Applied to + every air conditioner; the ones that report 0 are unchanged. +- **New power sensor on the air conditioners that report it** (#147): the power the unit + draws, in W, on the models whose cloud state carries it (seen on the 2026 Flexis and on + other recent series). Updated at most once every 30 seconds while the unit runs. +- **The cleaning counters survive an empty or partial maintenance answer** (#138): each + good answer is laid over the ones before, as the official app's store does, so a + counter missing from one answer keeps its last value instead of going unknown. + +- **The maintenance read sends the appliance type too, as the official app does** (#138): + the request for the cleaning counters carried only the appliance's address, the app's + carries the type as well. +- **A statistics answer whose washes counter went down is discarded as stale** (#138): the + cloud alternated the current statistics with an older version that carried no error, and + the washes counter swung between the two every minute. The last statistics are kept, the + diagnostics file says `rejected: stale` and the cycle timeline gets a row. After ten such + answers in a row the lower counter is taken as the new value. +- **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..00b287a 100644 --- a/custom_components/addhon/client/engine/appliance.py +++ b/custom_components/addhon/client/engine/appliance.py @@ -84,6 +84,17 @@ # swung every minute. Such an answer is discarded and the last good one kept; the # version does not change (the next poll asks v2 again). _STATISTICS_ERROR_KEYS = ("errorMessage", "errorType") +# A v2 answer can be stale without saying so: on 2026-11-11 a v5.29.0 dump of an HQD +# washer showed the cloud alternating the fresh statistics (`programsCounter` 41, rows +# dated to the second) with an older version carrying no error key (39, rows dated at +# midnight), and the washes counter swung 41<->39 every minute. The app compares nothing +# (apk2 decomp.txt @4192286-4192419, `apk2/analysis/issue138-beta3/21` section 4) but +# reads once per screen, not every minute. A v2 answer whose counter is lower than the +# last one taken is discarded like an error body, as `stale`. This many in a row and the +# lower counter is believed and becomes the base: a counter that really went back (an +# appliance reset, an account moved) must not freeze the statistics until a reload. At a +# poll a minute that is ten minutes; the alternation seen never got past one in a row. +STALE_STATISTICS_LIMIT = 10 def _statistics_error(answer: Mapping[str, Any]) -> Optional[str]: @@ -106,6 +117,53 @@ 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, for the `errorCode` + as for the `resultCode` (an error code of zero names no error).""" + code = answer.get("resultCode") + failed = not _blank(code) and not _zero(code) + error = answer.get("errorCode") + silent = all( + _blank(answer.get(key)) for key in _MAINTENANCE_ERROR_KEYS if key != "errorCode" + ) and (_blank(error) or _zero(error)) + if not failed and silent: + return None + # A zero or blank `errorCode` names no error even on an answer rejected for its + # `resultCode` or for another error field: that one is plain `maintenance`, never + # `maintenance_0` or a bare `maintenance_`. + named = isinstance(error, (str, int)) and not isinstance(error, bool) + if named and not _blank(error) and not _zero(error): + 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(): @@ -228,7 +286,19 @@ def __init__( # body gets instead (`_read_statistics`); a copy, the merge writes into the one # returned. self._statistics_kept: dict[str, Any] = {} + # The v2 answers discarded as stale since the last one taken + # (`_statistics_stale`, `STALE_STATISTICS_LIMIT`). + self._statistics_stale_run = 0 self._statistics_v1_only = False + # The good `/maintenance-cycle` answers taken, each laid over the ones before, {} + # before the first: what is merged into the statistics (`_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 + # Maintenance reads started, and the one whose answer the kept map holds: an + # answer from an earlier read never replaces a later one's. + self._maintenance_reads = 0 + self._maintenance_applied = 0 self._attributes: dict[str, Any] = {} self._zone = zone self._additional_data: dict[str, Any] = {} @@ -445,10 +515,16 @@ def adopt_pushed_parameter(self, name: str, data: Mapping[str, Any]) -> HonAttri 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 + v2 raised. A v2 answer discarded adds `"rejected"`, until the next answer taken: + an error body's `errorType` or `"error"`, or `"stale"` for a cycle counter that + went down; a `/maintenance-cycle` answer discarded as an error body 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 +1343,63 @@ 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 clears that. + + The kept map is the app's store: every good answer is laid over what is held + (`STORE_MAINTENANCE` is an `Object.assign` of the payload over the appliance's + entry, apk2 decomp.txt @1346088-1346113), and what is held is what gets merged. + So an empty answer, or one missing a cleaning map an earlier one carried, + leaves the counters where they were instead of dropping them for that poll; + an empty one says nothing and changes nothing else. As in the app, a map the + cloud stops sending stays until the restart. + + Two reads of one appliance can overlap. The answer of the earlier one, coming + back last, is not laid over the later one's. + """ + self._maintenance_reads += 1 + read = self._maintenance_reads + answer = await self.api.load_maintenance(self) + if not isinstance(answer, Mapping): + return answer + if not answer: + return dict(self._maintenance_kept) + rejected = _maintenance_error(answer) + if rejected is None: + if read > self._maintenance_applied: + self._maintenance_applied = read + self._maintenance_kept = {**self._maintenance_kept, **answer} + self._maintenance_rejected = None + return dict(self._maintenance_kept) + _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 +1408,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) @@ -1308,8 +1437,9 @@ async def _read_statistics(self) -> dict[str, Any]: answered as a 200 (seen mixed with stale statistics at alternate polls, dump of 2026-11-08): it is discarded, the last v2 answer taken is handed back ({} before one), the version stays v2, `statistics_source` says `rejected` and the cycle - log gets a row. Checked before the shape. An API without `load_statistics_v2` - reads v1. + log gets a row. Checked before the shape. A shaped answer whose + `programsCounter` is lower than the last one taken is discarded the same way, + as `stale` (`_statistics_stale`). An API without `load_statistics_v2` reads v1. """ read_v2 = getattr(self.api, "load_statistics_v2", None) if ( @@ -1334,15 +1464,23 @@ 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): + if self._statistics_stale(answer): + _LOGGER.debug( + "Statistics v2 answered a lower cycle counter for %s: " + "kept the last", + self.appliance_type, + ) + self._statistics_source = { + "version": "v2", "fallback": None, "rejected": "stale", + } + self._log_rejected("stale") + return dict(self._statistics_kept) self._statistics_source = {"version": "v2", "fallback": None} self._statistics_kept = dict(answer) + self._statistics_stale_run = 0 return answer fallback = "shape" else: @@ -1359,6 +1497,19 @@ async def _read_statistics(self) -> dict[str, Any]: self._statistics_source = {"version": "v1", "fallback": None} return await self.api.load_statistics(self) + def _statistics_stale(self, answer: Mapping[str, Any]) -> bool: + """Whether a v2 answer is an older version of the statistics held: both carry a + `programsCounter` that reads as a whole number and the answer's is lower (dump + of 2026-11-11, see `STALE_STATISTICS_LIMIT`). A counter absent or unreadable on + either side is not compared. The `STALE_STATISTICS_LIMIT`th such answer in a row + is not stale: the caller takes it, and it is the base from then on.""" + counter = _as_int(answer.get("programsCounter")) + held = _as_int(self._statistics_kept.get("programsCounter")) + if counter is None or held is None or counter >= held: + return False + self._statistics_stale_run += 1 + return self._statistics_stale_run < STALE_STATISTICS_LIMIT + async def update(self, force: bool = False) -> Optional[bool]: """Read the context, unless the last read is under 5 s old and not `force`d. diff --git a/custom_components/addhon/client/engine/cycle_log.py b/custom_components/addhon/client/engine/cycle_log.py index b3cd8f5..fda3fac 100644 --- a/custom_components/addhon/client/engine/cycle_log.py +++ b/custom_components/addhon/client/engine/cycle_log.py @@ -33,8 +33,10 @@ `loadingPercentage` it did not hold (the load measured and suggested, the start date of 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; + v2 answer discarded as an error body (`rejected`, its `errorType`) or for a cycle + counter that went down (`rejected`, `stale`), the statistics held unchanged, or a + `/maintenance-cycle` answer discarded as an error body (`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 +583,10 @@ 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 `stale` + for an answer whose cycle counter went down. 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/client/transport/api.py b/custom_components/addhon/client/transport/api.py index 6934608..4d7ab25 100644 --- a/custom_components/addhon/client/transport/api.py +++ b/custom_components/addhon/client/transport/api.py @@ -612,8 +612,19 @@ async def _load_statistics(self, appliance: Any, version: str) -> dict: return payload if isinstance(payload, dict) else {} async def load_maintenance(self, appliance: Any) -> dict: + """`GET /commands/v1/maintenance-cycle` with the two parameters the hOn app + sends for every appliance, `macAddress` and `applianceType` (apk2 decomp.txt + @1346942-1346975; `apk2/analysis/issue138-beta3/21`), the type as the statistics + read sends it. Only `macAddress` went until v5.29.0. + + For a laundry centre the app asks once per unit: `unit` is the `unitName` (WM + or TD) and `applianceType` carries that same name (@1385709-1385760). That is + deliberately not done here: the laundry centre is read-only and no entity of + its reads a cleaning counter, it would take two requests per appliance, and no + dump shows what the cloud answers to either form. To revisit with a dump.""" url = f"{API_URL}/commands/v1/maintenance-cycle" - params = {"macAddress": appliance.mac_address} + # No `unit`: see above. + params = {"macAddress": appliance.mac_address, "applianceType": appliance.appliance_type} async with self._connection.get(url, params=params) as response: data = await response.json(content_type=None) payload = data.get("payload", {}) if isinstance(data, dict) else {} diff --git a/custom_components/addhon/const.py b/custom_components/addhon/const.py index 4403b63..fb7b85e 100644 --- a/custom_components/addhon/const.py +++ b/custom_components/addhon/const.py @@ -259,6 +259,7 @@ AC_ATTR_ON_OFF = "settings.onOffStatus" AC_ATTR_COMPRESSOR_FREQ = "compressorFrequency" AC_ATTR_TOTAL_ENERGY = "totalElectricityUsed" +AC_ATTR_POWER = "acInput" # Power drawn right now (W), #147 # Air quality (direct attributes, confirmed on Roberto's AC) AC_ATTR_PM25 = "pm2p5ValueIndoor" # Indoor PM2.5 (µg/m³) AC_ATTR_CO2 = "co2ValueIndoor" # Indoor CO2 (ppm) diff --git a/custom_components/addhon/diagnostics.py b/custom_components/addhon/diagnostics.py index 6f455d3..11d2cea 100644 --- a/custom_components/addhon/diagnostics.py +++ b/custom_components/addhon/diagnostics.py @@ -1586,9 +1586,11 @@ def _statistics_source(appliance) -> dict | None: """`{version, fallback}` of the last statistics read (`HonAppliance.statistics_source`, 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.""" + null. `rejected`, printed only when the engine wrote it (a v2 answer discarded: an + error body, or `stale` for a cycle counter that went down), + 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 +1599,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/custom_components/addhon/manifest.json b/custom_components/addhon/manifest.json index 5384cba..ec1e4e7 100644 --- a/custom_components/addhon/manifest.json +++ b/custom_components/addhon/manifest.json @@ -11,5 +11,5 @@ "requirements": [ "awsiotsdk>=1.21.0" ], - "version": "5.29.0" + "version": "5.30.0" } diff --git a/custom_components/addhon/sensor.py b/custom_components/addhon/sensor.py index 523842f..e8a0ddc 100644 --- a/custom_components/addhon/sensor.py +++ b/custom_components/addhon/sensor.py @@ -32,6 +32,7 @@ EntityCategory, UnitOfEnergy, UnitOfMass, + UnitOfPower, UnitOfTemperature, UnitOfTime, UnitOfVolume, @@ -77,6 +78,7 @@ AC_ATTR_HUMIDITY_INDOOR, AC_ATTR_OUTDOOR_TEMP, AC_ATTR_PM25, + AC_ATTR_POWER, AC_ATTR_TOTAL_ENERGY, DOMAIN, DW_LEVEL_MAP, @@ -590,10 +592,20 @@ def _g_int(key: str, attr: str, icon: str | None = None) -> "HonSensorEntityDesc ), ) -# Air conditioner. ENERGY NOTE: hOn does NOT provide cumulative kWh for AS-class -# ACs (totalElectricityUsed reports 0 from the device itself, it is not a -# placeholder of ours). We keep the sensor anyway (useful on ACs that do report -# it); for real energy an external meter is needed. +# Air conditioner. ENERGY NOTE (#147): `totalElectricityUsed` is a counter in Wh on +# the ACs that meter (AS35SBBHRA-MB: 16-minute steps worth 289-660 W as Wh, with +# `acInput` reading 682 W in the same dump), and 0 from the device itself on the +# ones that do not -- it is not a placeholder of ours. Declared in Wh and shown in +# kWh: the state stays the number the device sent and Home Assistant converts it. +# The washer publishes the SAME key in kWh, so the unit belongs to this row and +# to no shared code. The hOn app never reads the counter: its consumption screen +# is a cloud series already in kWh. +# +# The power row lives only where the device reports `acInput`. +AC_POWER_KEY = "power" +# Seconds between two published power readings: the device pushes a new one about +# every 2 s while it runs (#126), some 1,800 recorder rows an hour unthrottled. +AC_POWER_MIN_INTERVAL = 30.0 _AC: tuple[HonSensorEntityDescription, ...] = ( HonSensorEntityDescription( key="temp_indoor", @@ -626,9 +638,31 @@ def _g_int(key: str, attr: str, icon: str | None = None) -> "HonSensorEntityDesc key="total_energy", translation_key="ac_total_energy", attr_key=AC_ATTR_TOTAL_ENERGY, - native_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, - device_class=SensorDeviceClass.ENERGY, + # Wh for every air conditioner, by decision (2026-11-11): no model has been + # seen counting in kWh. The -MB units are proven in Wh; read as kWh the -PA + # units of #73 exceed 5.8 times what the appliance can draw; the others + # report 0, which is 0 in either unit. + native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, # was kWh until v5.29.0 + # Upgrade path, by decision too: same unique_id, no statistics migration. An + # entity registered in kWh keeps showing kWh; its value drops 1000 times, the + # recorder reads that as a meter reset, and the statistics recorded before + # stay 1000 times too high. The CHANGELOG says so and how to correct them. + suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, # the display unit state_class=SensorStateClass.TOTAL_INCREASING, + device_class=SensorDeviceClass.ENERGY, + ), + HonSensorEntityDescription( + key=AC_POWER_KEY, + translation_key="ac_power", + attr_key=AC_ATTR_POWER, + native_unit_of_measurement=UnitOfPower.WATT, + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + # Created at setup from the attributes the device reports then, as every + # gated row is: an `acInput` that first shows up later gets its entity at + # the next reload of the integration. The three dumps that carry it have it + # from the first shadow, 0 with the unit off. + gated=True, # no late creation, for this row as for the others ), HonSensorEntityDescription( key="pm25", @@ -1618,6 +1652,10 @@ async def async_setup_entry( entity_class = HonWashDelaySensor elif app_type == APPLIANCE_AP: entity_class = HonAirPurifierSensor + elif app_type == APPLIANCE_AC and description.key == AC_POWER_KEY: + # Rate-limited, which needs the last published value: a value_fn + # only ever sees the number (#147). + entity_class = HonAcPowerSensor else: entity_class = HonSensor if entity_class is HonMyZoneModeSensor: @@ -1910,6 +1948,50 @@ def _finite(raw) -> float | None: return number if math.isfinite(number) else None +class HonAcPowerSensor(HonSensor): + """Power an air conditioner draws, published at most every 30 seconds (#147). + + `acInput` arrives over MQTT about every 2 s while the unit runs, moving by a + few watts each time (394-403 over 18 s in the #126 log). Every push already + refreshes all the entities, so following it would be one state change and one + recorder row per message. The reading is held instead: a new figure replaces + the published one only once `AC_POWER_MIN_INTERVAL` has passed since that one + went out. The last figure of a run is not lost to the hold -- when the pushes + stop, the 60 s poll reads the entity again after the window has closed. + + A reading that cannot be interpreted -- not a number, NaN, an infinity -- is + never held back, and neither is the first one after it: unknown is shown at + once, not papered over with an old number. + """ + + _published: float | None = None + _published_at: float | None = None + + @staticmethod + def _monotonic() -> float: + # Looked up at call time so a test can drive the clock. + return time.monotonic() + + @property + def native_value(self): + # NaN and the infinities are floats to Python and a reading to no one: they + # are unknown, like a value that is not a number at all. + value = _finite(super().native_value) + if value is None: + self._published = self._published_at = None + return None + now = self._monotonic() + if ( + self._published is not None + and self._published_at is not None + and now - self._published_at < AC_POWER_MIN_INTERVAL + ): + return self._published + # Only a finite figure gets this far, so only one is ever held. + self._published, self._published_at = value, now + return value + + class HonMyZoneTempSensor(HonSensor): """My Zone drawer temperature, corrected for the cloud bias of issue #75. diff --git a/custom_components/addhon/strings.json b/custom_components/addhon/strings.json index d0a2431..ba6d49d 100644 --- a/custom_components/addhon/strings.json +++ b/custom_components/addhon/strings.json @@ -274,6 +274,9 @@ "ac_total_energy": { "name": "Air conditioner total energy" }, + "ac_power": { + "name": "Air conditioner power" + }, "pm25": { "name": "PM2.5" }, diff --git a/custom_components/addhon/translations/en.json b/custom_components/addhon/translations/en.json index d0a2431..ba6d49d 100644 --- a/custom_components/addhon/translations/en.json +++ b/custom_components/addhon/translations/en.json @@ -274,6 +274,9 @@ "ac_total_energy": { "name": "Air conditioner total energy" }, + "ac_power": { + "name": "Air conditioner power" + }, "pm25": { "name": "PM2.5" }, diff --git a/custom_components/addhon/translations/fr.json b/custom_components/addhon/translations/fr.json index c6d2a0b..cf0e836 100644 --- a/custom_components/addhon/translations/fr.json +++ b/custom_components/addhon/translations/fr.json @@ -274,6 +274,9 @@ "ac_total_energy": { "name": "Énergie totale du climatiseur" }, + "ac_power": { + "name": "Puissance du climatiseur" + }, "pm25": { "name": "PM2.5" }, diff --git a/custom_components/addhon/translations/it.json b/custom_components/addhon/translations/it.json index 77034f2..08d5648 100644 --- a/custom_components/addhon/translations/it.json +++ b/custom_components/addhon/translations/it.json @@ -274,6 +274,9 @@ "ac_total_energy": { "name": "Energia Totale Condizionatore" }, + "ac_power": { + "name": "Potenza Condizionatore" + }, "pm25": { "name": "PM2.5" }, diff --git a/tests/conftest.py b/tests/conftest.py index 6efbcc9..1e94d8d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -117,7 +117,11 @@ def _handle_coordinator_update(self) -> None: if not hasattr(const, "UnitOfTime"): const.UnitOfTime = type("UnitOfTime", (), {"MINUTES": "min", "SECONDS": "s"}) if not hasattr(const, "UnitOfEnergy"): - const.UnitOfEnergy = type("UnitOfEnergy", (), {"KILO_WATT_HOUR": "kWh"}) + const.UnitOfEnergy = type( + "UnitOfEnergy", (), {"KILO_WATT_HOUR": "kWh", "WATT_HOUR": "Wh"} + ) + if not hasattr(const, "UnitOfPower"): + const.UnitOfPower = type("UnitOfPower", (), {"WATT": "W"}) if not hasattr(const, "UnitOfVolume"): const.UnitOfVolume = type("UnitOfVolume", (), {"LITERS": "L"}) if not hasattr(const, "UnitOfMass"): @@ -329,6 +333,7 @@ class SensorEntityDescription: translation_key: str | None = None icon: str | None = None native_unit_of_measurement: str | None = None + suggested_unit_of_measurement: str | None = None device_class: object | None = None state_class: object | None = None options: object | None = None diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.py index aa58c83..df08ff7 100644 --- a/tests/test_diagnostics.py +++ b/tests/test_diagnostics.py @@ -5819,7 +5819,9 @@ def test_every_emitted_name_is_a_static_table_field(self) -> None: # rows, three names each, on TD. # 647 with the dryer's two drying-time selects (#142): `dryTime` and # `dryTimeMM`, three names each, on TD. - 647, + # 648 with the air conditioner's power sensor (#147): one read name, + # `acInput`, on AC. + 648, seen, f"the sweep changed to {seen} names; re-measure and update this number " f"deliberately, naming what joined or left it", diff --git a/tests/test_sensor_per_type.py b/tests/test_sensor_per_type.py index 6f728b8..1ab5893 100644 --- a/tests/test_sensor_per_type.py +++ b/tests/test_sensor_per_type.py @@ -205,7 +205,7 @@ def test_ac_keys(self) -> None: self.assertEqual( self._keys("AC"), ["temp_indoor", "temp_outdoor", "humidity_indoor", "compressor_freq", - "total_energy", "pm25", "co2", "ch2o", "pm10", "voc", "co", + "total_energy", "power", "pm25", "co2", "ch2o", "pm10", "voc", "co", "air_quality"], ) @@ -826,5 +826,136 @@ async def test_the_other_models_read_delay_time_as_before(self) -> None: self.assertEqual(150.0, await self._delay(attributes, **kwargs)) +class AcEnergyAndPowerTest(unittest.IsolatedAsyncioTestCase): + """The AC energy counter is in Wh, and `acInput` is the power drawn (#147). + + Measured on an AS35SBBHRA-MB: seven 16-minute steps of `totalElectricityUsed` + worth 289-660 W as Wh, with `acInput` reading 682 in the same dump. + """ + + def _ac(self, key: str): + from custom_components.addhon.sensor import SENSORS + + return next(d for d in SENSORS["AC"] if d.key == key) + + async def _build(self, attributes: dict) -> dict: + from custom_components.addhon import sensor + from custom_components.addhon.const import DOMAIN + + data = {"ac-1": {"type": "AC", "name": "AC", "attributes": attributes, "settings": {}}} + coordinator = FakeCoordinator(data) + hass = FakeHass({DOMAIN: {"entry-1": {"coordinator": coordinator}}}) + added: list = [] + await sensor.async_setup_entry(hass, FakeEntry(), added.extend) + return {e._attr_unique_id: e for e in added if not getattr(e, "_addhon_account", False)} + + def test_the_ac_energy_counter_is_declared_in_watt_hours(self) -> None: + from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass + from homeassistant.const import UnitOfEnergy + + energy = self._ac("total_energy") + self.assertEqual(energy.attr_key, "totalElectricityUsed") + self.assertEqual(energy.native_unit_of_measurement, UnitOfEnergy.WATT_HOUR) + self.assertEqual(energy.suggested_unit_of_measurement, UnitOfEnergy.KILO_WATT_HOUR) + self.assertEqual(energy.device_class, SensorDeviceClass.ENERGY) + self.assertEqual(energy.state_class, SensorStateClass.TOTAL_INCREASING) + # The conversion is Home Assistant's: the state stays what the device sent. + self.assertIsNone(energy.value_fn) + + def test_the_washer_counter_keeps_kilowatt_hours(self) -> None: + from custom_components.addhon.sensor import SENSORS + from homeassistant.const import UnitOfEnergy + + # Same shadow key, another unit: a washer reports kWh with decimals. + energy = next(d for d in SENSORS["WM"] if d.key == "total_energy") + self.assertEqual(energy.attr_key, "totalElectricityUsed") + self.assertEqual(energy.native_unit_of_measurement, UnitOfEnergy.KILO_WATT_HOUR) + self.assertIsNone(energy.suggested_unit_of_measurement) + + async def test_the_ac_energy_state_is_the_raw_counter(self) -> None: + built = await self._build({"totalElectricityUsed": 47037}) + self.assertEqual(built["ac-1_total_energy"].native_value, 47037.0) + + def test_the_power_row(self) -> None: + from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass + from homeassistant.const import UnitOfPower + + power = self._ac("power") + self.assertEqual(power.attr_key, "acInput") + self.assertEqual(power.translation_key, "ac_power") + self.assertEqual(power.native_unit_of_measurement, UnitOfPower.WATT) + self.assertEqual(power.device_class, SensorDeviceClass.POWER) + self.assertEqual(power.state_class, SensorStateClass.MEASUREMENT) + self.assertTrue(power.gated) + + async def test_power_exists_only_where_the_device_reports_it(self) -> None: + from custom_components.addhon.sensor import HonAcPowerSensor + + without = await self._build({"totalElectricityUsed": 0}) + self.assertNotIn("ac-1_power", without) + + # 0 is a reading (the unit is off), not an absence. + with_it = await self._build({"totalElectricityUsed": 26, "acInput": 0}) + self.assertIsInstance(with_it["ac-1_power"], HonAcPowerSensor) + self.assertEqual(with_it["ac-1_power"].native_value, 0.0) + + async def test_power_is_published_at_most_every_thirty_seconds(self) -> None: + from custom_components.addhon.sensor import AC_POWER_MIN_INTERVAL + + self.assertEqual(AC_POWER_MIN_INTERVAL, 30.0) + attributes = {"acInput": 400} + power = (await self._build(attributes))["ac-1_power"] + clock = [1000.0] + power._monotonic = lambda: clock[0] + + self.assertEqual(power.native_value, 400.0) + # The device pushes a new figure every ~2 s (#126): held until the window ends. + for step, reading in ((2.0, 395), (4.0, 403), (29.9, 398)): + clock[0] = 1000.0 + step + attributes["acInput"] = reading + self.assertEqual(power.native_value, 400.0, step) + clock[0] = 1030.0 + self.assertEqual(power.native_value, 398.0) + # ...and the window restarts from the value just published. + clock[0] = 1040.0 + attributes["acInput"] = 682 + self.assertEqual(power.native_value, 398.0) + clock[0] = 1060.0 + self.assertEqual(power.native_value, 682.0) + + async def test_a_missing_power_reading_is_never_held_back(self) -> None: + attributes = {"acInput": 400} + power = (await self._build(attributes))["ac-1_power"] + clock = [1000.0] + power._monotonic = lambda: clock[0] + self.assertEqual(power.native_value, 400.0) + + # Unreadable inside the window: unknown at once, not the old figure. + clock[0] = 1005.0 + attributes["acInput"] = "n/a" + self.assertIsNone(power.native_value) + # And the first figure after it is published without waiting. + clock[0] = 1006.0 + attributes["acInput"] = 395 + self.assertEqual(power.native_value, 395.0) + + async def test_a_power_reading_that_is_not_finite_is_unknown(self) -> None: + # The cloud does hand out "NaN" for a parameter (#112): a float to Python. + for reading in ("NaN", "nan", "Infinity", "-inf", float("nan"), float("inf")): + with self.subTest(reading=reading): + attributes = {"acInput": 400} + power = (await self._build(attributes))["ac-1_power"] + clock = [1000.0] + power._monotonic = lambda: clock[0] + self.assertEqual(power.native_value, 400.0) + clock[0] = 1005.0 + attributes["acInput"] = reading + self.assertIsNone(power.native_value) + # Never held: the next figure is published at once. + clock[0] = 1006.0 + attributes["acInput"] = 395 + self.assertEqual(power.native_value, 395.0) + + if __name__ == "__main__": unittest.main() diff --git a/tests/test_statistics_endpoint.py b/tests/test_statistics_endpoint.py index 0e1881e..36ba5ff 100644 --- a/tests/test_statistics_endpoint.py +++ b/tests/test_statistics_endpoint.py @@ -19,6 +19,23 @@ 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. + +The same dump showed the stale statistics again, this time WITHOUT any error key: v2 +alternated the fresh answer (`programsCounter` 41, `loadingPercentage` dated to the second) +with an older one (39, rows dated at midnight), and the washes counter swung 41<->39 every +minute. The app has no check of its own (no comparison with the counter it holds, apk2 +decomp.txt @4192286-4192419; `apk2/analysis/issue138-beta3/21` section 4) but reads +once per screen, not every minute. A v2 answer whose counter is lower than the last one taken is +discarded as stale; ten in a row are believed (a counter that really went back to zero). """ from __future__ import annotations @@ -47,23 +64,30 @@ 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): self.calls.append("v2") if self.v2_error is not None: raise self.v2_error - return self.v2 + # A new map each poll, as the cloud's: the appliance merges the maintenance + # answer INTO what it is handed, and a shared map would carry one poll's + # cleaning counters into the next statistics answer. + return dict(self.v2) if isinstance(self.v2, dict) else self.v2 async def load_statistics(self, appliance): self.calls.append("v1") - return self.v1 + return dict(self.v1) if isinstance(self.v1, dict) else self.v1 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 +130,58 @@ 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}}, + } + + +def _stale_answer(counter=39): + """The older version v2 answered at alternate polls on 2026-11-11: a lower counter, + rows dated at midnight, no error key.""" + return { + "resultCode": "0", + "programsCounter": counter, + "loadingPercentage": [ + {"current": 1, "max": 9, "date": "2026-11-09T00:00:00Z"}, + ], + "temperatureUsage": {"tempUsageStatistics": {"temp40": 55}}, + } + + +_STALE = {"version": "v2", "fallback": None, "rejected": "stale"} +_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 @@ -485,6 +561,14 @@ def test_the_types_not_followed_keep_no_log(self) -> None: class DumpTest(unittest.TestCase): + def setUp(self) -> None: + # The cycle logs live at module level: without this the dump of one test printed + # the rows another class had left, in whatever order the tests ran. + from custom_components.addhon.client.engine import cycle_log + + cycle_log.forget_all() + self.addCleanup(cycle_log.forget_all) + def _block(self, source): api = _Api(v2={"programsCounter": 3}, v1={"programsCounter": 99}) app = _appliance(api) @@ -534,5 +618,420 @@ 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: + # Not in the statistics answer of this poll: only the kept one can give it. + self.assertNotIn(name, api.v2) + self.assertEqual(_CLEANING, app.statistics[name], 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": " "}, + # An error code that reads as zero is no error (decision of 2026-11-11). + {"errorCode": 0}, + {"errorCode": "0"}, + {"resultCode": "0", "errorCode": "0.0"}, + ): + 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"), + # A zero or blank error code names no error, whatever discarded the answer. + ({"resultCode": "1", "errorCode": 0}, "maintenance"), + ({"resultCode": "1", "errorCode": "0"}, "maintenance"), + ({"resultCode": "1", "errorCode": "0.0"}, "maintenance"), + ({"resultCode": "1", "errorCode": ""}, "maintenance"), + ({"errorCode": " ", "errorDescription": "SQL error: "}, "maintenance"), + ({"errorCode": 0, "errorMessage": "boom"}, "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_an_empty_maintenance_answer_keeps_the_last_cleaning_counters(self) -> None: + # As the app's store, which lays every answer over what it holds. + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + api.maintenance = {} + _run(app.load_statistics()) + for name in _CLEANING_MAPS: + self.assertNotIn(name, api.v2) + self.assertEqual(_CLEANING, app.statistics[name], name) + self.assertEqual({"version": "v2", "fallback": None}, app.statistics_source) + self.assertEqual([], self._events(app)) + + def test_a_maintenance_answer_missing_a_map_is_laid_over_the_last(self) -> None: + api = _Api(v2=_statistics_only(), maintenance=_good_maintenance()) + app = _appliance(api) + _run(app.load_statistics()) + api.maintenance = {"resultCode": "0", "drumCleaning": dict(_CLEANING, count="41")} + _run(app.load_statistics()) + self.assertEqual("41", app.statistics["drumCleaning"]["count"]) + self.assertEqual(_CLEANING, app.statistics["filterCleaning"]) + self.assertEqual(_CLEANING, app.statistics["drawerCleaning"]) + # ...and the map that came back partial is not what an error falls back to. + api.maintenance = _maintenance_error() + _run(app.load_statistics()) + self.assertEqual("41", app.statistics["drumCleaning"]["count"]) + self.assertEqual(_CLEANING, app.statistics["filterCleaning"]) + + def test_an_earlier_read_coming_back_last_is_not_laid_over_the_later_one(self) -> None: + older = dict(_good_maintenance(), drumCleaning=dict(_CLEANING, count="40")) + newer = dict(_good_maintenance(), drumCleaning=dict(_CLEANING, count="41")) + + async def overlap(): + api = _Api(v2=_statistics_only()) + app = _appliance(api) + first_may_answer = asyncio.Event() + answers = iter((older, newer)) + + async def load_maintenance(appliance): + answer = next(answers) + if answer is older: + await first_may_answer.wait() + return dict(answer) + + api.load_maintenance = load_maintenance + first = asyncio.ensure_future(app._read_maintenance()) + await asyncio.sleep(0) # the first read is out, waiting for its answer + await app._read_maintenance() + first_may_answer.set() + await first + # The cloud then answers an error: what is merged is what was kept. + api.load_maintenance = _Api(maintenance=_maintenance_error()).load_maintenance + return await app._read_maintenance() + + kept = _run(overlap()) + self.assertEqual("41", kept["drumCleaning"]["count"]) + + 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"]) + # Not in the statistics answer of this poll: only the kept one can give it. + self.assertNotIn("drumCleaning", api.v2) + self.assertEqual(_CLEANING, block["statistics"].get("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": "