From 61343fbe6846a59ada6063ce428b86a07c89101a Mon Sep 17 00:00:00 2001 From: Jasper Delahaije Date: Sat, 17 Oct 2026 09:37:49 +0200 Subject: [PATCH] Fix live timezone contracts and persist firmware and weight tracking --- custom_components/notty/api.py | 33 +++- custom_components/notty/coordinator.py | 6 +- custom_components/notty/device_features.py | 12 +- custom_components/notty/device_timezone.py | 77 +++++++- custom_components/notty/feature_contracts.py | 2 +- custom_components/notty/manifest.json | 2 +- custom_components/notty/sensor.py | 62 ++++++- custom_components/notty/services.yaml | 8 + custom_components/notty/strings.json | 24 +++ custom_components/notty/translations/en.json | 24 +++ custom_components/notty/translations/nl.json | 24 +++ custom_components/notty/update.py | 80 ++++++++- docs/apk-contracts.md | 2 + docs/apk-firmware.md | 7 + docs/app-validation.md | 9 +- docs/remaining-validation.md | 115 ++++++++++++ docs/validation-coverage.md | 11 +- pyproject.toml | 2 +- release-notes/v0.4.2.md | 30 ++++ scripts/app_validation.py | 34 +++- scripts/validate_schedule_observation.py | 180 +++++++++++++++++++ scripts/weight_report.py | 7 +- tests/test_app_validation.py | 17 ++ tests/test_device_timezone.py | 119 ++++++++++-- tests/test_pet_features.py | 11 ++ tests/test_remaining_firmware.py | 112 ++++++++++++ tests/test_schedule_observation.py | 89 +++++++++ tests/test_weight_probe.py | 6 +- tests/test_weight_sensors.py | 77 ++++++++ uv.lock | 2 +- 30 files changed, 1133 insertions(+), 51 deletions(-) create mode 100644 docs/remaining-validation.md create mode 100644 release-notes/v0.4.2.md create mode 100755 scripts/validate_schedule_observation.py create mode 100644 tests/test_remaining_firmware.py create mode 100644 tests/test_schedule_observation.py create mode 100644 tests/test_weight_sensors.py diff --git a/custom_components/notty/api.py b/custom_components/notty/api.py index a44c850..e1017e8 100644 --- a/custom_components/notty/api.py +++ b/custom_components/notty/api.py @@ -354,14 +354,14 @@ def timezone_catalog(value: JsonValue) -> list[JsonObject]: return rows -def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject]) -> JsonObject: - """Use the selected Windows catalog ID in the APK's misnamed IANA field. +def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject], *, iana_time_zone: str) -> JsonObject: + """Send a real IANA zone; live testing disproved the APK's Windows-name payload. Returns: Only the two fields serialized by the app. Raises: - NottyApiError: If the physical ID or catalog membership is invalid. + NottyApiError: If the physical ID, catalog membership or IANA name is invalid. """ if not device_id.isascii() or not device_id.isdecimal() or int(device_id) <= 0: msg = "Timezone changes require a positive numeric physical device ID" @@ -369,7 +369,26 @@ def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject]) -> if not any(row["id"] == catalog_id for row in rows): msg = "Choose an exact ID from the current NOTTY timezone catalog" raise NottyApiError(msg) - return {"user_device_id": int(device_id), "time_zone_iana": catalog_id} + return {"user_device_id": int(device_id), "time_zone_iana": validated_iana_zone(iana_time_zone)} + + +def validated_iana_zone(value: JsonValue) -> str: + """Validate an explicit IANA identifier without mapping Windows catalog names. + + Returns: + The unchanged valid IANA name. + + Raises: + NottyApiError: If the supplied value is not a known IANA name. + """ + msg = "Timezone changes require a valid IANA name, not a Windows catalog ID" + if not isinstance(value, str): + raise NottyApiError(msg) + try: + ZoneInfo(value) + except KeyError, ValueError, TypeError: + raise NottyApiError(msg) from None + return value def reminder_payload(action: str, data: JsonObject) -> JsonObject: @@ -716,7 +735,7 @@ async def time_zones(self) -> list[JsonObject]: """ return timezone_catalog(await self.request("GET", "/entity/get_time_zones")) - async def change_time_zone(self, device_id: str, catalog_id: str) -> JsonValue: + async def change_time_zone(self, device_id: str, catalog_id: str, *, iana_time_zone: str) -> JsonValue: """Validate fresh catalog membership before one explicit timezone write. Returns: @@ -724,7 +743,9 @@ async def change_time_zone(self, device_id: str, catalog_id: str) -> JsonValue: """ rows = await self.time_zones() return await self.request( - "POST", "/device/change_time_zone", data=timezone_payload(device_id, catalog_id, rows) + "POST", + "/device/change_time_zone", + data=timezone_payload(device_id, catalog_id, rows, iana_time_zone=iana_time_zone), ) diff --git a/custom_components/notty/coordinator.py b/custom_components/notty/coordinator.py index 27c7db2..92f5c95 100644 --- a/custom_components/notty/coordinator.py +++ b/custom_components/notty/coordinator.py @@ -586,8 +586,12 @@ async def _pet_info(self, device: JsonObject) -> JsonObject: "litter_user_device_id": device.get("_notty_litter_user_device_id"), "_notty_related": related, } - _merge_scalar_fields(info, device) related_info = related.get("info") + # Current profile readings take precedence over discovery summaries. + # Missing daily readings/units must not revive an older discovery value. + for field in ("today_weight", "yesterday_weight", "weight_unit"): + if field in device or (isinstance(related_info, dict) and field in related_info): + info[field] = related_info.get(field) if isinstance(related_info, dict) else None if isinstance(related_info, dict): pet_devices = related_info.get("pet_devices") if isinstance(pet_devices, list): diff --git a/custom_components/notty/device_features.py b/custom_components/notty/device_features.py index 02fa7f8..c2e4c4c 100644 --- a/custom_components/notty/device_features.py +++ b/custom_components/notty/device_features.py @@ -2,6 +2,8 @@ from __future__ import annotations +from collections.abc import Awaitable, Callable + from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError, plan_enabled from custom_components.notty.feature_contracts import identifier, object_rows, true_state @@ -97,7 +99,13 @@ class FirmwareApi: def __init__(self, api: NottyApi) -> None: self.api = api - async def install(self, device_id: str, version: str | None = None) -> str: + async def install( + self, + device_id: str, + version: str | None = None, + *, + before_confirm: Callable[[str, JsonObject], Awaitable[None]] | None = None, + ) -> str: """Confirm only the currently offered task for an owned litter box. Returns: @@ -125,6 +133,8 @@ async def install(self, device_id: str, version: str | None = None) -> str: if not firmware_task_id(task) or not isinstance(status, str) or status not in FIRMWARE_IDLE_STATUSES: msg = "Firmware task is absent, busy or has an unknown status" raise NottyApiError(msg) + if before_confirm is not None: + await before_confirm(target, current) await self.api.request( "POST", "/device/confirm_upgrade", data={"user_device_id": identifier(device_id), "task_id": task} ) diff --git a/custom_components/notty/device_timezone.py b/custom_components/notty/device_timezone.py index 1ed52cd..8824d0b 100644 --- a/custom_components/notty/device_timezone.py +++ b/custom_components/notty/device_timezone.py @@ -8,7 +8,15 @@ from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse from homeassistant.exceptions import HomeAssistantError -from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError +from custom_components.notty.api import ( + JsonObject, + JsonValue, + NottyApi, + NottyApiError, + dnd_local_time, + dnd_payload, + validated_iana_zone, +) from custom_components.notty.const import DOMAIN from custom_components.notty.coordinator import NOTTY_SERVER_TIME_ZONE, NottyCoordinator from custom_components.notty.validation import vol @@ -55,35 +63,90 @@ def timezone_change_fields(fields: JsonObject) -> str: Raises: NottyApiError: If fields are missing, extra or invalid. """ - if set(fields) != {"catalog_id", "confirm_schedule_change"} or fields.get("confirm_schedule_change") is not True: - msg = "Timezone changes require catalog_id and confirm_schedule_change: true" + required = {"catalog_id", "iana_time_zone", "confirm_schedule_change"} + if not required <= fields.keys() or fields.keys() - required - {"preserve_dnd_local_times"}: + msg = "Timezone changes require catalog_id, iana_time_zone and confirm_schedule_change: true" + raise NottyApiError(msg) + if ( + fields.get("confirm_schedule_change") is not True + or type(fields.get("preserve_dnd_local_times", False)) is not bool + ): + msg = "Timezone acknowledgement and preservation must be Booleans" raise NottyApiError(msg) identifier = fields["catalog_id"] if not isinstance(identifier, str) or not identifier.strip(): msg = "Choose an exact string ID from the NOTTY catalog" raise NottyApiError(msg) + zone = fields["iana_time_zone"] + if not isinstance(zone, str): + msg = "Choose an explicit IANA timezone name" + raise NottyApiError(msg) + validated_iana_zone(zone) return identifier +def _local_dnd(snapshot: JsonObject) -> JsonObject: + settings, zone = snapshot.get("settings"), snapshot.get("reported_iana") + if not isinstance(settings, dict) or not isinstance(zone, str): + msg = "DND preservation needs readable settings and a valid device IANA zone" + raise NottyApiError(msg) + dnd_payload({**settings, "time_zone_iana": zone}) + return { + key: dnd_local_time(settings.get(key), zone).strftime("%H:%M") for key in ("dnd_begin_time", "dnd_end_time") + } + + +async def _preserve_dnd(api: NottyApi, device_id: str, before: JsonObject, after: JsonObject) -> JsonObject: + settings = before.get("settings") + if not isinstance(settings, dict): + msg = "DND preservation requires the original settings" + raise NottyApiError(msg) + local = _local_dnd(before) + current = {**settings, "time_zone_iana": after.get("reported_iana")} + # The API can shift its raw DND fields on timezone changes. Preserve the + # owner's original local wall clocks, flags and LED with one explicit write. + await api.litter_action( + device_id, + "set_dnd", + dnd_payload(current, dnd_begin_time=local["dnd_begin_time"], dnd_end_time=local["dnd_end_time"]), + ) + return await timezone_snapshot(api, device_id) + + async def change_with_readback(api: NottyApi, device_id: str, fields: JsonObject) -> JsonObject: - """Make at most one write; report setting drift without retries or restoration. + """Change the timezone once and optionally preserve DND, without replay or rollback. Returns: Before/after readback. Matching fields do not prove unchanged firing times. """ identifier = timezone_change_fields(fields) + zone = str(fields["iana_time_zone"]) + preserve = fields.get("preserve_dnd_local_times") is True before = await timezone_snapshot(api, device_id) - if before["reported_windows"] == identifier: + if preserve: + _local_dnd(before) + if before["reported_windows"] == identifier and before["reported_iana"] == zone: return {"status": "unchanged", "before": before, "after": before} - await api.change_time_zone(device_id, identifier) + await api.change_time_zone(device_id, identifier, iana_time_zone=zone) try: after = await timezone_snapshot(api, device_id) except NottyApiError: return {"status": "write_acknowledged_readback_failed", "before": before} + if after["reported_iana"] != zone or after["reported_windows"] != identifier: + return {"status": "timezone_readback_mismatch", "before": before, "after": after} + preservation: str = "not_requested" + if preserve: + try: + after = await _preserve_dnd(api, device_id, before, after) + preservation = "local_clocks_match" if _local_dnd(before) == _local_dnd(after) else "local_clock_mismatch" + except NottyApiError: + return {"status": "timezone_changed_dnd_preservation_failed", "before": before, "after": after} changed: list[JsonValue] = [key for key in ("settings", "plans") if before[key] != after[key]] return { "status": "write_acknowledged_verify_in_app", "requested_catalog_id": identifier, + "requested_iana_time_zone": zone, + "dnd_preservation": preservation, "before": before, "after": after, "changed_schedule_fields": changed, @@ -137,6 +200,8 @@ async def handle(call: ServiceCall) -> JsonObject: vol.Required("user_device_id"): validator, vol.Required("operation"): vol.In(("list", "change")), vol.Optional("catalog_id"): str, + vol.Optional("iana_time_zone"): str, + vol.Optional("preserve_dnd_local_times"): bool, vol.Optional("confirm_schedule_change"): bool, } hass.services.async_register( diff --git a/custom_components/notty/feature_contracts.py b/custom_components/notty/feature_contracts.py index 3bc0b26..f8ea1cf 100644 --- a/custom_components/notty/feature_contracts.py +++ b/custom_components/notty/feature_contracts.py @@ -162,7 +162,7 @@ def profile_payload(pet_id: str, current: JsonObject, changes: JsonObject) -> Js msg = "Pet editing requires the current positive profile weight" raise NottyApiError(msg) unit = current.get("weight_unit") - if type(unit) is not int or unit not in {0, 1}: + if type(unit) is not int or unit not in {1, 2}: msg = "Pet editing requires a known current weight unit" raise NottyApiError(msg) devices = object_rows(current.get("pet_devices")) diff --git a/custom_components/notty/manifest.json b/custom_components/notty/manifest.json index ed04367..f0c3aae 100644 --- a/custom_components/notty/manifest.json +++ b/custom_components/notty/manifest.json @@ -10,5 +10,5 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Repsay/notty/issues", "requirements": [], - "version": "0.4.1" + "version": "0.4.2" } diff --git a/custom_components/notty/sensor.py b/custom_components/notty/sensor.py index 8da4961..3a3823d 100644 --- a/custom_components/notty/sensor.py +++ b/custom_components/notty/sensor.py @@ -1,6 +1,7 @@ from __future__ import annotations from datetime import UTC, datetime +import math from zoneinfo import ZoneInfo, ZoneInfoNotFoundError from homeassistant.components.sensor import SensorDeviceClass, SensorEntity, SensorStateClass @@ -78,6 +79,8 @@ ) WEIGHT_KEYS = {"today_weight", "yesterday_weight", "total_weight", "weight"} +POUNDS_TO_KILOGRAMS = 0.45359237 +WEIGHT_UNIT_FACTORS: dict[str | None, float] = {"kg": 1.0, "lb": POUNDS_TO_KILOGRAMS} TIMESTAMP_KEYS = { "latest_message_date_created", "messages_date_created", @@ -313,10 +316,23 @@ async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant req ) -> None: """Async setup entry.""" coordinator = entry.runtime_data - entities: list[NottySensor] = [] - for device_id, block in coordinator.data.items(): - entities.extend(NottySensor(coordinator, device_id, block["device"], key) for key in sensor_keys(block)) - async_add_entities(entities) + known: set[tuple[str, str]] = set() + + def discover() -> None: + """Discover recovered optional fields without duplicating existing entities.""" + entities: list[NottySensor] = [] + for device_id, block in coordinator.data.items(): + keys = set(sensor_keys(block)) + keys.update((WEIGHT_KEYS - SKIP_KEYS).intersection(merged_device_data(block))) + for key in sorted(keys): + if (device_id, key) not in known: + entities.append(NottySensor(coordinator, device_id, block["device"], key)) + known.add((device_id, key)) + if entities: + async_add_entities(entities) + + discover() + entry.async_on_unload(coordinator.async_add_listener(discover)) class NottySensor(NottyEntity, SensorEntity): @@ -329,6 +345,12 @@ def __init__(self, coordinator: NottyCoordinator, device_id: str, device: Device self._attr_entity_category = EntityCategory.DIAGNOSTIC raw_value = value_from_block(self.block, self.key) device_class, unit, state_class = sensor_metadata(key, raw_value) + if key in WEIGHT_KEYS: + device_class, unit, state_class = ( + SensorDeviceClass.WEIGHT, + UnitOfMass.KILOGRAMS, + SensorStateClass.MEASUREMENT, + ) if device_class is not None: self._attr_device_class = device_class if unit is not None: @@ -344,6 +366,8 @@ def native_value(self) -> StateType | datetime: StateType | datetime: The resulting native value. """ raw_value = value_from_block(self.block, self.key) + if self.key in WEIGHT_KEYS: + return self._weight_in_kilograms(raw_value) timestamp_value = _parse_timestamp_value(raw_value) if timestamp_value is not None and ( DATETIME_FIELD_FRAGMENT in self.key or self.key in {"latest_message_date_created", "messages_date_created"} @@ -354,6 +378,24 @@ def native_value(self) -> StateType | datetime: value = _number_or_original(raw_value) return value if isinstance(value, (str, int, float)) else None + def _weight_in_kilograms(self, raw_value: JsonValue) -> float | None: + value = _number_or_original(raw_value) + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + try: + finite = math.isfinite(value) + except OverflowError: + return None + if not finite or value <= 0: + return None + unit = self._reported_weight_unit() + factor = WEIGHT_UNIT_FACTORS.get(unit) + return float(value) * factor if factor is not None else None + + def _reported_weight_unit(self) -> str | None: + raw = value_from_block(self.block, "weight_unit") + return None if isinstance(raw, bool | float) else _enum_value("weight_unit", raw) + @property def extra_state_attributes(self) -> DeviceData | None: """Extra state attributes. @@ -361,7 +403,17 @@ def extra_state_attributes(self) -> DeviceData | None: Returns: DeviceData | None: The resulting extra state attributes. """ - attributes = {} + attributes: DeviceData = {} + if self.key in WEIGHT_KEYS: + attributes.update({ + "source_field": self.key, + "reported_unit": self._reported_weight_unit(), + "measurement_time": None, + "measurement_freshness": "not_reported", + "measurement_source": "cloud_daily_summary" + if self.key in {"today_weight", "yesterday_weight"} + else "cloud_reported_weight", + }) if self.key == FIELD_DEVICE_TIME_ZONE: attributes.update( timezone_context(value_from_block(self.block, self.key), self.coordinator.hass.config.time_zone) diff --git a/custom_components/notty/services.yaml b/custom_components/notty/services.yaml index c951643..5d683c4 100644 --- a/custom_components/notty/services.yaml +++ b/custom_components/notty/services.yaml @@ -20,6 +20,14 @@ device_time_zone: or numeric offset. selector: text: null + iana_time_zone: + description: Explicit valid IANA name, such as Europe/Amsterdam. The backend stores Windows names incorrectly in this field; catalog membership alone is insufficient. + selector: + text: null + preserve_dnd_local_times: + description: Preserve the original device-local DND clocks, switch and LED with an additional settings write after changing timezone. Inspect the readback response. + selector: + boolean: null confirm_schedule_change: description: Required true for change, acknowledging that scheduled operations use the selected device local time. selector: diff --git a/custom_components/notty/strings.json b/custom_components/notty/strings.json index d0832ef..5543a3d 100644 --- a/custom_components/notty/strings.json +++ b/custom_components/notty/strings.json @@ -250,6 +250,30 @@ "name": "Confirm irreversible deletion" } } + }, + "device_time_zone": { + "name": "Device time zone", + "description": "Choose a server catalog ID and a valid IANA time zone. Inspect readback and the app. Preserving local DND clocks requires an additional settings write.", + "fields": { + "user_device_id": { + "name": "Physical device ID" + }, + "operation": { + "name": "Operation" + }, + "catalog_id": { + "name": "Server catalog ID" + }, + "iana_time_zone": { + "name": "IANA time zone" + }, + "preserve_dnd_local_times": { + "name": "Preserve local DND clocks" + }, + "confirm_schedule_change": { + "name": "Confirm schedule changes" + } + } } } } diff --git a/custom_components/notty/translations/en.json b/custom_components/notty/translations/en.json index d0832ef..5543a3d 100644 --- a/custom_components/notty/translations/en.json +++ b/custom_components/notty/translations/en.json @@ -250,6 +250,30 @@ "name": "Confirm irreversible deletion" } } + }, + "device_time_zone": { + "name": "Device time zone", + "description": "Choose a server catalog ID and a valid IANA time zone. Inspect readback and the app. Preserving local DND clocks requires an additional settings write.", + "fields": { + "user_device_id": { + "name": "Physical device ID" + }, + "operation": { + "name": "Operation" + }, + "catalog_id": { + "name": "Server catalog ID" + }, + "iana_time_zone": { + "name": "IANA time zone" + }, + "preserve_dnd_local_times": { + "name": "Preserve local DND clocks" + }, + "confirm_schedule_change": { + "name": "Confirm schedule changes" + } + } } } } diff --git a/custom_components/notty/translations/nl.json b/custom_components/notty/translations/nl.json index ea9a3e4..0b02cf8 100644 --- a/custom_components/notty/translations/nl.json +++ b/custom_components/notty/translations/nl.json @@ -169,6 +169,30 @@ "name": "Onomkeerbaar wissen bevestigen" } } + }, + "device_time_zone": { + "name": "Tijdzone van apparaat", + "description": "Kies een servercatalogus-ID en een geldige IANA-tijdzone. Controleer de teruggelezen gegevens en de app. Het behouden van lokale niet-storen-tijden vereist een extra schrijfactie.", + "fields": { + "user_device_id": { + "name": "Fysiek apparaat-ID" + }, + "operation": { + "name": "Bewerking" + }, + "catalog_id": { + "name": "Servercatalogus-ID" + }, + "iana_time_zone": { + "name": "IANA-tijdzone" + }, + "preserve_dnd_local_times": { + "name": "Lokale niet-storen-tijden behouden" + }, + "confirm_schedule_change": { + "name": "Schemawijzigingen bevestigen" + } + } } } } diff --git a/custom_components/notty/update.py b/custom_components/notty/update.py index 79e31bf..1b97265 100644 --- a/custom_components/notty/update.py +++ b/custom_components/notty/update.py @@ -2,6 +2,7 @@ from __future__ import annotations +from hashlib import sha256 from typing import override from homeassistant.components.update import UpdateDeviceClass, UpdateEntity, UpdateEntityFeature @@ -9,6 +10,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.storage import Store from custom_components.notty.api import JsonObject, JsonValue, NottyApiError from custom_components.notty.coordinator import NottyCoordinator @@ -85,7 +87,60 @@ def __init__(self, coordinator: NottyCoordinator, device_id: str, device: Device super().__init__(coordinator, device_id, device) self._attr_unique_id = f"{device_id}_firmware" self._requested_version: str | None = None + self._requested_task: JsonValue = None + self._request_baseline: JsonObject = {} self._installing = False + identity = sha256(device_id.encode()).hexdigest() + self._request_store: Store[JsonObject] = Store( + coordinator.hass, 1, f"notty.{coordinator.entry_id}.{identity}.firmware" + ) + + async def async_added_to_hass(self) -> None: + """Recover the pending task without repeating its installation request.""" + saved = await self._request_store.async_load() + if isinstance(saved, dict): + target, task = saved.get("target"), saved.get("task") + if firmware_version(target) is not None and firmware_task_id(task): + self._requested_version = firmware_version(target) + self._requested_task = task + baseline = saved.get("baseline") + self._request_baseline = baseline if isinstance(baseline, dict) else {} + await super().async_added_to_hass() + self._reconcile_request() + + def _saved_request(self) -> JsonObject: + return {"target": self._requested_version, "task": self._requested_task, "baseline": self._request_baseline} + + async def _remember_request(self, target: str, metadata: JsonObject) -> None: + # Persist before the POST: a timeout may still mean the device accepted it. + task = metadata.get("task_id") + baseline = {key: metadata.get(key) for key in ("task_status", "utc_modified")} + await self._request_store.async_save({"target": target, "task": task, "baseline": baseline}) + self._requested_version, self._requested_task, self._request_baseline = target, task, baseline + + def _reconcile_request(self) -> None: + if self._requested_version is None or not self.available: + return + metadata = firmware_data(self.block) + same_task = ( + type(metadata.get("task_id")) is type(self._requested_task) + and metadata.get("task_id") == self._requested_task + and metadata.get("dest_version") == self._requested_version + ) + status = metadata.get("task_status") + changed = any(metadata.get(key) != value for key, value in self._request_baseline.items()) + failed = same_task and changed and isinstance(status, str) and status in {"FAILED", "CANCELED"} + if self.installed_version == self._requested_version or failed: + self._requested_version, self._requested_task = None, None + self._request_baseline = {} + self._request_store.async_delay_save(self._saved_request, 0) + elif same_task and changed and self._request_baseline != {"task_status": None, "utc_modified": None}: + self._request_baseline = {"task_status": None, "utc_modified": None} + self._request_store.async_delay_save(self._saved_request, 0) + + def _handle_coordinator_update(self) -> None: + self._reconcile_request() + super()._handle_coordinator_update() @property def supported_features(self) -> UpdateEntityFeature: @@ -94,7 +149,9 @@ def supported_features(self) -> UpdateEntityFeature: Returns: Full notes, plus install/progress when a current task is available. """ - features = UpdateEntityFeature.RELEASE_NOTES + features = UpdateEntityFeature.RELEASE_NOTES | UpdateEntityFeature.PROGRESS + if self._requested_version is not None or self._installing: + return features metadata = firmware_data(self.block) status = metadata.get("task_status") if ( @@ -123,8 +180,14 @@ def in_progress(self) -> bool | None: return False if isinstance(status, str) and status in FIRMWARE_IDLE_STATUSES else None if self.installed_version == self._requested_version: return False - status = firmware_data(self.block).get("task_status") - return not (isinstance(status, str) and status in {"FAILED", "CANCELED"}) + metadata = firmware_data(self.block) + if ( + type(metadata.get("task_id")) is not type(self._requested_task) + or metadata.get("task_id") != self._requested_task + or metadata.get("dest_version") != self._requested_version + ): + return None + return True async def async_install(self, version: str | None, backup: bool, **_kwargs: object) -> None: # ruff: ignore[boolean-type-hint-positional-argument] -- Home Assistant defines this positional callback signature. """Confirm the current offered task once, then rely on version readback. @@ -132,13 +195,15 @@ async def async_install(self, version: str | None, backup: bool, **_kwargs: obje Raises: HomeAssistantError: If unavailable, already running, backup requested or the API rejects the task. """ - if backup or not self.available or self.in_progress: + if backup or not self.available or self._installing or self._requested_version is not None: msg = "NOTTY firmware installation requires an available idle device and does not support backup" raise HomeAssistantError(msg) self._installing = True self.async_write_ha_state() try: - self._requested_version = await FirmwareApi(self.coordinator.api).install(self.device_id, version) + await FirmwareApi(self.coordinator.api).install( + self.device_id, version, before_confirm=self._remember_request + ) except NottyApiError as exc: raise HomeAssistantError(str(exc)) from exc finally: @@ -207,7 +272,10 @@ def extra_state_attributes(self) -> DeviceData | None: Only the reported task-status string, without task IDs or arbitrary response fields. """ status = firmware_data(self.block).get("task_status") - return {"task_status": status} if isinstance(status, str) else None + attributes: DeviceData = {"requested_version": self._requested_version} + if isinstance(status, str): + attributes["task_status"] = status + return attributes @override def version_is_newer(self, latest_version: str, installed_version: str) -> bool: diff --git a/docs/apk-contracts.md b/docs/apk-contracts.md index 4f6cc00..914533d 100644 --- a/docs/apk-contracts.md +++ b/docs/apk-contracts.md @@ -1,5 +1,7 @@ # APK-backed API contracts +**Live correction (17 October 2026):** The timezone setter assumption below was disproved by live testing. The backend stores the supplied Windows string as an invalid IANA value. Changes now require an explicit valid IANA name and verify both fields. See [remaining-validation.md](remaining-validation.md) for the corrected contract and opt-in DND preservation. + These contracts were traced in NOTTY Smart Pet 1.1.30 (SHA-256 `3b6dc21037f2802e92233ecd9f685e76b03a79afa2d82dd52a5dfcd689a18e6a`). Addresses refer to Blutter's ARM64 annotated assembly. APK inputs and decoded diff --git a/docs/apk-firmware.md b/docs/apk-firmware.md index a09e3ff..4fdff7b 100644 --- a/docs/apk-firmware.md +++ b/docs/apk-firmware.md @@ -74,3 +74,10 @@ discovery, offline devices, lifecycle, bounded notes, exact confirmation payload They do not verify production API payloads or device firmware behavior. No model has yet been validated for this new entity; no firmware update or cloud write was performed during development. #22 remains open for model validation and the separate realtime progress lifecycle. The HA entity tracks only its own requested target in memory until installed-version readback or a reported failure/cancellation; no measured percentage or restart persistence is claimed. + + +## Follow-up: restart persistence and native push + +The previous in-memory-only limitation is superseded by persistent task tracking. +The native event transport was traced to Android JPush, rather than a verified +HA-compatible socket. See [remaining-validation.md](remaining-validation.md). diff --git a/docs/app-validation.md b/docs/app-validation.md index c18fe9a..8e3edac 100644 --- a/docs/app-validation.md +++ b/docs/app-validation.md @@ -254,8 +254,7 @@ restarting the script, pass `--target-version EXACT_PREVIOUS_TARGET` and a new output directory. Only matching installed-version readback confirms completion; a success status alone does not. A failure from a different offered target is not attributed to the selected update. No firmware is installed by this monitor, -no percentage is inferred, and this does not add restart persistence or realtime -firmware-event subscriptions to HA itself. On the owner's current device there +no percentage is inferred. HA now separately persists its own requested task across restarts; the APK's native JPush firmware-event transport is not subscribed to by HA. On the owner's current device there is no offered firmware update, so installation/failure lifecycle validation needs a future offer. @@ -270,3 +269,9 @@ roundtrips do not assert that it occurred. Completed implementation tickets link to [#42](https://github.com/Repsay/notty/issues/42) for their remaining external acceptance checks. #21, #22 and #41 retain the specific timezone, firmware and measured-weight work. Emptying is excluded. + + +The live timezone contract was corrected after this guide was originally written. +Changes now require `iana_time_zone` in addition to the catalog ID. See +[remaining-validation.md](remaining-validation.md) before changing timezones; it +also documents DND preservation and the separate DST observation script. diff --git a/docs/remaining-validation.md b/docs/remaining-validation.md new file mode 100644 index 0000000..e2e9024 --- /dev/null +++ b/docs/remaining-validation.md @@ -0,0 +1,115 @@ +# Remaining litter-box validation + +## Timezones (#21) + +Live testing on 17 October 2026 disproved the APK-only setter assumption. Sending +`W. Europe Standard Time` under `time_zone_iana` stores that Windows name as the +reported IANA value. It is not a valid IANA zone and breaks later clock conversion. +Returning to the original Windows ID alone does not repair it. The backend also +shifts DND readback clocks during timezone changes. + +The change action now requires both the server catalog ID and an explicitly +selected valid IANA name. It sends the IANA name and verifies both reported fields. +No Windows-to-IANA mapping is invented. Existing change automations must add +`iana_time_zone`; incomplete requests fail before writing. + +```yaml +action: notty.device_time_zone +data: + user_device_id: YOUR_PHYSICAL_BOX_ID + operation: change + catalog_id: GMT Standard Time + iana_time_zone: Europe/London + confirm_schedule_change: true + preserve_dnd_local_times: true +``` + +Preserving DND is opt-in. It preserves the original device-local start/end, +enabled state and LED through one additional settings write. A preservation error +is reported as a partial failure after the timezone has changed; it never replays +the timezone change, silently rolls back or rewrites cleaning plans. Inspect the +response and phone app before retrying a partial failure. Unchanged raw clocks +alone do not prove unchanged local behavior. + +The corrected Amsterdam → London → Amsterdam run restored both timezone fields, +all original DND/settings values and every cleaning plan. DST firing remains an +external acceptance check. The offline observer handles gaps, repeated clocks, +non-hour offsets and UTC date boundaries without inventing device DST behavior: + +```sh +uv run python scripts/validate_schedule_observation.py \ + --date 2026-10-25 --local-time 02:30 --time-zone Europe/Amsterdam +``` + +On that date 02:30 has two UTC occurrences. Select `--occurrence 1` or `2` and +supply the independently observed physical start, for example +`--observed-at 2026-10-25T02:30:20+02:00`. No observation means pending, never pass. +A spring-forward gap has no valid occurrence. These calculations do not determine +whether NOTTY will skip, repeat or move a cleaning at that boundary. + +## Firmware (#22) + +HA persists its requested target, exact task identity and pre-confirmation status +before sending the installation POST. Reload/startup resumes tracking without +resending it. A transport timeout remains pending because acknowledgement may +have been lost after the backend accepted the request. A failed storage write +prevents the confirmation POST. + +Installed-version readback establishes completion. A matching task's new failure +or cancellation ends tracking; an old failure from before a retry does not. +Another task's failure cannot complete this request. Changed task identity makes +progress unknown and installation stays blocked while the original request is +unresolved. HA restart/reload recovery has automated coverage. No measured +percentage is fabricated. + +The APK's event path is Android JPush: `XjCore::jpInit` creates JPush at `0xbeb424`, +registers event handlers at `0xbeb478`, obtains a registration ID at `0xbeb4d4`, and +registers the phone token through `/message/update_device_token` at `0xbeb630`. +The event callback dispatches firmware event types 19/20. This is not a verified +HA-compatible WebSocket/MQTT endpoint. The integration keeps HTTP polling; it does +not overwrite a phone's push registration or claim a native JPush subscription. + +A fresh live read still reports no offered update. Installation, offline/reboot +and failure behavior on hardware require a future actual offer. Use +`validate_firmware.py` and `monitor_firmware.py` then. + +## Weight tracking (#41) + +The existing per-cat today/yesterday weight sensors now use fresh profile values +instead of allowing older discovery values to overwrite them. Unknown, absent, +zero, negative, Boolean and nonfinite values remain unknown. Missing daily values +never fall back to an editable profile/reference weight. New optional fields are +discovered after startup and existing entity IDs remain stable. + +APK `AddCatsController` compares tagged integer 1 with the kg label +(`0xbf39e8` → `0xbf3a14`) and integer 2 with lb +(`0xbf3a94` → `0xbf3ac0`). Its save closure `0xc8aecc` reads and returns the same +`weight_unit`. Profile editing now accepts exactly 1/2 rather than the erroneous +0/1. Daily weight sensors normalize recognized units to kilograms so HA statistics +keep a consistent unit. Other/missing unit codes produce unknown readings. + +Each sensor identifies its source field and daily cloud-summary role. It reports +measurement time as null and freshness as not reported: receiving a new poll is +not evidence of a new weigh-in. Standard HA Recorder can retain these reported +summary values going forward; it is not a timestamped per-visit weight log or a +historical import. + +Fresh live reads found weight candidates only in pet profiles, with no measurement +timestamps in the inspected responses. They do not establish an independent +measured source. `probe_weights.py --compare` can compare captures around an +independently observed visit. NOTTY's upstream attribution of a weight to the +wrong cat remains outside this integration; identities are never swapped. + +## Physical and installed-HA checks (#42) + +The owner physically confirmed normal cleaning and leveling after separate live +commands on 17 October 2026. Emptying is excluded and remains blocked in the +validation transport. The automatic delay still reads 0; its app meaning must be +established before testing a change which cannot restore that original value +through the APK-supported 1–15 minute setter. + +Fresh email-code exchange, actual installed-HA UI/reauth observations, selected +memo/reminder semantics and the exact effect of statistics deletion remain +external checks. No history is deleted merely to obtain a test result. Feature +scripts and the evidence audit retain pending/partial status separately from +API acknowledgement and owner observations. diff --git a/docs/validation-coverage.md b/docs/validation-coverage.md index 8ad601b..e89c98d 100644 --- a/docs/validation-coverage.md +++ b/docs/validation-coverage.md @@ -1,5 +1,7 @@ # Remaining-issue coverage +See [remaining-validation.md](remaining-validation.md) for corrected live timezone contracts, persistent firmware tracking, weight source/unit fixes and current external acceptance boundaries. + Every in-scope issue has implementation/contract tests and a dedicated live validation command. Tests do not operate hardware. Command examples and explicit write payloads are in [app-validation.md](app-validation.md). Emptying is blocked. @@ -9,14 +11,14 @@ write payloads are in [app-validation.md](app-validation.md). Emptying is blocke | #11 | Exact integer lock payload; live flag change/restoration confirmed | `validate_lock.py` | Optional physical-button/app observation on other models | | #12 | Shared DND builder; live switch change/restoration preserves raw clocks/LED | `validate_dnd.py` | DST/actual schedule firing belongs to #21 | | #14 | Email-code metadata and migration implemented; authenticated reads work | `validate_login.py` | Fresh code exchange with current metadata; HA expiry/reauth flow | -| #15 | Central APK mappings clean=1, empty=2, level=3 | `validate_cleaning.py` | Observe clean/level effects; empty testing is excluded by owner | +| #15 | Central APK mappings clean=1, empty=2, level=3 | `validate_cleaning.py` | Clean and level physically confirmed by owner on 17 October; empty testing excluded | | #16 | 1–15 minute Auto-only select and guarded action | `validate_settings.py` | Owner device reports 0; determine its meaning before a restorable write test | | #17 | Plan CRUD/toggle fixed for live type 2 and validated with cleanup | `validate_schedules.py` | Actual scheduled physical firing | | #19 | APK enums and guarded mode writes; all three mode readbacks passed with restoration | `validate_settings.py` | Actual scheduled physical firing and broader model behavior | | #20 | Alias entity, stable HA IDs/override tests; live rename/restoration passed | `validate_alias.py` | Broader model acceptance only | | #21 | Catalog/change actions, snapshot drift reporting and DST unit tests | `validate_timezone.py` | Explicit timezone transition and actual firing across date/DST boundaries | -| #22 | Update availability/install and Boolean pending target implemented | `validate_firmware.py`, `monitor_firmware.py` | Future offered update; realtime events and HA restart persistence remain unimplemented | -| #23 | Scoped association actions, preservation tests and a live restored association toggle | `validate_associations.py` | Selected association change/restoration and app readback | +| #22 | Update availability/install and Boolean pending target implemented | `validate_firmware.py`, `monitor_firmware.py` | Future offered update; restart persistence implemented; native JPush is not a verified HA transport; live offer pending | +| #23 | Scoped association actions, preservation tests and a live restored association toggle | `validate_associations.py` | API restoration passed; broader app/HA observations pending | | #24 | Account category switches/actions; live toggle/restoration passed | `validate_notifications.py` | Broader app/model acceptance only | | #25 | Scoped text memo list/detail/create/edit implemented | `validate_memos.py` | Selected text memo lifecycle and app date/reminder semantics | | #26 | Explicit irreversible empty-body statistics-clear action | `validate_statistics.py` | Exact affected counters/history, only when deletion is wanted | @@ -27,8 +29,7 @@ write payloads are in [app-validation.md](app-validation.md). Emptying is blocke HA unit tests cover entity lifecycle, account ownership, request contracts, invalid targets, name overrides, IDs, unknown data and failure recovery. A real HA installation is still needed to observe device/model-specific UI and expired -session reauthentication. Firmware-event support and measured weight/history are -separate development work; monitoring scripts do not imply they are implemented. +session reauthentication. Native push delivery and independently timestamped weigh-in history remain unverified; the integration uses persistent HTTP firmware tracking and clearly labeled cloud daily weight summaries. `validation_status.py` audits script coverage and private report counts without publishing names, weights, account IDs, credentials or capture contents. It keeps diff --git a/pyproject.toml b/pyproject.toml index d92a38c..c44c386 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "notty-home-assistant" -version = "0.4.1" +version = "0.4.2" description = "NOTTY smart litter box integration for Home Assistant" readme = "README.md" requires-python = ">=3.14.2" diff --git a/release-notes/v0.4.2.md b/release-notes/v0.4.2.md new file mode 100644 index 0000000..ffd5dad --- /dev/null +++ b/release-notes/v0.4.2.md @@ -0,0 +1,30 @@ +# NOTTY v0.4.2 + +Fix device timezone changes after live testing showed that the APK's Windows-name +payload corrupts the backend's IANA field and shifts DND clocks. Changes now require +an explicit valid `iana_time_zone`, validate the chosen server catalog ID, and check +both reported encodings. Existing change automations must add the new field. +Optional `preserve_dnd_local_times` keeps the original local interval, switch and LED +with one additional write. Partial failures are reported without replaying requests. +A live Amsterdam/London roundtrip restored all original settings and cleaning plans. + +Persist pending firmware tasks before confirmation so Home Assistant reloads/restarts +and uncertain transport failures do not resend installation requests. Track the exact +task, reject unrelated failures and stale pre-retry failure states, and require +installed-version readback for completion. Tracking remains polling-based: the APK's +native Android JPush channel is not a verified HA-compatible stream. Hardware update +validation still awaits an available firmware offer. + +Correct weight source precedence, kg/lb handling and profile-edit unit validation. +Fresh daily values take precedence over discovery summaries; missing/invalid readings +stay unknown. Daily cloud weight sensors retain stable IDs and use kilograms for HA +statistics. They identify their source and explicitly report unknown measurement time +and freshness. No per-visit weigh-in history or correction of NOTTY's upstream cat +attribution is claimed. + +Add an offline schedule-observation validator which distinguishes DST gaps, repeated +clocks and UTC date boundaries. Live cleaning and leveling were physically confirmed +by the owner. See docs/remaining-validation.md for completed and pending acceptance. +Emptying remains blocked in validation tools; no statistics history is deleted. + +Update through HACS and restart Home Assistant. diff --git a/scripts/app_validation.py b/scripts/app_validation.py index d02229d..7992f4e 100644 --- a/scripts/app_validation.py +++ b/scripts/app_validation.py @@ -68,6 +68,9 @@ PET_FEATURES = {"pets", "associations", "memos"} ACCOUNT_FEATURES = {"login", "notifications"} SOURCE_INFO = "info" +FEATURE_TIMEZONE = "timezone" +UNCHANGED = "unchanged" +DND_LOCAL_MATCH = "local_clocks_match" FIELD_CHECKS = "checks" MISMATCH = "mismatch" PENDING = "pending" @@ -376,7 +379,7 @@ async def execute( } result["write_status"] = "attempted" try: - await app_actions.apply(api, feature, target, operation, changes) + result["operation_result"] = await app_actions.apply(api, feature, target, operation, changes) result["write_status"] = "acknowledged_not_physically_verified" data, after_errors = await read_until_applied(api, feature, target, request, options) result.update({"data": data, "errors": after_errors, "captured_at": datetime.now(UTC).isoformat()}) @@ -464,6 +467,7 @@ def main(feature: str) -> int: status = comparison.get("status") if isinstance(comparison, dict) else None if ( result["failed_reads"] + or result["api_write_readback"] == MISMATCH or status == MISMATCH or result["restore_status"] not in {"not_requested", "readback_matches_baseline"} ): @@ -522,6 +526,8 @@ def write_readback(feature: str, capture: JsonObject, data: JsonObject) -> str: operation, changes = request.get("operation"), request.get("changes") if not isinstance(operation, str) or not isinstance(changes, dict): return "unreadable_request" + if feature == FEATURE_TIMEZONE: + return timezone_write_readback(capture, data, changes) try: actual = app_actions.restore_request(feature, operation, changes, data) except NottyApiError: @@ -529,6 +535,32 @@ def write_readback(feature: str, capture: JsonObject, data: JsonObject) -> str: return "match" if actual == (operation, changes) else MISMATCH +def timezone_write_readback(capture: JsonObject, data: JsonObject, changes: JsonObject) -> str: + """Check both timezone encodings and retain partial DND-preservation failures. + + Returns: + Match only for the requested zone and any explicitly requested preservation. + """ + info = data.get("info") + if not isinstance(info, dict): + return MISMATCH + if info.get("time_zone_iana") != changes.get("iana_time_zone") or info.get("time_zone_windows") != changes.get( + "catalog_id" + ): + return MISMATCH + outcome = capture.get("operation_result") + if not isinstance(outcome, dict) or outcome.get("status") not in {"unchanged", "write_acknowledged_verify_in_app"}: + return MISMATCH + if changes.get("preserve_dnd_local_times") is True and outcome.get("status") != UNCHANGED: + after = outcome.get("after") + settings = after.get("settings") if isinstance(after, dict) else None + if outcome.get("dnd_preservation") != DND_LOCAL_MATCH or not isinstance(settings, dict): + return MISMATCH + if any(info.get(key) != settings.get(key) for key in ("switch_dnd", "dnd_begin_time", "dnd_end_time", "led")): + return MISMATCH + return "match" + + async def read_until_applied( api: app_actions.ValidationApi, feature: str, target: app_actions.Target, request: JsonObject, options: Options ) -> tuple[JsonObject, list[JsonValue]]: diff --git a/scripts/validate_schedule_observation.py b/scripts/validate_schedule_observation.py new file mode 100755 index 0000000..0012b38 --- /dev/null +++ b/scripts/validate_schedule_observation.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python3 +"""Compare an observed start with a selected device-local schedule occurrence. + +Offline only: no device commands or timezone changes. This checks owner-supplied +observations, not whether the box will follow a particular DST policy. Ambiguous +and nonexistent local times are reported explicitly instead of silently shifted. +""" + +from __future__ import annotations + +import argparse +from dataclasses import dataclass +from datetime import UTC, date, datetime, time +import json +import math +from pathlib import Path +import sys +from typing import cast +from zoneinfo import ZoneInfo + +if not __package__: + sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from custom_components.notty.api import JsonObject, JsonValue +from scripts.console import console +from scripts.probe_datapoints import write_json + +MAX_TOLERANCE_SECONDS = 300 + + +def occurrences(day: date, clock: time, zone: str) -> list[datetime]: + """Resolve valid UTC instants, rejecting the zoneinfo normalization of DST gaps. + + Returns: + Zero, one or two chronologically ordered UTC instants. + + Raises: + ValueError: If the supplied wall clock includes a timezone. + """ + if clock.tzinfo is not None: + msg = "The scheduled clock must be a local time without an offset" + raise ValueError(msg) + wall = datetime.combine(day, clock) + selected_zone = ZoneInfo(zone) + candidates: set[datetime] = set() + for fold in (0, 1): + instant = wall.replace(tzinfo=selected_zone, fold=fold).astimezone(UTC) + if instant.astimezone(selected_zone).replace(tzinfo=None) == wall: + candidates.add(instant) + return sorted(candidates) + + +@dataclass(frozen=True) +class Schedule: + """One device-local calendar occurrence, without assuming recurrence.""" + + day: date + clock: time + zone: str + + +def report( + schedule: Schedule, + *, + observed_at: datetime | None = None, + occurrence: int | None = None, + tolerance_seconds: float = 60, +) -> JsonObject: + """Keep calendar analysis and supplied physical observation checks distinct. + + Returns: + Expected UTC candidates and an explicit observation verdict. + + Raises: + ValueError: If a timestamp is naive, tolerance is unbounded or an occurrence is invalid. + """ + if not math.isfinite(tolerance_seconds) or not 0 <= tolerance_seconds <= MAX_TOLERANCE_SECONDS: + msg = "Tolerance must be finite and between 0 and 300 seconds" + raise ValueError(msg) + candidates = occurrences(schedule.day, schedule.clock, schedule.zone) + if occurrence is not None and (type(occurrence) is not int or not 1 <= occurrence <= len(candidates)): + msg = "Select an existing occurrence, numbered 1 or 2 in UTC order" + raise ValueError(msg) + if observed_at is not None and (observed_at.tzinfo is None or observed_at.utcoffset() is None): + msg = "Observed timestamps must include their actual UTC offset" + raise ValueError(msg) + status = "pending_physical_observation" + delta: float | None = None + if not candidates: + status = "nonexistent_local_time_device_policy_unverified" + elif len(candidates) > 1 and occurrence is None: + status = "ambiguous_local_time_choose_occurrence" + elif observed_at is not None: + expected = candidates[(occurrence or 1) - 1] + delta = (observed_at.astimezone(UTC) - expected).total_seconds() + status = "supplied_observation_matches" if abs(delta) <= tolerance_seconds else "supplied_observation_mismatch" + instants: list[JsonValue] = [instant.isoformat() for instant in candidates] + return { + "feature": "schedule_observation", + "date": schedule.day.isoformat(), + "local_time": schedule.clock.isoformat(), + "time_zone": schedule.zone, + "expected_utc_occurrences": instants, + "selected_occurrence": occurrence, + "observed_at": observed_at.isoformat() if observed_at is not None else None, + "difference_seconds": delta, + "status": status, + "limitations": "Uses the supplied schedule, date, zone and observed start. Does not establish recurrence, device DST policy, physical completion or official-app agreement. No API requests are made.", + } + + +@dataclass +class Options: + """Explicit offline schedule and independent observation inputs.""" + + date: str + local_time: str + time_zone: str + observed_at: str | None = None + occurrence: int | None = None + tolerance_seconds: float = 60 + output: Path | None = None + + +def run(options: Options) -> JsonObject: + """Validate all inputs and optionally save an offline report. + + Returns: + Expected instants and the observation verdict. + + Raises: + ValueError: If an output already exists or date/clock inputs are invalid. + """ + if options.output and (options.output.exists() or options.output.is_symlink()): + msg = "Output must be a new file" + raise ValueError(msg) + result = report( + Schedule(date.fromisoformat(options.date), time.fromisoformat(options.local_time), options.time_zone), + observed_at=datetime.fromisoformat(options.observed_at) if options.observed_at else None, + occurrence=options.occurrence, + tolerance_seconds=options.tolerance_seconds, + ) + if options.output: + write_json(options.output, result) + return result + + +def main() -> int: + """Resolve one calendar occurrence without changing a device setting. + + Returns: + Zero for a supplied matching observation, one for mismatch, two for invalid inputs, three for pending/ambiguous. + """ + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--date", required=True, help="Device-local calendar date, YYYY-MM-DD") + parser.add_argument("--local-time", required=True, help="Scheduled device-local clock, HH:MM") + parser.add_argument("--time-zone", required=True, help="IANA zone read from the device, e.g. Europe/Amsterdam") + parser.add_argument( + "--observed-at", help="Independently observed physical start, ISO timestamp including UTC offset" + ) + parser.add_argument( + "--occurrence", type=int, choices=(1, 2), help="Select the first or second occurrence on a DST fold" + ) + parser.add_argument("--tolerance-seconds", type=float, default=60) + parser.add_argument("--output", type=Path) + options = cast("Options", parser.parse_args()) + try: + result = run(options) + console(json.dumps(result, indent=2, allow_nan=False)) + except OSError, ValueError, KeyError: + console( + "Invalid schedule observation; check the date, clock, IANA zone, UTC offset and output path.", + file=sys.stderr, + ) + return 2 + return {"supplied_observation_matches": 0, "supplied_observation_mismatch": 1}.get(str(result["status"]), 3) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/weight_report.py b/scripts/weight_report.py index 2fbb66f..a98257b 100644 --- a/scripts/weight_report.py +++ b/scripts/weight_report.py @@ -49,6 +49,8 @@ } PROFILE = "profile" FIELD_WEIGHT = "weight" +FIELD_WEIGHT_UNIT = "weight_unit" +APK_WEIGHT_UNITS = {1: "kg", 2: "lb"} MAX_FINDINGS = 500 MAX_DEPTH = 16 CAPTURE_VERSION = 1 @@ -84,6 +86,9 @@ def unit_evidence(row: JsonObject) -> JsonObject: if isinstance(value, str) and value.strip().lower() in {"kg", "lb", "lbs", "g"}: return {"field": key, "reported": value.strip().lower(), "status": "explicit_text"} if type(value) is int or (isinstance(value, str) and value.isascii() and value.isdecimal()): + code = int(value) + if key == FIELD_WEIGHT_UNIT and code in APK_WEIGHT_UNITS: + return {"field": key, "reported": value, "unit": APK_WEIGHT_UNITS[code], "status": "apk_enum"} return {"field": key, "reported": value, "status": "unverified_enum"} return {"status": "missing_or_unknown"} @@ -260,7 +265,7 @@ def report(capture: JsonObject, *, show_values: bool = False, before: JsonObject "limitations": [ "All device/pet weight fields are candidates until compared with the official app after a normal visit.", "Profile weight is an editable setting, not evidence of a litter-box measurement.", - "Numeric unit codes are not converted; verify the enum against APK and app settings.", + "Profile weight_unit 1=kg and 2=lb follows the APK; other numeric unit fields remain unverified.", "Timestamps are reported as supplied; their timezone and meaning are unverified.", "Historical response rows are not imported into Home Assistant history.", ], diff --git a/tests/test_app_validation.py b/tests/test_app_validation.py index 7f92aaa..f39ceb6 100644 --- a/tests/test_app_validation.py +++ b/tests/test_app_validation.py @@ -12,6 +12,7 @@ from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError from scripts import app_actions, app_validation +from scripts.app_validation import timezone_write_readback from scripts.probe_datapoints import write_json EXPECTED_MATCH = "matches_supplied_phone_app_values" @@ -193,3 +194,19 @@ async def test_child_lock_rejects_non_app_switch_encodings(switch: JsonValue) -> with pytest.raises(NottyApiError, match="integer switch"): await api.litter_action("123", "set_key", {"switch": switch}) api.request.assert_not_awaited() + + +@pytest.mark.parametrize("preservation", ["local_clock_mismatch", "not_requested"]) +def test_timezone_preservation_failure_cannot_pass(preservation: str) -> None: + """A valid timezone does not hide a failed requested DND preservation.""" + changes = {"catalog_id": "GMT Standard Time", "iana_time_zone": "Europe/London", "preserve_dnd_local_times": True} + capture = { + "operation_result": { + "status": "write_acknowledged_verify_in_app", + "dnd_preservation": preservation, + "after": {"settings": {}}, + } + } + data = {"info": {"time_zone_windows": "GMT Standard Time", "time_zone_iana": "Europe/London"}} + expected = "mismatch" + assert timezone_write_readback(capture, data, changes) == expected diff --git a/tests/test_device_timezone.py b/tests/test_device_timezone.py index ac84613..59f8ccd 100644 --- a/tests/test_device_timezone.py +++ b/tests/test_device_timezone.py @@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMock +from freezegun.api import FrozenDateTimeFactory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError import pytest @@ -26,7 +27,7 @@ {"id": WINDOWS_ID, "display_name": "(UTC+01:00) Amsterdam, Berlin", "offset": "01:00:00"}, {"id": "UTC", "display_name": "(UTC) Coordinated Universal Time", "offset": "00:00:00"}, ] -FIELDS: JsonObject = {"catalog_id": WINDOWS_ID, "confirm_schedule_change": True} +FIELDS: JsonObject = {"catalog_id": WINDOWS_ID, "iana_time_zone": LOCAL_ZONE, "confirm_schedule_change": True} INFO: JsonObject = { "user_device_id": 123, "time_zone_iana": LOCAL_ZONE, @@ -60,30 +61,33 @@ def test_catalog_string_fields(field: str, value: JsonValue) -> None: timezone_catalog([row]) -def test_exact_windows_id_is_serialized_in_misnamed_iana_field() -> None: - """The view passes catalog[id], not an IANA mapping or fixed offset.""" +def test_iana_name_is_serialized_and_windows_id_is_only_catalog_validation() -> None: + """Live testing requires valid IANA data even though the APK sends a Windows ID.""" rows = timezone_catalog(CATALOG) - assert timezone_payload(BOX_ID, WINDOWS_ID, rows) == {"user_device_id": 123, "time_zone_iana": WINDOWS_ID} + assert timezone_payload(BOX_ID, WINDOWS_ID, rows, iana_time_zone=LOCAL_ZONE) == { + "user_device_id": 123, + "time_zone_iana": LOCAL_ZONE, + } for invalid in (LOCAL_ZONE, "01:00:00", "1", "unknown", f" {WINDOWS_ID}"): with pytest.raises(NottyApiError): - timezone_payload(BOX_ID, invalid, rows) + timezone_payload(BOX_ID, invalid, rows, iana_time_zone=LOCAL_ZONE) @pytest.mark.parametrize("device_id", ["0", "-1", "box-1", "\uff11\uff12\uff13", "123/other", ""]) def test_invalid_physical_ids(device_id: str) -> None: """Never serialize pet IDs or URL/path fragments as physical IDs.""" with pytest.raises(NottyApiError): - timezone_payload(device_id, WINDOWS_ID, timezone_catalog(CATALOG)) + timezone_payload(device_id, WINDOWS_ID, timezone_catalog(CATALOG), iana_time_zone=LOCAL_ZONE) async def test_fresh_catalog_and_exact_api_payload() -> None: """Every write checks current membership and makes a single exact POST.""" api = NottyApi(MagicMock()) api.request = AsyncMock(side_effect=[CATALOG, {}]) - await api.change_time_zone(BOX_ID, WINDOWS_ID) + await api.change_time_zone(BOX_ID, WINDOWS_ID, iana_time_zone=LOCAL_ZONE) assert api.request.await_args_list[0].args == ("GET", "/entity/get_time_zones") api.request.assert_awaited_with( - "POST", "/device/change_time_zone", data={"user_device_id": 123, "time_zone_iana": WINDOWS_ID} + "POST", "/device/change_time_zone", data={"user_device_id": 123, "time_zone_iana": LOCAL_ZONE} ) assert api.request.await_count == TWO_READS @@ -93,7 +97,7 @@ async def test_unsupported_choice_never_writes() -> None: api = NottyApi(MagicMock()) api.request = AsyncMock(return_value=CATALOG) with pytest.raises(NottyApiError): - await api.change_time_zone(BOX_ID, LOCAL_ZONE) + await api.change_time_zone(BOX_ID, LOCAL_ZONE, iana_time_zone=LOCAL_ZONE) api.request.assert_awaited_once_with("GET", "/entity/get_time_zones") @@ -116,12 +120,15 @@ def test_changes_require_explicit_schedule_acknowledgement(fields: JsonObject) - async def test_changed_settings_are_reported_without_automatic_restore() -> None: """One write followed by readback exposes drift without a second write.""" api = MagicMock(spec=NottyApi) - api.litter_info.side_effect = [INFO, {**INFO, "time_zone_iana": LOCAL_ZONE, "dnd_begin_time": "23:00"}] + api.litter_info.side_effect = [ + INFO, + {**INFO, "time_zone_windows": WINDOWS_ID, "time_zone_iana": LOCAL_ZONE, "dnd_begin_time": "23:00"}, + ] api.request.return_value = [{"plan_id": 1, "time": "06:30", "open": True}] result = await change_with_readback(api, BOX_ID, FIELDS) assert result["status"] == ACKNOWLEDGED assert result["changed_schedule_fields"] == ["settings"] - api.change_time_zone.assert_awaited_once_with(BOX_ID, WINDOWS_ID) + api.change_time_zone.assert_awaited_once_with(BOX_ID, WINDOWS_ID, iana_time_zone=LOCAL_ZONE) assert api.request.await_count == TWO_READS @@ -203,3 +210,93 @@ async def test_ha_rejects_unknown_device_and_missing_confirmation(hass: HomeAssi with pytest.raises(HomeAssistantError): await hass.services.async_call("notty", SERVICE, data, blocking=True) runtime_api.change_time_zone.assert_not_awaited() + + +@pytest.mark.parametrize("zone", [WINDOWS_ID, "", "Bad/Unknown", "../UTC"]) +def test_windows_names_and_invalid_iana_names_never_write(zone: str) -> None: + """The accepted catalog ID must never be copied into an invalid IANA field.""" + with pytest.raises(NottyApiError, match="valid IANA"): + timezone_payload(BOX_ID, WINDOWS_ID, timezone_catalog(CATALOG), iana_time_zone=zone) + + +async def test_matching_windows_name_does_not_hide_corrupted_iana() -> None: + """Repair is still needed when the backend previously stored a Windows name as IANA.""" + api = MagicMock(spec=NottyApi) + api.litter_info.side_effect = [ + {**INFO, "time_zone_windows": WINDOWS_ID, "time_zone_iana": WINDOWS_ID}, + {**INFO, "time_zone_windows": WINDOWS_ID}, + ] + api.request.return_value = [] + result = await change_with_readback(api, BOX_ID, FIELDS) + assert result["status"] == ACKNOWLEDGED + api.change_time_zone.assert_awaited_once_with(BOX_ID, WINDOWS_ID, iana_time_zone=LOCAL_ZONE) + + +async def test_iana_readback_mismatch_cannot_be_reported_as_success() -> None: + """A backend acknowledgement with invalid timezone data is a failed readback.""" + api = MagicMock(spec=NottyApi) + api.litter_info.side_effect = [INFO, {**INFO, "time_zone_windows": WINDOWS_ID, "time_zone_iana": WINDOWS_ID}] + api.request.return_value = [] + result = await change_with_readback(api, BOX_ID, FIELDS) + expected = "timezone_readback_mismatch" + assert result["status"] == expected + api.litter_action.assert_not_awaited() + + +@pytest.mark.parametrize( + ("reference", "expected_begin"), [("2026-07-17T12:00:00+00:00", "13:00"), ("2026-01-17T12:00:00+00:00", "12:00")] +) +async def test_opt_in_dnd_preservation_keeps_local_clocks( + freezer: FrozenDateTimeFactory, reference: str, expected_begin: str +) -> None: + """Preservation uses device-local clocks while raw Shanghai readback offsets change.""" + freezer.move_to(reference) + api = MagicMock(spec=NottyApi) + original = {**INFO, "time_zone_windows": WINDOWS_ID, "dnd_begin_time": "19:00", "dnd_end_time": "10:00", "led": 0} + changed = {**original, "time_zone_windows": "GMT Standard Time", "time_zone_iana": "Europe/London"} + final = {**changed, "dnd_begin_time": "20:00", "dnd_end_time": "11:00"} + api.litter_info.side_effect = [original, changed, final] + api.request.return_value = [] + result = await change_with_readback( + api, + BOX_ID, + { + "catalog_id": "GMT Standard Time", + "iana_time_zone": "Europe/London", + "confirm_schedule_change": True, + "preserve_dnd_local_times": True, + }, + ) + expected = "local_clocks_match" + assert result["dnd_preservation"] == expected + from_freezer = api.litter_action.await_args.args[2] + assert from_freezer["dnd_begin_time"] == expected_begin + assert from_freezer["switch"] == original["switch_dnd"] + assert from_freezer["led"] == original["led"] + api.litter_action.assert_awaited_once() + + +async def test_preservation_preflight_blocks_unknown_led_before_timezone_write() -> None: + """Never change timezone when the additional requested DND write cannot be built.""" + api = MagicMock(spec=NottyApi) + api.litter_info.return_value = INFO + api.request.return_value = [] + with pytest.raises(NottyApiError, match="LED"): + await change_with_readback(api, BOX_ID, {**FIELDS, "preserve_dnd_local_times": True}) + api.change_time_zone.assert_not_awaited() + api.litter_action.assert_not_awaited() + + +async def test_dnd_write_failure_reports_partial_timezone_change() -> None: + """A second-write failure must not replay or silently restore the accepted timezone.""" + api = MagicMock(spec=NottyApi) + original = {**INFO, "led": 0} + after = {**original, "time_zone_windows": WINDOWS_ID} + api.litter_info.side_effect = [original, after] + api.request.return_value = [] + api.litter_action.side_effect = NottyApiError("synthetic DND failure") + result = await change_with_readback(api, BOX_ID, {**FIELDS, "preserve_dnd_local_times": True}) + expected = "timezone_changed_dnd_preservation_failed" + assert result["status"] == expected + api.change_time_zone.assert_awaited_once() + api.litter_action.assert_awaited_once() diff --git a/tests/test_pet_features.py b/tests/test_pet_features.py index 2e55bd2..66edbc1 100644 --- a/tests/test_pet_features.py +++ b/tests/test_pet_features.py @@ -122,6 +122,9 @@ def test_profile_payload_preserves_only_bound_devices_and_original_values() -> N {"pet_id": 8}, {"weight": float("nan")}, {"weight": 0}, + {"weight_unit": 0}, + {"weight_unit": True}, + {"weight_unit": 3}, {"pet_devices": None}, {"pet_devices": [{"user_device_id": 123}]}, ], @@ -305,3 +308,11 @@ async def test_shared_pet_cannot_create_a_memo() -> None: with pytest.raises(NottyApiError, match="owner"): await MemoApi(api).save(PET_ID, {"title": "Visit", "content": "Visit", "date": MEMO["date"]}) assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +def test_profile_edit_preserves_pound_unit() -> None: + """The APK labels unit 2 as lb and sends the same enum on save.""" + profile = {**PROFILE, "weight_unit": 2, "weight": 10.0} + result = profile_payload(PET_ID, profile, {"name": NEW_NAME}) + assert result["weight_unit"] == profile["weight_unit"] + assert result["weight"] == profile["weight"] diff --git a/tests/test_remaining_firmware.py b/tests/test_remaining_firmware.py new file mode 100644 index 0000000..3e8b479 --- /dev/null +++ b/tests/test_remaining_firmware.py @@ -0,0 +1,112 @@ +"""Firmware requests survive reloads without replay or unrelated-task completion.""" + +from unittest.mock import MagicMock + +from homeassistant.components.update import UpdateEntityFeature +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +import pytest + +from custom_components.notty.api import NottyApiError +from tests.test_device_features import UPGRADE +from tests.test_feature_ui import configure +from tests.test_lifecycle import setup + +ENTITY = "update.test_box_firmware" +METHOD_POST = "POST" +CONFIRM = "/device/confirm_upgrade" + + +def confirmations(api: MagicMock) -> int: + """Count only actual firmware confirmations. + + Returns: + The number of firmware writes. + """ + return sum(call.args[:2] == (METHOD_POST, CONFIRM) for call in api.request.await_args_list) + + +async def test_pending_install_survives_reload_without_replay(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Reloading uses persisted state, rejects duplicate installs and awaits version readback.""" + configure(runtime_api) + runtime_api.litter_related_info.return_value["upgrade"] = dict(UPGRADE) + entry = await setup(hass) + await hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True) + assert confirmations(runtime_api) == 1 + await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + state = hass.states.get(ENTITY) + assert state.attributes["in_progress"] is True + assert state.attributes["supported_features"] & UpdateEntityFeature.PROGRESS + assert not state.attributes["supported_features"] & UpdateEntityFeature.INSTALL + with pytest.raises(HomeAssistantError): + await hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True) + assert confirmations(runtime_api) == 1 + runtime_api.litter_related_info.return_value["upgrade"] = { + **UPGRADE, + "src_version": UPGRADE["dest_version"], + "dest_version": "", + } + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(ENTITY).attributes["in_progress"] is False + await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert hass.states.get(ENTITY).attributes["in_progress"] is False + assert confirmations(runtime_api) == 1 + + +async def test_other_task_failure_does_not_finish_pending_install(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """A changed task identity makes progress unknown, never claims failure or retries.""" + configure(runtime_api) + runtime_api.litter_related_info.return_value["upgrade"] = dict(UPGRADE) + entry = await setup(hass) + await hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True) + runtime_api.litter_related_info.return_value["upgrade"] = { + **UPGRADE, + "task_id": "other-task", + "task_status": "FAILED", + } + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + state = hass.states.get(ENTITY) + assert state.attributes["in_progress"] is None + assert not state.attributes["supported_features"] & UpdateEntityFeature.INSTALL + assert confirmations(runtime_api) == 1 + + +async def test_timed_out_confirmation_remains_pending_after_reload(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """An uncertain POST cannot be replayed merely because the caller saw an error.""" + configure(runtime_api) + original = runtime_api.request.side_effect + + def request(method: str, path: str, **kwargs: object) -> object: + if method == METHOD_POST and path == CONFIRM: + msg = "synthetic timeout" + raise NottyApiError(msg) + return original(method, path, **kwargs) + + runtime_api.request.side_effect = request + runtime_api.litter_related_info.return_value["upgrade"] = dict(UPGRADE) + entry = await setup(hass) + with pytest.raises(HomeAssistantError, match="synthetic timeout"): + await hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True) + await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert hass.states.get(ENTITY).attributes["in_progress"] is True + assert confirmations(runtime_api) == 1 + + +async def test_stale_failure_needs_a_new_task_observation(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Retrying an eligible failed task does not immediately fail from its old cached status.""" + configure(runtime_api) + runtime_api.litter_related_info.return_value["upgrade"] = {**UPGRADE, "task_status": "FAILED"} + runtime_api.request.side_effect = lambda *_args, **_kwargs: {**UPGRADE, "task_status": "FAILED"} + entry = await setup(hass) + await hass.services.async_call("update", "install", {"entity_id": ENTITY}, blocking=True) + assert hass.states.get(ENTITY).attributes["in_progress"] is True + for status in ("IN_PROGRESS", "FAILED"): + runtime_api.litter_related_info.return_value["upgrade"] = {**UPGRADE, "task_status": status} + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(ENTITY).attributes["in_progress"] is False diff --git a/tests/test_schedule_observation.py b/tests/test_schedule_observation.py new file mode 100644 index 0000000..81e2cfc --- /dev/null +++ b/tests/test_schedule_observation.py @@ -0,0 +1,89 @@ +"""DST boundary observations are checked as UTC instants without assuming device policy.""" + +from datetime import UTC, date, datetime, time +from pathlib import Path + +import pytest + +from scripts.validate_schedule_observation import Options, Schedule, occurrences, report, run + +ZONE = "Europe/Amsterdam" +MATCH = "supplied_observation_matches" +MISMATCH = "supplied_observation_mismatch" +AMBIGUOUS = "ambiguous_local_time_choose_occurrence" +GAP = "nonexistent_local_time_device_policy_unverified" +PENDING = "pending_physical_observation" +PRIVATE_MODE = 0o600 + + +@pytest.mark.parametrize( + ("day", "expected"), + [ + (date(2026, 3, 29), []), + (date(2026, 10, 25), ["2026-10-25T00:30:00+00:00", "2026-10-25T01:30:00+00:00"]), + (date(2026, 10, 24), ["2026-10-24T00:30:00+00:00"]), + ], +) +def test_european_gap_and_fold(day: date, expected: list[str]) -> None: + """Nonexistent clocks have no candidate; repeated clocks have two distinct instants.""" + assert [instant.isoformat() for instant in occurrences(day, time(2, 30), ZONE)] == expected + + +def test_crossing_midnight_in_a_non_hour_offset_zone() -> None: + """A device-local date may correspond to the preceding UTC date.""" + assert occurrences(date(2026, 10, 17), time(0, 15), "Asia/Kathmandu") == [ + datetime(2026, 10, 16, 18, 30, tzinfo=UTC) + ] + + +@pytest.mark.parametrize( + ("observed", "selection", "expected"), + [ + (None, None, AMBIGUOUS), + ("2026-10-25T02:30:00+02:00", None, AMBIGUOUS), + ("2026-10-25T02:30:00+02:00", 1, MATCH), + ("2026-10-25T02:30:00+01:00", 2, MATCH), + ("2026-10-25T02:30:00+01:00", 1, MISMATCH), + ], +) +def test_observation_selects_explicit_fold(observed: str | None, selection: int | None, expected: str) -> None: + """The same wall clock with another UTC offset is a different scheduled occurrence.""" + result = report( + Schedule(date(2026, 10, 25), time(2, 30), ZONE), + observed_at=datetime.fromisoformat(observed) if observed else None, + occurrence=selection, + ) + assert result["status"] == expected + + +def test_gap_and_unobserved_schedule_never_pass() -> None: + """Computing a calendar candidate is not physical validation.""" + assert report(Schedule(date(2026, 3, 29), time(2, 30), ZONE))["status"] == GAP + assert report(Schedule(date(2026, 10, 17), time(8), ZONE))["status"] == PENDING + + +@pytest.mark.parametrize("tolerance", [-1, 301, float("nan"), float("inf")]) +def test_unbounded_tolerance_rejected(tolerance: float) -> None: + """A broad tolerance must not hide a timezone or date error.""" + with pytest.raises(ValueError, match="Tolerance"): + report(Schedule(date(2026, 10, 17), time(8), ZONE), tolerance_seconds=tolerance) + + +def test_naive_observations_and_nonexistent_selection_rejected() -> None: + """Never invent an observation's offset or a second occurrence on an ordinary day.""" + schedule = Schedule(date(2026, 10, 17), time(8), ZONE) + with pytest.raises(ValueError, match="UTC offset"): + report(schedule, observed_at=datetime(2026, 10, 17, 8, tzinfo=UTC).replace(tzinfo=None)) + with pytest.raises(ValueError, match="existing occurrence"): + report(schedule, occurrence=2) + with pytest.raises(ValueError, match="without an offset"): + occurrences(schedule.day, time(8, tzinfo=UTC), ZONE) + + +def test_output_is_private_and_cannot_overwrite_evidence(tmp_path: Path) -> None: + """Saved observation evidence is local and cannot replace an earlier report.""" + options = Options("2026-10-17", "08:00", ZONE, output=tmp_path / "observed.private.json") + assert run(options)["status"] == PENDING + assert options.output.stat().st_mode & 0o777 == PRIVATE_MODE + with pytest.raises(ValueError, match="new file"): + run(options) diff --git a/tests/test_weight_probe.py b/tests/test_weight_probe.py index 4201932..dafb5d1 100644 --- a/tests/test_weight_probe.py +++ b/tests/test_weight_probe.py @@ -13,7 +13,7 @@ from scripts import probe_datapoints, probe_weights, weight_report PRIVATE_MODE = 0o600 -EXPECTED_ENUM = "unverified_enum" +EXPECTED_ENUM = "apk_enum" EXPECTED_SETTING = "profile_setting" GET = "GET" FIELD_VALUE = "reported_value" @@ -21,6 +21,7 @@ EXPECTED_DETAIL_PATH = "/device/litter_box/pet_data_detail/123?pet_id=7" FORBIDDEN_PATH_PARTS = ("pet_id=8", "pet_id=99", "/456") PRIVATE_MARKER = "secret-token" +ANALYSIS_TIME = "analysed_at" def capture() -> JsonObject: @@ -54,7 +55,8 @@ def capture() -> JsonObject: def test_report_separates_profile_and_candidate_without_leaking_values() -> None: """Default reports keep personal keys, names, measurements and IDs private.""" result = weight_report.report(capture()) - text = json.dumps(result) + # The analysis clock is public metadata and may coincide with a fixture date. + text = json.dumps({key: value for key, value in result.items() if key != ANALYSIS_TIME}) for secret in ("Secret cat", "private-person-key", "4.8", "4.1", "2026-10-17", "08:00", "pet:7", "box:123"): assert secret not in text sources = result["sources"] diff --git a/tests/test_weight_sensors.py b/tests/test_weight_sensors.py new file mode 100644 index 0000000..50dd5cd --- /dev/null +++ b/tests/test_weight_sensors.py @@ -0,0 +1,77 @@ +"""Cloud daily weight summaries preserve units and never invent a weigh-in timestamp.""" + +from unittest.mock import MagicMock + +from homeassistant.core import HomeAssistant +import pytest + +from tests.test_feature_ui import configure +from tests.test_lifecycle import setup + +ENTITY = "sensor.milo_today_weight" +UNKNOWN = "unknown" +MEASUREMENT = "measurement" +FIELD_TODAY = "today_weight" +UNIT_KG = "kg" +FRESHNESS = "not_reported" + + +@pytest.mark.parametrize( + ("unit", "value", "expected"), + [ + (1, 4.2, 4.2), + ("1", "4.2", 4.2), + (2, 10, 4.5359237), + ("2", "10", 4.5359237), + (None, 4.2, None), + (99, 4.2, None), + (True, 4.2, None), + (1.0, 4.2, None), + (1, False, None), + (1, 0, None), + (1, -1, None), + (1, "nan", None), + (1, "inf", None), + (1, 10**400, None), + (1, None, None), + ], +) +async def test_weight_units_and_unknown_values( + hass: HomeAssistant, runtime_api: MagicMock, unit: object, value: object, expected: float | None +) -> None: + """Keep one statistics unit while rejecting invalid values or unknown unit codes.""" + profile, _ = configure(runtime_api) + profile.update({"today_weight": value, "weight_unit": unit}) + await setup(hass) + state = hass.states.get(ENTITY) + assert state is not None + if expected is None: + assert state.state == UNKNOWN + else: + assert float(state.state) == pytest.approx(expected) + assert state.attributes["unit_of_measurement"] == UNIT_KG + assert state.attributes["state_class"] == MEASUREMENT + assert state.attributes["measurement_time"] is None + assert state.attributes["source_field"] == FIELD_TODAY + assert state.attributes["measurement_freshness"] == FRESHNESS + runtime_api.save_pet_weight.assert_not_awaited() + + +async def test_late_weight_discovery_missing_data_and_unit_change(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Discover optional weights once and do not reuse yesterday/profile values on data loss.""" + profile, _ = configure(runtime_api) + entry = await setup(hass) + assert hass.states.get(ENTITY) is None + profile.update({"today_weight": 10, "yesterday_weight": 11, "weight_unit": 2}) + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert float(hass.states.get(ENTITY).state) == pytest.approx(4.5359237) + profile.pop("today_weight") + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(ENTITY).state == UNKNOWN + profile.update({"today_weight": 4.2, "weight_unit": 1}) + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert float(hass.states.get(ENTITY).state) == pytest.approx(4.2) + assert len([state for state in hass.states.async_all() if state.entity_id == ENTITY]) == 1 diff --git a/uv.lock b/uv.lock index fab285b..ef7e953 100644 --- a/uv.lock +++ b/uv.lock @@ -1916,7 +1916,7 @@ wheels = [ [[package]] name = "notty-home-assistant" -version = "0.4.1" +version = "0.4.2" source = { virtual = "." } dependencies = [ { name = "aiohttp" },