Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ cleaning mode unchanged. The app describes Scheduled mode as cleaning at configu
fixed times; behavior outside that mode and with an empty plan list remains
unverified. Create does not send an enable state, matching the app; inspect readback
to see the server's resulting state. Update preserves a disabled plan by omitting
its enable field. Unknown plan quantity/recurrence types block time edits.
its enable field. Unknown plan quantities/types block time edits. Live litter-box plans use `plan_type_id: 2` and may omit quantity; the app's edit payload still uses `quantity: 1`.

**Times are raw NOTTY schedule-clock values in `HH:MM`, not Home Assistant local
times or UTC timestamps.** Readback returns `clock_basis: notty_schedule_clock`
Expand Down
32 changes: 27 additions & 5 deletions custom_components/notty/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
ACTION_SET_AUTO_DELAY = "set_auto_delay"
ACTION_SET_ALIAS = "set_alias"
ACTION_SET_LANGUAGE = "set_language"
ACTION_SET_KEY = "set_key"
MODE_SCHEDULED = 2
MIN_ALIAS_UNITS = 2
MAX_ALIAS_UNITS = 8
Expand All @@ -34,6 +35,7 @@
PLAN_ACTIONS = set(PLAN_FIELDS)
PLAN_TIME_RE = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
MAX_LITTER_PLANS = 10
LITTER_PLAN_TYPE_ID = 2


ACTION_SET_MODE = "set_mode"
Expand Down Expand Up @@ -134,6 +136,24 @@
_LOGGER = logging.getLogger(__name__)


def child_lock_payload(device_id: str, data: JsonObject) -> JsonObject:
"""Construct the app's exact integer child-lock fields.

Returns:
Only integer user_device_id and switch; no legacy device_id alias.

Raises:
NottyApiError: If identity, fields or switch encoding is invalid.
"""
if not device_id.isascii() or not device_id.isdecimal() or int(device_id) <= 0:
msg = "Child lock requires a positive numeric physical device ID"
raise NottyApiError(msg)
if set(data) != {"switch"} or type(data.get("switch")) is not int or data["switch"] not in {0, 1}:
msg = "Child lock accepts only integer switch 0 or 1"
raise NottyApiError(msg)
return {"user_device_id": int(device_id), "switch": data["switch"]}


def matches_value(value: object, choices: tuple[object, ...]) -> bool:
"""Compare JSON values without requiring hashability.

Expand Down Expand Up @@ -248,11 +268,11 @@ def _plan_time_fields(data: JsonObject, current: JsonObject) -> JsonObject:
if not isinstance(clock, str) or not PLAN_TIME_RE.fullmatch(clock):
msg = "Schedule time must be a NOTTY clock value in HH:MM format"
raise NottyApiError(msg)
for field in ("quantity", "plan_type_id"):
value = current.get(field, 1)
if type(value) is not int or value != 1:
msg = "Cannot edit an unsupported schedule quantity or recurrence type"
raise NottyApiError(msg)
quantity = current.get("quantity", 1)
plan_type = current.get("plan_type_id", LITTER_PLAN_TYPE_ID)
if type(quantity) is not int or quantity != 1 or type(plan_type) is not int or plan_type != LITTER_PLAN_TYPE_ID:
msg = "Cannot edit an unsupported schedule quantity or plan type"
raise NottyApiError(msg)
return {"time": clock, "quantity": 1}


Expand Down Expand Up @@ -1332,6 +1352,8 @@ async def litter_action(self, device_id: str, action: str, data: JsonObject | No
return await self.request("POST", path, data=payload)

async def _setting_payload(self, device_id: str, action: str, data: JsonObject) -> JsonObject | None:
if action == ACTION_SET_KEY:
return child_lock_payload(device_id, data)
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
Expand Down
2 changes: 1 addition & 1 deletion custom_components/notty/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
"iot_class": "cloud_polling",
"issue_tracker": "https://github.com/Repsay/notty/issues",
"requirements": [],
"version": "0.4.0"
"version": "0.4.1"
}
12 changes: 9 additions & 3 deletions docs/apk-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ output remain local and ignored. Tests use synthetic data.
| Litter renewal reminder | `open_litter_remind`, `default_remaining_days`, `remaining_days` | `/device/litter_box/set_litter_remind`: `action` (1 enable, 2 disable) and required `cycle_time`; `user_device_id` |
| Trash bag reminder | `open_garbagebag_remind`, `garbage_bag_cycle_time`, `garbage_bag_remaining_days` | `/device/litter_box/set_garbage_bag_remind`: `action` (1 enable, 2 disable) and required `cycle_time`; `user_device_id` |

The client currently adds a `device_id` alias alongside `user_device_id` for
device actions. That is existing compatibility behavior, not a field established
by these app paths.
Some older device actions retain a `device_id` alias alongside `user_device_id`.
That is compatibility behavior, not a field established by these app paths.
Child lock now uses only the exact APK fields.

## Child lock (#11)

Expand All @@ -24,6 +24,12 @@ in context field `0x13`. Its shared closure at `0xccd7dc` converts the Dart bool
to an integer (`cset`, then the Dart small-integer tag shift): true becomes `1`,
false becomes `0`. The map inserts `switch` at `0xcd3ebc` and POSTs at `0xcd3f04`.
Reading state continues to use `switch_key` and entity unique IDs are unchanged.
The physical-ID closure `0xcc1b14` boxes the controller ID as an integer. The
child-lock builder now sends exactly integer `user_device_id` and integer
`switch`, rejecting legacy aliases, target overrides and non-enum values. An
owner-authorized live change and restoration both matched fresh API readback
after two seconds on 17 October 2026. This verifies the endpoint flag transition,
not physical button behavior on every model.

## Do Not Disturb (#12)

Expand Down
9 changes: 9 additions & 0 deletions docs/apk-schedules.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,12 @@ read-only listing and failures without retries. No schedule writes were performe
against the owner's account or physical device. Server acceptance, creation's
default enable state, actual firing time, DST behavior and recurrence require
owner-observed live checks; #17 remains open for that validation.

## Live plan-schema correction (17 October 2026)

Fresh litter-box plans, including a temporary plan created with this client,
report `plan_type_id: 2` and omit `quantity`. The earlier synthetic type-1
assumption incorrectly blocked edits. Editing now accepts the observed type 2
(or absent type metadata) and quantity 1 (or absent quantity), while rejecting
unknown types/quantities. The write still sends only time, quantity 1 and the
selected native plan ID. No recurrence meaning is inferred from the type marker.
67 changes: 65 additions & 2 deletions docs/app-validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,11 +110,11 @@ uv run python scripts/validate_lock.py \
```

`--roundtrip` restores and checks the original lock, mode/delay/language, alias,
pet edited fields or notification category. It attempts restoration even after
pet edited fields, a selected association or notification category. It attempts restoration even after
an uncertain write failure. Inspect the restoration file and app before retrying
an interrupted test. Immediate readback may lag; a mismatch needs investigation,
not a blind repeat. Roundtrips are deliberately rejected for motor commands,
reminder countdowns, schedules, timezone changes, associations, memos, firmware
reminder countdowns, schedules, timezone changes, memos, firmware
and deleted history because their original effect cannot be generically restored.
Those operations can be selected explicitly without `--roundtrip`.

Expand Down Expand Up @@ -207,3 +207,66 @@ or history deletion was performed in this development run. Those scripts exist
for explicit owner-selected tests with app/physical observations. No empty command
was sent. Raw captures and editable app-value templates remain private under
`probe-output/app-validation-20261017/`; they are not published in GitHub.

## Follow-up verification, 17 October 2026

The child-lock request now follows the exact APK contract: integer
`user_device_id`, integer `switch`, and no legacy `device_id` field. A live
transition and restoration both matched API readback after two seconds. This
resolves the earlier unchanged-immediate-readback result. The scripts now poll
GET readback after one mutation; they never resend a write while waiting.
Use `--readback-attempts 4 --readback-interval 2` to control the bounded wait.
Restoration also waits for matching readback. A final mismatch remains a failure.

DND off/on, English/Icons and Auto/Soft stool changes were also observed in live
API readback, then restored. Raw DND boundaries and LED were unchanged throughout.
DND switch-only and selected known-association roundtrips are now supported; clock edits still require explicit
before/after app verification. Actual scheduled firing and DST remain separate
checks, not implied by matching JSON clocks. The device currently reports
`auto_delay: 0`, outside the app-traced 1–15 minute write options; an automatic
roundtrip must not alter it because the original value cannot be safely restored
through that established contract.

Inspect coverage of every in-scope issue without contacting NOTTY:

```sh
uv run python scripts/validation_status.py \
--evidence-dir /absolute/path/to/probe-output
```

This lists script coverage, observed API/app comparisons, failures and restoration
results. It does not automatically close an issue or treat a script's existence
as successful validation. Older failure reports can coexist with newer passes.
Feeders/water (#27/#28) remain deferred. See [issue coverage](validation-coverage.md).

Monitor an owner-selected firmware update without starting another installation:

```sh
uv run python scripts/monitor_firmware.py \
--session-file probe-output/session.private.json \
--device-id YOUR_PHYSICAL_BOX_ID \
--output-dir probe-output/firmware-observation \
--samples 12 --interval 10
```

Each sample and the selected target are saved privately. To continue after
restarting the script, pass `--target-version EXACT_PREVIOUS_TARGET` and a new
output directory. Only matching installed-version readback confirms completion;
a success status alone does not. A failure from a different offered target is
not attributed to the selected update. No firmware is installed by this monitor,
no percentage is inferred, and this does not add restart persistence or realtime
firmware-event subscriptions to HA itself. On the owner's current device there
is no offered firmware update, so installation/failure lifecycle validation needs
a future offer.

The follow-up schedule test found and fixed a real edit guard error: litter-box
plans report `plan_type_id: 2`, not the earlier assumed 1. After correction,
a temporary plan passed create, edit, disable, enable and delete. Scheduled mode
readback also matched, then the original mode and all original plan records
were restored. A selected pet association was toggled and restored with matching
readback. Actual scheduled physical firing still needs observation; these
roundtrips do not assert that it occurred.

Completed implementation tickets link to [#42](https://github.com/Repsay/notty/issues/42)
for their remaining external acceptance checks. #21, #22 and #41 retain the
specific timezone, firmware and measured-weight work. Emptying is excluded.
35 changes: 35 additions & 0 deletions docs/validation-coverage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Remaining-issue coverage

Every in-scope issue has implementation/contract tests and a dedicated live
validation command. Tests do not operate hardware. Command examples and explicit
write payloads are in [app-validation.md](app-validation.md). Emptying is blocked.

| Issue | Current implementation / evidence | Validation command | Remaining acceptance |
| --- | --- | --- | --- |
| #11 | Exact integer lock payload; live flag change/restoration confirmed | `validate_lock.py` | Optional physical-button/app observation on other models |
| #12 | Shared DND builder; live switch change/restoration preserves raw clocks/LED | `validate_dnd.py` | DST/actual schedule firing belongs to #21 |
| #14 | Email-code metadata and migration implemented; authenticated reads work | `validate_login.py` | Fresh code exchange with current metadata; HA expiry/reauth flow |
| #15 | Central APK mappings clean=1, empty=2, level=3 | `validate_cleaning.py` | Observe clean/level effects; empty testing is excluded by owner |
| #16 | 1–15 minute Auto-only select and guarded action | `validate_settings.py` | Owner device reports 0; determine its meaning before a restorable write test |
| #17 | Plan CRUD/toggle fixed for live type 2 and validated with cleanup | `validate_schedules.py` | Actual scheduled physical firing |
| #19 | APK enums and guarded mode writes; all three mode readbacks passed with restoration | `validate_settings.py` | Actual scheduled physical firing and broader model behavior |
| #20 | Alias entity, stable HA IDs/override tests; live rename/restoration passed | `validate_alias.py` | Broader model acceptance only |
| #21 | Catalog/change actions, snapshot drift reporting and DST unit tests | `validate_timezone.py` | Explicit timezone transition and actual firing across date/DST boundaries |
| #22 | Update availability/install and Boolean pending target implemented | `validate_firmware.py`, `monitor_firmware.py` | Future offered update; realtime events and HA restart persistence remain unimplemented |
| #23 | Scoped association actions, preservation tests and a live restored association toggle | `validate_associations.py` | Selected association change/restoration and app readback |
| #24 | Account category switches/actions; live toggle/restoration passed | `validate_notifications.py` | Broader app/model acceptance only |
| #25 | Scoped text memo list/detail/create/edit implemented | `validate_memos.py` | Selected text memo lifecycle and app date/reminder semantics |
| #26 | Explicit irreversible empty-body statistics-clear action | `validate_statistics.py` | Exact affected counters/history, only when deletion is wanted |
| #41 | Private weight before/after probes and cat-ID validation | `probe_weights.py` | Independently observed visits, measured source/freshness/history; upstream attribution is outside scope |
| #42 | Consolidated live acceptance checklist | `validation_status.py` plus feature scripts | Remaining physical/app observations; no untested criterion is treated as passed |
| #27/#28 | Deferred by owner | None | Feeder/water support excluded |

HA unit tests cover entity lifecycle, account ownership, request contracts,
invalid targets, name overrides, IDs, unknown data and failure recovery. A real HA
installation is still needed to observe device/model-specific UI and expired
session reauthentication. Firmware-event support and measured weight/history are
separate development work; monitoring scripts do not imply they are implemented.

`validation_status.py` audits script coverage and private report counts without
publishing names, weights, account IDs, credentials or capture contents. It keeps
API readback, app-field matches and full acceptance distinct.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "notty-home-assistant"
version = "0.4.0"
version = "0.4.1"
description = "NOTTY smart litter box integration for Home Assistant"
readme = "README.md"
requires-python = ">=3.14.2"
Expand Down
23 changes: 23 additions & 0 deletions release-notes/v0.4.1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# NOTTY v0.4.1

Fix litter-box schedule editing: live plans report plan_type_id 2 and omit
quantity. The previous type-1 assumption rejected those plans. Keep unknown
plan types/quantities blocked while sending the app's quantity-1 edit payload.

Fix the child-lock request to send only the APK's integer physical
`user_device_id` and integer `switch` fields. Legacy target aliases, extra fields
and loosely coerced switch values are rejected. A live lock transition and
restoration matched fresh readback after two seconds.

Validation scripts now wait for bounded GET readback after a single write and
again after restoring a setting. Add DND switch-only and scoped association roundtrips, a read-only
firmware lifecycle monitor and a private-evidence coverage audit for all
in-scope issues. Empty-litter commands remain prohibited in validation tools.

Live DND, screen-language, association and all three cleaning-mode changes were
restored. Temporary schedule CRUD/toggle validation restored every original plan; raw
DND clocks/LED stayed unchanged. Actual scheduled firing/DST, fresh login-code
exchange, a future firmware offer and independently observed cat weigh-ins still
need their own acceptance evidence. Feeders and water dispensers remain deferred.

Update through HACS and restart Home Assistant. Existing entity IDs are retained.
35 changes: 34 additions & 1 deletion scripts/app_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
ALIAS = "alias"
PETS = "pets"
NOTIFICATIONS = "notifications"
DND = "dnd"
ASSOCIATIONS = "associations"


@dataclass
Expand Down Expand Up @@ -337,6 +339,8 @@ def restore_request(feature: str, operation: str, changes: JsonObject, before: J
"""
if feature in {"lock", "settings"} and operation in {SET_KEY, SET_DELAY, SET_MODE, "set_language"}:
return _setting_restore(operation, changes, before)
if feature == DND and operation == SET_DND:
return _dnd_restore(changes, before)
if feature == ALIAS:
device = before.get("device")
if isinstance(device, dict):
Expand All @@ -347,11 +351,13 @@ def restore_request(feature: str, operation: str, changes: JsonObject, before: J
profile = before.get("profile")
if isinstance(profile, dict) and all(key in profile for key in changes):
return "update", profile_changes({key: profile[key] for key in changes})
if feature == ASSOCIATIONS:
return _association_restore(changes, before)
if feature == NOTIFICATIONS:
restored = _notification_restore(changes, before)
if restored is not None:
return restored
msg = "Automatic restoration is supported only for lock, mode/delay/language, alias, pet fields and notifications"
msg = "Automatic restoration requires a supported lock/DND toggle, mode/delay/language, alias, pet field, association or notification change"
raise NottyApiError(msg)


Expand Down Expand Up @@ -382,3 +388,30 @@ def _setting_restore(operation: str, changes: JsonObject, before: JsonObject) ->
msg = "Original setting is outside the restorable write range"
raise NottyApiError(msg)
return operation, {field: value}


def _dnd_restore(changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]:
require_fields(changes, {"switch_dnd"})
info = before.get("info")
state = plan_enabled(info.get("switch_dnd")) if isinstance(info, dict) else None
if state is None:
msg = "DND restoration requires a known original switch state"
raise NottyApiError(msg)
return SET_DND, {"switch_dnd": int(state)}


def _association_restore(changes: JsonObject, before: JsonObject) -> tuple[str, JsonObject]:
require_fields(changes, set())
profile = before.get("profile")
rows = before.get("associations")
pet_id = identifier(profile.get("pet_id")) if isinstance(profile, dict) else None
matches = (
[row for row in rows if isinstance(row, dict) and row.get("pet_id") == pet_id] if isinstance(rows, list) else []
)
state = (
plan_enabled(matches[0].get("is_associated")) if len(matches) == 1 and isinstance(matches[0], dict) else None
)
if state is None:
msg = "Association restoration requires one known account pet and binding state"
raise NottyApiError(msg)
return ASSOCIATE if state else "disassociate", {}
Loading
Loading