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
33 changes: 27 additions & 6 deletions custom_components/notty/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -354,22 +354,41 @@ def timezone_catalog(value: JsonValue) -> list[JsonObject]:
return rows


def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject]) -> JsonObject:
"""Use the selected Windows catalog ID in the APK's misnamed IANA field.
def timezone_payload(device_id: str, catalog_id: str, rows: list[JsonObject], *, iana_time_zone: str) -> JsonObject:
"""Send a real IANA zone; live testing disproved the APK's Windows-name payload.

Returns:
Only the two fields serialized by the app.

Raises:
NottyApiError: If the physical ID or catalog membership is invalid.
NottyApiError: If the physical ID, catalog membership or IANA name is invalid.
"""
if not device_id.isascii() or not device_id.isdecimal() or int(device_id) <= 0:
msg = "Timezone changes require a positive numeric physical device ID"
raise NottyApiError(msg)
if not any(row["id"] == catalog_id for row in rows):
msg = "Choose an exact ID from the current NOTTY timezone catalog"
raise NottyApiError(msg)
return {"user_device_id": int(device_id), "time_zone_iana": catalog_id}
return {"user_device_id": int(device_id), "time_zone_iana": validated_iana_zone(iana_time_zone)}


def validated_iana_zone(value: JsonValue) -> str:
"""Validate an explicit IANA identifier without mapping Windows catalog names.

Returns:
The unchanged valid IANA name.

Raises:
NottyApiError: If the supplied value is not a known IANA name.
"""
msg = "Timezone changes require a valid IANA name, not a Windows catalog ID"
if not isinstance(value, str):
raise NottyApiError(msg)
try:
ZoneInfo(value)
except KeyError, ValueError, TypeError:
raise NottyApiError(msg) from None
return value


def reminder_payload(action: str, data: JsonObject) -> JsonObject:
Expand Down Expand Up @@ -716,15 +735,17 @@ async def time_zones(self) -> list[JsonObject]:
"""
return timezone_catalog(await self.request("GET", "/entity/get_time_zones"))

async def change_time_zone(self, device_id: str, catalog_id: str) -> JsonValue:
async def change_time_zone(self, device_id: str, catalog_id: str, *, iana_time_zone: str) -> JsonValue:
"""Validate fresh catalog membership before one explicit timezone write.

Returns:
The server acknowledgement, not proof of schedule preservation.
"""
rows = await self.time_zones()
return await self.request(
"POST", "/device/change_time_zone", data=timezone_payload(device_id, catalog_id, rows)
"POST",
"/device/change_time_zone",
data=timezone_payload(device_id, catalog_id, rows, iana_time_zone=iana_time_zone),
)


Expand Down
6 changes: 5 additions & 1 deletion custom_components/notty/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -586,8 +586,12 @@ async def _pet_info(self, device: JsonObject) -> JsonObject:
"litter_user_device_id": device.get("_notty_litter_user_device_id"),
"_notty_related": related,
}
_merge_scalar_fields(info, device)
related_info = related.get("info")
# Current profile readings take precedence over discovery summaries.
# Missing daily readings/units must not revive an older discovery value.
for field in ("today_weight", "yesterday_weight", "weight_unit"):
if field in device or (isinstance(related_info, dict) and field in related_info):
info[field] = related_info.get(field) if isinstance(related_info, dict) else None
if isinstance(related_info, dict):
pet_devices = related_info.get("pet_devices")
if isinstance(pet_devices, list):
Expand Down
12 changes: 11 additions & 1 deletion custom_components/notty/device_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

from collections.abc import Awaitable, Callable

from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError, plan_enabled
from custom_components.notty.feature_contracts import identifier, object_rows, true_state

Expand Down Expand Up @@ -97,7 +99,13 @@ class FirmwareApi:
def __init__(self, api: NottyApi) -> None:
self.api = api

async def install(self, device_id: str, version: str | None = None) -> str:
async def install(
self,
device_id: str,
version: str | None = None,
*,
before_confirm: Callable[[str, JsonObject], Awaitable[None]] | None = None,
) -> str:
"""Confirm only the currently offered task for an owned litter box.

Returns:
Expand Down Expand Up @@ -125,6 +133,8 @@ async def install(self, device_id: str, version: str | None = None) -> str:
if not firmware_task_id(task) or not isinstance(status, str) or status not in FIRMWARE_IDLE_STATUSES:
msg = "Firmware task is absent, busy or has an unknown status"
raise NottyApiError(msg)
if before_confirm is not None:
await before_confirm(target, current)
await self.api.request(
"POST", "/device/confirm_upgrade", data={"user_device_id": identifier(device_id), "task_id": task}
)
Expand Down
77 changes: 71 additions & 6 deletions custom_components/notty/device_timezone.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,15 @@
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse
from homeassistant.exceptions import HomeAssistantError

from custom_components.notty.api import JsonObject, JsonValue, NottyApi, NottyApiError
from custom_components.notty.api import (
JsonObject,
JsonValue,
NottyApi,
NottyApiError,
dnd_local_time,
dnd_payload,
validated_iana_zone,
)
from custom_components.notty.const import DOMAIN
from custom_components.notty.coordinator import NOTTY_SERVER_TIME_ZONE, NottyCoordinator
from custom_components.notty.validation import vol
Expand Down Expand Up @@ -55,35 +63,90 @@ def timezone_change_fields(fields: JsonObject) -> str:
Raises:
NottyApiError: If fields are missing, extra or invalid.
"""
if set(fields) != {"catalog_id", "confirm_schedule_change"} or fields.get("confirm_schedule_change") is not True:
msg = "Timezone changes require catalog_id and confirm_schedule_change: true"
required = {"catalog_id", "iana_time_zone", "confirm_schedule_change"}
if not required <= fields.keys() or fields.keys() - required - {"preserve_dnd_local_times"}:
msg = "Timezone changes require catalog_id, iana_time_zone and confirm_schedule_change: true"
raise NottyApiError(msg)
if (
fields.get("confirm_schedule_change") is not True
or type(fields.get("preserve_dnd_local_times", False)) is not bool
):
msg = "Timezone acknowledgement and preservation must be Booleans"
raise NottyApiError(msg)
identifier = fields["catalog_id"]
if not isinstance(identifier, str) or not identifier.strip():
msg = "Choose an exact string ID from the NOTTY catalog"
raise NottyApiError(msg)
zone = fields["iana_time_zone"]
if not isinstance(zone, str):
msg = "Choose an explicit IANA timezone name"
raise NottyApiError(msg)
validated_iana_zone(zone)
return identifier


def _local_dnd(snapshot: JsonObject) -> JsonObject:
settings, zone = snapshot.get("settings"), snapshot.get("reported_iana")
if not isinstance(settings, dict) or not isinstance(zone, str):
msg = "DND preservation needs readable settings and a valid device IANA zone"
raise NottyApiError(msg)
dnd_payload({**settings, "time_zone_iana": zone})
return {
key: dnd_local_time(settings.get(key), zone).strftime("%H:%M") for key in ("dnd_begin_time", "dnd_end_time")
}


async def _preserve_dnd(api: NottyApi, device_id: str, before: JsonObject, after: JsonObject) -> JsonObject:
settings = before.get("settings")
if not isinstance(settings, dict):
msg = "DND preservation requires the original settings"
raise NottyApiError(msg)
local = _local_dnd(before)
current = {**settings, "time_zone_iana": after.get("reported_iana")}
# The API can shift its raw DND fields on timezone changes. Preserve the
# owner's original local wall clocks, flags and LED with one explicit write.
await api.litter_action(
device_id,
"set_dnd",
dnd_payload(current, dnd_begin_time=local["dnd_begin_time"], dnd_end_time=local["dnd_end_time"]),
)
return await timezone_snapshot(api, device_id)


async def change_with_readback(api: NottyApi, device_id: str, fields: JsonObject) -> JsonObject:
"""Make at most one write; report setting drift without retries or restoration.
"""Change the timezone once and optionally preserve DND, without replay or rollback.

Returns:
Before/after readback. Matching fields do not prove unchanged firing times.
"""
identifier = timezone_change_fields(fields)
zone = str(fields["iana_time_zone"])
preserve = fields.get("preserve_dnd_local_times") is True
before = await timezone_snapshot(api, device_id)
if before["reported_windows"] == identifier:
if preserve:
_local_dnd(before)
if before["reported_windows"] == identifier and before["reported_iana"] == zone:
return {"status": "unchanged", "before": before, "after": before}
await api.change_time_zone(device_id, identifier)
await api.change_time_zone(device_id, identifier, iana_time_zone=zone)
try:
after = await timezone_snapshot(api, device_id)
except NottyApiError:
return {"status": "write_acknowledged_readback_failed", "before": before}
if after["reported_iana"] != zone or after["reported_windows"] != identifier:
return {"status": "timezone_readback_mismatch", "before": before, "after": after}
preservation: str = "not_requested"
if preserve:
try:
after = await _preserve_dnd(api, device_id, before, after)
preservation = "local_clocks_match" if _local_dnd(before) == _local_dnd(after) else "local_clock_mismatch"
except NottyApiError:
return {"status": "timezone_changed_dnd_preservation_failed", "before": before, "after": after}
changed: list[JsonValue] = [key for key in ("settings", "plans") if before[key] != after[key]]
return {
"status": "write_acknowledged_verify_in_app",
"requested_catalog_id": identifier,
"requested_iana_time_zone": zone,
"dnd_preservation": preservation,
"before": before,
"after": after,
"changed_schedule_fields": changed,
Expand Down Expand Up @@ -137,6 +200,8 @@ async def handle(call: ServiceCall) -> JsonObject:
vol.Required("user_device_id"): validator,
vol.Required("operation"): vol.In(("list", "change")),
vol.Optional("catalog_id"): str,
vol.Optional("iana_time_zone"): str,
vol.Optional("preserve_dnd_local_times"): bool,
vol.Optional("confirm_schedule_change"): bool,
}
hass.services.async_register(
Expand Down
2 changes: 1 addition & 1 deletion custom_components/notty/feature_contracts.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def profile_payload(pet_id: str, current: JsonObject, changes: JsonObject) -> Js
msg = "Pet editing requires the current positive profile weight"
raise NottyApiError(msg)
unit = current.get("weight_unit")
if type(unit) is not int or unit not in {0, 1}:
if type(unit) is not int or unit not in {1, 2}:
msg = "Pet editing requires a known current weight unit"
raise NottyApiError(msg)
devices = object_rows(current.get("pet_devices"))
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.1"
"version": "0.4.2"
}
62 changes: 57 additions & 5 deletions custom_components/notty/sensor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from datetime import UTC, datetime
import math
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError

from homeassistant.components.sensor import SensorDeviceClass, SensorEntity, SensorStateClass
Expand Down Expand Up @@ -78,6 +79,8 @@
)

WEIGHT_KEYS = {"today_weight", "yesterday_weight", "total_weight", "weight"}
POUNDS_TO_KILOGRAMS = 0.45359237
WEIGHT_UNIT_FACTORS: dict[str | None, float] = {"kg": 1.0, "lb": POUNDS_TO_KILOGRAMS}
TIMESTAMP_KEYS = {
"latest_message_date_created",
"messages_date_created",
Expand Down Expand Up @@ -313,10 +316,23 @@ async def async_setup_entry( # ruff: ignore[unused-async] -- Home Assistant req
) -> None:
"""Async setup entry."""
coordinator = entry.runtime_data
entities: list[NottySensor] = []
for device_id, block in coordinator.data.items():
entities.extend(NottySensor(coordinator, device_id, block["device"], key) for key in sensor_keys(block))
async_add_entities(entities)
known: set[tuple[str, str]] = set()

def discover() -> None:
"""Discover recovered optional fields without duplicating existing entities."""
entities: list[NottySensor] = []
for device_id, block in coordinator.data.items():
keys = set(sensor_keys(block))
keys.update((WEIGHT_KEYS - SKIP_KEYS).intersection(merged_device_data(block)))
for key in sorted(keys):
if (device_id, key) not in known:
entities.append(NottySensor(coordinator, device_id, block["device"], key))
known.add((device_id, key))
if entities:
async_add_entities(entities)

discover()
entry.async_on_unload(coordinator.async_add_listener(discover))


class NottySensor(NottyEntity, SensorEntity):
Expand All @@ -329,6 +345,12 @@ def __init__(self, coordinator: NottyCoordinator, device_id: str, device: Device
self._attr_entity_category = EntityCategory.DIAGNOSTIC
raw_value = value_from_block(self.block, self.key)
device_class, unit, state_class = sensor_metadata(key, raw_value)
if key in WEIGHT_KEYS:
device_class, unit, state_class = (
SensorDeviceClass.WEIGHT,
UnitOfMass.KILOGRAMS,
SensorStateClass.MEASUREMENT,
)
if device_class is not None:
self._attr_device_class = device_class
if unit is not None:
Expand All @@ -344,6 +366,8 @@ def native_value(self) -> StateType | datetime:
StateType | datetime: The resulting native value.
"""
raw_value = value_from_block(self.block, self.key)
if self.key in WEIGHT_KEYS:
return self._weight_in_kilograms(raw_value)
timestamp_value = _parse_timestamp_value(raw_value)
if timestamp_value is not None and (
DATETIME_FIELD_FRAGMENT in self.key or self.key in {"latest_message_date_created", "messages_date_created"}
Expand All @@ -354,14 +378,42 @@ def native_value(self) -> StateType | datetime:
value = _number_or_original(raw_value)
return value if isinstance(value, (str, int, float)) else None

def _weight_in_kilograms(self, raw_value: JsonValue) -> float | None:
value = _number_or_original(raw_value)
if isinstance(value, bool) or not isinstance(value, (int, float)):
return None
try:
finite = math.isfinite(value)
except OverflowError:
return None
if not finite or value <= 0:
return None
unit = self._reported_weight_unit()
factor = WEIGHT_UNIT_FACTORS.get(unit)
return float(value) * factor if factor is not None else None

def _reported_weight_unit(self) -> str | None:
raw = value_from_block(self.block, "weight_unit")
return None if isinstance(raw, bool | float) else _enum_value("weight_unit", raw)

@property
def extra_state_attributes(self) -> DeviceData | None:
"""Extra state attributes.

Returns:
DeviceData | None: The resulting extra state attributes.
"""
attributes = {}
attributes: DeviceData = {}
if self.key in WEIGHT_KEYS:
attributes.update({
"source_field": self.key,
"reported_unit": self._reported_weight_unit(),
"measurement_time": None,
"measurement_freshness": "not_reported",
"measurement_source": "cloud_daily_summary"
if self.key in {"today_weight", "yesterday_weight"}
else "cloud_reported_weight",
})
if self.key == FIELD_DEVICE_TIME_ZONE:
attributes.update(
timezone_context(value_from_block(self.block, self.key), self.coordinator.hass.config.time_zone)
Expand Down
8 changes: 8 additions & 0 deletions custom_components/notty/services.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ device_time_zone:
or numeric offset.
selector:
text: null
iana_time_zone:
description: Explicit valid IANA name, such as Europe/Amsterdam. The backend stores Windows names incorrectly in this field; catalog membership alone is insufficient.
selector:
text: null
preserve_dnd_local_times:
description: Preserve the original device-local DND clocks, switch and LED with an additional settings write after changing timezone. Inspect the readback response.
selector:
boolean: null
confirm_schedule_change:
description: Required true for change, acknowledging that scheduled operations use the selected device local time.
selector:
Expand Down
Loading
Loading