diff --git a/.github/workflows/validate.yml b/.github/workflows/validate.yml index 0b632e0..7b7b823 100644 --- a/.github/workflows/validate.yml +++ b/.github/workflows/validate.yml @@ -21,6 +21,19 @@ jobs: - run: uv run ruff format --check . - run: uv run mypy . - run: uv run pytest --cov=custom_components.notty --cov=scripts --cov-report=term-missing + minimum-home-assistant: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v6 + - run: uv python install 3.14 + - run: uv venv --python 3.14 + # The nearest historical test harness pins 2026.3.1; explicitly override + # only HA to exercise our exact declared minimum, including its dependencies. + - run: | + echo 'homeassistant==2026.3.0' > /tmp/notty-ha-override.txt + uv pip install --override /tmp/notty-ha-override.txt 'pytest-homeassistant-custom-component==0.13.317' pytest-cov + - run: .venv/bin/pytest --cov=custom_components.notty --cov=scripts --cov-report=term-missing hassfest: runs-on: ubuntu-latest steps: diff --git a/README.md b/README.md index 9490b1c..314ba42 100644 --- a/README.md +++ b/README.md @@ -42,17 +42,17 @@ Only fields returned by the account/device are exposed. The coordinator polls ev | Sensors | Litter box state, cleaning counts, pet weight/usage, event times, duration statistics, reminders and related data | | Binary sensors | Connectivity, locks and reported boolean settings | | Buttons | Clean, level, empty, reminder resets, weight reset and calibration | -| Switches | Child lock, Do Not Disturb, litter-renewal reminder and trash-bag reminder | -| Actions | List and manage fixed-clock cleaning plans with explicit plan IDs | +| Switches | Child lock, Do Not Disturb, reminders, pet neutered state and account notification preferences | +| Actions | Cleaning plans, pet profiles/associations/memos, notification preferences and explicitly confirmed statistics deletion | | Selects | Cleaning mode, automatic cleaning delay, known screen languages and reminder intervals | | Time | Do Not Disturb start/end | -| Text | NOTTY cloud device name, independent of your HA display-name override | -| Update | Read-only firmware versions, availability and release-note summary | +| Text / Date | Cloud device name, pet name and pet birthday; HA display-name overrides are preserved | +| Update | Firmware availability, release notes and explicit installation of a fresh eligible offered task | | Number | Pet weight, with existing litter-box binding preserved | Pet records become separate devices linked to the litter box. They do not receive litter-box command buttons. Known sensor fields use explicit units and device classes; unknown scalar fields remain ordinary sensors. Times and schedules are not guessed to be durations, and the weight-unit enum is not a weight measurement. -The mode entity displays the APK-backed labels Auto (`1`), Scheduled (`2`) and Soft stool (`3`), with numeric fallback for unknown values. Mode writes remain blocked in the select and API; `set_mode` is no longer offered by the generic service while schedule setup and live mode behavior remain unverified. +The mode entity displays the APK-backed labels Auto (`1`), Scheduled (`2`) and Soft stool (`3`), with numeric fallback for unknown values. The select and `set_mode` action support these three integer values. Writes require fresh matching physical-device identity and a known current mode; Scheduled also requires at least one enabled plan. Selecting the current mode skips the write. Live mode changes and automatic cleaning behavior still need owner validation. Automatic cleaning delay is available as a configuration select (1–15 minutes) when the device reports `auto_delay`. It is unavailable outside Auto mode, matching the app. Unknown delay values remain in the raw attributes without guessing a supported option. @@ -97,11 +97,11 @@ validation. Capture and inspect its before/after response: device-local schedule interpretation may change even when raw clock strings stay the same. It never automatically rewrites DND or cleaning schedules. See [issue #21](https://github.com/Repsay/notty/issues/21). -For physical litter boxes that report `open_litter_remind` or `open_garbagebag_remind`, configuration switches enable (`action=1`) or disable (`action=2`) each reminder using the reported configured interval (`default_remaining_days`: 5–30 days; `garbage_bag_cycle_time`: 2–15 days). **Both operations require `cycle_time`.** Owner tests on a real NOTTY device confirmed that action 1 enables the reminder and restarts its countdown, while action 2 disables it without changing the configured cycle. Unknown state or missing/invalid cycle data prevents writes. **The litter-renewal interval selector is enabled for an already enabled reminder:** an owner test confirmed that `action=3` changes the configured litter interval and updates the remaining countdown (30 → 29 days). Selecting the same interval skips the write. Reminder reset buttons and the trash-bag interval selector remain blocked, as their live semantics have not been established. +For physical litter boxes that report `open_litter_remind` or `open_garbagebag_remind`, configuration switches enable (`action=1`) or disable (`action=2`) each reminder using the reported configured interval (`default_remaining_days`: 5–30 days; `garbage_bag_cycle_time`: 2–15 days). **Both operations require `cycle_time`.** Owner tests on a real NOTTY device confirmed that action 1 enables the reminder and restarts its countdown, while action 2 disables it without changing the configured cycle. Unknown state or missing/invalid cycle data prevents writes. **The litter-renewal interval selector is enabled for an already enabled reminder:** an owner test confirmed that `action=3` changes the configured litter interval and updates the remaining countdown (30 → 29 days). Selecting the same interval skips the write. Additional APK tracing establishes action 3 as the Reset choice for both reminder types. Reset buttons now preserve the configured cycle; the trash-bag interval select supports 2–15 days. Both require an enabled reminder and valid fresh cycle data. Same-cycle reset and trash-bag interval writes still need live validation. Two actions are also available in **Developer tools → Actions**: `notty.litter_box_one_key` and `notty.litter_box_action`. Their schemas are in [services.yaml](custom_components/notty/services.yaml). They require the **physical `user_device_id`**, not a pet ID. One-key codes are now traced from the APK: **clean=1, empty=2, level=3**. The former clean=0, level=1 and sterilize=3 mappings were incorrect. The unsupported sterilize button/action has been removed. Review existing automations, especially numeric one-key values: `1` cleans and `3` levels. Static request evidence does not confirm physical behavior; validate each operation individually before relying on automations. -Reminder enable/disable is available through the configuration switches (both send the configured cycle, not the remaining-day countdown). `set_litter_reminder_days` supports a changed 5–30 day cycle when the device explicitly reports an enabled litter reminder. Generic reset and trash-bag interval actions still reject requests until verified against the live API. +Reminder enable/disable is available through the configuration switches (both send the configured cycle, not the remaining-day countdown). `set_litter_reminder_days` supports a changed 5–30 day cycle when the device explicitly reports an enabled litter reminder. Generic reset and trash-bag interval actions use the same validated action-3 contract. A reset must supply the current configured cycle; it cannot silently change it. ## Sessions and troubleshooting @@ -183,8 +183,7 @@ reported cloud name. An unchanged or rejected readback is never replaced with an optimistic value. The integration-provided device registry name follows cloud readback; your separate Home Assistant display-name override (`name_by_user`), physical device ID, entity unique IDs and existing entity IDs are preserved. -Polling also reflects renames made in the official app. Pet names use a different -API and have no cloud-device-name control. +Polling also reflects renames made in the official app. Pet names use their own profile text entity and `/pet/save` API. The contract is traced from the APK and covered by synthetic tests, but a live rename has not been validated in this development session. See [alias evidence](docs/apk-cloud-alias.md). @@ -200,12 +199,9 @@ no offered update. Missing or malformed metadata makes the entity unavailable; it does not mean the device is up to date. If the optional endpoint recovers after startup, the entity appears without reloading the integration. -This is the read-only phase of [#22](https://github.com/Repsay/notty/issues/22). -The entity offers no install action, automatic updates or progress percentage. -Use the official NOTTY app to perform firmware updates. Raw task status is not -proof of measured progress or a successful installation; only fresh version -readback establishes the installed version. No physical device/model has been -validated for this new entity yet. See [APK firmware evidence](docs/apk-firmware.md). +The entity exposes installation only for an offered task with a usable task ID and a recognized idle/terminal status. An explicit HA update installation rechecks account ownership, device status, offered version and task before confirming it once. Requested versions must match the current offer; backup is unsupported. Full release notes are available in the update dialog. + +Progress is a Boolean tracking this HA session's requested target until fresh installed-version readback or a reported failure/cancellation. No percentage is fabricated. Tracking does not survive an HA restart and does not subscribe to the app's separate realtime firmware events. Unknown task states prevent installation. Firmware installation has not been live-tested; [#22](https://github.com/Repsay/notty/issues/22) remains open for model and lifecycle validation. See [APK firmware evidence](docs/apk-firmware.md). ## Cleaning plans @@ -250,3 +246,23 @@ count. Missing IDs, IDs from another box, malformed list responses and extra fie are rejected. Successful writes refresh the coordinator and return fresh readback when a response is requested. No schedule actions run automatically during setup, polling or read-only probes. See [APK schedule evidence](docs/apk-schedules.md). + +## Pet editing and additional actions + +Existing pets have configuration controls for **name, sex, neutered state and birthday**. The `notty.pet_profile` action also edits breed using IDs from `operation: breeds`. Every profile write fetches current ownership, weight/unit, images and device bindings first, preserving all currently bound devices and leaving unbound candidates unbound. Shared pets are read-only. Profile changes and association changes are serialized per pet, and displayed values come from fresh cloud readback. + +Use these actions from **Developer tools → Actions**; request a response to inspect server IDs and readback: + +| Action | Operations / fields | +| --- | --- | +| `notty.pet_profile` | `pet_id`; `get`, `breeds`, or `update` with `changes` containing name, birthday (`YYYY-MM-DD`), sex (1/2), is_sterilization (Boolean), breed_id | +| `notty.pet_association` | Physical `user_device_id`; `list`, `associate` or `disassociate`; changes require one explicit `pet_id` | +| `notty.pet_memo` | `pet_id`; `list`, `detail`, `create` or `update`; detail/update require `memo_id`; changes contain title/content/date/remind | +| `notty.notification_preferences` | Physical `user_device_id` selects the account; `list`, `block` or `unblock`; changes require a server-listed `message_type_id` | +| `notty.clear_statistics` | Physical `user_device_id` plus `confirm_irreversible: true`; permanently deletes that device's statistics | + +Memo dates use the app's raw `YYYY-MM-DD HH:MM` wall clock; the integration does not infer a timezone. Creates default to no reminder; updates preserve omitted text and reminder fields. Memo attachments and pet creation/deletion are outside this release. + +Notification switches appear under a separate **NOTTY account** device. On means the category is unblocked. These are account-wide NOTTY litter-box preferences, affecting the official app rather than HA notifications. Feeders, water dispensers and their standalone LED controls are excluded. Litter-box DND continues to preserve its LED setting. + +These writes have APK-backed contracts and mocked HA tests. Read-only production checks found the breed catalog, owner profiles and five litter-box notification categories; they did not exercise new writes, memo details, firmware installation or irreversible statistics deletion. Follow the [validation checklist](docs/live-validation.md) before relying on them. Request evidence is in [pet and maintenance contracts](docs/apk-pet-maintenance.md). diff --git a/custom_components/notty/api.py b/custom_components/notty/api.py index 8d13a34..d50633b 100644 --- a/custom_components/notty/api.py +++ b/custom_components/notty/api.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from datetime import UTC, date, datetime, time import json import logging @@ -14,6 +15,8 @@ ACTION_ONE_KEY = "one_key" ACTION_SET_AUTO_DELAY = "set_auto_delay" ACTION_SET_ALIAS = "set_alias" +ACTION_SET_LANGUAGE = "set_language" +MODE_SCHEDULED = 2 MIN_ALIAS_UNITS = 2 MAX_ALIAS_UNITS = 8 @@ -37,6 +40,7 @@ DEVICE_TYPE_LITTER_BOX = "litter_box" ONE_KEY_ACTIONS = {"clean": 1, "empty": 2, "level": 3} LITTER_MODES = {1: "Auto", 2: "Scheduled", 3: "Soft stool"} +SCREEN_LANGUAGES = {0: "Simplified Chinese", 1: "English", 2: "Traditional Chinese", 3: "Icons"} MAX_DELAY_MINUTES = 15 type JsonValue = bool | int | float | str | list[JsonValue] | dict[str, JsonValue] | None @@ -93,6 +97,7 @@ } SAFE_LITTER_ACTIONS = ( "one_key", + "set_mode", "set_key", "reset_litter_reminder", "reset_garbage_bag_reminder", @@ -117,6 +122,12 @@ REMINDER_UPDATE = 3 REMINDER_LITTER_INTERVAL_ACTION = "set_litter_reminder_days" REMINDER_TOGGLE_ACTIONS = {"set_litter_remind", "set_garbage_bag_remind"} +REMINDER_INTERVAL_ACTIONS = {"set_litter_reminder_days", "set_garbage_bag_reminder_days"} +REMINDER_RESET_ACTIONS = {"reset_litter_reminder", "reset_garbage_bag_reminder"} +REMINDER_ENABLED_FIELDS = { + "default_remaining_days": "open_litter_remind", + "garbage_bag_cycle_time": "open_garbagebag_remind", +} LIST_KEYS = ("list", "devices", "rows", "items", "data") LITTER_BIND_KEYS = ("bind_litter_box", "litter_box", "litter_box_id", "litter_box_user_device_id", "lb_user_device_id") @@ -344,8 +355,8 @@ def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject]) -> def reminder_payload(action: str, data: JsonObject) -> JsonObject: """Build a validated reminder request using owner-observed live operation codes. - Litter interval changes (3) were verified on an already enabled reminder; - reset and trash-bag interval changes remain blocked pending live testing. + The app's Reset choice returns action 3; action 2 disables a reminder. + Changes and explicit resets carry the configured cycle, never remaining days. Returns: Only the validated operation and configured cycle, without read fields. @@ -353,7 +364,7 @@ def reminder_payload(action: str, data: JsonObject) -> JsonObject: Raises: NottyApiError: If an action or configured interval is unverified. """ - if action == REMINDER_LITTER_INTERVAL_ACTION: + if action in REMINDER_INTERVAL_ACTIONS | REMINDER_RESET_ACTIONS: operation = data.get("action", REMINDER_UPDATE) if type(operation) is not int or operation != REMINDER_UPDATE: msg = "Litter interval action must use action=3" @@ -364,7 +375,7 @@ def reminder_payload(action: str, data: JsonObject) -> JsonObject: msg = "Reminder action must be an integer: enable=1, disable=2" raise NottyApiError(msg) else: - msg = "Reminder reset and trash bag interval changes are disabled pending live endpoint verification" + msg = "Unsupported reminder action" raise NottyApiError(msg) cycle = data.get("cycle_time") if isinstance(cycle, str) and cycle.isascii() and cycle.isdecimal(): @@ -525,6 +536,7 @@ class NottyTransport: """HTTP transport that propagates expired sessions without replaying requests.""" def __init__(self, session: aiohttp.ClientSession, **options: Unpack[ConnectionOptions]) -> None: + self._mutation_locks: dict[str, asyncio.Lock] = {} self._session = session email = options.get("email") verification_code = options.get("verification_code") @@ -537,6 +549,14 @@ def __init__(self, session: aiohttp.ClientSession, **options: Unpack[ConnectionO self.client_id = options.get("client_id", DEFAULT_CLIENT_ID) self.region_code = options.get("region_code", "NL") + def mutation_lock(self, scope: str) -> asyncio.Lock: + """Serialize read-modify-write operations across entity and service callers. + + Returns: + The shared per-account lock for the selected pet or device scope. + """ + return self._mutation_locks.setdefault(scope, asyncio.Lock()) + def _headers(self) -> dict[str, str]: headers = { "Accept": "application/json, text/plain, */*", @@ -1298,20 +1318,74 @@ async def litter_action(self, device_id: str, action: str, data: JsonObject | No if action in PLAN_ACTIONS: return await self.manage_litter_plan(device_id, action, data or {}) + if action == ACTION_SET_MODE: + return await self._change_mode(device_id, data or {}) path = LITTER_ACTION_ENDPOINTS.get(action) if not path: msg = f"Unsupported litter box action: {action}" raise NottyApiError(msg) if action == ACTION_ONE_KEY: return await self.command(device_id, (data or {}).get(ACTION_ONE_KEY)) - if action == ACTION_SET_MODE: - msg = "NOTTY mode changes remain disabled pending schedule prerequisites and live validation" - raise NottyApiError(msg) - settings = reminder_payload(action, data or {}) if action in REMINDER_CYCLE_FIELDS else (data or {}) + payload = await self._setting_payload(device_id, action, data or {}) + if payload is None: + return None + return await self.request("POST", path, data=payload) + + async def _setting_payload(self, device_id: str, action: str, data: JsonObject) -> JsonObject | None: + settings = reminder_payload(action, data) if action in REMINDER_CYCLE_FIELDS else data + if action in REMINDER_RESET_ACTIONS | REMINDER_INTERVAL_ACTIONS and not await self._validate_reminder_edit( + device_id, action, settings + ): + return None + if action == ACTION_SET_LANGUAGE: + language = settings.get("language") + if set(settings) != {"language"} or type(language) is not int or language not in SCREEN_LANGUAGES: + msg = "Choose a supported NOTTY screen language" + raise NottyApiError(msg) payload = {**settings, **self._device_payload(device_id)} if action == ACTION_SET_AUTO_DELAY: delay = payload.get("delay") if type(delay) is not int or not 1 <= delay <= MAX_DELAY_MINUTES: msg = "Automatic cleaning delay must be an integer from 1 to 15 minutes" raise NottyApiError(msg) - return await self.request("POST", path, data=payload) + return payload + + async def _change_mode(self, device_id: str, data: JsonObject) -> JsonValue: + mode = data.get("mode") + if set(data) != {"mode"} or type(mode) is not int or mode not in LITTER_MODES: + msg = "Choose Auto, Scheduled or Soft stool with no additional fields" + raise NottyApiError(msg) + if not device_id.isascii() or not device_id.isdecimal() or int(device_id) <= 0: + msg = "Mode changes require a positive numeric physical device ID" + raise NottyApiError(msg) + current = await self.litter_info(device_id) + if str(current.get("user_device_id")) != device_id: + msg = "Mode readback does not match the selected physical device" + raise NottyApiError(msg) + current_mode = current.get("mode") + if type(current_mode) is not int or current_mode not in LITTER_MODES: + msg = "Mode changes require known current device mode" + raise NottyApiError(msg) + if mode == current_mode: + return None + if mode == MODE_SCHEDULED and not any( + plan_enabled(row.get("open")) is True for row in await self.litter_plans(device_id) + ): + msg = "Scheduled mode requires at least one enabled cleaning plan" + raise NottyApiError(msg) + return await self.request( + "POST", "/device/litter_box/set_mode", data={"user_device_id": int(device_id), "mode": mode} + ) + + async def _validate_reminder_edit(self, device_id: str, action: str, settings: JsonObject) -> bool: + current = await self.litter_info(device_id) + cycle_field = REMINDER_CYCLE_FIELDS[action] + enabled = current.get(REMINDER_ENABLED_FIELDS[cycle_field]) + cycle = current.get(cycle_field) + if plan_enabled(enabled) is not True or type(cycle) is not int or cycle not in REMINDER_DAY_RANGES[cycle_field]: + msg = "Reminder edits require an enabled reminder with a valid configured cycle" + raise NottyApiError(msg) + if action in REMINDER_RESET_ACTIONS and cycle != settings["cycle_time"]: + msg = "Reset must preserve the current configured cycle" + raise NottyApiError(msg) + return action in REMINDER_RESET_ACTIONS or cycle != settings["cycle_time"] diff --git a/custom_components/notty/binary_sensor.py b/custom_components/notty/binary_sensor.py index 732f320..2e99978 100644 --- a/custom_components/notty/binary_sensor.py +++ b/custom_components/notty/binary_sensor.py @@ -1,7 +1,8 @@ from __future__ import annotations +from typing import TYPE_CHECKING + from homeassistant.components.binary_sensor import BinarySensorEntity -from homeassistant.components.binary_sensor.const import BinarySensorDeviceClass from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -9,6 +10,14 @@ from custom_components.notty.entity import NottyEntity, merged_device_data, title_from_key, value_from_block from custom_components.notty.models import DeviceBlock, DeviceData, NottyConfigEntry +if TYPE_CHECKING: + from homeassistant.components.binary_sensor.const import BinarySensorDeviceClass +else: + try: + from homeassistant.components.binary_sensor.const import BinarySensorDeviceClass + except ModuleNotFoundError: + from homeassistant.components.binary_sensor import BinarySensorDeviceClass + BINARY_KEYS = { "online", "is_online", diff --git a/custom_components/notty/bootstrap.py b/custom_components/notty/bootstrap.py index 8a79d58..22c3e7a 100644 --- a/custom_components/notty/bootstrap.py +++ b/custom_components/notty/bootstrap.py @@ -9,6 +9,9 @@ from custom_components.notty.api import ( ONE_KEY_ACTIONS, REMINDER_CYCLE_FIELDS, + REMINDER_DAY_RANGES, + REMINDER_ENABLED_FIELDS, + REMINDER_INTERVAL_ACTIONS, REMINDER_LITTER_INTERVAL_ACTION, SAFE_LITTER_ACTIONS, JsonObject, @@ -34,6 +37,7 @@ from custom_components.notty.coordinator import NottyCoordinator from custom_components.notty.device_timezone import SERVICE_DEVICE_TIME_ZONE, register_timezone_service from custom_components.notty.entity import value_from_block +from custom_components.notty.feature_services import FEATURE_SERVICES, register_feature_services from custom_components.notty.models import NottyConfigEntry from custom_components.notty.schedule import SERVICE_LITTER_BOX_SCHEDULE, register_schedule_service from custom_components.notty.validation import vol @@ -64,14 +68,29 @@ def _get_coordinator(hass: HomeAssistant, user_device_id: str) -> NottyCoordinat raise HomeAssistantError(msg) -def _validate_litter_interval_change(coordinator: NottyCoordinator, device_id: str, data: JsonObject) -> None: +def _get_pet_coordinator(hass: HomeAssistant, pet_id: str) -> NottyCoordinator: + for entry in cast("list[NottyConfigEntry]", hass.config_entries.async_entries(DOMAIN)): + coordinator = cast("NottyCoordinator | None", getattr(entry, "runtime_data", None)) + if isinstance(coordinator, NottyCoordinator) and any( + block["device"].get("_notty_source") == SOURCE_PET and str(block["device"].get("pet_id")) == pet_id + for block in coordinator.data.values() + ): + return coordinator + msg = "The pet was not found in a loaded NOTTY account" + raise HomeAssistantError(msg) + + +def _validate_litter_interval_change( + coordinator: NottyCoordinator, device_id: str, data: JsonObject, action: str = REMINDER_LITTER_INTERVAL_ACTION +) -> None: """Reject untested reminder states and no-op cycle writes. Raises: NottyApiError: If the target is not an enabled reminder with a valid changing interval. """ block = coordinator.data[device_id] - enabled = value_from_block(block, "open_litter_remind") + cycle_field = REMINDER_CYCLE_FIELDS[action] + enabled = value_from_block(block, REMINDER_ENABLED_FIELDS[cycle_field]) if not ( enabled is True or (type(enabled) is int and enabled == 1) @@ -79,10 +98,10 @@ def _validate_litter_interval_change(coordinator: NottyCoordinator, device_id: s ): msg = "Litter interval changes require an enabled reminder" raise NottyApiError(msg) - current_cycle = value_from_block(block, "default_remaining_days") + current_cycle = value_from_block(block, cycle_field) if isinstance(current_cycle, str) and current_cycle.isascii() and current_cycle.isdecimal(): current_cycle = int(current_cycle) - if type(current_cycle) is not int or current_cycle not in range(5, 31): + if type(current_cycle) is not int or current_cycle not in REMINDER_DAY_RANGES[cycle_field]: msg = "Litter interval changes require a valid configured cycle" raise NottyApiError(msg) if data["cycle_time"] == current_cycle: @@ -91,6 +110,7 @@ def _validate_litter_interval_change(coordinator: NottyCoordinator, device_id: s def _register_services(hass: HomeAssistant) -> None: + register_feature_services(hass, _get_coordinator, _get_pet_coordinator) register_schedule_service(hass, _get_coordinator) register_timezone_service(hass, _get_coordinator) @@ -131,8 +151,8 @@ async def handle_litter_box_action(call: ServiceCall) -> None: try: if action in REMINDER_CYCLE_FIELDS: action_data = reminder_payload(action, action_data) - if action == REMINDER_LITTER_INTERVAL_ACTION: - _validate_litter_interval_change(coordinator, user_device_id, action_data) + if action in REMINDER_INTERVAL_ACTIONS: + _validate_litter_interval_change(coordinator, user_device_id, action_data, action) await coordinator.api.litter_action(user_device_id, action, action_data) except NottyApiError as err: raise HomeAssistantError(str(err)) from err @@ -209,6 +229,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: NottyConfigEntry) -> bo hass.services.async_remove(DOMAIN, SERVICE_LITTER_BOX_SCHEDULE) hass.services.async_remove(DOMAIN, SERVICE_DEVICE_TIME_ZONE) + for service in FEATURE_SERVICES: + hass.services.async_remove(DOMAIN, service) return unloaded diff --git a/custom_components/notty/button.py b/custom_components/notty/button.py index e87906e..f24dbab 100644 --- a/custom_components/notty/button.py +++ b/custom_components/notty/button.py @@ -7,7 +7,14 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from custom_components.notty.api import ONE_KEY_ACTIONS, REMINDER_CYCLE_FIELDS, NottyApiError, reminder_payload +from custom_components.notty.api import ( + ONE_KEY_ACTIONS, + REMINDER_CYCLE_FIELDS, + REMINDER_ENABLED_FIELDS, + NottyApiError, + plan_enabled, + reminder_payload, +) from custom_components.notty.coordinator import NottyCoordinator from custom_components.notty.entity import NottyEntity, value_from_block from custom_components.notty.models import DeviceData, NottyConfigEntry @@ -86,6 +93,27 @@ def __init__( self._attr_translation_key = description.key self._attr_unique_id = f"{device_id}_{description.key}" + @property + def available(self) -> bool: + """Require an enabled reminder and configured cycle for its reset button. + + Returns: + Whether the command can be attempted from current readback. + """ + action = self.entity_description.key + if action not in REMINDER_CYCLE_FIELDS: + return super().available + if ( + plan_enabled(value_from_block(self.block, REMINDER_ENABLED_FIELDS[REMINDER_CYCLE_FIELDS[action]])) + is not True + ): + return False + try: + reminder_payload(action, {"cycle_time": value_from_block(self.block, REMINDER_CYCLE_FIELDS[action])}) + except NottyApiError: + return False + return super().available + async def async_press(self) -> None: """Press the command or reset the reminder using its configured interval. diff --git a/custom_components/notty/const.py b/custom_components/notty/const.py index 09e9289..244f11a 100644 --- a/custom_components/notty/const.py +++ b/custom_components/notty/const.py @@ -14,4 +14,4 @@ CONF_REGION_CODE = "region_code" DEFAULT_REGION_CODE = "NL" DEFAULT_SCAN_INTERVAL = 60 -PLATFORMS = ["sensor", "binary_sensor", "button", "switch", "select", "time", "number", "text", "update"] +PLATFORMS = ["sensor", "binary_sensor", "button", "switch", "select", "time", "number", "text", "update", "date"] diff --git a/custom_components/notty/coordinator.py b/custom_components/notty/coordinator.py index e043257..27c7db2 100644 --- a/custom_components/notty/coordinator.py +++ b/custom_components/notty/coordinator.py @@ -27,6 +27,7 @@ DEFAULT_SCAN_INTERVAL, DOMAIN, ) +from custom_components.notty.device_features import NotificationApi from custom_components.notty.models import CoordinatorData, DeviceData, NottyConfigEntry TOILET_EVENT_TYPE_ID = 12 @@ -495,6 +496,7 @@ def __init__(self, hass: HomeAssistant, api: NottyApi, entry: NottyConfigEntry | self.api = api self._entry = entry self.entry_id = entry.entry_id if entry is not None else None + self.notification_categories: list[JsonObject] | None = None async def _async_update_data(self) -> CoordinatorData: try: @@ -542,6 +544,7 @@ async def _collect_data(self) -> CoordinatorData: _LOGGER.debug("Skipping NOTTY litter box without bound info payload: %s", device) continue _merge_block(out, did, device, info, device_type) + await self._read_notification_categories(out) if self._entry is not None: previous_data = cast("JsonObject", self._entry.data) data = dict(previous_data) @@ -558,6 +561,22 @@ async def _collect_data(self) -> CoordinatorData: self.hass.config_entries.async_update_entry(self._entry, data=data) return out + async def _read_notification_categories(self, data: CoordinatorData) -> None: + physical = [block for block in data.values() if block["device"].get("_notty_source") != SOURCE_PET] + self.notification_categories = None + if not physical: + return + try: + self.notification_categories = await NotificationApi(self.api).categories() + except NottyAuthError: + raise + except NottyApiError: + _LOGGER.debug("Optional NOTTY notification preferences are unavailable") + # Include category changes in coordinator equality so preference-only changes + # notify listeners even when device and pet measurements remain unchanged. + for block in physical: + block["info"]["_notty_notification_categories"] = cast("JsonValue", self.notification_categories) + async def _pet_info(self, device: JsonObject) -> JsonObject: pet_id = str(device.get("pet_id") or "").removeprefix("pet_") related = await self.api.pet_related_info(pet_id) if pet_id else {} diff --git a/custom_components/notty/date.py b/custom_components/notty/date.py new file mode 100644 index 0000000..d538555 --- /dev/null +++ b/custom_components/notty/date.py @@ -0,0 +1,14 @@ +"""Pet birthday calendar controls.""" + +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from custom_components.notty.models import NottyConfigEntry +from custom_components.notty.pet_entities import NottyPetBirthday, add_pet_entities + + +async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant requires an async platform setup callback. + _hass: HomeAssistant, entry: NottyConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback +) -> None: + """Expose birthday editing on the existing pet devices.""" + add_pet_entities(entry, async_add_entities, NottyPetBirthday) diff --git a/custom_components/notty/device_features.py b/custom_components/notty/device_features.py new file mode 100644 index 0000000..02fa7f8 --- /dev/null +++ b/custom_components/notty/device_features.py @@ -0,0 +1,159 @@ +"""Litter-box maintenance and account notification operations from the APK.""" + +from __future__ import annotations + +from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError, plan_enabled +from custom_components.notty.feature_contracts import identifier, object_rows, true_state + +SOURCE_PET = "pet" +LITTER_WORD = "litter" +SAND_WORD = "sand" +LITTER_MESSAGE_GROUP = 3 +LITTER_PRODUCT_ID = 2 +MAX_TASK_ID_LENGTH = 128 +FIRMWARE_IDLE_STATUSES = {"", "SUCCEEDED", "FAILED", "CANCELED"} + + +async def owned_litter(api: NottyApi, device_id: str) -> JsonObject: + """Require a current account-owned physical litter box for maintenance writes. + + Returns: + The matching discovery metadata. + + Raises: + NottyApiError: If ownership or supported device kind cannot be established. + """ + selected = identifier(device_id) + for row in await api.devices(): + if row.get("_notty_source") == SOURCE_PET: + continue + raw_id = row.get("user_device_id") + if raw_id is None or identifier(raw_id) != selected: + continue + kind = " ".join(str(row.get(key, "")) for key in ("device_type", "type", "device_name", "product_name")).lower() + if true_state(row.get("is_owner")) and ( + LITTER_WORD in kind or SAND_WORD in kind or row.get("device_id") == LITTER_PRODUCT_ID + ): + return row + msg = "The action requires an account-owned physical NOTTY litter box" + raise NottyApiError(msg) + + +class NotificationApi: + """Account-wide NOTTY litter-box notification categories, independent of HA notifications.""" + + def __init__(self, api: NottyApi) -> None: + self.api = api + + async def categories(self) -> list[JsonObject]: + """Read the APK's litter-box message group, not a physical device filter. + + Returns: + Public category IDs, names and block states. + + Raises: + NottyApiError: If category IDs or scope are malformed. + """ + rows = object_rows( + await self.api.request("GET", f"/message/get_type_block_stats_list?message_group_id={LITTER_MESSAGE_GROUP}") + ) + seen: set[int] = set() + result: list[JsonObject] = [] + for row in rows: + category_id = identifier(row.get("message_type_id")) + if category_id in seen or row.get("message_type_group_id") != LITTER_MESSAGE_GROUP: + msg = "Notification category IDs or group scope are invalid" + raise NottyApiError(msg) + seen.add(category_id) + result.append({key: row.get(key) for key in ("message_type_id", "message_type_name", "blocked")}) + return result + + async def set_blocked(self, category_id: JsonValue, *, blocked: bool) -> list[JsonObject]: + """Change exactly one server-listed account category without retries. + + Returns: + Fresh category readback. + + Raises: + NottyApiError: If the category or its current state is unknown. + """ + selected = identifier(category_id) + rows = await self.categories() + row = next((row for row in rows if identifier(row["message_type_id"]) == selected), None) + if row is None or plan_enabled(row["blocked"]) is None: + msg = "Select a notification category with a known current block state" + raise NottyApiError(msg) + if plan_enabled(row["blocked"]) is blocked: + return rows + await self.api.request( + "POST", "/message/block_type", data={"message_type_id": row["message_type_id"], "block": blocked} + ) + return await self.categories() + + +class FirmwareApi: + """Fresh upgrade eligibility and the app's explicit task confirmation.""" + + def __init__(self, api: NottyApi) -> None: + self.api = api + + async def install(self, device_id: str, version: str | None = None) -> str: + """Confirm only the currently offered task for an owned litter box. + + Returns: + The requested target version; installation completion requires later readback. + + Raises: + NottyApiError: If no eligible task exists or the requested version differs. + """ + device = await owned_litter(self.api, device_id) + if device.get("status_id") == 0 or plan_enabled(device.get("online", device.get("is_online"))) is False: + msg = "Firmware installation requires an online litter box" + raise NottyApiError(msg) + current = await self.api.request("GET", f"/device/check_upgrade/{identifier(device_id)}") + if not isinstance(current, dict): + msg = "Firmware metadata is unavailable" + raise NottyApiError(msg) + installed, target, task = current.get("src_version"), current.get("dest_version"), current.get("task_id") + if not isinstance(installed, str) or not installed.strip(): + msg = "Firmware installation requires a known installed version" + raise NottyApiError(msg) + if not isinstance(target, str) or not target.strip() or target == installed or version not in {None, target}: + msg = "Only the currently offered NOTTY firmware version can be installed" + raise NottyApiError(msg) + status = current.get("task_status") + 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) + await self.api.request( + "POST", "/device/confirm_upgrade", data={"user_device_id": identifier(device_id), "task_id": task} + ) + return target + + +def firmware_task_id(value: JsonValue) -> bool: + """Validate opaque task IDs without converting their server-provided type. + + Returns: + Whether a positive integer or bounded printable task string is present. + """ + return (type(value) is int and value > 0) or ( + isinstance(value, str) and bool(value.strip()) and value.isprintable() and len(value) <= MAX_TASK_ID_LENGTH + ) + + +async def clear_statistics(api: NottyApi, device_id: str, *, confirmed: bool) -> JsonObject: + """Clear device statistics only after explicit irreversible-action acknowledgement. + + Returns: + Acknowledgement metadata; affected sensors refresh through the coordinator. + + Raises: + NottyApiError: If confirmation or ownership is absent. + """ + if confirmed is not True: + msg = "Statistics deletion requires confirm_irreversible: true" + raise NottyApiError(msg) + await owned_litter(api, device_id) + await api.request("POST", f"/device/clear_statistics/{identifier(device_id)}", data={}) + return {"status": "write_acknowledged", "scope": "selected_device_statistics", "reversible": False} diff --git a/custom_components/notty/entity.py b/custom_components/notty/entity.py index a22b356..fc8a8cd 100644 --- a/custom_components/notty/entity.py +++ b/custom_components/notty/entity.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import cast + from homeassistant.helpers.device_registry import DeviceInfo, async_get from homeassistant.helpers.update_coordinator import CoordinatorEntity @@ -104,6 +106,9 @@ def title_from_key(key: str) -> str: return aliases.get(key, key.replace("_", " ").title()) +FIELD_VIA_DEVICE_ID = "via_device_id" + + class NottyEntity(CoordinatorEntity[NottyCoordinator]): _attr_has_entity_name = True @@ -126,7 +131,10 @@ def __init__(self, coordinator: NottyCoordinator, device_id: str, device: Device else: parent = registry.async_get_device(identifiers={(DOMAIN, str(parent_device_id))}) if parent is not None: - device_info["via_device_id"] = parent.id + if FIELD_VIA_DEVICE_ID in DeviceInfo.__annotations__: + device_info["via_device_id"] = parent.id + else: + device_info.update(cast("DeviceInfo", {"via_device": (DOMAIN, str(parent_device_id))})) self._attr_device_info = device_info @property @@ -146,3 +154,15 @@ def available(self) -> bool: bool: The resulting available. """ return super().available and self.device_id in (self.coordinator.data or {}) + + def update_device_name(self, name: str) -> None: + """Refresh the integration-provided name while preserving the HA user override.""" + if self.coordinator.entry_id is None: + return + registry = async_get(self.hass) + if hasattr(registry, "async_get_device_by_identifier"): + device = registry.async_get_device_by_identifier((DOMAIN, self.device_id), self.coordinator.entry_id) + else: + device = registry.async_get_device(identifiers={(DOMAIN, self.device_id)}) + if device is not None and device.name != name: + registry.async_update_device(device.id, name=name) diff --git a/custom_components/notty/feature_contracts.py b/custom_components/notty/feature_contracts.py new file mode 100644 index 0000000..3bc0b26 --- /dev/null +++ b/custom_components/notty/feature_contracts.py @@ -0,0 +1,216 @@ +"""Validation for APK-backed pet and account actions.""" + +from __future__ import annotations + +from datetime import date, datetime +import math + +from custom_components.notty.api import JsonObject, JsonValue, NottyApiError, plan_enabled + +PET_EDIT_FIELDS = {"name", "birthday", "sex", "is_sterilization", "breed_id"} +PET_SAVE_FIELDS = ( + "image_path", + "image_url", + "name", + "breed_id", + "breed_name", + "sex", + "sex_name", + "is_sterilization", + "birthday", + "weight", + "collar_id", + "is_default", + "age", + "shareds", + "device_number", +) +MEMO_FIELDS = {"title", "content", "date", "remind"} +MAX_PET_NAME_UNITS = 10 +MAX_MEMO_TITLE = 255 +MAX_MEMO_CONTENT = 10000 +SEX_NAMES = {1: "Male", 2: "Female"} +FIELD_NAME = "name" +FIELD_BIRTHDAY = "birthday" +FIELD_SEX = "sex" +FIELD_NEUTERED = "is_sterilization" +FIELD_BREED = "breed_id" +MIN_PET_NAME_UNITS = 2 +TRUE_TEXT = "1" +NULL_CHAR = "\x00" + + +def identifier(value: JsonValue) -> int: + """Accept positive decimal IDs without coercing Boolean or floating-point values. + + Returns: + A physical, pet, category or memo integer ID. + + Raises: + NottyApiError: If the identifier is missing or invalid. + """ + if type(value) is int and value > 0: + return value + if isinstance(value, str) and value.isascii() and value.isdecimal() and int(value) > 0: + return int(value) + msg = "A positive numeric NOTTY ID is required" + raise NottyApiError(msg) + + +def object_rows(value: JsonValue) -> list[JsonObject]: + """Require an explicit list, optionally under the app's list/data field. + + Returns: + Object records without treating a malformed response as an empty list. + + Raises: + NottyApiError: If records are unavailable or malformed. + """ + if isinstance(value, dict): + value = value.get("list", value.get("data")) + if not isinstance(value, list) or any(not isinstance(row, dict) for row in value): + msg = "NOTTY returned an unreadable record list" + raise NottyApiError(msg) + return [row for row in value if isinstance(row, dict)] + + +def true_state(value: JsonValue) -> bool: + """Recognize explicit ownership/on states. + + Returns: + True only for Boolean true or integer/string one. + """ + return value is True or (type(value) is int and value == 1) or (isinstance(value, str) and value == TRUE_TEXT) + + +def require_owner(profile: JsonObject) -> None: + """Reject edits of shared pets without confirmed ownership. + + Raises: + NottyApiError: If ownership is false or unknown. + """ + if not true_state(profile.get("is_owner")): + msg = "Only the NOTTY pet owner can edit this pet" + raise NottyApiError(msg) + + +def _birthday(value: JsonValue) -> str: + if not isinstance(value, str): + msg = "Pet birthday must use YYYY-MM-DD" + raise NottyApiError(msg) + try: + parsed = date.fromisoformat(value) + except ValueError as exc: + msg = "Pet birthday must be a valid YYYY-MM-DD date" + raise NottyApiError(msg) from exc + if parsed.isoformat() != value or parsed > datetime.now().astimezone().date(): + msg = "Pet birthday must be an existing calendar date" + raise NottyApiError(msg) + return value + + +def profile_changes(changes: JsonObject) -> JsonObject: + """Validate the supported edit subset without inventing pet fields. + + Returns: + Validated changes, preserving accepted name text. + + Raises: + NottyApiError: If a field, enum, date or name is invalid. + """ + if not changes or changes.keys() - PET_EDIT_FIELDS: + msg = "Pet edits support name, birthday, sex, is_sterilization and breed_id" + raise NottyApiError(msg) + result = dict(changes) + if FIELD_NAME in result: + name = result["name"] + if not isinstance(name, str) or not name.strip() or not name.isprintable(): + msg = "Pet name must contain printable text" + raise NottyApiError(msg) + if not MIN_PET_NAME_UNITS <= len(name.encode("utf-16-le")) // 2 <= MAX_PET_NAME_UNITS: + msg = "Pet name must contain 2 to 10 UTF-16 units" + raise NottyApiError(msg) + if FIELD_BIRTHDAY in result: + result["birthday"] = _birthday(result["birthday"]) + if FIELD_SEX in result and (type(result["sex"]) is not int or result["sex"] not in SEX_NAMES): + msg = "Pet sex must be 1 (male) or 2 (female)" + raise NottyApiError(msg) + if FIELD_NEUTERED in result and type(result["is_sterilization"]) is not bool: + msg = "Pet neutered state must be a Boolean" + raise NottyApiError(msg) + if FIELD_BREED in result: + result["breed_id"] = identifier(result["breed_id"]) + return result + + +def profile_payload(pet_id: str, current: JsonObject, changes: JsonObject) -> JsonObject: + """Preserve the complete known app profile and every device binding during edits. + + Returns: + The APK pet/save fields with an explicit pet ID and unchanged binding list. + + Raises: + NottyApiError: If ownership, identity, weight or binding metadata is unknown. + """ + require_owner(current) + if identifier(current.get("pet_id")) != identifier(pet_id): + msg = "Pet profile identity mismatch" + raise NottyApiError(msg) + payload = {key: current[key] for key in PET_SAVE_FIELDS if key in current} + weight = current.get("weight") + if not isinstance(weight, (int, float)) or isinstance(weight, bool) or not math.isfinite(weight) or weight <= 0: + 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}: + msg = "Pet editing requires a known current weight unit" + raise NottyApiError(msg) + devices = object_rows(current.get("pet_devices")) + if any(plan_enabled(device.get("is_bind")) is None for device in devices): + msg = "Pet editing requires known binding states for every listed device" + raise NottyApiError(msg) + bindings = [ + str(identifier(device.get("user_device_id"))) for device in devices if plan_enabled(device.get("is_bind")) + ] + payload.update({"pet_id": identifier(pet_id), "user_device_ids": ",".join(bindings), "weight_unit": unit}) + payload.update(profile_changes(changes)) + if not isinstance(payload.get("name"), str) or not payload["name"]: + msg = "Pet editing requires the current pet name" + raise NottyApiError(msg) + _birthday(payload.get("birthday")) + return payload + + +def memo_payload(pet_id: str, current: JsonObject, changes: JsonObject, *, create: bool) -> JsonObject: + """Validate the app's text memo fields and raw NOTTY wall-clock date. + + Returns: + A pet-scoped memo request; existing reminder metadata is preserved. + + Raises: + NottyApiError: If fields or the date/identity are invalid. + """ + if changes.keys() - MEMO_FIELDS or not changes: + msg = "Memo changes support only title, content, date and remind" + raise NottyApiError(msg) + result = {key: current[key] for key in (*MEMO_FIELDS, "memo_id", "expired") if key in current} + result.update(changes) + for key, limit in (("title", MAX_MEMO_TITLE), ("content", MAX_MEMO_CONTENT)): + text = result.get(key) + if not isinstance(text, str) or not text.strip() or len(text) > limit or NULL_CHAR in text: + msg = "Memo title and content must contain bounded, nonblank text" + raise NottyApiError(msg) + result[key] = text.strip() + clock = result.get("date") + try: + valid_date = ( + isinstance(clock, str) + and datetime.strptime(f"{clock} +0000", "%Y-%m-%d %H:%M %z").strftime("%Y-%m-%d %H:%M") == clock + ) + except ValueError: + valid_date = False + if not valid_date or type(result.get("remind")) is not bool: + msg = "Memo date must use YYYY-MM-DD HH:MM with an explicit Boolean reminder" + raise NottyApiError(msg) + result.update({"pet_id": identifier(pet_id), "memo_id": 0 if create else identifier(current.get("memo_id"))}) + return result diff --git a/custom_components/notty/feature_services.py b/custom_components/notty/feature_services.py new file mode 100644 index 0000000..3913065 --- /dev/null +++ b/custom_components/notty/feature_services.py @@ -0,0 +1,270 @@ +"""Native HA actions for pet editing, associations, memos and account preferences.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable, Coroutine +from typing import cast + +from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse +from homeassistant.exceptions import HomeAssistantError + +from custom_components.notty.api import JsonObject, JsonValue, NottyApiError +from custom_components.notty.const import DOMAIN +from custom_components.notty.coordinator import NottyCoordinator +from custom_components.notty.device_features import NotificationApi, clear_statistics, owned_litter +from custom_components.notty.feature_contracts import identifier +from custom_components.notty.pet_api import MemoApi, PetApi +from custom_components.notty.validation import vol + +SERVICE_PET_PROFILE = "pet_profile" +SERVICE_PET_ASSOCIATION = "pet_association" +SERVICE_PET_MEMO = "pet_memo" +SERVICE_NOTIFICATIONS = "notification_preferences" +SERVICE_CLEAR_STATISTICS = "clear_statistics" +FEATURE_SERVICES = ( + SERVICE_PET_PROFILE, + SERVICE_PET_ASSOCIATION, + SERVICE_PET_MEMO, + SERVICE_NOTIFICATIONS, + SERVICE_CLEAR_STATISTICS, +) +OP_LIST = "list" +OP_GET = "get" +OP_BREEDS = "breeds" +OP_CREATE = "create" +OP_UPDATE = "update" +OP_DETAIL = "detail" +OP_ASSOCIATE = "associate" +OP_BLOCK = "block" +OPERATION_FIELDS = { + SERVICE_PET_PROFILE: {OP_GET: set[str](), OP_BREEDS: set[str](), OP_UPDATE: {"changes"}}, + SERVICE_PET_ASSOCIATION: {OP_LIST: set[str](), OP_ASSOCIATE: {"pet_id"}, "disassociate": {"pet_id"}}, + SERVICE_PET_MEMO: { + OP_LIST: set[str](), + OP_DETAIL: {"memo_id"}, + OP_CREATE: {"changes"}, + OP_UPDATE: {"memo_id", "changes"}, + }, + SERVICE_NOTIFICATIONS: {OP_LIST: set[str](), OP_BLOCK: {"message_type_id"}, "unblock": {"message_type_id"}}, +} + +type ResolveCoordinator = Callable[[HomeAssistant, str], NottyCoordinator] + + +def profile_response(value: JsonObject) -> JsonObject: + """Expose useful profile fields without backend URLs or unrelated health data. + + Returns: + Supported profile values, ownership and current device bindings. + """ + return { + key: value[key] + for key in ( + "name", + "birthday", + "sex", + "is_sterilization", + "breed_id", + "breed_name", + "weight", + "weight_unit", + "pet_id", + "is_owner", + "pet_devices", + ) + if key in value + } + + +def _changes(data: JsonObject) -> JsonObject: + value = data.get("changes", {}) + if isinstance(value, dict): + return value + msg = "Changes must be an object of supported fields" + raise NottyApiError(msg) + + +class FeatureHandlers: + """Resolve loaded accounts and return readback after explicit service writes.""" + + def __init__(self, hass: HomeAssistant, physical: ResolveCoordinator, pet: ResolveCoordinator) -> None: + self.hass, self.physical, self.pet = hass, physical, pet + + async def profile(self, data: JsonObject) -> JsonObject: + """Read or edit an existing pet, or list its server breed choices. + + Returns: + Selected profile or breed readback. + """ + pet_id = str(identifier(data["pet_id"])) + coordinator = self.pet(self.hass, pet_id) + api = PetApi(coordinator.api) + operation = data["operation"] + if operation == OP_BREEDS: + return {"breeds": cast("JsonValue", await api.breeds())} + if operation == OP_GET: + return {"profile": profile_response(await api.profile(pet_id))} + result = await api.update(pet_id, _changes(data)) + await coordinator.async_request_refresh() + return {"profile": profile_response(result), "status": "readback_after_write"} + + async def association(self, data: JsonObject) -> JsonObject: + """List or change one pet-to-litter-box association. + + Returns: + Fresh associations; unrelated bindings are never submitted. + """ + device_id = str(identifier(data["user_device_id"])) + coordinator = self.physical(self.hass, device_id) + api = PetApi(coordinator.api) + operation = data["operation"] + if operation == OP_LIST: + rows = await api.associations(device_id) + else: + await owned_litter(coordinator.api, device_id) + rows = await api.associate( + device_id, str(identifier(data.get("pet_id"))), enabled=operation == OP_ASSOCIATE + ) + await coordinator.async_request_refresh() + return {"pets": cast("JsonValue", rows)} + + async def memo(self, data: JsonObject) -> JsonObject: + """List/read/create/edit one selected pet's text memos. + + Returns: + Memo details or fresh list readback after a write. + + Raises: + NottyApiError: If a read-only memo listing fails. + """ + pet_id = str(identifier(data["pet_id"])) + coordinator = self.pet(self.hass, pet_id) + api = MemoApi(coordinator.api) + operation = data["operation"] + if operation == OP_DETAIL: + return {"memo": await api.detail(pet_id, data.get("memo_id"))} + if operation in {OP_CREATE, OP_UPDATE}: + memo_id = identifier(data.get("memo_id")) if operation == OP_UPDATE else None + await api.save(pet_id, _changes(data), memo_id=memo_id) + await coordinator.async_request_refresh() + try: + rows = await api.list_memos(pet_id) + except NottyApiError: + if operation == OP_LIST: + raise + return {"status": "write_acknowledged_readback_failed", "clock_basis": "notty_memo_wall_clock"} + return {"memos": cast("JsonValue", rows), "clock_basis": "notty_memo_wall_clock"} + + async def notifications(self, data: JsonObject) -> JsonObject: + """Operate on account preferences, using a device only to select its account. + + Returns: + Current account-wide litter-box notification categories. + """ + coordinator = self.physical(self.hass, str(identifier(data["user_device_id"]))) + api = NotificationApi(coordinator.api) + if data["operation"] == OP_LIST: + rows = await api.categories() + else: + rows = await api.set_blocked(data.get("message_type_id"), blocked=data["operation"] == OP_BLOCK) + return {"scope": "notty_account_litter_box_categories", "categories": cast("JsonValue", rows)} + + async def statistics(self, data: JsonObject) -> JsonObject: + """Clear statistics only after explicit confirmation of irreversible deletion. + + Returns: + Server acknowledgement, followed by coordinator sensor refresh. + """ + device_id = str(identifier(data["user_device_id"])) + coordinator = self.physical(self.hass, device_id) + result = await clear_statistics(coordinator.api, device_id, confirmed=data.get("confirm_irreversible") is True) + await coordinator.async_request_refresh() + return result + + +def _validate_operation(service: str, data: JsonObject) -> None: + if service == SERVICE_CLEAR_STATISTICS: + return + operation = str(data["operation"]) + target = "pet_id" if service in {SERVICE_PET_PROFILE, SERVICE_PET_MEMO} else "user_device_id" + expected = {target, "operation"} | OPERATION_FIELDS[service][operation] + if set(data) != expected: + msg = "Fields do not match the selected NOTTY operation" + raise NottyApiError(msg) + + +def _wrap( + service: str, handler: Callable[[JsonObject], Awaitable[JsonObject]] +) -> Callable[[ServiceCall], Coroutine[None, None, JsonObject]]: + async def handle(call: ServiceCall) -> JsonObject: + """Translate API validation errors to native HA action errors. + + Returns: + The selected operation's response. + + Raises: + HomeAssistantError: If validation or the API request fails. + """ + try: + data = cast("JsonObject", call.data) + _validate_operation(service, data) + return await handler(data) + except NottyApiError as exc: + raise HomeAssistantError(str(exc)) from exc + + return handle + + +def register_feature_services(hass: HomeAssistant, physical: ResolveCoordinator, pet: ResolveCoordinator) -> None: + """Expose native action schemas and responses for the remaining litter/pet features.""" + handlers = FeatureHandlers(hass, physical, pet) + id_value = vol.Any(str, int) + changes: dict[object, object] = {vol.Optional("changes"): cast("type[dict[str, object]]", dict)} + schemas: dict[str, tuple[Callable[[JsonObject], Awaitable[JsonObject]], dict[object, object]]] = { + SERVICE_PET_PROFILE: ( + handlers.profile, + { + vol.Required("pet_id"): id_value, + vol.Required("operation"): vol.In(("get", "update", "breeds")), + **changes, + }, + ), + SERVICE_PET_ASSOCIATION: ( + handlers.association, + { + vol.Required("user_device_id"): id_value, + vol.Required("operation"): vol.In(("list", "associate", "disassociate")), + vol.Optional("pet_id"): id_value, + }, + ), + SERVICE_PET_MEMO: ( + handlers.memo, + { + vol.Required("pet_id"): id_value, + vol.Required("operation"): vol.In(("list", "detail", "create", "update")), + vol.Optional("memo_id"): id_value, + **changes, + }, + ), + SERVICE_NOTIFICATIONS: ( + handlers.notifications, + { + vol.Required("user_device_id"): id_value, + vol.Required("operation"): vol.In(("list", "block", "unblock")), + vol.Optional("message_type_id"): id_value, + }, + ), + SERVICE_CLEAR_STATISTICS: ( + handlers.statistics, + {vol.Required("user_device_id"): id_value, vol.Required("confirm_irreversible"): bool}, + ), + } + for service, (handler, schema) in schemas.items(): + if not hass.services.has_service(DOMAIN, service): + hass.services.async_register( + DOMAIN, + service, + _wrap(service, handler), + schema=vol.Schema(schema), + supports_response=SupportsResponse.OPTIONAL, + ) diff --git a/custom_components/notty/icons.json b/custom_components/notty/icons.json index 8f3c32c..172ea7d 100644 --- a/custom_components/notty/icons.json +++ b/custom_components/notty/icons.json @@ -29,6 +29,12 @@ }, "switch_dnd": { "default": "mdi:moon-waning-crescent" + }, + "pet_neutered": { + "default": "mdi:medical-bag" + }, + "notification_category": { + "default": "mdi:bell" } }, "select": { @@ -46,6 +52,9 @@ }, "auto_delay": { "default": "mdi:timer-cog-outline" + }, + "pet_sex": { + "default": "mdi:gender-male-female" } }, "time": { @@ -64,12 +73,20 @@ "text": { "cloud_alias": { "default": "mdi:form-textbox" + }, + "pet_name": { + "default": "mdi:cat" } }, "update": { "firmware": { "default": "mdi:chip" } + }, + "date": { + "pet_birthday": { + "default": "mdi:cake-variant" + } } }, "services": { @@ -81,6 +98,24 @@ }, "litter_box_schedule": { "service": "mdi:calendar-clock" + }, + "device_time_zone": { + "service": "mdi:earth" + }, + "pet_profile": { + "service": "mdi:cat" + }, + "pet_association": { + "service": "mdi:link-variant" + }, + "pet_memo": { + "service": "mdi:notebook-edit-outline" + }, + "notification_preferences": { + "service": "mdi:bell-cog" + }, + "clear_statistics": { + "service": "mdi:chart-box-outline" } } } diff --git a/custom_components/notty/manifest.json b/custom_components/notty/manifest.json index 3eda380..9d93a77 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.3.0" + "version": "0.4.0" } diff --git a/custom_components/notty/notification_switch.py b/custom_components/notty/notification_switch.py new file mode 100644 index 0000000..9352201 --- /dev/null +++ b/custom_components/notty/notification_switch.py @@ -0,0 +1,111 @@ +"""Account-level notification category switches with explicit cloud scope.""" + +from __future__ import annotations + +from homeassistant.components.switch import SwitchEntity +from homeassistant.const import EntityCategory +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.update_coordinator import CoordinatorEntity + +from custom_components.notty.api import JsonObject, NottyApiError, plan_enabled +from custom_components.notty.const import DOMAIN +from custom_components.notty.coordinator import NottyCoordinator +from custom_components.notty.device_features import NotificationApi +from custom_components.notty.models import NottyConfigEntry + + +class NottyNotificationSwitch(CoordinatorEntity[NottyCoordinator], SwitchEntity): + """One NOTTY account preference, never a Home Assistant notification toggle.""" + + _attr_has_entity_name = True + _attr_entity_category = EntityCategory.CONFIG + _attr_translation_key = "notification_category" + + def __init__(self, coordinator: NottyCoordinator, entry: NottyConfigEntry, row: JsonObject) -> None: + super().__init__(coordinator) + self.category_id = str(row["message_type_id"]) + self._attr_unique_id = f"{entry.entry_id}_notification_{self.category_id}" + self._attr_translation_placeholders = {"category": str(row.get("message_type_name") or self.category_id)} + self._attr_device_info = DeviceInfo( + identifiers={(DOMAIN, f"account_{entry.entry_id}")}, + name="NOTTY account", + manufacturer="NOTTY", + model="Cloud notification preferences", + entry_type=DeviceEntryType.SERVICE, + ) + + @property + def category(self) -> JsonObject | None: + """The latest matching category. + + Returns: + Current account record, otherwise unavailable. + """ + return next( + ( + row + for row in self.coordinator.notification_categories or [] + if str(row["message_type_id"]) == self.category_id + ), + None, + ) + + @property + def available(self) -> bool: + """Whether the account preference has a known current state. + + Returns: + True only with successful coordinator data and explicit block state. + """ + row = self.category + return super().available and row is not None and plan_enabled(row.get("blocked")) is not None + + @property + def is_on(self) -> bool | None: + """Enabled notifications correspond to the inverse cloud block flag. + + Returns: + True for unblocked, false for blocked, or unknown. + """ + row = self.category + blocked = plan_enabled(row.get("blocked")) if row is not None else None + return not blocked if blocked is not None else None + + async def _set_enabled(self, *, enabled: bool) -> None: + if not self.available: + msg = "NOTTY notification preference is currently unavailable" + raise HomeAssistantError(msg) + try: + await NotificationApi(self.coordinator.api).set_blocked(self.category_id, blocked=not enabled) + except NottyApiError as exc: + raise HomeAssistantError(str(exc)) from exc + await self.coordinator.async_request_refresh() + + async def async_turn_on(self, **_kwargs: object) -> None: + """Enable this category in the NOTTY account.""" + await self._set_enabled(enabled=True) + + async def async_turn_off(self, **_kwargs: object) -> None: + """Block this category in the NOTTY account.""" + await self._set_enabled(enabled=False) + + +def add_notification_switches(entry: NottyConfigEntry, add: AddConfigEntryEntitiesCallback) -> None: + """Discover current and later-recovered account categories once per config entry.""" + coordinator = entry.runtime_data + known: set[str] = set() + + def discover() -> None: + entities: list[NottyNotificationSwitch] = [] + for row in coordinator.notification_categories or []: + identifier = str(row["message_type_id"]) + if identifier not in known: + entities.append(NottyNotificationSwitch(coordinator, entry, row)) + known.add(identifier) + if entities: + add(entities) + + discover() + entry.async_on_unload(coordinator.async_add_listener(discover)) diff --git a/custom_components/notty/pet_api.py b/custom_components/notty/pet_api.py new file mode 100644 index 0000000..a2a6f39 --- /dev/null +++ b/custom_components/notty/pet_api.py @@ -0,0 +1,184 @@ +"""Pet profile, association and text-memo requests traced from the Android app.""" + +from __future__ import annotations + +from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError, plan_enabled +from custom_components.notty.feature_contracts import ( + FIELD_BREED, + FIELD_SEX, + identifier, + memo_payload, + object_rows, + profile_changes, + profile_payload, + require_owner, +) + + +class PetApi: + """Account-scoped profile edits with fresh ownership and binding readback.""" + + def __init__(self, api: NottyApi) -> None: + self.api = api + + async def profile(self, pet_id: str) -> JsonObject: + """Read a pet belonging to the current account, rejecting identity mismatch. + + Returns: + The fresh server profile, including current binding/ownership metadata. + + Raises: + NottyApiError: If the pet is absent or the response is invalid. + """ + selected = identifier(pet_id) + pets = await self.api.pets() + if not any(identifier(row.get("pet_id")) == selected for row in pets): + msg = "The selected pet does not belong to this NOTTY account" + raise NottyApiError(msg) + value = await self.api.request("GET", f"/pet/info/{selected}") + if not isinstance(value, dict) or identifier(value.get("pet_id")) != selected: + msg = "Pet profile readback does not match the selected pet" + raise NottyApiError(msg) + return value + + async def breeds(self) -> list[JsonObject]: + """Read the public catalog rather than inventing breed IDs. + + Returns: + Server breed IDs and names. + + Raises: + NottyApiError: If the catalog contains malformed or duplicate records. + """ + rows = object_rows(await self.api.request("GET", "/pet/breeds")) + seen: set[int] = set() + result: list[JsonObject] = [] + for row in rows: + breed_id = identifier(row.get("breed_id")) + name = row.get("breed_name") + if breed_id in seen or not isinstance(name, str) or not name.strip(): + msg = "NOTTY returned an invalid breed catalog" + raise NottyApiError(msg) + seen.add(breed_id) + result.append({"breed_id": breed_id, "breed_name": name}) + return result + + async def update(self, pet_id: str, changes: JsonObject) -> JsonObject: + """Save supported edits while preserving current images, units and all bindings. + + Returns: + Fresh profile readback; a successful write alone is not confirmation. + + """ + async with self.api.mutation_lock(f"pet:{identifier(pet_id)}"): + return await self._update(pet_id, changes) + + async def _update(self, pet_id: str, changes: JsonObject) -> JsonObject: + changes = profile_changes(changes) + current = await self.profile(pet_id) + payload = profile_payload(pet_id, current, changes) + if FIELD_BREED in changes: + match = next((row for row in await self.breeds() if row["breed_id"] == changes["breed_id"]), None) + if match is None: + msg = "Choose a breed from the current NOTTY breed catalog" + raise NottyApiError(msg) + payload["breed_name"] = match["breed_name"] + if FIELD_SEX in changes: + payload["sex_name"] = "弟弟" if changes["sex"] == 1 else "妹妹" + if all(current.get(key) == value for key, value in changes.items()): + return current + await self.api.request("POST", "/pet/save", data=payload) + try: + return await self.profile(pet_id) + except NottyApiError as exc: + msg = "Pet write was acknowledged, but profile readback failed; refresh before retrying" + raise NottyApiError(msg) from exc + + async def associations(self, device_id: str) -> list[JsonObject]: + """Read pet candidates and binding states for one selected litter box. + + Returns: + Fresh device association records. + """ + return object_rows(await self.api.request("GET", f"/device/get_associated_pets/{identifier(device_id)}")) + + async def associate(self, device_id: str, pet_id: str, *, enabled: bool) -> list[JsonObject]: + """Change exactly one known association, preserving every other pet binding. + + Returns: + Fresh association readback. + + """ + async with self.api.mutation_lock(f"pet:{identifier(pet_id)}"): + return await self._associate(device_id, pet_id, enabled=enabled) + + async def _associate(self, device_id: str, pet_id: str, *, enabled: bool) -> list[JsonObject]: + current = await self.profile(pet_id) + require_owner(current) + selected = identifier(pet_id) + rows = await self.associations(device_id) + matches = [row for row in rows if identifier(row.get("pet_id")) == selected] + if len(matches) != 1 or plan_enabled(matches[0].get("is_associated")) is None: + msg = "The pet must have a known association state for this litter box" + raise NottyApiError(msg) + if plan_enabled(matches[0]["is_associated"]) is enabled: + return rows + await self.api.request( + "POST", + "/device/associate_pet", + data={"user_device_id": identifier(device_id), "pet_id": selected, "associate": enabled}, + ) + return await self.associations(device_id) + + +class MemoApi: + """Explicit pet-scoped text memos; no attachment upload or pet deletion.""" + + def __init__(self, api: NottyApi) -> None: + self.api = api + self.pets = PetApi(api) + + async def list_memos(self, pet_id: str) -> list[JsonObject]: + """List fresh memos for a pet in the account. + + Returns: + Server memo records scoped to the selected pet. + """ + await self.pets.profile(pet_id) + return object_rows(await self.api.request("GET", f"/pet/memos/{identifier(pet_id)}")) + + async def detail(self, pet_id: str, memo_id: JsonValue) -> JsonObject: + """Require fresh pet membership before retrieving a memo by its global ID. + + Returns: + The matching memo detail. + + Raises: + NottyApiError: If the ID belongs to another pet or detail is inconsistent. + """ + selected = identifier(memo_id) + rows = await self.list_memos(pet_id) + if not any(identifier(row.get("memo_id")) == selected for row in rows): + msg = "The memo does not belong to the selected pet" + raise NottyApiError(msg) + value = await self.api.request("GET", f"/pet/memo_detail/{selected}") + if not isinstance(value, dict) or identifier(value.get("memo_id")) != selected: + msg = "Memo detail identity mismatch" + raise NottyApiError(msg) + if value.get("pet_id") is not None and identifier(value["pet_id"]) != identifier(pet_id): + msg = "Memo detail belongs to another pet" + raise NottyApiError(msg) + return value + + async def save(self, pet_id: str, changes: JsonObject, *, memo_id: JsonValue = None) -> JsonValue: + """Create or edit an owner's memo using the app's complete text fields. + + Returns: + Server acknowledgement; callers refresh the memo list after writing. + """ + require_owner(await self.pets.profile(pet_id)) + create = memo_id is None + current: JsonObject = {"remind": False, "expired": False} if create else await self.detail(pet_id, memo_id) + payload = memo_payload(pet_id, current, changes, create=create) + path = "/pet/add_memo" if create else "/pet/edit_memo" + return await self.api.request("POST", path, data=payload) diff --git a/custom_components/notty/pet_entities.py b/custom_components/notty/pet_entities.py new file mode 100644 index 0000000..f60d57e --- /dev/null +++ b/custom_components/notty/pet_entities.py @@ -0,0 +1,223 @@ +"""Owner-only pet profile controls with cloud readback and stable device identity.""" + +from __future__ import annotations + +from datetime import date + +from homeassistant.components.date import DateEntity +from homeassistant.components.select import SelectEntity +from homeassistant.components.switch import SwitchEntity +from homeassistant.components.text import TextEntity, TextMode +from homeassistant.const import EntityCategory +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from custom_components.notty.api import JsonObject, NottyApiError +from custom_components.notty.entity import NottyEntity +from custom_components.notty.feature_contracts import MAX_PET_NAME_UNITS, true_state +from custom_components.notty.models import NottyConfigEntry +from custom_components.notty.pet_api import PetApi + +SOURCE_PET = "pet" +MAX_STATE_LENGTH = 255 +PET_SEX_OPTIONS = {1: "male", 2: "female"} + + +class NottyPetProfileEntity(NottyEntity): + """Common ownership, profile lookup, mutation and registry-name handling.""" + + _attr_entity_category = EntityCategory.CONFIG + profile_key: str + + @property + def profile(self) -> JsonObject: + """Fresh detailed fields before falling back to discovery metadata. + + Returns: + Current pet data, never a modified local copy after a write. + """ + related = self.block["info"].get("_notty_related") + detail = related.get("info") if isinstance(related, dict) else None + return {**self.block["device"], **(detail if isinstance(detail, dict) else {})} + + @property + def unique_id(self) -> str: + """Keep profile controls tied to the existing pet identity. + + Returns: + A stable ID independent of pet names or associations. + """ + return f"{self.device_id}_profile_{self.profile_key}" + + @property + def available(self) -> bool: + """Permit profile changes only for current account-owned pets. + + Returns: + Whether the current pet is present and editable. + """ + return super().available and true_state(self.profile.get("is_owner")) + + async def apply(self, changes: JsonObject) -> None: + """Use fresh ownership/binding validation and then poll authoritative state. + + Raises: + HomeAssistantError: If a shared/unavailable pet or API error prevents editing. + """ + if not self.available: + msg = "Only a current NOTTY pet owner can change this profile" + raise HomeAssistantError(msg) + try: + await PetApi(self.coordinator.api).update(str(self.profile.get("pet_id")), changes) + except NottyApiError as exc: + raise HomeAssistantError(str(exc)) from exc + await self.coordinator.async_request_refresh() + + def _handle_coordinator_update(self) -> None: + name = self.profile.get("name") + if self.available and isinstance(name, str) and name.strip(): + self.update_device_name(name) + super()._handle_coordinator_update() + + +class NottyPetName(NottyPetProfileEntity, TextEntity): + """Edit the pet's cloud name independently from HA's display-name override.""" + + profile_key = "name" + _attr_name = "Name" + _attr_translation_key = "pet_name" + _attr_mode = TextMode.TEXT + _attr_native_min = 1 + + @property + def native_value(self) -> str | None: + """The exact reported pet name. + + Returns: + A printable name, otherwise unknown. + """ + value = self.profile.get("name") + return value if isinstance(value, str) and value.isprintable() and 0 < len(value) <= MAX_STATE_LENGTH else None + + @property + def native_max(self) -> int: + """Accommodate longer existing readback without relaxing write validation. + + Returns: + The UI display bound; API writes validate UTF-16 units explicitly. + """ + return max(MAX_PET_NAME_UNITS, len(self.native_value or "")) + + async def async_set_value(self, value: str) -> None: + """Save a name through the full profile-preserving request.""" + await self.apply({"name": value}) + + +class NottyPetSex(NottyPetProfileEntity, SelectEntity): + """Select the app's established male/female values.""" + + profile_key = "sex" + _attr_name = "Sex" + _attr_translation_key = "pet_sex" + + @property + def options(self) -> list[str]: + """Supported pet sex choices. + + Returns: + Only the app's established male and female values. + """ + return list(PET_SEX_OPTIONS.values()) + + @property + def current_option(self) -> str | None: + """Only established sex enums. + + Returns: + The selected sex, or unknown for unsupported values. + """ + value = self.profile.get("sex") + return PET_SEX_OPTIONS.get(value) if type(value) is int else None + + async def async_select_option(self, option: str) -> None: + """Save the selected app enum. + + Raises: + HomeAssistantError: If an unsupported option is supplied. + """ + values = {label: value for value, label in PET_SEX_OPTIONS.items()} + if option not in values: + msg = "Choose a supported pet sex" + raise HomeAssistantError(msg) + await self.apply({"sex": values[option]}) + + +class NottyPetNeutered(NottyPetProfileEntity, SwitchEntity): + """Edit the app's nullable neutered-state Boolean.""" + + profile_key = "is_sterilization" + _attr_name = "Neutered" + _attr_translation_key = "pet_neutered" + + @property + def is_on(self) -> bool | None: + """Boolean readback, keeping unknown separate from false. + + Returns: + Reported neutered state, or unknown. + """ + value = self.profile.get("is_sterilization") + return value if type(value) is bool else None + + async def async_turn_on(self, **_kwargs: object) -> None: + """Record neutered state without changing any device setting.""" + await self.apply({"is_sterilization": True}) + + async def async_turn_off(self, **_kwargs: object) -> None: + """Record non-neutered state without changing any device setting.""" + await self.apply({"is_sterilization": False}) + + +class NottyPetBirthday(NottyPetProfileEntity, DateEntity): + """Edit a calendar date without timezone conversion.""" + + profile_key = "birthday" + _attr_name = "Birthday" + _attr_translation_key = "pet_birthday" + + @property + def native_value(self) -> date | None: + """A valid birthday calendar date. + + Returns: + Date readback, otherwise unknown. + """ + value = self.profile.get("birthday") + try: + return date.fromisoformat(value) if isinstance(value, str) else None + except ValueError: + return None + + async def async_set_value(self, value: date) -> None: + """Save the date without shifting it across local midnight.""" + await self.apply({"birthday": value.isoformat()}) + + +def add_pet_entities( + entry: NottyConfigEntry, add: AddConfigEntryEntitiesCallback, factory: type[NottyPetProfileEntity] +) -> None: + """Discover pet profile controls initially and for pets found on later polls.""" + coordinator = entry.runtime_data + known: set[str] = set() + + def discover() -> None: + entities: list[NottyPetProfileEntity] = [] + for device_id, block in coordinator.data.items(): + if device_id not in known and block["device"].get("_notty_source") == SOURCE_PET: + entities.append(factory(coordinator, device_id, block["device"])) + known.add(device_id) + if entities: + add(entities) + + discover() + entry.async_on_unload(coordinator.async_add_listener(discover)) diff --git a/custom_components/notty/select.py b/custom_components/notty/select.py index c9f52ec..467c68a 100644 --- a/custom_components/notty/select.py +++ b/custom_components/notty/select.py @@ -9,10 +9,11 @@ from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from custom_components.notty.api import LITTER_MODES, JsonValue +from custom_components.notty.api import LITTER_MODES, SCREEN_LANGUAGES, JsonValue from custom_components.notty.coordinator import NottyCoordinator from custom_components.notty.entity import NottyEntity, value_from_block from custom_components.notty.models import DeviceBlock, DeviceData, NottyConfigEntry +from custom_components.notty.pet_entities import NottyPetSex, add_pet_entities DEVICE_TYPE_LITTER_BOX = "litter_box" SOURCE_PET = "pet" @@ -51,7 +52,12 @@ class NottySelectDescription(SelectEntityDescription): fallback_key="lb_mode", ), NottySelectDescription( - key="language", name="Screen Language", action="set_language", field="language", value_options={1: "English"} + key="language", + name="Screen Language", + action="set_language", + field="language", + value_options=SCREEN_LANGUAGES, + entity_category=EntityCategory.CONFIG, ), NottySelectDescription( key="default_remaining_days", @@ -78,6 +84,7 @@ async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant req ) -> None: """Async setup entry.""" coordinator = entry.runtime_data + add_pet_entities(entry, async_add_entities, NottyPetSex) entities: list[NottySelect] = [] for device_id, block in coordinator.data.items(): if block.get("type") != DEVICE_TYPE_LITTER_BOX: @@ -161,9 +168,14 @@ def available(self) -> bool: Returns: bool: The resulting available. """ - if self.entity_description.key == FIELD_LITTER_INTERVAL: - state = value_from_block(self.block, FIELD_LITTER_ENABLED) - cycle = _as_int(value_from_block(self.block, FIELD_LITTER_INTERVAL)) + if self.entity_description.key in {FIELD_LITTER_INTERVAL, "garbage_bag_cycle_time"}: + enabled_field = ( + FIELD_LITTER_ENABLED + if self.entity_description.key == FIELD_LITTER_INTERVAL + else "open_garbagebag_remind" + ) + state = value_from_block(self.block, enabled_field) + cycle = _as_int(value_from_block(self.block, self.entity_description.key)) return ( super().available and _litter_reminder_enabled(state) @@ -200,11 +212,8 @@ async def async_select_option(self, option: str) -> None: if self.entity_description.key == FIELD_AUTO_DELAY and not self.available: msg = "NOTTY cleaning delay can only be changed in Auto mode with current device data" raise HomeAssistantError(msg) - if self.entity_description.key == FIELD_LITTER_INTERVAL and not self.available: - msg = "NOTTY litter interval changes require an enabled reminder and a valid configured cycle" - raise HomeAssistantError(msg) - if self.entity_description.key == FIELD_MODE: - msg = "NOTTY mode changes remain disabled pending schedule prerequisites and live validation" + if self.entity_description.key in {FIELD_LITTER_INTERVAL, "garbage_bag_cycle_time"} and not self.available: + msg = "NOTTY interval changes require an enabled reminder and a valid configured cycle" raise HomeAssistantError(msg) reverse = {label: value for value, label in self.entity_description.value_options.items()} if option not in reverse: @@ -212,7 +221,7 @@ async def async_select_option(self, option: str) -> None: msg = "NOTTY cleaning delay must be between 1 and 15 minutes" raise HomeAssistantError(msg) return - if self.entity_description.key == FIELD_LITTER_INTERVAL and option == self.current_option: + if option == self.current_option: # An identical interval might reset an elapsed countdown; this has not been verified. return await self.coordinator.api.litter_action( diff --git a/custom_components/notty/services.yaml b/custom_components/notty/services.yaml index f148cb4..c951643 100644 --- a/custom_components/notty/services.yaml +++ b/custom_components/notty/services.yaml @@ -1,27 +1,29 @@ device_time_zone: name: Device time zone - description: List server-supported zones or explicitly change the device zone. Changes may reinterpret cleaning and DND schedule clocks. Catalog offsets describe standard time, not the current DST offset. Inspect the before/after response and verify in the app. + description: List server-supported zones or explicitly change the device zone. Changes may reinterpret cleaning and DND + schedule clocks. Catalog offsets describe standard time, not the current DST offset. Inspect the before/after response + and verify in the app. fields: user_device_id: required: true selector: - text: + text: null operation: required: true selector: select: options: - - list - - change + - list + - change catalog_id: - description: Exact server ID from the list response, such as W. Europe Standard Time. Do not substitute an IANA name or numeric offset. + description: Exact server ID from the list response, such as W. Europe Standard Time. Do not substitute an IANA name + or numeric offset. selector: - text: + text: null confirm_schedule_change: description: Required true for change, acknowledging that scheduled operations use the selected device local time. selector: - boolean: - + boolean: null litter_box_one_key: name: Litter box one-key action description: Run one of the NOTTY app one-key litter box actions. @@ -30,77 +32,178 @@ litter_box_one_key: name: User device ID required: true selector: - text: + text: null one_key: name: One-key action required: true selector: select: options: - - clean - - level - - empty - + - clean + - level + - empty litter_box_action: name: Litter box action - description: Call a NOTTY litter box action or setting. The litter reminder interval action (set_litter_reminder_days) is available only for an enabled reminder and a changed valid cycle (5–30 days). Reset and trash-bag interval actions remain disabled. + description: Run a supported litter-box command or setting. Scheduled mode requires an enabled plan. Reminder resets use + action 3 with the configured cycle. fields: user_device_id: name: User device ID required: true selector: - text: + text: null action: name: Action required: true selector: select: options: - - one_key - - set_key - - reset_litter_reminder - - reset_garbage_bag_reminder - - set_litter_reminder_days - - set_garbage_bag_reminder_days - - set_dnd - - set_language - - reset_device_weight - - horizontal_calibration + - one_key + - set_mode + - set_key + - reset_litter_reminder + - reset_garbage_bag_reminder + - set_litter_reminder_days + - set_garbage_bag_reminder_days + - set_dnd + - set_language + - reset_device_weight + - horizontal_calibration data: name: Data required: false selector: - object: - + object: null litter_box_schedule: name: Litter box cleaning schedules - description: List, create, update, enable, disable or delete a NOTTY cleaning plan. Times use the NOTTY schedule clock in HH:MM format, with no timezone conversion. Creating or enabling a plan may schedule cleaning; cleaning mode is left unchanged. + description: List, create, update, enable, disable or delete a NOTTY cleaning plan. Times use the NOTTY schedule clock in + HH:MM format, with no timezone conversion. Creating or enabling a plan may schedule cleaning; cleaning mode is left unchanged. fields: user_device_id: name: Physical user device ID required: true selector: - text: + text: null operation: name: Operation required: true selector: select: options: - - list - - create - - update - - enable - - disable - - delete + - list + - create + - update + - enable + - disable + - delete plan_id: name: Plan ID description: Required for update, enable, disable and delete. Obtain the exact ID with the list operation. selector: - text: + text: null time: name: NOTTY schedule clock - description: Required for create and update. Enter HH:MM as shown by the NOTTY schedule clock; do not use a timestamp or assume Home Assistant timezone conversion. - example: "06:30" + description: Required for create and update. Enter HH:MM as shown by the NOTTY schedule clock; do not use a timestamp + or assume Home Assistant timezone conversion. + example: 06:30 selector: - text: + text: null +pet_profile: + name: Pet profile + description: 'Read or edit an existing owned pet. Changes: name, birthday (YYYY-MM-DD), sex (1 male, 2 female), is_sterilization + (Boolean), breed_id from the breed catalog. Preserves weight, units, images and all bindings.' + fields: + pet_id: &id001 + name: Pet ID + required: true + selector: + text: null + operation: + name: Operation + required: true + selector: + select: + options: + - get + - update + - breeds + changes: &id002 + name: Changes + selector: + object: null +pet_association: + name: Pet association + description: List or associate/disassociate one owned pet with an owned litter box. Preserves unrelated pets and bindings. + fields: + user_device_id: &id003 + name: Physical litter-box ID + required: true + selector: + text: null + operation: + name: Operation + required: true + selector: + select: + options: + - list + - associate + - disassociate + pet_id: + name: Pet ID + required: false + selector: + text: null +pet_memo: + name: Pet memo + description: 'List/read/create/edit pet text memos. Writes require ownership. Changes: title, content, date (YYYY-MM-DD + HH:MM in the NOTTY memo clock), remind (Boolean). Attachments are unsupported.' + fields: + pet_id: *id001 + operation: + name: Operation + required: true + selector: + select: + options: + - list + - detail + - create + - update + memo_id: + name: Memo ID + required: false + selector: + text: null + changes: *id002 +notification_preferences: + name: NOTTY notification preferences + description: Read or block/unblock account-wide litter-box notification categories. The physical box selects the account. + These cloud preferences are separate from HA notifications. + fields: + user_device_id: *id003 + operation: + name: Operation + required: true + selector: + select: + options: + - list + - block + - unblock + message_type_id: + name: Notification category ID + required: false + selector: + text: null +clear_statistics: + name: Clear device statistics + description: Permanently delete the selected litter box’s cloud statistics. This cannot be undone. Sensors refresh afterward; + exact counter/history effects require owner validation. + fields: + user_device_id: *id003 + confirm_irreversible: + name: Confirm irreversible deletion + required: true + selector: + boolean: null diff --git a/custom_components/notty/strings.json b/custom_components/notty/strings.json index c97ae74..d0832ef 100644 --- a/custom_components/notty/strings.json +++ b/custom_components/notty/strings.json @@ -64,6 +64,12 @@ }, "open_garbagebag_remind": { "name": "Trash bag reminder" + }, + "pet_neutered": { + "name": "Neutered" + }, + "notification_category": { + "name": "{category} notifications" } }, "select": { @@ -81,6 +87,13 @@ }, "auto_delay": { "name": "Automatic cleaning delay" + }, + "pet_sex": { + "name": "Sex", + "state": { + "male": "Male", + "female": "Female" + } } }, "time": { @@ -99,12 +112,20 @@ "text": { "cloud_alias": { "name": "Cloud name" + }, + "pet_name": { + "name": "Name" } }, "update": { "firmware": { "name": "Firmware" } + }, + "date": { + "pet_birthday": { + "name": "Birthday" + } } }, "services": { @@ -154,6 +175,81 @@ "description": "Required for create and update. Use HH:MM as shown by the NOTTY schedule clock, without timezone conversion." } } + }, + "pet_profile": { + "name": "Pet profile", + "description": "Read or edit an existing owned pet. Changes: name, birthday (YYYY-MM-DD), sex (1 male, 2 female), is_sterilization (Boolean), breed_id from the breed catalog. Preserves weight, units, images and all bindings.", + "fields": { + "pet_id": { + "name": "Pet ID" + }, + "operation": { + "name": "Operation" + }, + "changes": { + "name": "Changes" + } + } + }, + "pet_association": { + "name": "Pet association", + "description": "List or associate/disassociate one owned pet with an owned litter box. Preserves unrelated pets and bindings.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "operation": { + "name": "Operation" + }, + "pet_id": { + "name": "Pet ID" + } + } + }, + "pet_memo": { + "name": "Pet memo", + "description": "List/read/create/edit pet text memos. Writes require ownership. Changes: title, content, date (YYYY-MM-DD HH:MM in the NOTTY memo clock), remind (Boolean). Attachments are unsupported.", + "fields": { + "pet_id": { + "name": "Pet ID" + }, + "operation": { + "name": "Operation" + }, + "memo_id": { + "name": "Memo ID" + }, + "changes": { + "name": "Changes" + } + } + }, + "notification_preferences": { + "name": "NOTTY notification preferences", + "description": "Read or block/unblock account-wide litter-box notification categories. The physical box selects the account. These cloud preferences are separate from HA notifications.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "operation": { + "name": "Operation" + }, + "message_type_id": { + "name": "Notification category ID" + } + } + }, + "clear_statistics": { + "name": "Clear device statistics", + "description": "Permanently delete the selected litter box’s cloud statistics. This cannot be undone. Sensors refresh afterward; exact counter/history effects require owner validation.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "confirm_irreversible": { + "name": "Confirm irreversible deletion" + } + } } } } diff --git a/custom_components/notty/switch.py b/custom_components/notty/switch.py index 5edc3fd..1556cce 100644 --- a/custom_components/notty/switch.py +++ b/custom_components/notty/switch.py @@ -13,6 +13,8 @@ from custom_components.notty.coordinator import NottyCoordinator from custom_components.notty.entity import NottyEntity, merged_device_data, value_from_block from custom_components.notty.models import DeviceData, NottyConfigEntry +from custom_components.notty.notification_switch import add_notification_switches +from custom_components.notty.pet_entities import NottyPetNeutered, add_pet_entities DEVICE_TYPE_LITTER_BOX = "litter_box" SOURCE_PET = "pet" @@ -56,6 +58,8 @@ async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant req ) -> None: """Async setup entry.""" coordinator = entry.runtime_data + add_notification_switches(entry, async_add_entities) + add_pet_entities(entry, async_add_entities, NottyPetNeutered) entities: list[NottySwitch] = [] for device_id, block in coordinator.data.items(): if block.get("type") != DEVICE_TYPE_LITTER_BOX: diff --git a/custom_components/notty/text.py b/custom_components/notty/text.py index 702a637..9030ff4 100644 --- a/custom_components/notty/text.py +++ b/custom_components/notty/text.py @@ -14,6 +14,7 @@ from custom_components.notty.coordinator import NottyCoordinator from custom_components.notty.entity import NottyEntity from custom_components.notty.models import DeviceBlock, DeviceData, NottyConfigEntry +from custom_components.notty.pet_entities import NottyPetName, add_pet_entities DEVICE_TYPE_LITTER_BOX = "litter_box" SOURCE_PET = "pet" @@ -37,6 +38,7 @@ async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant req ) -> None: """Expose cloud-name configuration only for physical litter boxes.""" coordinator = entry.runtime_data + add_pet_entities(entry, async_add_entities, NottyPetName) async_add_entities( NottyCloudAlias(coordinator, device_id, block["device"]) for device_id, block in coordinator.data.items() diff --git a/custom_components/notty/translations/en.json b/custom_components/notty/translations/en.json index c97ae74..d0832ef 100644 --- a/custom_components/notty/translations/en.json +++ b/custom_components/notty/translations/en.json @@ -64,6 +64,12 @@ }, "open_garbagebag_remind": { "name": "Trash bag reminder" + }, + "pet_neutered": { + "name": "Neutered" + }, + "notification_category": { + "name": "{category} notifications" } }, "select": { @@ -81,6 +87,13 @@ }, "auto_delay": { "name": "Automatic cleaning delay" + }, + "pet_sex": { + "name": "Sex", + "state": { + "male": "Male", + "female": "Female" + } } }, "time": { @@ -99,12 +112,20 @@ "text": { "cloud_alias": { "name": "Cloud name" + }, + "pet_name": { + "name": "Name" } }, "update": { "firmware": { "name": "Firmware" } + }, + "date": { + "pet_birthday": { + "name": "Birthday" + } } }, "services": { @@ -154,6 +175,81 @@ "description": "Required for create and update. Use HH:MM as shown by the NOTTY schedule clock, without timezone conversion." } } + }, + "pet_profile": { + "name": "Pet profile", + "description": "Read or edit an existing owned pet. Changes: name, birthday (YYYY-MM-DD), sex (1 male, 2 female), is_sterilization (Boolean), breed_id from the breed catalog. Preserves weight, units, images and all bindings.", + "fields": { + "pet_id": { + "name": "Pet ID" + }, + "operation": { + "name": "Operation" + }, + "changes": { + "name": "Changes" + } + } + }, + "pet_association": { + "name": "Pet association", + "description": "List or associate/disassociate one owned pet with an owned litter box. Preserves unrelated pets and bindings.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "operation": { + "name": "Operation" + }, + "pet_id": { + "name": "Pet ID" + } + } + }, + "pet_memo": { + "name": "Pet memo", + "description": "List/read/create/edit pet text memos. Writes require ownership. Changes: title, content, date (YYYY-MM-DD HH:MM in the NOTTY memo clock), remind (Boolean). Attachments are unsupported.", + "fields": { + "pet_id": { + "name": "Pet ID" + }, + "operation": { + "name": "Operation" + }, + "memo_id": { + "name": "Memo ID" + }, + "changes": { + "name": "Changes" + } + } + }, + "notification_preferences": { + "name": "NOTTY notification preferences", + "description": "Read or block/unblock account-wide litter-box notification categories. The physical box selects the account. These cloud preferences are separate from HA notifications.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "operation": { + "name": "Operation" + }, + "message_type_id": { + "name": "Notification category ID" + } + } + }, + "clear_statistics": { + "name": "Clear device statistics", + "description": "Permanently delete the selected litter box’s cloud statistics. This cannot be undone. Sensors refresh afterward; exact counter/history effects require owner validation.", + "fields": { + "user_device_id": { + "name": "Physical litter-box ID" + }, + "confirm_irreversible": { + "name": "Confirm irreversible deletion" + } + } } } } diff --git a/custom_components/notty/translations/nl.json b/custom_components/notty/translations/nl.json index e489150..ea9a3e4 100644 --- a/custom_components/notty/translations/nl.json +++ b/custom_components/notty/translations/nl.json @@ -32,6 +32,13 @@ "select": { "auto_delay": { "name": "Automatische reinigingsvertraging" + }, + "pet_sex": { + "name": "Geslacht", + "state": { + "male": "Mannetje", + "female": "Vrouwtje" + } } }, "switch": { @@ -40,17 +47,31 @@ }, "open_garbagebag_remind": { "name": "Herinnering afvalzak vervangen" + }, + "pet_neutered": { + "name": "Gecastreerd" + }, + "notification_category": { + "name": "{category}-meldingen" } }, "text": { "cloud_alias": { "name": "Cloudnaam" + }, + "pet_name": { + "name": "Naam" } }, "update": { "firmware": { "name": "Firmware" } + }, + "date": { + "pet_birthday": { + "name": "Geboortedatum" + } } }, "services": { @@ -73,6 +94,81 @@ "description": "Vereist voor aanmaken en wijzigen. Gebruik HH:MM volgens de NOTTY-planklok, zonder tijdzoneconversie." } } + }, + "pet_profile": { + "name": "Huisdierprofiel", + "description": "Bekijk of wijzig een bestaand huisdier waarvan je eigenaar bent. Ondersteunde velden: name, birthday, sex, is_sterilization en breed_id. Gewicht, eenheden, afbeeldingen en koppelingen blijven behouden.", + "fields": { + "pet_id": { + "name": "Huisdier-ID" + }, + "operation": { + "name": "Bewerking" + }, + "changes": { + "name": "Wijzigingen" + } + } + }, + "pet_association": { + "name": "Huisdier koppelen", + "description": "Bekijk, koppel of ontkoppel één huisdier van een kattenbak waarvan je eigenaar bent. Andere koppelingen blijven behouden.", + "fields": { + "user_device_id": { + "name": "Fysiek kattenbak-ID" + }, + "operation": { + "name": "Bewerking" + }, + "pet_id": { + "name": "Huisdier-ID" + } + } + }, + "pet_memo": { + "name": "Huisdiernotitie", + "description": "Bekijk, maak of wijzig tekstnotities. Wijzigen vereist eigenaarschap. Velden: title, content, date (YYYY-MM-DD HH:MM in de NOTTY-notitieklok) en remind (booleaans).", + "fields": { + "pet_id": { + "name": "Huisdier-ID" + }, + "operation": { + "name": "Bewerking" + }, + "memo_id": { + "name": "Notitie-ID" + }, + "changes": { + "name": "Wijzigingen" + } + } + }, + "notification_preferences": { + "name": "NOTTY-meldingsvoorkeuren", + "description": "Bekijk of blokkeer meldingscategorieën voor alle kattenbakken van dit NOTTY-account. De kattenbak selecteert het account. Dit zijn geen Home Assistant-meldingen.", + "fields": { + "user_device_id": { + "name": "Fysiek kattenbak-ID" + }, + "operation": { + "name": "Bewerking" + }, + "message_type_id": { + "name": "Meldingscategorie-ID" + } + } + }, + "clear_statistics": { + "name": "Apparaatstatistieken wissen", + "description": "Verwijder definitief de cloudstatistieken van de gekozen kattenbak. Dit kan niet ongedaan worden gemaakt. Sensoren worden daarna vernieuwd.", + "fields": { + "user_device_id": { + "name": "Fysiek kattenbak-ID" + }, + "confirm_irreversible": { + "name": "Onomkeerbaar wissen bevestigen" + } + } } } } diff --git a/custom_components/notty/update.py b/custom_components/notty/update.py index ff46aa9..79e31bf 100644 --- a/custom_components/notty/update.py +++ b/custom_components/notty/update.py @@ -1,4 +1,4 @@ -"""Read-only firmware availability from the NOTTY upgrade-check response.""" +"""Firmware availability and explicit installation of the current offered task.""" from __future__ import annotations @@ -7,10 +7,12 @@ from homeassistant.components.update import UpdateDeviceClass, UpdateEntity, UpdateEntityFeature from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from custom_components.notty.api import JsonObject, JsonValue +from custom_components.notty.api import JsonObject, JsonValue, NottyApiError from custom_components.notty.coordinator import NottyCoordinator +from custom_components.notty.device_features import FIRMWARE_IDLE_STATUSES, FirmwareApi, firmware_task_id from custom_components.notty.entity import NottyEntity, value_from_block from custom_components.notty.models import DeviceBlock, DeviceData, NottyConfigEntry @@ -72,17 +74,86 @@ def discover() -> None: class NottyFirmwareUpdate(NottyEntity, UpdateEntity): - """Report upgrade availability without offering installation or guessed progress.""" + """Install a fresh eligible task without claiming measured percentage progress.""" _attr_translation_key = "firmware" _attr_name = "Firmware" _attr_device_class = UpdateDeviceClass.FIRMWARE _attr_entity_category = EntityCategory.DIAGNOSTIC - _attr_supported_features = UpdateEntityFeature(0) def __init__(self, coordinator: NottyCoordinator, device_id: str, device: DeviceData) -> None: super().__init__(coordinator, device_id, device) self._attr_unique_id = f"{device_id}_firmware" + self._requested_version: str | None = None + self._installing = False + + @property + def supported_features(self) -> UpdateEntityFeature: + """Expose installation only when cached metadata contains an eligible task. + + Returns: + Full notes, plus install/progress when a current task is available. + """ + features = UpdateEntityFeature.RELEASE_NOTES + metadata = firmware_data(self.block) + status = metadata.get("task_status") + if ( + firmware_task_id(metadata.get("task_id")) + and isinstance(status, str) + and status in FIRMWARE_IDLE_STATUSES + and self.latest_version != self.installed_version + and self.available + ): + features |= UpdateEntityFeature.INSTALL | UpdateEntityFeature.PROGRESS + return features + + @property + def in_progress(self) -> bool | None: + """Track this HA-requested target until installed-version readback or failure. + + Returns: + Boolean progress, unknown when unavailable; never a fabricated percentage. + """ + if not self.available: + return None + if self._installing: + return True + if self._requested_version is None: + status = firmware_data(self.block).get("task_status") + 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"}) + + 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. + + Raises: + HomeAssistantError: If unavailable, already running, backup requested or the API rejects the task. + """ + if backup or not self.available or self.in_progress: + 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) + except NottyApiError as exc: + raise HomeAssistantError(str(exc)) from exc + finally: + self._installing = False + self.async_write_ha_state() + await self.coordinator.async_request_refresh() + + async def async_release_notes(self) -> str | None: + """Return the complete already-fetched firmware description. + + Returns: + Full cloud notes without an external URL request. + """ + value = firmware_data(self.block).get("firmware_desc") + return value if isinstance(value, str) else None @property def installed_version(self) -> str | None: diff --git a/docs/apk-contracts.md b/docs/apk-contracts.md index 9b12f4c..7b8574c 100644 --- a/docs/apk-contracts.md +++ b/docs/apk-contracts.md @@ -223,12 +223,7 @@ with a supplied, validated `cycle_time` in the 5–30 day range. Only Selecting the existing interval does not write, since the effect of an unchanged-cycle action 3 on a partially elapsed countdown is unverified. -`reset_litter_reminder`, `reset_garbage_bag_reminder`, and -`set_garbage_bag_reminder_days` remain **blocked at the API -boundary**, including their HA reset buttons, the trash-bag interval -selector and generic service. The original `action=2` assumption -disabled reminders, and bag action 3 has not been tested live. - +Further static tracing of the Reset label in `SettingController` (`0xcccb30`, action insertion `0xcccc68`) establishes action **3** with the configured cycle for both reminder types. Reset buttons and the trash-bag interval selector now use this contract, with fresh enabled-state/cycle validation. Reset must retain the existing cycle; interval changes skip same-value writes. Same-cycle reset and trash-bag action 3 have **not** been exercised live. The original action-2 reset assumption remains incorrect. See [additional APK evidence](apk-pet-maintenance.md). ## Verification boundary diff --git a/docs/apk-firmware.md b/docs/apk-firmware.md index 9bed94e..a09e3ff 100644 --- a/docs/apk-firmware.md +++ b/docs/apk-firmware.md @@ -37,9 +37,9 @@ explicit offline flags or missing/malformed metadata. It reads the current raw upgrade response rather than stale flattened version summaries. Release notes are summarized to Home Assistant's 255-character limit. Only raw `task_status` is added as a custom attribute; task IDs and arbitrary backend fields are not -copied into the entity. Installation and progress features are not advertised. +copied into the entity. Installation eligibility is computed from current metadata; full notes are exposed in the update dialog. -## Confirmation request traced, but not enabled +## Explicit confirmation of a fresh task `confirmUpdate` (`0xcc5264`) builds only `task_id` (`0xcc52f0`) and `user_device_id` (`0xcc5314`), then POSTs `/device/confirm_upgrade` at `0xcc5338`. @@ -47,8 +47,7 @@ Closure `0xcc548c` gets the current task observable; `0xcc5224` boxes the physic ID as an integer. The success callback sets an app-local busy flag at `0xcc53e4`. This is not independent evidence of a completed installation. The task-ID type, current-task eligibility, supported models and behavior during failures still -need live verification. The unchecked generic `confirm_upgrade` API action has -been removed; the firmware entity never invokes installation. +need live verification. The unchecked generic `confirm_upgrade` API action remains removed. The update entity supports an explicit install after fresh owned-device and offered-task checks, preserving the server task ID type and using an integer physical ID. An absent/busy/unknown task or a requested version different from the offer is rejected. No automatic installation or request replay is implemented. ## Progress is a separate event flow @@ -71,8 +70,7 @@ version. Later version readback remains authoritative. Synthetic tests cover version availability, explicit empty versus missing targets, opaque version labels, task failures/unknown states, metadata loss/recovery, late -discovery, offline devices, lifecycle, bounded notes and blocked installation. +discovery, offline devices, lifecycle, bounded notes, exact confirmation payloads and rejected absent/busy/unknown tasks. 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, installation -and progress work after their contracts are established. +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. diff --git a/docs/apk-pet-maintenance.md b/docs/apk-pet-maintenance.md new file mode 100644 index 0000000..2190543 --- /dev/null +++ b/docs/apk-pet-maintenance.md @@ -0,0 +1,48 @@ +# Pet, account and maintenance request evidence + +Source: NOTTY Smart Pet 1.1.30+76, SHA-256 +`3b6dc21037f2802e92233ecd9f685e76b03a79afa2d82dd52a5dfcd689a18e6a`. +Addresses below refer to local Blutter ARM64 disassembly. The APK, decoded +sources, account captures and session credentials remain ignored. + +| Feature | Caller / address | Contract | +| --- | --- | --- | +| Reminder Reset | `SettingController`, Reset label closure `0xcccb30`, action insertion `0xcccc68` | Label selection produces integer action 3 (Dart tagged 6); configured cycle is retained. Disable is action 2. | +| Screen language | `SettingController::setLanguage`, `0xcd32a0`–`0xcd33b0`, field `0xcd3430`, POST `0xcd3454` | `/device/litter_box/set_language`, language 0 Simplified Chinese, 1 English, 2 Traditional Chinese, 3 Icons | +| Associated pets | GET URL `0xc098f4`, request `0xc09910` | `/device/get_associated_pets/{physicalID}` | +| Association write | fields `0xcc3db4`, `0xcc3dd8`, `0xcc3dfc`, POST `0xcc3e20` | `/device/associate_pet`: integer pet_id, Boolean associate, integer user_device_id. Closure `0xcc41a4` toggles a captured Boolean. | +| Notification categories | `MessageSettingController::getMessageList`, litter mapping `0xc0a314` | GET `/message/get_type_block_stats_list?message_group_id=3` for litter product type 2 | +| Notification write | fields `0xcc7cac`, `0xcc7cd0`, POST `0xcc7cf4`; Boolean closure `0xc953f4` | `/message/block_type`: Boolean block, message_type_id; no physical ID. Account/category scope. | +| Delete statistics | `SettingController::cleanStatistics`, integer ID `0xcc9bc8`, URL `0xcc9c08`, empty map `0xcc9c28`, POST `0xcc9c3c` | `/device/clear_statistics/{physicalID}` with empty object body. App warns deletion is irreversible. Exact affected history remains unverified. | +| Pet profile | `AddCatsController`, GET `0xbf3ec4`/`0xbf3ee0` | `/pet/info/{petID}` | +| Breed catalog | GET `0xbf3ccc`/`0xbf3cd8` | `/pet/breeds` | +| Pet save | `enterNotty`, copied fields `0xc8af68`, weight unit `0xc8aecc`, POST `0xc8accc` | `/pet/save`, copies profile fields, includes weight_unit. App rejects non-owners (`0xc8bbdc`). | +| Binding list on save | `0xbf41e8`, `0xbf4228`, `0xbf427c` | Comma-separated user_device_ids. Preserve only devices marked is_bind; unbound candidates must remain unbound. | +| Pet sex | `0xc8d238`–`0xc8d248` | Male 1, female 2; neutered state is nullable Boolean (`0xd20f50`). Birthday is YYYY-MM-DD. | +| Pet name | `CatsNameController`, `0xaff688` | App guidance 2–10 characters; integration bounds Dart UTF-16 units conservatively. | +| Memo detail | `0xbf7c00`/`0xbf7c1c` | GET `/pet/memo_detail/{memoID}`; integration checks fresh selected-pet memo membership first. | +| Memo save | `addOrUpdateMemo`, paths `0xca7078`/`0xca7084`, pet_id `0xca7108`, POST `0xca715c` | memo_id 0 creates via `/pet/add_memo`; existing ID edits via `/pet/edit_memo`. Text fields title, content, date; Boolean remind/expired retained. Date is raw YYYY-MM-DD HH:MM, without inferred timezone. | + +Standalone `setLed` (`0xcc4f54`) selects water `/set_led` at `0xcc5090` +or feeder at `0xcc50a4`, otherwise an empty path. It does not establish a +standalone litter-box LED setter. Feeders and water remain outside this work. + +Profile writes fetch fresh account membership, ownership and binding data, +serialize per-pet mutations, preserve weight/unit/image metadata, and refresh +readback without optimistic state. Supported changes are name, birthday, sex, +neutered state and catalog-selected breed. Association writes target exactly +one pet and one physical litter box. Memo attachments and pet creation/deletion +are not implemented. + +Read-only production checks returned 95 breeds (`breed_id`, `breed_name`, +`letter`), five litter notification categories (group 3; IDs 8, 9, 10, 11, 22; +Boolean `blocked`), and two owned pet profiles with weight_unit 1 and explicit +`pet_devices[].is_bind` states. Both memo lists were empty. These checks validate +read schemas, not write acceptance. No profile, association, notification, memo, +mode, statistics or firmware write was performed for this feature batch. + +Synthetic contracts live in `tests/test_pet_features.py` and +`tests/test_device_features.py`; native HA behavior is exercised in +`tests/test_feature_ui.py`. Their invented IDs, names, versions and text do not +contain private captures. Firmware evidence is documented separately in +[apk-firmware.md](apk-firmware.md). diff --git a/docs/development-checks.md b/docs/development-checks.md index 7e3c892..eae4f42 100644 --- a/docs/development-checks.md +++ b/docs/development-checks.md @@ -18,13 +18,13 @@ The HTTP boundary uses a recursive JSON value type. Device blocks and config-ent runtime data have explicit types. Casts describe framework, JSON-decoder and CLI boundaries; response parsers narrow their values before accessing rows or fields. The schema adapter uses Probatio on newer Home Assistant versions and falls back -to Voluptuous on older versions. The test environment exercises the installed -Home Assistant version; an older installation still needs compatibility testing. +to Voluptuous on older versions. CI exercises the locked development Home Assistant version and the declared minimum 2026.3.0. The minimum job uses the nearest historical test plugin (0.13.317, normally pinned to 2026.3.1) with an explicit HA 2026.3.0 override. Registry linking uses the version-supported parent-device field and lookup API. ## Narrow exceptions - Home Assistant requires coroutine entry points even when a platform's setup is synchronous. Those functions alone have local `RUF029` exceptions. +- The update installation callback defines `backup` as a positional Boolean; only that framework signature has a Boolean-argument lint exception. - Home Assistant requires the platform filenames `select.py` and `time.py`. Those two files alone have `A005` exceptions. - `CONF_REFRESH_TOKEN` is a schema key, not a credential. Its declaration alone has diff --git a/docs/live-validation.md b/docs/live-validation.md index c0022e6..b43eebf 100644 --- a/docs/live-validation.md +++ b/docs/live-validation.md @@ -34,7 +34,7 @@ Start with read-only captures. This checklist is for the device owner; the autom DND and plan snapshots and verify the app timezone and actual firing times across DST/date boundaries. No timezone change has been live-tested. 7. Only after read behavior is confirmed, verify each command individually using normal device precautions. Record the action, request field/code, resulting physical behavior, and reported state. Do not run a command sweep. - - For issue #18, action 1 (with configured cycle) has been live-verified to enable/restart a countdown, and action 2 (with configured cycle) disables both reminder types. Action 3 without cycle is rejected. Action 3 with a changed cycle (30 → 29 days) is accepted for **litter renewal** and updated both the configured cycle and remaining days. Do **not** use action 2 to reset a reminder. Keep reset buttons and **trash-bag interval adjustment** disabled until their contracts are tested separately, one explicitly confirmed request at a time, with before/after enabled state, configured days, remaining days, and app verification. Do not send a command sweep. + - For issue #18, action 1 (with configured cycle) has been live-verified to enable/restart a countdown, and action 2 (with configured cycle) disables both reminder types. Action 3 without cycle is rejected. Action 3 with a changed cycle (30 → 29 days) is accepted for **litter renewal** and updated both the configured cycle and remaining days. Do **not** use action 2 to reset a reminder. Reset buttons and **trash-bag interval adjustment** now use the separately traced action-3 APK contract. Validate them separately, one owner-selected request at a time, with before/after enabled state, configured days, remaining days, and app verification. Do not send a command sweep. 8. Check pet-weight updates preserve the existing litter-box association. This path has regression tests but still needs production validation. 9. Turn real responses into small synthetic test fixtures with invented IDs, names and timestamps. Keep tokens, account details, images, and raw captures out of Git/issues. @@ -43,6 +43,16 @@ Document the Home Assistant version, device model/firmware, account region, logi Cloud name (#20): use one physical litter box and a short test name. Compare NOTTY app and refreshed HA cloud-name readback, then restore the original name. Check the HA user display-name override and all entity IDs remain unchanged. Do not treat HTTP success without cloud readback as a confirmed rename. No live rename was performed during implementation. -Firmware availability (#22): compare the update entity's installed/offered versions and release summary against the official app. Observe an explicit empty target versus an unavailable endpoint. If an update is performed in the official app, check that later polling reports the newly installed version. Installation and progress tracking are not implemented by this integration. Record model/firmware evidence before claiming support. +Firmware availability (#22): compare the update entity's installed/offered versions and release summary against the official app. Observe an explicit empty target versus an unavailable endpoint. If an update is performed in the official app, check that later polling reports the newly installed version. An explicit HA install now revalidates the offered task and confirms it once. Verify acknowledgement, failure/offline recovery and final installed-version readback during an owner-selected update. Only this HA session's requested target is tracked; no measured percentage or realtime subscription is implemented. Record model/firmware evidence before claiming support. -For #15, use the APK-backed mapping clean=1, empty=2, level=3; the old clean=0 and sterilize=3 labels were incorrect. Validate each physical effect separately with the owner present. No stop/pause or litter-box sterilize command has been established by the inspected callers. For #19, compare Scheduled=2 and Soft stool=3 against app readback; mode changes from this integration remain blocked pending schedule prerequisites and live checks. +For #15, use the APK-backed mapping clean=1, empty=2, level=3; the old clean=0 and sterilize=3 labels were incorrect. Validate each physical effect separately with the owner present. No stop/pause or litter-box sterilize command has been established by the inspected callers. For #19, compare Scheduled=2 and Soft stool=3 against app readback; mode changes now require fresh matching device identity/current mode, and Scheduled requires a fresh enabled plan. Verify mode readback and actual scheduling behavior separately. + +## Pet and account features + +Read-only development checks found 95 breeds, two owner profiles and five litter-box notification categories (group 3); pet memo lists were empty. New writes remain unverified live. + +- Edit one existing pet field and verify app/API readback; restore it. Check weight/unit, image, all bound devices and all unbound candidates remain unchanged, and HA entity IDs/user display names are retained. +- Associate/disassociate one owner-selected pet with one physical litter box; compare both association and profile readback before/after, then restore it. +- List account notification categories; toggle only an owner-selected category and verify the official app preference, then restore it. This is account scope. +- Create one owner-selected test memo, read its detail and edit it; verify date/reminder semantics in the app. No attachment or delete support is implemented. +- Statistics clearing permanently deletes data. Validate it only when the owner explicitly wants that device's history removed; record which counters/history actually change. An acknowledgement alone does not establish the affected scope. diff --git a/pyproject.toml b/pyproject.toml index 1962d4e..b25fe53 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "notty-home-assistant" -version = "0.3.0" +version = "0.4.0" description = "NOTTY smart litter box integration for Home Assistant" readme = "README.md" requires-python = ">=3.14.2" diff --git a/release-notes/v0.4.0.md b/release-notes/v0.4.0.md new file mode 100644 index 0000000..3094650 --- /dev/null +++ b/release-notes/v0.4.0.md @@ -0,0 +1,33 @@ +# NOTTY v0.4.0 + +Existing pets now have Home Assistant controls for name, sex, neutered state and +birthday. Actions support breed edits, pet-to-litter-box associations, text memo +listing/detail/create/edit, account notification preferences and explicitly +confirmed irreversible device-statistics deletion. Profile saves preserve fresh +weight/unit, image metadata and every existing device binding. Shared pets cannot +be edited; HA name overrides and entity identities are retained. + +Litter-box mode selection supports Auto, Scheduled and Soft stool, with fresh +identity/current-state validation and an enabled-plan prerequisite for Scheduled. +Both reminder reset buttons use the APK's action 3 and preserve the configured +cycle. Trash-bag interval changes and all four screen-language values are exposed. +Firmware update entities support explicit confirmation of a fresh eligible offer, +full notes and Boolean pending-target tracking. No measured percentage or +restart-persistent firmware progress is claimed. + +Adds English/Dutch names, action selectors and icons. Fixes minimum-version +binary-sensor imports and pet device linking; CI now exercises Home Assistant +2026.3.0 as well as the locked development version. The timezone probe also runs +without Home Assistant installed. Feeders and water dispensers remain excluded. + +The integration is experimental. New write contracts are traced from the APK +and tested with synthetic responses. Read-only live checks verified breed, +owner-profile and notification-category schemas. New pet/memo/notification/mode +writes, same-cycle resets, trash-bag interval changes, firmware installation and +statistics deletion still need owner validation; no such operations were run +for this release. Memo dates retain the NOTTY wall clock without inferred timezone. + +After updating through HACS, restart Home Assistant. Existing entity unique IDs +and integration credentials are retained. Review action field descriptions before +using new writes in automations; statistics deletion requires +`confirm_irreversible: true` and cannot be undone. diff --git a/scripts/probe_timezones.py b/scripts/probe_timezones.py index 82f1c4a..4f6216c 100755 --- a/scripts/probe_timezones.py +++ b/scripts/probe_timezones.py @@ -14,14 +14,15 @@ import json from pathlib import Path import sys -from typing import cast +from typing import TYPE_CHECKING, cast import aiohttp if not __package__: sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -from custom_components.notty.api import JsonObject, JsonValue +if TYPE_CHECKING: + from custom_components.notty.api import JsonObject, JsonValue from scripts import probe_datapoints from scripts.console import console from scripts.validate_commands import load_session diff --git a/tests/test_apk_commands.py b/tests/test_apk_commands.py index 2ef92a8..7e8c670 100644 --- a/tests/test_apk_commands.py +++ b/tests/test_apk_commands.py @@ -7,7 +7,6 @@ from unittest.mock import AsyncMock, MagicMock from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError import pytest from custom_components.notty.api import LITTER_MODES, NottyApi, NottyApiError @@ -93,16 +92,15 @@ async def test_unsupported_service_options_are_rejected( async def test_mode_labels_follow_ui_callers( hass: HomeAssistant, runtime_api: MagicMock, fixture: dict[str, object] ) -> None: - """Present only traced mode labels while retaining the existing write boundary.""" + """Present traced labels and keep selecting the current mode a read-only no-op.""" value = fixture["payload"]["mode"] runtime_api.device_info.return_value["mode"] = value await setup(hass) assert LITTER_MODES[value] == fixture["label"] assert hass.states.get("select.test_box_mode").state == fixture["label"] - with pytest.raises(HomeAssistantError, match="mode changes remain disabled"): - await hass.services.async_call( - "select", "select_option", {"entity_id": "select.test_box_mode", "option": fixture["label"]}, blocking=True - ) + await hass.services.async_call( + "select", "select_option", {"entity_id": "select.test_box_mode", "option": fixture["label"]}, blocking=True + ) runtime_api.litter_action.assert_not_awaited() @@ -110,9 +108,10 @@ async def test_raw_mode_action_cannot_bypass_guard() -> None: """The lower-level API applies the same mode-write boundary as the select.""" api = NottyApi(MagicMock()) api.request = AsyncMock() + api.litter_info = AsyncMock(return_value={"user_device_id": 123}) for value in (1, 2, 3): - with pytest.raises(NottyApiError, match="mode changes remain disabled"): - await api.litter_action("synthetic-box", "set_mode", {"mode": value}) + with pytest.raises(NottyApiError, match="known current device mode"): + await api.litter_action("123", "set_mode", {"mode": value}) api.request.assert_not_awaited() diff --git a/tests/test_cloud_alias.py b/tests/test_cloud_alias.py index c6a0cef..346fa57 100644 --- a/tests/test_cloud_alias.py +++ b/tests/test_cloud_alias.py @@ -86,7 +86,11 @@ async def test_cloud_rename_preserves_registry_identity_and_user_override( numeric_device(runtime_api) entry = await setup(hass) registry = async_get_device_registry(hass) - device = registry.async_get_device_by_identifier(("notty", "123"), entry.entry_id) + device = ( + registry.async_get_device_by_identifier(("notty", "123"), entry.entry_id) + if hasattr(registry, "async_get_device_by_identifier") + else registry.async_get_device(identifiers={("notty", "123")}) + ) registry.async_update_device(device.id, name_by_user=EXPECTED_OVERRIDE) entities = async_get_entity_registry(hass) registered = entities.async_get(ENTITY) @@ -194,7 +198,11 @@ async def test_app_rename_updates_cloud_field_and_registry_without_ha_override_l runtime_api.device_info.return_value["alias"] = "Old Info" entry = await setup(hass) registry = async_get_device_registry(hass) - device = registry.async_get_device_by_identifier(("notty", "123"), entry.entry_id) + device = ( + registry.async_get_device_by_identifier(("notty", "123"), entry.entry_id) + if hasattr(registry, "async_get_device_by_identifier") + else registry.async_get_device(identifiers={("notty", "123")}) + ) registry.async_update_device(device.id, name_by_user=EXPECTED_OVERRIDE) runtime_api.devices.return_value[0]["alias"] = EXPECTED_ALIAS await entry.runtime_data.async_refresh() @@ -210,7 +218,11 @@ async def test_missing_alias_recovers_without_a_reload(hass: HomeAssistant, runt numeric_device(runtime_api) runtime_api.devices.return_value[0]["alias"] = None entry = await setup(hass) - unavailable = [state for state in hass.states.async_all("text") if state.state == EXPECTED_UNAVAILABLE] + unavailable = [ + state + for state in hass.states.async_all("text") + if state.state == EXPECTED_UNAVAILABLE and state.entity_id.endswith("_cloud_name") + ] assert len(unavailable) == 1 runtime_api.devices.return_value[0]["alias"] = EXPECTED_ALIAS await entry.runtime_data.async_refresh() diff --git a/tests/test_device_features.py b/tests/test_device_features.py new file mode 100644 index 0000000..b419ef9 --- /dev/null +++ b/tests/test_device_features.py @@ -0,0 +1,199 @@ +"""Account scope, firmware task eligibility and irreversible maintenance contracts.""" + +from __future__ import annotations + +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError +from custom_components.notty.device_features import FirmwareApi, NotificationApi, clear_statistics + +BOX_ID = "123" +METHOD_GET = "GET" +METHOD_POST = "POST" +FIELD_DEVICE_ID = "user_device_id" +FIELD_OWNER = "is_owner" +FIELD_DEVICES = "pet_devices" +BREED_ID = 9 +BREED_NAME = "Synthetic breed" +RESET_CODE = 3 +TARGET_VERSION = "0.9.9" +UPGRADE: JsonObject = {"src_version": "0.9.8", "dest_version": TARGET_VERSION, "task_id": "task-7", "task_status": ""} +CATEGORIES: list[JsonValue] = [ + {"message_type_id": 12, "message_type_name": "Cleaning", "message_type_group_id": 3, "blocked": False}, + {"message_type_id": 13, "message_type_name": "Fault", "message_type_group_id": 3, "blocked": True}, +] + + +def client() -> NottyApi: + """Construct an owned litter-box client without any live transport. + + Returns: + The isolated API client. + """ + api = NottyApi(MagicMock()) + api.devices = AsyncMock( + return_value=[{"user_device_id": 123, "device_type": "litter_box", "is_owner": True, "status_id": 1}] + ) + api.request = AsyncMock() + return api + + +async def test_notifications_are_account_group_reads_and_boolean_category_writes() -> None: + """A physical ID never enters the account-level category request.""" + api = client() + api.request.side_effect = [CATEGORIES, {}, CATEGORIES] + await NotificationApi(api).set_blocked(12, blocked=True) + api.request.assert_any_await("GET", "/message/get_type_block_stats_list?message_group_id=3") + api.request.assert_any_await("POST", "/message/block_type", data={"message_type_id": 12, "block": True}) + assert all(FIELD_DEVICE_ID not in call.kwargs.get("data", {}) for call in api.request.await_args_list) + + +async def test_notification_same_state_does_not_write() -> None: + """An already blocked category is a read-only no-op.""" + api = client() + api.request.return_value = CATEGORIES + await NotificationApi(api).set_blocked(13, blocked=True) + api.request.assert_awaited_once_with("GET", "/message/get_type_block_stats_list?message_group_id=3") + + +@pytest.mark.parametrize( + "rows", + [ + [], + [{"message_type_id": 12, "message_type_group_id": 4, "blocked": False}], + CATEGORIES + CATEGORIES, + [{"message_type_id": 12, "message_type_group_id": 3, "blocked": None}], + ], +) +async def test_unknown_notification_scope_ids_and_states_never_write(rows: JsonValue) -> None: + """Reject foreign categories, ambiguous IDs and missing block-state readback.""" + api = client() + api.request.return_value = rows + with pytest.raises(NottyApiError): + await NotificationApi(api).set_blocked(12, blocked=True) + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +@pytest.mark.parametrize("task", ["task-7", 7]) +async def test_firmware_confirmation_preserves_native_task_id_type(task: JsonValue) -> None: + """The APK confirms the fresh task using only task_id and integer physical ID.""" + api = client() + api.request.side_effect = [{**UPGRADE, "task_id": task}, {}] + assert await FirmwareApi(api).install(BOX_ID) == TARGET_VERSION + api.request.assert_awaited_with("POST", "/device/confirm_upgrade", data={"task_id": task, "user_device_id": 123}) + + +@pytest.mark.parametrize( + "changes", + [ + {"dest_version": ""}, + {"dest_version": "0.9.8"}, + {"dest_version": None}, + {"src_version": None}, + {"task_id": None}, + {"task_id": ""}, + {"task_id": True}, + {"task_id": -1}, + {"task_status": "RUNNING"}, + {"task_status": "unknown"}, + {"task_status": []}, + ], +) +async def test_invalid_or_busy_firmware_tasks_never_write(changes: JsonObject) -> None: + """Unknown state must not be treated as permission to start an upgrade.""" + api = client() + api.request.return_value = {**UPGRADE, **changes} + with pytest.raises(NottyApiError): + await FirmwareApi(api).install(BOX_ID) + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +async def test_firmware_refuses_arbitrary_version_and_never_retries_rejection() -> None: + """Users cannot request a non-offered version or reuse another firmware task.""" + api = client() + api.request.return_value = UPGRADE + with pytest.raises(NottyApiError): + await FirmwareApi(api).install(BOX_ID, "some-other-version") + api.request.reset_mock() + api.request.side_effect = [UPGRADE, NottyApiError("rejected")] + with pytest.raises(NottyApiError): + await FirmwareApi(api).install(BOX_ID) + posts = [call for call in api.request.await_args_list if call.args[0] == METHOD_POST] + assert len(posts) == 1 + + +@pytest.mark.parametrize( + "device", + [ + {"user_device_id": 123, "device_type": "litter_box", "is_owner": False}, + {"user_device_id": 123, "device_type": "feeder", "is_owner": True}, + {"user_device_id": 123, "device_type": "litter_box", "is_owner": True, "_notty_source": "pet"}, + {"user_device_id": 123, "device_type": "litter_box", "is_owner": True, "status_id": 0}, + ], +) +async def test_firmware_requires_owned_online_physical_litter_box(device: JsonObject) -> None: + """Shared devices, pets, feeders and explicit offline readback cannot install.""" + api = client() + api.devices.return_value = [device] + with pytest.raises(NottyApiError): + await FirmwareApi(api).install(BOX_ID) + api.request.assert_not_awaited() + + +async def test_statistics_reset_requires_confirmation_then_posts_empty_body_to_scoped_path() -> None: + """The APK places the device ID in the path, not a guessed JSON body.""" + api = client() + with pytest.raises(NottyApiError): + await clear_statistics(api, BOX_ID, confirmed=False) + api.devices.assert_not_awaited() + api.request.assert_not_awaited() + await clear_statistics(api, BOX_ID, confirmed=True) + api.request.assert_awaited_once_with("POST", "/device/clear_statistics/123", data={}) + + +@pytest.mark.parametrize("mode", [0, 4, True, 1.0, "2"]) +async def test_unknown_mode_values_never_write(mode: JsonValue) -> None: + """Only the traced integer modes are accepted.""" + api = client() + with pytest.raises(NottyApiError): + await api.litter_action(BOX_ID, "set_mode", {"mode": mode}) + api.request.assert_not_awaited() + + +async def test_scheduled_mode_requires_a_fresh_enabled_plan() -> None: + """An empty/disabled schedule list cannot silently create scheduled mode.""" + api = client() + api.litter_info = AsyncMock(return_value={"user_device_id": 123, "mode": 1}) + api.litter_plans = AsyncMock(return_value=[{"plan_id": 1, "open": False}]) + with pytest.raises(NottyApiError, match="enabled cleaning plan"): + await api.litter_action(BOX_ID, "set_mode", {"mode": 2}) + api.request.assert_not_awaited() + api.litter_plans.return_value = [{"plan_id": 1, "open": True}] + await api.litter_action(BOX_ID, "set_mode", {"mode": 2}) + api.request.assert_awaited_once_with("POST", "/device/litter_box/set_mode", data={"user_device_id": 123, "mode": 2}) + + +@pytest.mark.parametrize( + ("action", "cycle_field", "enabled_field", "cycle"), + [ + ("reset_litter_reminder", "default_remaining_days", "open_litter_remind", 20), + ("reset_garbage_bag_reminder", "garbage_bag_cycle_time", "open_garbagebag_remind", 7), + ], +) +async def test_reminder_reset_uses_three_and_preserves_the_configured_cycle( + action: str, cycle_field: str, enabled_field: str, cycle: int +) -> None: + """An explicit reset is distinct from disable and interval editing.""" + api = client() + api.litter_info = AsyncMock(return_value={cycle_field: cycle, enabled_field: True}) + await api.litter_action(BOX_ID, action, {"cycle_time": cycle}) + post = api.request.await_args + assert post.kwargs["data"]["action"] == RESET_CODE + assert post.kwargs["data"]["cycle_time"] == cycle + api.litter_info.return_value[enabled_field] = False + api.request.reset_mock() + with pytest.raises(NottyApiError): + await api.litter_action(BOX_ID, action, {"cycle_time": cycle}) + api.request.assert_not_awaited() diff --git a/tests/test_feature_ui.py b/tests/test_feature_ui.py new file mode 100644 index 0000000..63ac27c --- /dev/null +++ b/tests/test_feature_ui.py @@ -0,0 +1,298 @@ +"""Native HA controls, action schemas, ownership and account-preference lifecycle.""" + +from __future__ import annotations + +from copy import deepcopy +from datetime import date +import json +from pathlib import Path +from unittest.mock import MagicMock + +from homeassistant.components.update import UpdateEntityFeature +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.device_registry import async_get as devices +from homeassistant.helpers.entity_registry import async_get as entities +import pytest +import yaml + +from custom_components.notty.api import JsonObject, JsonValue +from custom_components.notty.feature_services import FEATURE_SERVICES +from tests.test_device_features import CATEGORIES, UPGRADE +from tests.test_lifecycle import setup +from tests.test_pet_features import BOX_ID, NEW_NAME, PET_ID, PROFILE + +METHOD_GET = "GET" +METHOD_POST = "POST" +EXPECTED_ON = "on" +EXPECTED_OFF = "off" +EXPECTED_UNAVAILABLE = "unavailable" +HA_OVERRIDE = "My cat display name" +SERVICE_PROFILE = "pet_profile" +SERVICE_MEMO = "pet_memo" +DOMAIN = "notty" +MALE = "male" +FEMALE_CODE = 2 +NEW_BIRTHDAY = "2021-04-03" +PET_SAVE = "/pet/save" +CLEANING = "cleaning" +FIELD_IMAGE_URL = "image_url" + + +def configure(runtime_api: MagicMock) -> tuple[JsonObject, list[JsonValue]]: + """Set up a writable fake cloud with independent authoritative readback. + + Returns: + Mutable server pet data and account category data for explicit polling tests. + """ + profile = deepcopy(PROFILE) + categories = deepcopy(CATEGORIES) + runtime_api.devices.return_value = [ + {"user_device_id": 123, "device_type": "litter_box", "alias": "Test box", "is_owner": True, "status_id": 1}, + {**profile, "_notty_source": "pet", "device_type": "litter_box", "id": "pet_7", "alias": "Milo"}, + ] + runtime_api.pets.return_value = [{"pet_id": 7}] + runtime_api.device_info.return_value.update({"user_device_id": 123, "mode": 1, "language": 1}) + runtime_api.pet_related_info.return_value = {"info": profile, "memos": []} + + def request(method: str, path: str, *, data: JsonObject | None = None) -> JsonValue: + if path.startswith("/message/get_type_block_stats_list"): + return deepcopy(categories) + if path.startswith("/pet/info/"): + return deepcopy(profile) + if method == METHOD_POST and path.endswith("/pet/save"): + assert data is not None + profile.update(data) + return {} + if path.endswith("/message/block_type"): + assert data is not None + for row in categories: + if row["message_type_id"] == data["message_type_id"]: + row["blocked"] = data["block"] + return {} + return [] if path.startswith("/pet/memos/") else UPGRADE if path.endswith("/device/check_upgrade/123") else {} + + runtime_api.request.side_effect = request + return profile, categories + + +async def test_native_pet_controls_keep_names_and_entity_identity(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Editing a cloud pet updates readback without losing the HA display-name override.""" + configure(runtime_api) + entry = await setup(hass) + registry = devices(hass) + if hasattr(registry, "async_get_device_by_identifier"): + pet = registry.async_get_device_by_identifier((DOMAIN, "pet_7"), entry.entry_id) + else: + pet = registry.async_get_device(identifiers={(DOMAIN, "pet_7")}) + assert pet is not None + registry.async_update_device(pet.id, name_by_user=HA_OVERRIDE) + before = {(item.entity_id, item.unique_id, item.device_id) for item in entities(hass).entities.values()} + assert hass.states.get("text.milo_name").state == PROFILE["name"] + assert hass.states.get("select.milo_sex").state == MALE + assert hass.states.get("date.milo_birthday").state == PROFILE["birthday"] + await hass.services.async_call( + "text", "set_value", {"entity_id": "text.milo_name", "value": NEW_NAME}, blocking=True + ) + await hass.async_block_till_done() + assert hass.states.get("text.milo_name").state == NEW_NAME + assert registry.async_get(pet.id).name == NEW_NAME + assert registry.async_get(pet.id).name_by_user == HA_OVERRIDE + assert {(item.entity_id, item.unique_id, item.device_id) for item in entities(hass).entities.values()} == before + + +async def test_pet_profile_sex_neutered_and_birthday_controls(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Native setters write through the full profile-preserving path.""" + profile, _ = configure(runtime_api) + await setup(hass) + await hass.services.async_call( + "select", "select_option", {"entity_id": "select.milo_sex", "option": "female"}, blocking=True + ) + await hass.services.async_call("switch", "turn_on", {"entity_id": "switch.milo_neutered"}, blocking=True) + await hass.services.async_call( + "date", "set_value", {"entity_id": "date.milo_birthday", "date": date(2021, 4, 3)}, blocking=True + ) + assert profile["sex"] == FEMALE_CODE + assert profile["is_sterilization"] is True + assert profile["birthday"] == NEW_BIRTHDAY + posts = [call for call in runtime_api.request.await_args_list if call.args[0] == METHOD_POST] + assert all(call.args[1] == PET_SAVE and call.kwargs["data"]["user_device_ids"] == BOX_ID for call in posts) + + +async def test_shared_pet_controls_are_unavailable_and_cannot_write( + hass: HomeAssistant, runtime_api: MagicMock +) -> None: + """Permission changes are visible in the native UI, not only in error handling.""" + profile, _ = configure(runtime_api) + profile["is_owner"] = False + await setup(hass) + for entity_id in ("text.milo_name", "select.milo_sex", "switch.milo_neutered", "date.milo_birthday"): + assert hass.states.get(entity_id).state == EXPECTED_UNAVAILABLE + with pytest.raises(HomeAssistantError): + await hass.services.async_call( + "notty", + SERVICE_PROFILE, + {"pet_id": PET_ID, "operation": "update", "changes": {"name": NEW_NAME}}, + blocking=True, + ) + assert all(call.args[0] == METHOD_GET for call in runtime_api.request.await_args_list) + + +async def test_notification_only_poll_changes_update_the_ui(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Coordinator equality must notice account preference changes independently of measurements.""" + _, categories = configure(runtime_api) + entry = await setup(hass) + switches = [state for state in hass.states.async_all("switch") if CLEANING in state.entity_id] + assert len(switches) == 1 + entity_id = switches[0].entity_id + assert hass.states.get(entity_id).state == EXPECTED_ON + categories[0]["blocked"] = True + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(entity_id).state == EXPECTED_OFF + await hass.services.async_call("switch", "turn_on", {"entity_id": entity_id}, blocking=True) + assert hass.states.get(entity_id).state == EXPECTED_ON + posts = [call for call in runtime_api.request.await_args_list if call.args[0] == METHOD_POST] + assert posts[-1].kwargs["data"] == {"message_type_id": 12, "block": False} + + +@pytest.mark.parametrize( + ("service", "data"), + [ + (SERVICE_PROFILE, {"pet_id": 7, "operation": "get", "changes": {"name": NEW_NAME}}), + (SERVICE_PROFILE, {"pet_id": 999, "operation": "update", "changes": {"name": NEW_NAME}}), + (SERVICE_MEMO, {"pet_id": 7, "operation": "create", "memo_id": 42, "changes": {}}), + (SERVICE_MEMO, {"pet_id": 7, "operation": "update", "changes": {}}), + ("notification_preferences", {"user_device_id": 123, "operation": "list", "message_type_id": 12}), + ("clear_statistics", {"user_device_id": 123, "confirm_irreversible": False}), + ], +) +async def test_actions_reject_mismatched_fields_and_unknown_targets_before_writing( + hass: HomeAssistant, runtime_api: MagicMock, service: str, data: JsonObject +) -> None: + """A read operation cannot silently accept write inputs or target another account.""" + configure(runtime_api) + await setup(hass) + with pytest.raises(HomeAssistantError): + await hass.services.async_call("notty", service, data, blocking=True) + assert all(call.args[0] == METHOD_GET for call in runtime_api.request.await_args_list) + + +async def test_feature_services_unload_with_last_account(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Every new action follows the existing integration lifecycle.""" + configure(runtime_api) + entry = await setup(hass) + assert all(hass.services.has_service("notty", service) for service in FEATURE_SERVICES) + await hass.config_entries.async_unload(entry.entry_id) + assert all(not hass.services.has_service("notty", service) for service in FEATURE_SERVICES) + + +async def test_firmware_install_tracks_offered_target_until_version_readback( + hass: HomeAssistant, runtime_api: MagicMock +) -> None: + """An acknowledged request never fabricates installed version or percentage progress.""" + configure(runtime_api) + runtime_api.litter_related_info.return_value["upgrade"] = dict(UPGRADE) + entry = await setup(hass) + entity = "update.test_box_firmware" + state = hass.states.get(entity) + assert state.attributes["supported_features"] & UpdateEntityFeature.INSTALL + await hass.services.async_call("update", "install", {"entity_id": entity}, blocking=True) + state = hass.states.get(entity) + assert state.attributes["in_progress"] is True + assert state.attributes["installed_version"] == UPGRADE["src_version"] + assert state.attributes.get("update_percentage") is None + 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 + + +def test_ui_metadata_covers_all_new_entities_and_services() -> None: + """Icons, English/Dutch names and action fields remain aligned with registration.""" + root = Path(__file__).resolve().parents[1] / "custom_components" / "notty" + icons = json.loads((root / "icons.json").read_text()) + schema = yaml.safe_load((root / "services.yaml").read_text()) + for language in ("en", "nl"): + translations = json.loads((root / "translations" / f"{language}.json").read_text()) + for service in FEATURE_SERVICES: + assert icons["services"][service]["service"].startswith("mdi:") + assert set(translations["services"][service]["fields"]) == set(schema[service]["fields"]) + for platform, key in ( + ("text", "pet_name"), + ("date", "pet_birthday"), + ("select", "pet_sex"), + ("switch", "pet_neutered"), + ("switch", "notification_category"), + ): + assert translations["entity"][platform][key]["name"] + assert icons["entity"][platform][key]["default"].startswith("mdi:") + + +async def test_notification_endpoint_loss_and_late_recovery(hass: HomeAssistant, runtime_api: MagicMock) -> None: + """Optional failures keep measurements running and recovered categories appear once.""" + _, categories = configure(runtime_api) + saved = deepcopy(categories) + categories.clear() + entry = await setup(hass) + assert not any(CLEANING in state.entity_id for state in hass.states.async_all("switch")) + categories.extend(saved) + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + switches = [state for state in hass.states.async_all("switch") if CLEANING in state.entity_id] + assert len(switches) == 1 + entity_id = switches[0].entity_id + categories[0]["blocked"] = None + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(entity_id).state == EXPECTED_UNAVAILABLE + assert hass.states.get("sensor.test_box_today_clean_count").state != EXPECTED_UNAVAILABLE + categories[0]["blocked"] = False + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert hass.states.get(entity_id).state == EXPECTED_ON + assert len([state for state in hass.states.async_all("switch") if CLEANING in state.entity_id]) == 1 + + +async def test_profile_action_returns_filtered_authoritative_readback( + hass: HomeAssistant, runtime_api: MagicMock +) -> None: + """Native actions return fresh profile values without unrelated backend fields.""" + profile, _ = configure(runtime_api) + profile["image_url"] = "https://example.invalid/private-image" + await setup(hass) + result = await hass.services.async_call( + DOMAIN, + SERVICE_PROFILE, + {"pet_id": PET_ID, "operation": "update", "changes": {"name": NEW_NAME}}, + blocking=True, + return_response=True, + ) + assert result["profile"]["name"] == NEW_NAME + assert FIELD_IMAGE_URL not in result["profile"] + post = next(call for call in runtime_api.request.await_args_list if call.args[0] == METHOD_POST) + assert post.kwargs["data"]["image_url"] == profile["image_url"] + + +async def test_statistics_action_requires_explicit_confirmation_and_exact_target( + hass: HomeAssistant, runtime_api: MagicMock +) -> None: + """The destructive service uses its scoped empty-body APK contract once.""" + configure(runtime_api) + await setup(hass) + result = await hass.services.async_call( + DOMAIN, + "clear_statistics", + {"user_device_id": BOX_ID, "confirm_irreversible": True}, + blocking=True, + return_response=True, + ) + assert result["reversible"] is False + posts = [call for call in runtime_api.request.await_args_list if call.args[0] == METHOD_POST] + assert len(posts) == 1 + assert posts[0].args == (METHOD_POST, "/device/clear_statistics/123") + assert posts[0].kwargs["data"] == {} diff --git a/tests/test_firmware.py b/tests/test_firmware.py index d361dc8..a1e4133 100644 --- a/tests/test_firmware.py +++ b/tests/test_firmware.py @@ -6,6 +6,7 @@ from pathlib import Path from unittest.mock import AsyncMock, MagicMock +from homeassistant.components.update import UpdateEntityFeature from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -41,7 +42,7 @@ async def test_firmware_entity_reports_app_fields(hass: HomeAssistant, runtime_a assert entity.attributes["latest_version"] == EXPECTED_LATEST assert entity.attributes["release_summary"] == CONTRACT["offered"]["firmware_desc"] assert entity.attributes["task_status"] == CONTRACT["offered"]["task_status"] - assert entity.attributes["supported_features"] == 0 + assert not entity.attributes["supported_features"] & UpdateEntityFeature.INSTALL assert entity.attributes.get("update_percentage") is None assert PRIVATE_VALUE not in json.dumps(dict(entity.attributes)) assert FIELD_TASK_ID not in entity.attributes diff --git a/tests/test_lifecycle.py b/tests/test_lifecycle.py index e228ed9..a3a59d6 100644 --- a/tests/test_lifecycle.py +++ b/tests/test_lifecycle.py @@ -66,8 +66,16 @@ async def test_setup_entities_services_and_unload(hass: HomeAssistant, runtime_a assert hass.states.get("number.test_cat_weight").state == EXPECTED_4_2 assert not any(s.entity_id.startswith("button.test_cat_") for s in hass.states.async_all()) registry = async_get_device_registry(hass) - parent = registry.async_get_device_by_identifier(("notty", "box-1"), entry.entry_id) - pet = registry.async_get_device_by_identifier(("notty", "pet_cat-1"), entry.entry_id) + parent = ( + registry.async_get_device_by_identifier(("notty", "box-1"), entry.entry_id) + if hasattr(registry, "async_get_device_by_identifier") + else registry.async_get_device(identifiers={("notty", "box-1")}) + ) + pet = ( + registry.async_get_device_by_identifier(("notty", "pet_cat-1"), entry.entry_id) + if hasattr(registry, "async_get_device_by_identifier") + else registry.async_get_device(identifiers={("notty", "pet_cat-1")}) + ) assert parent is not None assert pet is not None assert pet.via_device_id == parent.id @@ -251,7 +259,7 @@ async def test_live_shape_pet_binding_survives_merge(hass: HomeAssistant, runtim assert block["info"]["pet_devices"][0]["user_device_id"] == EXPECTED_BLOCK_INFO_PET_DEVICES_0_USER_DEVICE_ID -async def test_mode_1_is_auto_and_mode_changes_are_blocked(hass: HomeAssistant, runtime_api: MagicMock) -> None: +async def test_mode_1_is_auto_and_reselecting_it_is_noop(hass: HomeAssistant, runtime_api: MagicMock) -> None: """Raw mode=1 was verified as Auto in the actual NOTTY mobile app.""" modes = next(description for description in SELECTS if description.key == FIELD_MODE) assert modes.value_options == {1: "Auto", 2: "Scheduled", 3: "Soft stool"} @@ -261,10 +269,9 @@ async def test_mode_1_is_auto_and_mode_changes_are_blocked(hass: HomeAssistant, assert mode is not None assert mode.state == EXPECTED_AUTO assert mode.attributes["options"] == ["Auto", "Scheduled", "Soft stool"] - with pytest.raises(HomeAssistantError, match="mode changes remain disabled"): - await hass.services.async_call( - "select", "select_option", {"entity_id": "select.test_box_mode", "option": "Auto"}, blocking=True - ) + await hass.services.async_call( + "select", "select_option", {"entity_id": "select.test_box_mode", "option": "Auto"}, blocking=True + ) runtime_api.litter_action.assert_not_awaited() diff --git a/tests/test_pet_features.py b/tests/test_pet_features.py new file mode 100644 index 0000000..2e55bd2 --- /dev/null +++ b/tests/test_pet_features.py @@ -0,0 +1,307 @@ +"""Synthetic APK pet contracts and ownership/binding preservation regressions.""" + +from __future__ import annotations + +import asyncio +from copy import deepcopy +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError +from custom_components.notty.feature_contracts import ( + identifier, + memo_payload, + object_rows, + profile_changes, + profile_payload, +) +from custom_components.notty.pet_api import MemoApi, PetApi + +PET_ID = "7" +BOX_ID = "123" +METHOD_GET = "GET" +METHOD_POST = "POST" +FIELD_DEVICE_ID = "user_device_id" +FIELD_OWNER = "is_owner" +FIELD_DEVICES = "pet_devices" +BREED_ID = 9 +BREED_NAME = "Synthetic breed" +RESET_CODE = 3 +NEW_NAME = "Luna" +PROFILE: JsonObject = { + "pet_id": 7, + "name": "Milo", + "birthday": "2020-05-04", + "sex": 1, + "sex_name": "Male", + "is_sterilization": False, + "breed_id": 5, + "breed_name": "Domestic", + "weight": 4.2, + "weight_unit": 1, + "is_owner": True, + "image_path": "existing-image", + "collar_id": 8, + "is_default": False, + "pet_devices": [{"user_device_id": 123, "is_bind": True}, {"user_device_id": 456, "is_bind": False}], +} +MEMO: JsonObject = { + "memo_id": 42, + "title": "Visit", + "content": "Routine visit", + "date": "2026-10-16 15:00", + "remind": True, + "expired": False, +} +EXPECTED_SEX = 2 + + +def client() -> NottyApi: + """Create a transport with every HTTP entry point mocked. + + Returns: + A client that cannot contact the production service. + """ + api = NottyApi(MagicMock()) + api.pets = AsyncMock(return_value=[{"pet_id": 7}]) + api.request = AsyncMock() + return api + + +@pytest.mark.parametrize("value", [True, False, None, 0, -1, 1.0, "", "0", "7/other", "\uff17"]) +def test_feature_ids_reject_ambiguous_targets(value: JsonValue) -> None: + """No Boolean, float or URL fragment can identify a pet or physical device.""" + with pytest.raises(NottyApiError): + identifier(value) + + +@pytest.mark.parametrize( + "changes", + [ + {}, + {"pet_id": 99}, + {"user_device_ids": "999"}, + {"weight": 9}, + {"name": "A"}, + {"name": " "}, + {"name": "bad\nname"}, + {"name": "long pet name"}, + {"birthday": "2026-02-30"}, + {"birthday": "20260101"}, + {"sex": True}, + {"sex": 9}, + {"is_sterilization": 1}, + {"breed_id": False}, + ], +) +def test_pet_edits_validate_supported_fields(changes: JsonObject) -> None: + """Reject identity/binding injection and malformed profile values before HTTP.""" + with pytest.raises(NottyApiError): + profile_changes(changes) + + +def test_profile_payload_preserves_only_bound_devices_and_original_values() -> None: + """The app's user_device_ids string must never bind previously unbound candidates.""" + original = deepcopy(PROFILE) + payload = profile_payload(PET_ID, original, {"name": NEW_NAME}) + assert payload["name"] == NEW_NAME + assert payload["user_device_ids"] == BOX_ID + for field in ("weight", "weight_unit", "image_path", "collar_id", "is_default", "birthday", "sex"): + assert payload[field] == original[field] + assert original == PROFILE + assert FIELD_OWNER not in payload + assert FIELD_DEVICES not in payload + + +@pytest.mark.parametrize( + "changes", + [ + {"is_owner": False}, + {"is_owner": None}, + {"pet_id": 8}, + {"weight": float("nan")}, + {"weight": 0}, + {"pet_devices": None}, + {"pet_devices": [{"user_device_id": 123}]}, + ], +) +def test_unknown_profile_or_binding_state_prevents_save(changes: JsonObject) -> None: + """A fresh incomplete profile cannot become a destructive replacement.""" + with pytest.raises(NottyApiError): + profile_payload(PET_ID, {**PROFILE, **changes}, {"name": NEW_NAME}) + + +async def test_pet_update_exact_wire_and_authoritative_readback() -> None: + """A successful POST alone must not become optimistic profile state.""" + api = client() + api.request.side_effect = [PROFILE, {}, PROFILE] + result = await PetApi(api).update(PET_ID, {"name": NEW_NAME}) + api.request.assert_any_await( + "POST", + "/pet/save", + data={ + "image_path": "existing-image", + "name": NEW_NAME, + "breed_id": 5, + "breed_name": "Domestic", + "sex": 1, + "sex_name": "Male", + "is_sterilization": False, + "birthday": "2020-05-04", + "weight": 4.2, + "collar_id": 8, + "is_default": False, + "pet_id": 7, + "user_device_ids": "123", + "weight_unit": 1, + }, + ) + assert result["name"] == PROFILE["name"] + + +async def test_shared_or_foreign_pets_never_write() -> None: + """Account membership and fresh ownership are independently required.""" + api = client() + api.pets.return_value = [{"pet_id": 8}] + with pytest.raises(NottyApiError): + await PetApi(api).update(PET_ID, {"name": NEW_NAME}) + api.request.assert_not_awaited() + api.pets.return_value = [{"pet_id": 7}] + api.request.return_value = {**PROFILE, "is_owner": False} + with pytest.raises(NottyApiError): + await PetApi(api).update(PET_ID, {"name": NEW_NAME}) + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +async def test_concurrent_profile_controls_preserve_both_changes() -> None: + """Two HA controls sharing an account must not overwrite each other's fresh edits.""" + api = client() + state = deepcopy(PROFILE) + + async def request(method: str, _path: str, *, data: JsonObject | None = None) -> JsonValue: + if method == METHOD_GET: + result = deepcopy(state) + await asyncio.sleep(0) + return result + assert data is not None + state.update(data) + return {} + + api.request.side_effect = request + await asyncio.gather(PetApi(api).update(PET_ID, {"name": NEW_NAME}), PetApi(api).update(PET_ID, {"sex": 2})) + assert state["name"] == NEW_NAME + assert state["sex"] == EXPECTED_SEX + assert state["user_device_ids"] == BOX_ID + + +async def test_breed_change_uses_server_catalog_name() -> None: + """A breed ID is not accepted unless the current server catalog contains it.""" + api = client() + api.request.side_effect = [PROFILE, [{"breed_id": 9, "breed_name": "Synthetic breed"}], {}, PROFILE] + await PetApi(api).update(PET_ID, {"breed_id": 9}) + post = next(call for call in api.request.await_args_list if call.args[0] == METHOD_POST) + assert post.kwargs["data"]["breed_id"] == BREED_ID + assert post.kwargs["data"]["breed_name"] == BREED_NAME + + +async def test_association_changes_only_one_boolean_binding() -> None: + """The app serializes a Boolean associate value and integer pet/device IDs.""" + api = client() + before = [{"pet_id": 7, "is_associated": False}, {"pet_id": 8, "is_associated": True}] + api.request.side_effect = [PROFILE, before, {}, before] + result = await PetApi(api).associate(BOX_ID, PET_ID, enabled=True) + api.request.assert_any_await( + "POST", "/device/associate_pet", data={"pet_id": 7, "user_device_id": 123, "associate": True} + ) + assert result == before + + +@pytest.mark.parametrize("rows", [[{"pet_id": 8, "is_associated": True}], [{"pet_id": 7, "is_associated": None}]]) +async def test_unknown_association_target_or_state_never_writes(rows: list[JsonObject]) -> None: + """Never blindly toggle a pet missing from the selected device's fresh candidates.""" + api = client() + api.request.side_effect = [PROFILE, rows] + with pytest.raises(NottyApiError): + await PetApi(api).associate(BOX_ID, PET_ID, enabled=True) + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +async def test_create_memo_exact_text_contract() -> None: + """Create uses memo_id zero, integer pet ID, raw clock text and Boolean reminder.""" + api = client() + api.request.side_effect = [PROFILE, {}] + await MemoApi(api).save(PET_ID, {"title": " Visit ", "content": "Routine visit", "date": "2026-10-16 15:00"}) + api.request.assert_awaited_with( + "POST", + "/pet/add_memo", + data={ + "pet_id": 7, + "memo_id": 0, + "title": "Visit", + "content": "Routine visit", + "date": "2026-10-16 15:00", + "remind": False, + "expired": False, + }, + ) + + +async def test_memo_global_id_requires_fresh_pet_membership() -> None: + """A memo from another pet cannot be retrieved or edited by guessing its ID.""" + api = client() + memos = MemoApi(api) + memos.list_memos = AsyncMock(return_value=[{"memo_id": 99}]) + with pytest.raises(NottyApiError): + await memos.detail(PET_ID, 42) + api.request.assert_not_awaited() + + +@pytest.mark.parametrize( + "changes", + [ + {"pet_id": 8}, + {"memo_id": 99}, + {"date": "2026-10-16T15:00:00Z"}, + {"remind": 1}, + {"title": ""}, + {"content": "\x00"}, + ], +) +def test_memo_edits_reject_identity_clock_and_state_guessing(changes: JsonObject) -> None: + """Unsupported timestamps and injected targets cannot become API writes.""" + with pytest.raises(NottyApiError): + memo_payload(PET_ID, MEMO, changes, create=False) + + +@pytest.mark.parametrize("value", [None, {}, {"data": None}, [None], [1]]) +def test_record_lists_do_not_hide_unavailable_or_malformed_responses(value: JsonValue) -> None: + """An endpoint failure must not look like an empty association/memo list.""" + with pytest.raises(NottyApiError): + object_rows(value) + + +async def test_memo_edit_preserves_omitted_fields_and_native_identity() -> None: + """Changing content keeps reminder/date/title and targets the listed memo only.""" + api = client() + api.request.side_effect = [PROFILE, PROFILE, [MEMO], MEMO, {}] + await MemoApi(api).save(PET_ID, {"content": "Updated visit"}, memo_id=42) + api.request.assert_awaited_with("POST", "/pet/edit_memo", data={**MEMO, "pet_id": 7, "content": "Updated visit"}) + + +async def test_memo_detail_rejects_a_different_pet_in_readback() -> None: + """Even a listed global ID cannot override mismatched detail ownership.""" + api = client() + api.request.side_effect = [PROFILE, [MEMO], {**MEMO, "pet_id": 8}] + with pytest.raises(NottyApiError, match="another pet"): + await MemoApi(api).detail(PET_ID, 42) + assert all(call.args[0] == METHOD_GET for call in api.request.await_args_list) + + +async def test_shared_pet_cannot_create_a_memo() -> None: + """Memo edits require the same fresh owner permission as profile changes.""" + api = client() + api.request.return_value = {**PROFILE, "is_owner": False} + 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) diff --git a/tests/test_reminders.py b/tests/test_reminders.py index af658f7..e0d6402 100644 --- a/tests/test_reminders.py +++ b/tests/test_reminders.py @@ -61,11 +61,12 @@ async def test_wire_contract(reminder: Reminder, operation: int) -> None: @pytest.mark.parametrize( "action", ["reset_litter_reminder", "reset_garbage_bag_reminder", "set_garbage_bag_reminder_days"] ) -async def test_unverified_reminder_operations_do_not_write(action: str) -> None: +async def test_reminder_edits_without_current_state_do_not_write(action: str) -> None: """Observed action 2 disables reminders and must not be reused for reset/update.""" api = NottyApi(MagicMock()) api.request = AsyncMock() - with pytest.raises(NottyApiError, match="disabled pending live endpoint verification"): + api.litter_info = AsyncMock(return_value={}) + with pytest.raises(NottyApiError, match="enabled reminder"): await api.litter_action("box-1", action, {"cycle_time": 10}) api.request.assert_not_awaited() @@ -74,6 +75,7 @@ async def test_litter_interval_action_three_wire_contract() -> None: """Owner observed action 3 changing enabled litter interval from 30 to 29.""" api = NottyApi(MagicMock()) api.request = AsyncMock() + api.litter_info = AsyncMock(return_value={"open_litter_remind": True, "default_remaining_days": 30}) await api.litter_action("box-1", "set_litter_reminder_days", {"cycle_time": 29}) api.request.assert_awaited_once_with( "POST", @@ -213,18 +215,18 @@ async def test_unknown_state_cannot_be_written( ("reset_garbage_bag_reminder", "garbage_bag_cycle_time", 7), ], ) -async def test_reset_button_is_blocked_until_verified( +async def test_reset_button_uses_action_three_and_the_configured_cycle( hass: HomeAssistant, runtime_api: MagicMock, button: str, cycle_key: str, cycle: int ) -> None: """Action 2 disables the device; never use it for a reset button.""" runtime_api.device_info.return_value[cycle_key] = cycle + runtime_api.device_info.return_value[ + "open_litter_remind" if button == RESET_LITTER else "open_garbagebag_remind" + ] = True await setup(hass) entity_name = "reset_litter_renewal_reminder" if button == RESET_LITTER else "reset_trash_bag_reminder" - with pytest.raises(HomeAssistantError, match="disabled pending live endpoint verification"): - await hass.services.async_call( - "button", "press", {"entity_id": f"button.test_box_{entity_name}"}, blocking=True - ) - runtime_api.litter_action.assert_not_awaited() + await hass.services.async_call("button", "press", {"entity_id": f"button.test_box_{entity_name}"}, blocking=True) + runtime_api.litter_action.assert_awaited_once_with("box-1", button, {"action": 3, "cycle_time": cycle}) runtime_api.endpoint_action.assert_not_awaited() @@ -337,7 +339,7 @@ async def test_generic_litter_interval_rejects_unchanged(hass: HomeAssistant, ru @pytest.mark.parametrize("reminder", REMINDERS) -async def test_generic_reset_service_is_blocked( +async def test_generic_reset_service_requires_an_explicit_cycle( hass: HomeAssistant, runtime_api: MagicMock, reminder: Reminder ) -> None: """An existing cycle does not justify sending unverified reset action codes.""" @@ -345,7 +347,7 @@ async def test_generic_reset_service_is_blocked( reset_action = "reset_litter_reminder" if action == ACTION_LITTER else "reset_garbage_bag_reminder" runtime_api.device_info.return_value[cycle_key] = cycle await setup(hass) - with pytest.raises(HomeAssistantError, match="disabled pending live endpoint verification"): + with pytest.raises(HomeAssistantError, match="cycle_time"): await hass.services.async_call( "notty", "litter_box_action", {"user_device_id": "box-1", "action": reset_action}, blocking=True ) @@ -361,7 +363,7 @@ async def test_generic_reset_service_rejects_missing_interval( reset_action = "reset_litter_reminder" if action == ACTION_LITTER else "reset_garbage_bag_reminder" runtime_api.device_info.return_value["remaining_days"] = 12 await setup(hass) - with pytest.raises(HomeAssistantError, match="disabled pending live endpoint verification"): + with pytest.raises(HomeAssistantError, match="cycle_time"): await hass.services.async_call( "notty", "litter_box_action", {"user_device_id": "box-1", "action": reset_action}, blocking=True ) diff --git a/uv.lock b/uv.lock index 3976c8a..9bb7ebc 100644 --- a/uv.lock +++ b/uv.lock @@ -1916,7 +1916,7 @@ wheels = [ [[package]] name = "notty-home-assistant" -version = "0.3.0" +version = "0.4.0" source = { virtual = "." } dependencies = [ { name = "aiohttp" },