From 5012518f45a2c0e2a4f02776b371fd989e8074d6 Mon Sep 17 00:00:00 2001 From: ICEMANno1 <11725574+ICEMANno1@users.noreply.github.com> Date: Tue, 17 Nov 2026 17:38:46 +0100 Subject: [PATCH] Add thermostat weekly schedule support Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- README.md | 40 + .../bosch-rbsh-trv0-zb-eu-0x32051514.json | 336 ++- .../bosch-rbsh-trv0-zb-eu-0x38011514.json | 336 ++- tests/data/devices/bosch-rbsh-trv0-zb-eu.json | 334 ++- .../bosch-rbsh-trv1-zb-eu-0x11087140.json | 1900 +++++++++++++++++ tests/test_climate.py | 1011 ++++++++- zha/application/platforms/climate/__init__.py | 55 +- zha/application/platforms/climate/const.py | 1 + zha/quirks.py | 1 + zha/zigbee/device.py | 153 +- zha/zigbee/weekly_schedule.py | 651 ++++++ 11 files changed, 4738 insertions(+), 80 deletions(-) create mode 100644 tests/data/devices/bosch-rbsh-trv1-zb-eu-0x11087140.json create mode 100644 zha/zigbee/weekly_schedule.py diff --git a/README.md b/README.md index f2e7f6002..64ade6313 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,46 @@ ZHA is a versatile and hardware-independent Zigbee gateway implementation, desig - **Unified Zigbee Network:** By utilizing ZHA, you can establish a single Zigbee network, simplifying device management and enhancing interoperability. - **Low-Bandwidth Communication:** Zigbee operates on a low-bandwidth communication protocol, utilizing small, low-power digital radios to connect devices within local Zigbee wireless private area networks. +## Thermostat weekly schedules + +Weekly schedules are opt-in. A quirk exposes a feature registered in +`zha.zigbee.weekly_schedule.WEEKLY_SCHEDULE_PROVIDERS`; standard ZCL schedules use +`THERMOSTAT_WEEKLY_SCHEDULE`. Other thermostat families can subclass +`WeeklyScheduleProvider`, implement its read, write, limit and optional clear +primitives, declare `WeeklyScheduleCapabilities`, and register their own feature. +Validation, caching, snapshots, change detection and verification are shared. +Uploads with `only_changed=True` write only days whose fresh read differs and +report them in `written_days`. + +`has_verified_schedule` is true after a complete, verified upload in the current +session. It is invalidated by known schedule mutations, cluster replacement, or a +failed or mismatching fresh read. Consumers can subscribe to +`EVENT_VERIFIED_CHANGED` on the provider to update their state. Changes made +outside ZHA may not be detected until the schedule is read again. + +Thermostat entities can read a heat-only weekly schedule or explicitly upload a +complete seven-day schedule. Uploads require fresh heat limits and a complete +pre-write read, then write and verify each day separately. The in-memory cache may +be incomplete or stale and is not synchronized with changes made outside ZHA. +Clearing removes the entire device schedule, including cooling where supported. +It snapshots and verifies the heat schedule only; cooling is not read back or +included in the snapshot. An unconfirmed clear may still have changed the device; +the affected cache is marked unknown. No automatic retry or rollback is attempted. +The thermostat's operating mode and clock are not changed. Device and radio limits +can be lower than the protocol's transition-count limit. Large schedules may +exceed radio frame limits, and a failed upload can leave the week partly updated. +No unverified device-specific transition limit is enforced. + +Uploads take all seven lowercase weekday names, each with ordered `(minute, +centi-degrees Celsius)` transitions beginning at midnight. Results include +`days` with `HH:MM`/Celsius transitions and UTC update timestamps, `complete`, +and `pre_write_snapshot`. A day's `null` transitions are unknown; an empty list +is a known empty schedule. The snapshot is in-memory only. Upload failures report +changed, unknown and unattempted days; they do not automatically roll back. + +The independent design was informed by Zigbee2MQTT's +[Bosch BTH-RA converter](https://github.com/Koenkk/zigbee-herdsman-converters/blob/master/src/lib/bosch.ts). + ## Getting Started With Development To bootstrap a development environment for ZHA, follow these steps: diff --git a/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x32051514.json b/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x32051514.json index cbbf4ac26..f6c72daa9 100644 --- a/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x32051514.json +++ b/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x32051514.json @@ -553,6 +553,110 @@ "native_step": 0.5, "native_unit_of_measurement": "\u00b0C" }, + { + "fallback_name": "Frost protection temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "frost_protection_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Away preset temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-away_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "away_preset_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Decalcification day", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_day", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_day", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 6, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Decalcification hour", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_hour", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_hour", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 23, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, { "fallback_name": "Display brightness", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-display_brightness", @@ -600,18 +704,18 @@ "group_id": null, "native_value": 10, "mode": "auto", - "native_max_value": 30, - "native_min_value": 5, + "native_max_value": 255, + "native_min_value": 2, "native_step": 1, "native_unit_of_measurement": null }, { - "fallback_name": "Remote temperature", - "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "fallback_name": "Eco temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-eco_temperature", "migrate_unique_ids": [], "platform": "number", "class_name": "NumberConfigurationEntity", - "translation_key": null, + "translation_key": "eco_temperature", "translation_placeholders": null, "device_class": "temperature", "state_class": null, @@ -624,12 +728,90 @@ "endpoint_id": 1, "available": true, "group_id": null, - "native_value": 0.0, + "native_value": null, "mode": "auto", "native_max_value": 30, "native_min_value": 5, "native_step": 0.1, - "native_unit_of_measurement": null + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Holiday temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-holiday_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "holiday_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "External temperature sensor value", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "external_temperature_sensor_value", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 0.0, + "mode": "auto", + "native_max_value": 80, + "native_min_value": -80, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Window open temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "window_open_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 10, + "native_min_value": 5, + "native_step": 1, + "native_unit_of_measurement": "\u00b0C" } ], "select": [ @@ -886,6 +1068,29 @@ "suggested_display_precision": null, "unit": null }, + { + "fallback_name": "Error status", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-error_state", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "Sensor", + "translation_key": "error_status", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null + }, { "fallback_name": "Operating mode", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-operating_mode", @@ -911,9 +1116,67 @@ "options": [ "Schedule", "Manual", + "Eco", + "Away", + "Holiday", "Pause" ] }, + { + "fallback_name": "Remote temperature source", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature_source", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "remote_temperature_source", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "Internal", + "External" + ] + }, + { + "fallback_name": "Restart reason", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-restart_reason", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "restart_reason", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "cold_start", + "warm_start", + "firmware_installed" + ] + }, { "fallback_name": "Valve adaptation status", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-valve_adapt_status", @@ -941,11 +1204,41 @@ "ReadyToCalibrate", "CalibrationInProgress", "Error", - "Success" + "Success", + "FixMotorStarted", + "FixMotorFailed", + "FixMotorSuccessful" ] } ], "switch": [ + { + "fallback_name": "Frost protection", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_enabled", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "frost_protection", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "anti_freeze_enabled", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Boost heating", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-boost_heating", @@ -973,6 +1266,33 @@ "off_value": 0, "on_value": 1 }, + { + "fallback_name": "Light ring on temperature change", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-light_ring_on_temperature_change", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "light_ring_on_temperature_change", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "light_ring_on_temperature_change", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Window open", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open", diff --git a/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x38011514.json b/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x38011514.json index fc76c9b09..1a7bdec06 100644 --- a/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x38011514.json +++ b/tests/data/devices/bosch-rbsh-trv0-zb-eu-0x38011514.json @@ -552,6 +552,110 @@ "native_step": 0.5, "native_unit_of_measurement": "\u00b0C" }, + { + "fallback_name": "Frost protection temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "frost_protection_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Away preset temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-away_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "away_preset_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Decalcification day", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_day", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_day", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 6, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Decalcification hour", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_hour", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_hour", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 23, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, { "fallback_name": "Display brightness", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-display_brightness", @@ -599,18 +703,18 @@ "group_id": null, "native_value": 10, "mode": "auto", - "native_max_value": 30, - "native_min_value": 5, + "native_max_value": 255, + "native_min_value": 2, "native_step": 1, "native_unit_of_measurement": null }, { - "fallback_name": "Remote temperature", - "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "fallback_name": "Eco temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-eco_temperature", "migrate_unique_ids": [], "platform": "number", "class_name": "NumberConfigurationEntity", - "translation_key": null, + "translation_key": "eco_temperature", "translation_placeholders": null, "device_class": "temperature", "state_class": null, @@ -623,12 +727,90 @@ "endpoint_id": 1, "available": true, "group_id": null, - "native_value": 0.0, + "native_value": null, "mode": "auto", "native_max_value": 30, "native_min_value": 5, "native_step": 0.1, - "native_unit_of_measurement": null + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Holiday temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-holiday_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "holiday_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "External temperature sensor value", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "external_temperature_sensor_value", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 0.0, + "mode": "auto", + "native_max_value": 80, + "native_min_value": -80, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Window open temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "window_open_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 10, + "native_min_value": 5, + "native_step": 1, + "native_unit_of_measurement": "\u00b0C" } ], "select": [ @@ -914,6 +1096,29 @@ "suggested_display_precision": null, "unit": null }, + { + "fallback_name": "Error status", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-error_state", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "Sensor", + "translation_key": "error_status", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null + }, { "fallback_name": "Operating mode", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-operating_mode", @@ -939,9 +1144,67 @@ "options": [ "Schedule", "Manual", + "Eco", + "Away", + "Holiday", "Pause" ] }, + { + "fallback_name": "Remote temperature source", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature_source", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "remote_temperature_source", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "Internal", + "External" + ] + }, + { + "fallback_name": "Restart reason", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-restart_reason", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "restart_reason", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "cold_start", + "warm_start", + "firmware_installed" + ] + }, { "fallback_name": "Valve adaptation status", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-valve_adapt_status", @@ -969,11 +1232,41 @@ "ReadyToCalibrate", "CalibrationInProgress", "Error", - "Success" + "Success", + "FixMotorStarted", + "FixMotorFailed", + "FixMotorSuccessful" ] } ], "switch": [ + { + "fallback_name": "Frost protection", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_enabled", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "frost_protection", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "anti_freeze_enabled", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Boost heating", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-boost_heating", @@ -1001,6 +1294,33 @@ "off_value": 0, "on_value": 1 }, + { + "fallback_name": "Light ring on temperature change", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-light_ring_on_temperature_change", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "light_ring_on_temperature_change", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "light_ring_on_temperature_change", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Window open", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open", diff --git a/tests/data/devices/bosch-rbsh-trv0-zb-eu.json b/tests/data/devices/bosch-rbsh-trv0-zb-eu.json index d7096cef8..e08dc2a1e 100644 --- a/tests/data/devices/bosch-rbsh-trv0-zb-eu.json +++ b/tests/data/devices/bosch-rbsh-trv0-zb-eu.json @@ -428,6 +428,110 @@ "native_step": 0.5, "native_unit_of_measurement": "\u00b0C" }, + { + "fallback_name": "Frost protection temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "frost_protection_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Away preset temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-away_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "away_preset_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Decalcification day", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_day", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_day", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 6, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Decalcification hour", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-decalcification_hour", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_hour", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 23, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, { "fallback_name": "Display brightness", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-display_brightness", @@ -475,18 +579,18 @@ "group_id": null, "native_value": null, "mode": "auto", - "native_max_value": 30, - "native_min_value": 5, + "native_max_value": 255, + "native_min_value": 2, "native_step": 1, "native_unit_of_measurement": null }, { - "fallback_name": "Remote temperature", - "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "fallback_name": "Eco temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-eco_temperature", "migrate_unique_ids": [], "platform": "number", "class_name": "NumberConfigurationEntity", - "translation_key": null, + "translation_key": "eco_temperature", "translation_placeholders": null, "device_class": "temperature", "state_class": null, @@ -504,7 +608,85 @@ "native_max_value": 30, "native_min_value": 5, "native_step": 0.1, - "native_unit_of_measurement": null + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Holiday temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-holiday_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "holiday_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "External temperature sensor value", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "external_temperature_sensor_value", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 80, + "native_min_value": -80, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Window open temperature", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "window_open_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "mode": "auto", + "native_max_value": 10, + "native_min_value": 5, + "native_step": 1, + "native_unit_of_measurement": "\u00b0C" } ], "select": [ @@ -761,6 +943,29 @@ "suggested_display_precision": null, "unit": null }, + { + "fallback_name": "Error status", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-error_state", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "Sensor", + "translation_key": "error_status", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null + }, { "fallback_name": "Operating mode", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-operating_mode", @@ -786,9 +991,67 @@ "options": [ "Schedule", "Manual", + "Eco", + "Away", + "Holiday", "Pause" ] }, + { + "fallback_name": "Remote temperature source", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-remote_temperature_source", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "remote_temperature_source", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "Internal", + "External" + ] + }, + { + "fallback_name": "Restart reason", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-restart_reason", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "restart_reason", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": null, + "suggested_display_precision": null, + "unit": null, + "options": [ + "cold_start", + "warm_start", + "firmware_installed" + ] + }, { "fallback_name": "Valve adaptation status", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-valve_adapt_status", @@ -816,11 +1079,41 @@ "ReadyToCalibrate", "CalibrationInProgress", "Error", - "Success" + "Success", + "FixMotorStarted", + "FixMotorFailed", + "FixMotorSuccessful" ] } ], "switch": [ + { + "fallback_name": "Frost protection", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-anti_freeze_enabled", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "frost_protection", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "anti_freeze_enabled", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Boost heating", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-boost_heating", @@ -848,6 +1141,33 @@ "off_value": 0, "on_value": 1 }, + { + "fallback_name": "Light ring on temperature change", + "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-light_ring_on_temperature_change", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "light_ring_on_temperature_change", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:d1:eb:38:68", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "light_ring_on_temperature_change", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, { "fallback_name": "Window open", "unique_id": "ab:cd:ef:12:d1:eb:38:68-1-window_open", diff --git a/tests/data/devices/bosch-rbsh-trv1-zb-eu-0x11087140.json b/tests/data/devices/bosch-rbsh-trv1-zb-eu-0x11087140.json new file mode 100644 index 000000000..26bf46287 --- /dev/null +++ b/tests/data/devices/bosch-rbsh-trv1-zb-eu-0x11087140.json @@ -0,0 +1,1900 @@ +{ + "version": 3, + "ieee": "ab:cd:ef:12:89:8d:b9:45", + "nwk": "0x1234", + "manufacturer": "BOSCH", + "model": "RBSH-TRV1-ZB-EU", + "friendly_manufacturer": "BOSCH", + "friendly_model": "RBSH-TRV1-ZB-EU", + "name": "BOSCH RBSH-TRV1-ZB-EU", + "quirk_applied": true, + "quirk_class": "zhaquirks.bosch.rbsh_trv0_zb_eu:(BOSCH / RBSH-TRV0-ZB-EU)", + "exposes_features": [ + "thermostat_weekly_schedule" + ], + "manufacturer_code": 4617, + "power_source": "Battery or Unknown", + "lqi": 188, + "rssi": -53, + "last_seen": "1970-01-01T00:00:00+00:00", + "available": true, + "device_type": "EndDevice", + "active_coordinator": false, + "node_descriptor": { + "logical_type": "EndDevice", + "complex_descriptor_available": false, + "user_descriptor_available": false, + "reserved": 0, + "aps_flags": 0, + "frequency_band": 8, + "mac_capability_flags": 128, + "manufacturer_code": 4617, + "maximum_buffer_size": 82, + "maximum_incoming_transfer_size": 82, + "server_mask": 11264, + "maximum_outgoing_transfer_size": 82, + "descriptor_capability_field": 0 + }, + "endpoints": { + "1": { + "profile_id": 260, + "device_type": { + "name": "THERMOSTAT", + "id": 769 + }, + "in_clusters": [ + { + "cluster_id": "0x0000", + "endpoint_attribute": "basic", + "attributes": [ + { + "id": "0x0013", + "name": "alarm_mask", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x0001", + "name": "app_version", + "zcl_type": "uint8", + "value": 1 + }, + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x0006", + "name": "date_code", + "zcl_type": "string", + "value": "20240510" + }, + { + "id": "0x0014", + "name": "disable_local_config", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x0003", + "name": "hw_version", + "zcl_type": "uint8", + "value": 1 + }, + { + "id": "0x0010", + "name": "location_desc", + "zcl_type": "string", + "unsupported": true + }, + { + "id": "0x0004", + "name": "manufacturer", + "zcl_type": "string", + "value": "BOSCH" + }, + { + "id": "0x0005", + "name": "model", + "zcl_type": "string", + "value": "RBSH-TRV1-ZB-EU" + }, + { + "id": "0x0007", + "name": "power_source", + "zcl_type": "enum8", + "value": 3 + }, + { + "id": "0x000a", + "name": "product_code", + "zcl_type": "octstr", + "value": { + "__type": "", + "repr": "b''" + } + }, + { + "id": "0x000b", + "name": "product_url", + "zcl_type": "string", + "value": "" + }, + { + "id": "0xfffe", + "name": "reporting_status", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0002", + "name": "stack_version", + "zcl_type": "uint8", + "value": 1 + }, + { + "id": "0x4000", + "name": "sw_build_id", + "zcl_type": "string", + "unsupported": true + }, + { + "id": "0x0000", + "name": "zcl_version", + "zcl_type": "uint8", + "value": 8 + } + ] + }, + { + "cluster_id": "0x0001", + "endpoint_attribute": "power", + "attributes": [ + { + "id": "0x0035", + "name": "battery_alarm_mask", + "zcl_type": "map8", + "value": 0 + }, + { + "id": "0x003e", + "name": "battery_alarm_state", + "zcl_type": "map32", + "value": 0 + }, + { + "id": "0x0021", + "name": "battery_percentage_remaining", + "zcl_type": "uint8", + "value": 200 + }, + { + "id": "0x0033", + "name": "battery_quantity", + "zcl_type": "uint8", + "value": 2 + }, + { + "id": "0x0031", + "name": "battery_size", + "zcl_type": "enum8", + "value": 3 + }, + { + "id": "0x0036", + "name": "battery_volt_min_thres", + "zcl_type": "uint8", + "value": 22 + }, + { + "id": "0x0037", + "name": "battery_volt_thres1", + "zcl_type": "uint8", + "value": 23 + }, + { + "id": "0x0038", + "name": "battery_volt_thres2", + "zcl_type": "uint8", + "value": 24 + }, + { + "id": "0x0039", + "name": "battery_volt_thres3", + "zcl_type": "uint8", + "value": 29 + }, + { + "id": "0x0020", + "name": "battery_voltage", + "zcl_type": "uint8", + "value": 30 + }, + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + } + ] + }, + { + "cluster_id": "0x0003", + "endpoint_attribute": "identify", + "attributes": [ + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x0000", + "name": "identify_time", + "zcl_type": "uint16", + "value": 0 + } + ] + }, + { + "cluster_id": "0x0020", + "endpoint_attribute": "poll_control", + "attributes": [ + { + "id": "0x0000", + "name": "checkin_interval", + "zcl_type": "uint32", + "value": 6480 + }, + { + "id": "0x0004", + "name": "checkin_interval_min", + "zcl_type": "uint32", + "value": 240 + }, + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x0003", + "name": "fast_poll_timeout", + "zcl_type": "uint16", + "value": 240 + }, + { + "id": "0x0006", + "name": "fast_poll_timeout_max", + "zcl_type": "uint16", + "value": 240 + }, + { + "id": "0x0001", + "name": "long_poll_interval", + "zcl_type": "uint32", + "value": 30 + }, + { + "id": "0x0005", + "name": "long_poll_interval_min", + "zcl_type": "uint32", + "value": 0 + }, + { + "id": "0xfffe", + "name": "reporting_status", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0002", + "name": "short_poll_interval", + "zcl_type": "uint16", + "value": 2 + } + ] + }, + { + "cluster_id": "0x0201", + "endpoint_attribute": "thermostat", + "attributes": [ + { + "id": "0x0006", + "name": "abs_max_cool_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0004", + "name": "abs_max_heat_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0005", + "name": "abs_min_cool_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0003", + "name": "abs_min_heat_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0041", + "name": "ac_capacity", + "zcl_type": "uint16", + "unsupported": true + }, + { + "id": "0x400e", + "name": "anti_freeze_enabled", + "zcl_type": "bool", + "value": 1 + }, + { + "id": "0x400f", + "name": "anti_freeze_temperature", + "zcl_type": "uint16", + "value": 500 + }, + { + "id": "0x4009", + "name": "away_temperature", + "zcl_type": "uint16", + "value": 1000 + }, + { + "id": "0x4043", + "name": "boost_heating", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x001b", + "name": "ctrl_sequence_of_oper", + "zcl_type": "enum8", + "value": 2 + }, + { + "id": "0x4023", + "name": "decalcification_day", + "zcl_type": "enum8", + "value": 6 + }, + { + "id": "0x4024", + "name": "decalcification_hour", + "zcl_type": "enum8", + "value": 11 + }, + { + "id": "0x4008", + "name": "eco_temperature", + "zcl_type": "uint16", + "value": 1700 + }, + { + "id": "0x003a", + "name": "emergency_heat_delta", + "zcl_type": "uint8", + "unsupported": true + }, + { + "id": "0x5000", + "name": "error_state", + "zcl_type": "map8", + "value": 0 + }, + { + "id": "0x400a", + "name": "holiday_temperature", + "zcl_type": "uint16", + "value": 500 + }, + { + "id": "0x0000", + "name": "local_temperature", + "zcl_type": "int16", + "value": 1850 + }, + { + "id": "0x0010", + "name": "local_temperature_calibration", + "zcl_type": "int8", + "value": -5 + }, + { + "id": "0x0018", + "name": "max_cool_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0016", + "name": "max_heat_setpoint_limit", + "zcl_type": "int16", + "value": 3000 + }, + { + "id": "0x0017", + "name": "min_cool_setpoint_limit", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0015", + "name": "min_heat_setpoint_limit", + "zcl_type": "int16", + "value": 1600 + }, + { + "id": "0x0022", + "name": "number_of_daily_transitions", + "zcl_type": "uint8", + "value": 6 + }, + { + "id": "0x0021", + "name": "number_of_weekly_transitions", + "zcl_type": "uint8", + "value": 42 + }, + { + "id": "0x0002", + "name": "occupancy", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x0011", + "name": "occupied_cooling_setpoint", + "zcl_type": "int16", + "value": 2300 + }, + { + "id": "0x0012", + "name": "occupied_heating_setpoint", + "zcl_type": "int16", + "value": 1650 + }, + { + "id": "0x0034", + "name": "occupied_setback", + "zcl_type": "uint8", + "unsupported": true + }, + { + "id": "0x0036", + "name": "occupied_setback_max", + "zcl_type": "uint8", + "unsupported": true + }, + { + "id": "0x4007", + "name": "operating_mode", + "zcl_type": "enum8", + "value": 1 + }, + { + "id": "0x0001", + "name": "outdoor_temperature", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0007", + "name": "pi_cooling_demand", + "zcl_type": "uint8", + "unsupported": true + }, + { + "id": "0x4020", + "name": "pi_heating_demand", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x0025", + "name": "programing_oper_mode", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x001a", + "name": "remote_sensing", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x4040", + "name": "remote_temperature", + "zcl_type": "int16", + "value": 0 + }, + { + "id": "0x4041", + "name": "remote_temperature_source", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x5010", + "name": "restart_reason", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x001e", + "name": "running_mode", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0029", + "name": "running_state", + "zcl_type": "map16", + "unsupported": true + }, + { + "id": "0x0031", + "name": "setpoint_change_amount", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0030", + "name": "setpoint_change_source", + "zcl_type": "enum8", + "value": 2 + }, + { + "id": "0x0032", + "name": "setpoint_change_source_timestamp", + "zcl_type": "UTC", + "unsupported": true + }, + { + "id": "0x0020", + "name": "start_of_week", + "zcl_type": "enum8", + "value": 6 + }, + { + "id": "0x001c", + "name": "system_mode", + "zcl_type": "enum8", + "value": 4 + }, + { + "id": "0x0023", + "name": "temp_setpoint_hold", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0024", + "name": "temp_setpoint_hold_duration", + "zcl_type": "uint16", + "unsupported": true + }, + { + "id": "0x0013", + "name": "unoccupied_cooling_setpoint", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0014", + "name": "unoccupied_heating_setpoint", + "zcl_type": "int16", + "unsupported": true + }, + { + "id": "0x0037", + "name": "unoccupied_setback", + "zcl_type": "uint8", + "unsupported": true + }, + { + "id": "0x4022", + "name": "valve_adapt_status", + "zcl_type": "enum8", + "value": 4 + }, + { + "id": "0x4042", + "name": "window_open", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x4050", + "name": "window_open_temperature", + "zcl_type": "enum8", + "value": 8 + } + ] + }, + { + "cluster_id": "0x0204", + "endpoint_attribute": "thermostat_ui", + "attributes": [ + { + "id": "0x403b", + "name": "display_brightness", + "zcl_type": "enum8", + "value": 7 + }, + { + "id": "0x403a", + "name": "display_on_time", + "zcl_type": "enum8", + "value": 10 + }, + { + "id": "0x400b", + "name": "display_orientation", + "zcl_type": "uint8", + "value": 0 + }, + { + "id": "0x4039", + "name": "displayed_temperature", + "zcl_type": "enum8", + "value": 1 + }, + { + "id": "0x0001", + "name": "keypad_lockout", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x4031", + "name": "light_ring_on_temperature_change", + "zcl_type": "enum8", + "value": 1 + }, + { + "id": "0x0002", + "name": "schedule_programming_visibility", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0000", + "name": "temperature_display_mode", + "zcl_type": "enum8", + "value": 0 + } + ] + }, + { + "cluster_id": "0x0b05", + "endpoint_attribute": "diagnostic", + "attributes": [ + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x011c", + "name": "last_message_lqi", + "zcl_type": "uint8", + "value": 192 + }, + { + "id": "0x011d", + "name": "last_message_rssi", + "zcl_type": "int8", + "value": -51 + }, + { + "id": "0xfffe", + "name": "reporting_status", + "zcl_type": "enum8", + "unsupported": true + } + ] + } + ], + "out_clusters": [ + { + "cluster_id": "0x000a", + "endpoint_attribute": "time", + "attributes": [ + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x0004", + "name": "dst_end", + "zcl_type": "uint32", + "unsupported": true + }, + { + "id": "0x0005", + "name": "dst_shift", + "zcl_type": "int32", + "unsupported": true + }, + { + "id": "0x0003", + "name": "dst_start", + "zcl_type": "uint32", + "unsupported": true + }, + { + "id": "0x0008", + "name": "last_set_time", + "zcl_type": "UTC", + "unsupported": true + }, + { + "id": "0x0007", + "name": "local_time", + "zcl_type": "uint32", + "unsupported": true + }, + { + "id": "0xfffe", + "name": "reporting_status", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0006", + "name": "standard_time", + "zcl_type": "uint32", + "unsupported": true + }, + { + "id": "0x0000", + "name": "time", + "zcl_type": "UTC", + "unsupported": true + }, + { + "id": "0x0001", + "name": "time_status", + "zcl_type": "map8", + "unsupported": true + }, + { + "id": "0x0002", + "name": "time_zone", + "zcl_type": "int32", + "unsupported": true + }, + { + "id": "0x0009", + "name": "valid_until_time", + "zcl_type": "UTC", + "unsupported": true + } + ] + }, + { + "cluster_id": "0x0019", + "endpoint_attribute": "ota", + "attributes": [ + { + "id": "0xfffd", + "name": "cluster_revision", + "zcl_type": "uint16", + "value": 1 + }, + { + "id": "0x0002", + "name": "current_file_version", + "zcl_type": "uint32", + "value": 285765952 + }, + { + "id": "0x0003", + "name": "current_zigbee_stack_version", + "zcl_type": "uint16", + "unsupported": true + }, + { + "id": "0x0004", + "name": "downloaded_file_version", + "zcl_type": "uint32", + "value": 4294967295 + }, + { + "id": "0x0005", + "name": "downloaded_zigbee_stack_version", + "zcl_type": "uint16", + "value": 65535 + }, + { + "id": "0x0001", + "name": "file_offset", + "zcl_type": "uint32", + "value": 4294967295 + }, + { + "id": "0x0008", + "name": "image_type_id", + "zcl_type": "uint16", + "value": 65535 + }, + { + "id": "0x0006", + "name": "image_upgrade_status", + "zcl_type": "enum8", + "value": 0 + }, + { + "id": "0x0007", + "name": "manufacturer_id", + "zcl_type": "uint16", + "value": 4617 + }, + { + "id": "0x0009", + "name": "minimum_block_req_delay", + "zcl_type": "uint16", + "value": 0 + }, + { + "id": "0xfffe", + "name": "reporting_status", + "zcl_type": "enum8", + "unsupported": true + }, + { + "id": "0x0000", + "name": "upgrade_server_id", + "zcl_type": "EUI64", + "value": "ab:cd:ef:12:00:00:00:01" + } + ], + "last_query_cmd": { + "manufacturer_code": 4617, + "image_type": 12306, + "current_file_version": 285765952, + "hardware_version": null + } + } + ] + } + }, + "original_signature": { + "manufacturer": "BOSCH", + "model": "RBSH-TRV1-ZB-EU", + "node_desc": { + "logical_type": 2, + "complex_descriptor_available": 0, + "user_descriptor_available": 0, + "reserved": 0, + "aps_flags": 0, + "frequency_band": 8, + "mac_capability_flags": 128, + "manufacturer_code": 4617, + "maximum_buffer_size": 82, + "maximum_incoming_transfer_size": 82, + "server_mask": 11264, + "maximum_outgoing_transfer_size": 82, + "descriptor_capability_field": 0 + }, + "endpoints": { + "1": { + "profile_id": "0x0104", + "device_type": "0x0301", + "input_clusters": [ + "0x0000", + "0x0001", + "0x0003", + "0x0020", + "0x0201", + "0x0204", + "0x0b05" + ], + "output_clusters": [ + "0x000a", + "0x0019" + ] + } + } + }, + "zha_lib_entities": { + "button": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-3", + "migrate_unique_ids": [], + "platform": "button", + "class_name": "IdentifyButton", + "translation_key": null, + "translation_placeholders": null, + "device_class": "identify", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "command": "identify", + "args": [ + 5 + ], + "kwargs": {} + }, + { + "fallback_name": "Calibrate valve", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-calibrate_valve", + "migrate_unique_ids": [], + "platform": "button", + "class_name": "Button", + "translation_key": "calibrate_valve", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "command": "calibrate_valve", + "args": [], + "kwargs": {} + } + ], + "climate": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1", + "migrate_unique_ids": [], + "platform": "climate", + "class_name": "Thermostat", + "translation_key": "thermostat", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": null, + "entity_registry_enabled_default": true, + "enabled": true, + "primary": true, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "current_temperature": 18.5, + "outdoor_temperature": null, + "target_temperature": 16.5, + "target_temperature_high": null, + "target_temperature_low": null, + "hvac_action": "idle", + "hvac_mode": "heat", + "preset_mode": "none", + "fan_mode": "auto", + "max_temp": 30.0, + "min_temp": 16.0, + "supported_features": 385, + "fan_modes": null, + "preset_modes": [], + "hvac_modes": [ + "off", + "heat", + "auto" + ], + "sys_mode": "[4]/heat", + "occupancy": null, + "occupied_cooling_setpoint": 2300, + "occupied_heating_setpoint": 1650, + "pi_heating_demand": 0, + "pi_cooling_demand": null, + "unoccupied_cooling_setpoint": null, + "unoccupied_heating_setpoint": null + } + ], + "number": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-local_temperature_calibration", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "BoschThermostatLocalTempCalibration", + "translation_key": "local_temperature_calibration", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": -0.5, + "mode": "box", + "native_max_value": 5.0, + "native_min_value": -5.0, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-max_heat_setpoint_limit", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "MaxHeatSetpointLimit", + "translation_key": "max_heat_setpoint_limit", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 30.0, + "mode": "box", + "native_max_value": 327.67, + "native_min_value": 16.0, + "native_step": 0.5, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-min_heat_setpoint_limit", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "MinHeatSetpointLimit", + "translation_key": "min_heat_setpoint_limit", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 16.0, + "mode": "box", + "native_max_value": 30.0, + "native_min_value": -273.15000000000003, + "native_step": 0.5, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Frost protection temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-anti_freeze_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "frost_protection_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 5.0, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Away preset temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-away_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "away_preset_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 10.0, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Decalcification day", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-decalcification_day", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_day", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 6, + "mode": "auto", + "native_max_value": 6, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Decalcification hour", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-decalcification_hour", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "decalcification_hour", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 11, + "mode": "auto", + "native_max_value": 23, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Display brightness", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-display_brightness", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "display_brightness", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 7, + "mode": "auto", + "native_max_value": 10, + "native_min_value": 0, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Display on-time", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-display_on_time", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "display_on_time", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 10, + "mode": "auto", + "native_max_value": 255, + "native_min_value": 2, + "native_step": 1, + "native_unit_of_measurement": null + }, + { + "fallback_name": "Eco temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-eco_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "eco_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 17.0, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Holiday temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-holiday_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "holiday_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 5.0, + "mode": "auto", + "native_max_value": 30, + "native_min_value": 5, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "External temperature sensor value", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-remote_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "external_temperature_sensor_value", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 0.0, + "mode": "auto", + "native_max_value": 80, + "native_min_value": -80, + "native_step": 0.1, + "native_unit_of_measurement": "\u00b0C" + }, + { + "fallback_name": "Window open temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-window_open_temperature", + "migrate_unique_ids": [], + "platform": "number", + "class_name": "NumberConfigurationEntity", + "translation_key": "window_open_temperature", + "translation_placeholders": null, + "device_class": "temperature", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 8, + "mode": "auto", + "native_max_value": 10, + "native_min_value": 5, + "native_step": 1, + "native_unit_of_measurement": "\u00b0C" + } + ], + "select": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-516-keypad_lockout", + "migrate_unique_ids": [], + "platform": "select", + "class_name": "KeypadLockout", + "translation_key": "keypad_lockout", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "current_option": "Unlock", + "enum": "KeypadLockoutEnum", + "options": [ + "Unlock", + "Lock1", + "Lock2", + "Lock3", + "Lock4" + ] + }, + { + "fallback_name": "Control sequence", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-ctrl_sequence_of_oper", + "migrate_unique_ids": [], + "platform": "select", + "class_name": "ZCLEnumSelectEntity", + "translation_key": "ctrl_sequence_of_oper", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "current_option": "Heating", + "enum": "BoschControlSequenceOfOperation", + "options": [ + "Cooling", + "Heating" + ] + }, + { + "fallback_name": "Display orientation", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-display_orientation", + "migrate_unique_ids": [], + "platform": "select", + "class_name": "ZCLEnumSelectEntity", + "translation_key": "display_orientation", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "current_option": "Normal", + "enum": "BoschDisplayOrientation", + "options": [ + "Normal", + "Flipped" + ] + }, + { + "fallback_name": "Displayed temperature", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-displayed_temperature", + "migrate_unique_ids": [], + "platform": "select", + "class_name": "ZCLEnumSelectEntity", + "translation_key": "displayed_temperature", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "current_option": "Measured", + "enum": "BoschDisplayedTemperature", + "options": [ + "Target", + "Measured" + ] + } + ], + "sensor": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-0-lqi", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "LQISensor", + "translation_key": "lqi", + "translation_placeholders": null, + "device_class": null, + "state_class": "measurement", + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": null, + "available": true, + "group_id": null, + "native_value": 188, + "suggested_display_precision": null, + "unit": null + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-0-rssi", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "RSSISensor", + "translation_key": "rssi", + "translation_placeholders": null, + "device_class": "signal_strength", + "state_class": "measurement", + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": null, + "available": true, + "group_id": null, + "native_value": -53, + "suggested_display_precision": null, + "unit": "dBm" + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-1", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "Battery", + "translation_key": null, + "translation_placeholders": null, + "device_class": "battery", + "state_class": "measurement", + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [ + "battery_quantity", + "battery_size", + "battery_voltage" + ], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 100.0, + "suggested_display_precision": 0, + "unit": "%", + "battery_size": "AA", + "battery_quantity": 2, + "battery_voltage": 3.0 + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-hvac_action", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "ThermostatHVACAction", + "translation_key": "hvac_action", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": null, + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "idle", + "suggested_display_precision": null, + "unit": null + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-pi_heating_demand", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "PiHeatingDemand", + "translation_key": "pi_heating_demand", + "translation_placeholders": null, + "device_class": null, + "state_class": "measurement", + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 0, + "suggested_display_precision": 0, + "unit": "%" + }, + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-513-setpoint_change_source", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "SetpointChangeSource", + "translation_key": "setpoint_change_source", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "External", + "suggested_display_precision": null, + "unit": null, + "options": [ + "Manual", + "Schedule", + "External" + ] + }, + { + "fallback_name": "Error status", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-error_state", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "Sensor", + "translation_key": "error_status", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": 0, + "suggested_display_precision": null, + "unit": null + }, + { + "fallback_name": "Operating mode", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-operating_mode", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "operating_mode", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "Manual", + "suggested_display_precision": null, + "unit": null, + "options": [ + "Schedule", + "Manual", + "Eco", + "Away", + "Holiday", + "Pause" + ] + }, + { + "fallback_name": "Remote temperature source", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-remote_temperature_source", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "remote_temperature_source", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "Internal", + "suggested_display_precision": null, + "unit": null, + "options": [ + "Internal", + "External" + ] + }, + { + "fallback_name": "Restart reason", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-restart_reason", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "restart_reason", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": false, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "cold_start", + "suggested_display_precision": null, + "unit": null, + "options": [ + "cold_start", + "warm_start", + "firmware_installed" + ] + }, + { + "fallback_name": "Valve adaptation status", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-valve_adapt_status", + "migrate_unique_ids": [], + "platform": "sensor", + "class_name": "EnumSensor", + "translation_key": "valve_adapt_status", + "translation_placeholders": null, + "device_class": "enum", + "state_class": null, + "entity_category": "diagnostic", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "native_value": "Success", + "suggested_display_precision": null, + "unit": null, + "options": [ + "Unknown", + "ReadyToCalibrate", + "CalibrationInProgress", + "Error", + "Success", + "FixMotorStarted", + "FixMotorFailed", + "FixMotorSuccessful" + ] + } + ], + "switch": [ + { + "fallback_name": "Frost protection", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-anti_freeze_enabled", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "frost_protection", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": true, + "inverted": false, + "attribute_name": "anti_freeze_enabled", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, + { + "fallback_name": "Boost heating", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-boost_heating", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "boost_heating", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "boost_heating", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, + { + "fallback_name": "Light ring on temperature change", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-light_ring_on_temperature_change", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "light_ring_on_temperature_change", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": true, + "inverted": false, + "attribute_name": "light_ring_on_temperature_change", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + }, + { + "fallback_name": "Window open", + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-window_open", + "migrate_unique_ids": [], + "platform": "switch", + "class_name": "ConfigurableAttributeSwitch", + "translation_key": "window_open", + "translation_placeholders": null, + "device_class": null, + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "is_on": false, + "inverted": false, + "attribute_name": "window_open", + "invert_attribute_name": null, + "force_inverted": false, + "off_value": 0, + "on_value": 1 + } + ], + "update": [ + { + "fallback_name": null, + "unique_id": "ab:cd:ef:12:89:8d:b9:45-1-25-firmware_update", + "migrate_unique_ids": [], + "platform": "update", + "class_name": "FirmwareUpdateEntity", + "translation_key": null, + "translation_placeholders": null, + "device_class": "firmware", + "state_class": null, + "entity_category": "config", + "entity_registry_enabled_default": true, + "enabled": true, + "primary": false, + "extra_state_attribute_names": [], + "device_ieee": "ab:cd:ef:12:89:8d:b9:45", + "endpoint_id": 1, + "available": true, + "group_id": null, + "installed_version": "0x11087140", + "in_progress": false, + "update_percentage": null, + "latest_version": null, + "release_summary": null, + "release_notes": null, + "release_url": null, + "supported_features": 23 + } + ] + }, + "neighbors": [], + "routes": [] +} \ No newline at end of file diff --git a/tests/test_climate.py b/tests/test_climate.py index 12df5b02a..049fc9151 100644 --- a/tests/test_climate.py +++ b/tests/test_climate.py @@ -5,6 +5,7 @@ import asyncio from collections.abc import Iterator import logging +from types import SimpleNamespace from typing import Any from unittest.mock import AsyncMock, MagicMock, PropertyMock, call, patch import zoneinfo @@ -18,7 +19,7 @@ import zigpy.profiles from zigpy.typing import UNDEFINED import zigpy.zcl.clusters -from zigpy.zcl.clusters.hvac import FanMode, FanModeSequence, Thermostat +from zigpy.zcl.clusters.hvac import FanMode, FanModeSequence, SeqMode, Thermostat import zigpy.zcl.foundation as zcl_f from tests.common import ( @@ -30,6 +31,7 @@ get_entity, join_zigpy_device, send_attributes_report, + zigpy_device_from_json, ) from zha.application import Platform from zha.application.const import ( @@ -56,8 +58,21 @@ ) from zha.const import STATE_CHANGED from zha.exceptions import ZHAException -from zha.quirks import THERMOSTAT_FAN_ONLY_HVAC, DeviceMatch, DeviceRegistry, ModelInfo +from zha.quirks import ( + THERMOSTAT_FAN_ONLY_HVAC, + THERMOSTAT_WEEKLY_SCHEDULE, + DeviceMatch, + DeviceRegistry, + ModelInfo, +) from zha.zigbee.device import Device +from zha.zigbee.weekly_schedule import ( + Transition, + WeeklyScheduleCapabilities, + WeeklyScheduleProvider, + WriteAcknowledgement, + ZclWeeklySchedule, +) _LOGGER = logging.getLogger(__name__) @@ -722,6 +737,74 @@ async def test_hvac_modes( # pylint: disable=unused-argument assert set(entity.hvac_modes) == modes +async def test_weekly_schedule_adds_auto_mode( + zha_gateway: Gateway, +) -> None: + """Expose and set Auto only for heating-only thermostats with schedules.""" + device = await device_climate_mock( + zha_gateway, + CLIMATE, + plug={ + "ctrl_sequence_of_oper": Thermostat.ControlSequenceOfOperation.Heating_Only + }, + ) + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + cluster = device.device.endpoints[1].thermostat + + assert HVACMode.AUTO not in entity.hvac_modes + with patch.object(device, "weekly_schedule", return_value=object()): + assert HVACMode.AUTO in entity.hvac_modes + await entity.async_set_hvac_mode(HVACMode.AUTO) + await zha_gateway.async_block_till_done() + assert cluster.write_attributes.call_args[0][0] == { + "system_mode": Thermostat.SystemMode.Auto + } + + await send_attributes_report( + zha_gateway, cluster, {0x001C: Thermostat.SystemMode.Auto} + ) + assert entity.state.hvac_mode == HVACMode.AUTO + + +@pytest.mark.parametrize( + ("preset", "target", "attribute"), + ( + (PRESET_NONE, 21, "occupied_heating_setpoint"), + (PRESET_AWAY, 16, "unoccupied_heating_setpoint"), + ), +) +async def test_weekly_schedule_auto_temperature( + zha_gateway: Gateway, preset: str, target: int, attribute: str +) -> None: + """Auto reports and writes the appropriate heating target.""" + device = await device_climate_mock( + zha_gateway, + CLIMATE, + plug={ + "ctrl_sequence_of_oper": Thermostat.ControlSequenceOfOperation.Heating_Only, + "system_mode": Thermostat.SystemMode.Auto, + "occupied_heating_setpoint": 2100, + "unoccupied_heating_setpoint": 1600, + }, + ) + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + cluster = device.device.endpoints[1].thermostat + entity._preset = preset + + with patch.object(device, "weekly_schedule", return_value=object()): + assert entity.state.hvac_mode == HVACMode.AUTO + assert entity.state.target_temperature == target + await entity.async_set_temperature(temperature=22) + await zha_gateway.async_block_till_done() + + assert entity.state.target_temperature == 22 + assert cluster.write_attributes.call_args.args[0] == {attribute: 2200} + + @pytest.mark.parametrize( "sys_mode, preset, target_temp", ( @@ -1920,6 +2003,816 @@ async def test_thermostat_default_local_temperature_calibration_config( assert local_temperature_calibration_entity._multiplier == 0.1 +_WEEKDAY_BITS = { + "monday": 2, + "tuesday": 4, + "wednesday": 8, + "thursday": 16, + "friday": 32, + "saturday": 64, + "sunday": 1, +} + + +@pytest.fixture +async def weekly_schedule_device(zha_gateway: Gateway): + """Provide a thermostat with mocked device-side schedule commands.""" + device = await device_climate_mock(zha_gateway, CLIMATE, plug={}) + device.exposes_features.add(THERMOSTAT_WEEKLY_SCHEDULE) + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + cluster = device.device.endpoints[1].thermostat + cluster.read_attributes.reset_mock() + cluster.write_attributes.reset_mock() + stored = {bit: [] for bit in _WEEKDAY_BITS.values()} + + async def command(command_id, **kwargs): + if command_id == 0x02: + day = int(kwargs["days_to_return"]) + values = stored[day] + return Thermostat.ClientCommandDefs.get_weekly_schedule_response.schema( + num_transitions_for_sequence=len(values) // 2, + day_of_week_for_sequence=day, + mode_for_sequence=SeqMode.Heat, + values=values, + ) + if command_id == 0x01: + stored[int(kwargs["day_of_week_for_sequence"])] = list(kwargs["values"]) + elif command_id == 0x03: + for day in stored: + stored[day] = [] + else: + raise AssertionError(f"Unexpected command {command_id}") + return zcl_f.DefaultResponse(command_id=command_id, status=zcl_f.Status.SUCCESS) + + cluster.command = AsyncMock(side_effect=command) + return entity, device, cluster, stored + + +async def test_weekly_schedule_upload_and_raw_invalidation( + weekly_schedule_device, +) -> None: + """Seven transitions per day are uploaded, verified and invalidated by raw writes.""" + entity, device, cluster, stored = weekly_schedule_device + cached = await entity.async_get_weekly_schedule(refresh=False) + assert not cached["complete"] + assert cached["days"]["monday"]["transitions"] is None + cluster.command.assert_not_awaited() + + transitions = [ + (0, 2000), + (120, 1950), + (240, 2050), + (360, 2100), + (480, 2000), + (600, 1950), + (720, 1900), + ] + schedule = {day: list(transitions) for day in _WEEKDAY_BITS} + result = await entity.async_set_weekly_schedule(schedule) + + assert entity.weekly_schedule.has_verified_schedule + assert result["complete"] + assert result["pre_write_snapshot"]["complete"] + assert result["pre_write_snapshot"]["days"]["monday"]["transitions"] == [] + assert result["days"]["monday"]["transitions"] == [ + {"time": f"{minute // 60:02}:{minute % 60:02}", "temperature": value / 100} + for minute, value in transitions + ] + assert result["days"]["monday"]["updated_at"] is not None + assert cluster.read_attributes.await_args.kwargs["allow_cache"] is False + cluster.write_attributes.assert_not_awaited() + + writes = [ + item + for item in cluster.command.await_args_list + if item.args[0] == Thermostat.ServerCommandDefs.set_weekly_schedule.id + ] + assert len(writes) == 7 + expected_values = [ + value for minute, temperature in transitions for value in (minute, temperature) + ] + for (day, bit), write in zip(_WEEKDAY_BITS.items(), writes, strict=True): + assert write.kwargs == { + "num_transitions_for_sequence": 7, + "day_of_week_for_sequence": bit, + "mode_for_sequence": SeqMode.Heat, + "values": expected_values, + "retries": 0, + } + assert stored[bit] == expected_values, day + + raw_response = await device.issue_cluster_command( + 1, + Thermostat.cluster_id, + 1, + "server", + None, + { + "num_transitions_for_sequence": 1, + "day_of_week_for_sequence": 2, + "mode_for_sequence": 1, + "values": [0, 1800], + }, + return_response=True, + ) + assert raw_response.status == zcl_f.Status.SUCCESS + assert not entity.weekly_schedule.has_verified_schedule + cached = await entity.async_get_weekly_schedule(refresh=False) + assert not cached["complete"] + assert cached["days"]["monday"]["transitions"] is None + assert cached["days"]["tuesday"]["transitions"] is not None + assert cached["pre_write_snapshot"]["complete"] + + await device.issue_cluster_command(1, Thermostat.cluster_id, 3, "server", None, {}) + cached = await entity.async_get_weekly_schedule(refresh=False) + assert all(day["transitions"] is None for day in cached["days"].values()) + fresh = await entity.async_get_weekly_schedule() + assert fresh["complete"] + assert all(day["transitions"] == [] for day in fresh["days"].values()) + + +async def test_weekly_schedule_verification_tracks_device_changes( + weekly_schedule_device, +) -> None: + """Only a successful upload remains verified after matching reads.""" + entity, _device, cluster, stored = weekly_schedule_device + provider = entity.weekly_schedule + events: list[bool] = [] + provider.on_event(provider.EVENT_VERIFIED_CHANGED, events.append) + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + + await entity.async_set_weekly_schedule(schedule) + assert provider.has_verified_schedule + assert events[-1] is True + await entity.async_get_weekly_schedule() + assert provider.has_verified_schedule + + stored[_WEEKDAY_BITS["monday"]] = [0, 1900] + await entity.async_get_weekly_schedule() + assert not provider.has_verified_schedule + assert events[-1] is False + + await entity.async_set_weekly_schedule(schedule) + assert provider.has_verified_schedule + working = cluster.command.side_effect + + async def failed_write(command_id, **kwargs): + if command_id == 1: + raise zigpy.exceptions.DeliveryError("offline") + return await working(command_id, **kwargs) + + with ( + patch.object(cluster, "command", side_effect=failed_write), + pytest.raises(ZHAException, match="Schedule upload stopped"), + ): + await entity.async_set_weekly_schedule( + {day: [(0, 2100)] for day in _WEEKDAY_BITS} + ) + assert not provider.has_verified_schedule + assert events[-1] is False + + await entity.async_set_weekly_schedule(schedule) + await entity.async_clear_weekly_schedule() + assert not provider.has_verified_schedule + assert events[-1] is False + + +async def test_weekly_schedule_clear_snapshots_and_verifies( + weekly_schedule_device, +) -> None: + """Clear once after a fresh snapshot and verify each heat day is empty.""" + entity, _device, cluster, stored = weekly_schedule_device + for bit in stored: + stored[bit] = [0, 1950, 480, 2100] + + result = await entity.async_clear_weekly_schedule() + + assert result["complete"] + assert all(day["transitions"] == [] for day in result["days"].values()) + assert result["pre_write_snapshot"]["complete"] + assert result["pre_write_snapshot"]["days"]["monday"]["transitions"] == [ + {"time": "00:00", "temperature": 19.5}, + {"time": "08:00", "temperature": 21.0}, + ] + assert all(values == [] for values in stored.values()) + commands = cluster.command.await_args_list + assert [item.args[0] for item in commands] == [2] * 7 + [3] + [2] * 7 + assert commands[7].kwargs == {"retries": 0} + cluster.write_attributes.assert_not_awaited() + assert await entity.async_get_weekly_schedule(refresh=False) == result + + +async def test_weekly_schedule_clear_requires_complete_preflight( + weekly_schedule_device, +) -> None: + """A failed fresh snapshot prevents the clear command from being sent.""" + entity, _device, cluster, stored = weekly_schedule_device + for bit in stored: + stored[bit] = [0, 2000] + command = cluster.command.side_effect + + async def fail_wednesday(command_id, **kwargs): + if command_id == 2 and kwargs["days_to_return"] == 8: + raise TimeoutError("no response") + return await command(command_id, **kwargs) + + cluster.command.side_effect = fail_wednesday + with pytest.raises(ZHAException, match="Unable to read the wednesday schedule"): + await entity.async_clear_weekly_schedule() + assert not any(item.args[0] == 3 for item in cluster.command.await_args_list) + assert all(values == [0, 2000] for values in stored.values()) + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["pre_write_snapshot"] is None + assert cached["days"]["wednesday"]["transitions"] is None + + +async def test_weekly_schedule_clear_requires_device_command( + weekly_schedule_device, +) -> None: + """A missing clear command is reported before reading or writing.""" + entity, _device, cluster, _stored = weekly_schedule_device + commands = { + key: value for key, value in cluster.server_commands.items() if key != 3 + } + with ( + patch.object(cluster, "server_commands", commands), + pytest.raises(ZHAException, match="does not support schedule clearing"), + ): + await entity.async_clear_weekly_schedule() + cluster.command.assert_not_awaited() + + +async def test_weekly_schedule_clear_cancellation_invalidates_cache( + weekly_schedule_device, +) -> None: + """Cancellation during clear leaves the schedule unknown and snapshot available.""" + entity, _device, cluster, stored = weekly_schedule_device + for bit in stored: + stored[bit] = [0, 2000] + command = cluster.command.side_effect + started = asyncio.Event() + + async def pause_clear(command_id, **kwargs): + if command_id == 3: + started.set() + await asyncio.Event().wait() + return await command(command_id, **kwargs) + + cluster.command.side_effect = pause_clear + clear = asyncio.create_task(entity.async_clear_weekly_schedule()) + waiting_for_clear = asyncio.create_task(started.wait()) + done, _ = await asyncio.wait( + (clear, waiting_for_clear), return_when=asyncio.FIRST_COMPLETED + ) + if clear in done: + waiting_for_clear.cancel() + await clear + assert waiting_for_clear in done + clear.cancel() + with pytest.raises(asyncio.CancelledError): + await clear + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["pre_write_snapshot"]["complete"] + assert all(day["transitions"] is None for day in cached["days"].values()) + + +@pytest.mark.parametrize( + ("failure", "message"), + [ + ("timeout", "Unable to confirm schedule clearing"), + ("response_error", "Unable to confirm schedule clearing"), + ("rejected", "Schedule clear returned status"), + ("unexpected_ack", "Unexpected schedule clear acknowledgement"), + ("readback", "heat schedule read-back failed"), + ("nonempty", "did not remove heat transitions on"), + ], +) +async def test_weekly_schedule_clear_surfaces_failure( + weekly_schedule_device, failure: str, message: str +) -> None: + """A failed or unverified clear is reported without retry or rollback.""" + entity, _device, cluster, stored = weekly_schedule_device + for bit in stored: + stored[bit] = [0, 2000] + command = cluster.command.side_effect + clear_attempted = False + + async def fail_clear(command_id, **kwargs): + nonlocal clear_attempted + if command_id == 3: + clear_attempted = True + if failure == "rejected": + return zcl_f.DefaultResponse( + command_id=3, status=zcl_f.Status.UNSUP_CLUSTER_COMMAND + ) + if failure == "response_error": + return ValueError("device command failed") + response = await command(command_id, **kwargs) + if failure == "timeout": + raise TimeoutError("acknowledgement lost") + if failure == "unexpected_ack": + return zcl_f.DefaultResponse(command_id=1, status=zcl_f.Status.SUCCESS) + if failure == "nonempty": + stored[4] = [0, 1900] + return response + if ( + clear_attempted + and failure == "readback" + and command_id == 2 + and kwargs["days_to_return"] == 4 + ): + raise TimeoutError("read-back lost") + return await command(command_id, **kwargs) + + cluster.command.side_effect = fail_clear + with pytest.raises(ZHAException, match=message) as err: + await entity.async_clear_weekly_schedule() + assert "No rollback was attempted" in str(err.value) + assert sum(item.args[0] == 3 for item in cluster.command.await_args_list) == 1 + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["pre_write_snapshot"]["complete"] + assert cached["pre_write_snapshot"]["days"]["monday"]["transitions"] == [ + {"time": "00:00", "temperature": 20.0} + ] + if failure in ("timeout", "response_error", "rejected", "unexpected_ack"): + assert all(day["transitions"] is None for day in cached["days"].values()) + elif failure == "readback": + assert cached["days"]["monday"]["transitions"] == [] + assert cached["days"]["tuesday"]["transitions"] is None + else: + assert cached["days"]["tuesday"]["transitions"] == [ + {"time": "00:00", "temperature": 19.0} + ] + + +@pytest.mark.parametrize( + "problem", + [ + "missing_day", + "empty_day", + "malformed_transition", + "duplicate_time", + "invalid_temperature", + "missing_midnight", + "too_many", + "out_of_limits", + "limits_unavailable", + "heat_limits_transport_failure", + "invalid_heat_limits", + ], +) +async def test_weekly_schedule_validation_precedes_writes( + weekly_schedule_device, problem: str +) -> None: + """Invalid complete-week uploads never write any day.""" + entity, _device, cluster, _stored = weekly_schedule_device + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + if problem == "missing_day": + del schedule["sunday"] + elif problem == "empty_day": + schedule["sunday"] = [] + elif problem == "malformed_transition": + schedule["sunday"] = [(0, 2000, 1)] + elif problem == "duplicate_time": + schedule["sunday"] = [(0, 2000), (0, 2100)] + elif problem == "invalid_temperature": + schedule["sunday"] = [(0, True)] + elif problem == "missing_midnight": + schedule["sunday"] = [(60, 2000)] + elif problem == "too_many": + schedule["sunday"] = [(minute, 2000) for minute in range(256)] + elif problem == "out_of_limits": + schedule["sunday"] = [(0, 5000)] + elif problem == "limits_unavailable": + cluster.PLUGGED_ATTR_READS["min_heat_setpoint_limit"] = None + elif problem == "heat_limits_transport_failure": + cluster.read_attributes.side_effect = TimeoutError("radio unavailable") + elif problem == "invalid_heat_limits": + cluster.read_attributes.return_value = ( + {"min_heat_setpoint_limit": 3000, "max_heat_setpoint_limit": 1600}, + {}, + ) + + with pytest.raises(ZHAException): + await entity.async_set_weekly_schedule(schedule) + cluster.command.assert_not_awaited() + + +@pytest.mark.parametrize( + ("temperature", "direction"), + [(5000, "too high"), (600, "too low")], +) +async def test_weekly_schedule_heat_limit_error_identifies_temperature( + weekly_schedule_device, temperature: int, direction: str +) -> None: + """Out-of-range temperatures identify the value, day, time, and limits.""" + entity, _device, cluster, _stored = weekly_schedule_device + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + schedule["sunday"] = [(0, 2000), (390, temperature)] + + with pytest.raises(ZHAException) as err: + await entity.async_set_weekly_schedule(schedule) + assert str(err.value) == ( + f"The temperature {temperature / 100:g} °C on Sunday at 06:30 is " + f"{direction}. Choose a temperature within the thermostat's " + "allowed range of 7 to 29 °C." + ) + cluster.command.assert_not_awaited() + + +@pytest.mark.parametrize( + ("response", "message"), + [ + (ValueError("command failed"), "Unable to read the monday schedule"), + ( + zcl_f.DefaultResponse(command_id=2, status=zcl_f.Status.FAILURE), + "device returned", + ), + ("unexpected response", "Unexpected schedule response"), + ], +) +async def test_weekly_schedule_rejects_non_schedule_responses( + weekly_schedule_device, response, message: str +) -> None: + """Command errors, default responses and non-struct replies are rejected.""" + entity, _device, cluster, _stored = weekly_schedule_device + cluster.command.return_value = response + cluster.command.side_effect = None + with pytest.raises(ZHAException, match=message): + await entity.async_get_weekly_schedule() + + +async def test_weekly_schedule_does_not_enforce_unverified_device_limit( + weekly_schedule_device, +) -> None: + """A mocked twelve-transition payload is not rejected by a guessed limit.""" + entity, _device, cluster, stored = weekly_schedule_device + transitions = [(minute, 2000) for minute in range(12)] + result = await entity.async_set_weekly_schedule( + {day: list(transitions) for day in _WEEKDAY_BITS} + ) + assert result["complete"] + assert len(stored[2]) == 24 + assert sum(item.args[0] == 1 for item in cluster.command.await_args_list) == 7 + + +async def test_weekly_schedule_incomplete_preflight( + weekly_schedule_device, +) -> None: + """A failed fresh pre-read aborts before writes and leaves unknown days marked.""" + entity, _device, cluster, _stored = weekly_schedule_device + command = cluster.command.side_effect + + async def fail_wednesday(command_id, **kwargs): + if command_id == 2 and kwargs["days_to_return"] == 8: + raise TimeoutError("no response") + return await command(command_id, **kwargs) + + cluster.command.side_effect = fail_wednesday + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + with pytest.raises(ZHAException, match="Unable to read the wednesday schedule"): + await entity.async_set_weekly_schedule(schedule) + assert not any(item.args[0] == 1 for item in cluster.command.await_args_list) + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["days"]["monday"]["transitions"] == [] + assert cached["days"]["wednesday"]["transitions"] is None + assert cached["pre_write_snapshot"] is None + + +async def test_weekly_schedule_missing_thermostat_cluster_clears_cache( + weekly_schedule_device, +) -> None: + """A missing endpoint cluster fails explicitly and clears stale cache.""" + entity, device, _cluster, _stored = weekly_schedule_device + await entity.async_get_weekly_schedule() + with ( + patch.object(device, "async_get_cluster", side_effect=KeyError("missing")), + pytest.raises( + ZHAException, match="The thermostat cluster is no longer available" + ), + ): + await entity.async_get_weekly_schedule(refresh=False) + cached = entity.weekly_schedule._snapshot() + assert not cached["complete"] + assert entity.weekly_schedule._pre_write_snapshot is None + + +async def test_weekly_schedule_missing_write_command(weekly_schedule_device) -> None: + """A missing set command is rejected before snapshot reads or writes.""" + entity, _device, cluster, _stored = weekly_schedule_device + commands = { + key: value for key, value in cluster.server_commands.items() if key != 1 + } + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + with ( + patch.object(cluster, "server_commands", commands), + pytest.raises(ZHAException, match="does not support schedule writes"), + ): + await entity.async_set_weekly_schedule(schedule) + cluster.command.assert_not_awaited() + + +async def test_weekly_schedule_rejects_unencodable_payload( + weekly_schedule_device, +) -> None: + """Payload serialization errors are reported before any device command.""" + entity, _device, cluster, _stored = weekly_schedule_device + commands = dict(cluster.server_commands) + + class InvalidSchema: + def __init__(self, **_kwargs) -> None: + raise ValueError("payload too large") + + commands[1] = SimpleNamespace(schema=InvalidSchema) + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + with ( + patch.object(cluster, "server_commands", commands), + pytest.raises(ZHAException, match="monday schedule cannot be encoded"), + ): + await entity.async_set_weekly_schedule(schedule) + cluster.command.assert_not_awaited() + + +async def test_weekly_schedule_cluster_replacement_aborts_before_first_write( + weekly_schedule_device, +) -> None: + """A replaced cluster during preflight aborts before changing a day.""" + entity, device, cluster, _stored = weekly_schedule_device + manager = entity.weekly_schedule + endpoint = device.device.endpoints[1] + original_command = cluster.command.side_effect + + async def replace_after_sunday(command_id, **kwargs): + response = await original_command(command_id, **kwargs) + if command_id == 2 and int(kwargs["days_to_return"]) == 1: + endpoint.in_clusters[Thermostat.cluster_id] = Thermostat(endpoint) + return response + + cluster.command.side_effect = replace_after_sunday + with pytest.raises(ZHAException, match="thermostat cluster changed"): + await entity.async_set_weekly_schedule( + {day: [(0, 2000)] for day in _WEEKDAY_BITS} + ) + assert not any(item.args[0] == 1 for item in cluster.command.await_args_list) + cached = manager._snapshot() + assert not cached["complete"] + assert manager._pre_write_snapshot is None + + +async def test_weekly_schedule_cluster_change_after_snapshot_is_reported( + weekly_schedule_device, +) -> None: + """A cluster change just before writing is reported with the saved snapshot.""" + entity, _device, cluster, _stored = weekly_schedule_device + manager = entity.weekly_schedule + original = manager._ensure_same_cluster + checks = 0 + + def replace_before_write(current_cluster) -> None: + nonlocal checks + checks += 1 + if checks == 9: + raise ZHAException("The thermostat cluster changed during the operation") + original(current_cluster) + + with ( + patch.object(manager, "_ensure_same_cluster", side_effect=replace_before_write), + pytest.raises( + ZHAException, + match=r"Observed changed days: \[\]; unknown attempted days: \[\]", + ), + ): + await entity.async_set_weekly_schedule( + {day: [(0, 2000)] for day in _WEEKDAY_BITS} + ) + assert checks == 9 + assert not any(item.args[0] == 1 for item in cluster.command.await_args_list) + assert manager._pre_write_snapshot["complete"] + + +@pytest.mark.parametrize( + ("count", "days", "mode", "values"), + [ + (2, 2, 1, [0, 2000]), + (1, 4, 1, [0, 2000]), + (1, 2, 2, [0, 2000]), + (2, 2, 1, [60, 2000, 60, 2100]), + ], +) +async def test_weekly_schedule_rejects_malformed_read_back( + weekly_schedule_device, count: int, days: int, mode: int, values: list[int] +) -> None: + """A mismatched or invalid response is never cached as a known day.""" + entity, _device, cluster, _stored = weekly_schedule_device + cluster.command.return_value = ( + Thermostat.ClientCommandDefs.get_weekly_schedule_response.schema( + num_transitions_for_sequence=count, + day_of_week_for_sequence=days, + mode_for_sequence=mode, + values=values, + ) + ) + cluster.command.side_effect = None + with pytest.raises(ZHAException, match="schedule (response|transition)"): + await entity.async_get_weekly_schedule() + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["days"]["monday"]["transitions"] is None + + +async def test_weekly_schedule_partial_failure_preserves_snapshot( + weekly_schedule_device, +) -> None: + """A lost acknowledgement and failed read-back leave the attempted day unknown.""" + entity, _device, cluster, _stored = weekly_schedule_device + command = cluster.command.side_effect + attempted_tuesday = False + + async def fail_tuesday(command_id, **kwargs): + nonlocal attempted_tuesday + if command_id == 1 and kwargs["day_of_week_for_sequence"] == 4: + attempted_tuesday = True + raise TimeoutError("acknowledgement lost") + if command_id == 2 and kwargs["days_to_return"] == 4 and attempted_tuesday: + raise TimeoutError("read-back lost") + return await command(command_id, **kwargs) + + cluster.command.side_effect = fail_tuesday + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + with pytest.raises( + ZHAException, + match=r"Observed changed days: \['monday'\]; unknown attempted days: \['tuesday'\]", + ): + await entity.async_set_weekly_schedule(schedule) + writes = [item for item in cluster.command.await_args_list if item.args[0] == 1] + assert len(writes) == 2 + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["days"]["monday"]["transitions"] == [ + {"time": "00:00", "temperature": 20.0} + ] + assert cached["days"]["tuesday"]["transitions"] is None + assert cached["pre_write_snapshot"]["complete"] + assert cached["pre_write_snapshot"]["days"]["monday"]["transitions"] == [] + + +async def test_weekly_schedule_lost_acknowledgement_with_matching_readback( + weekly_schedule_device, +) -> None: + """An exact read-back establishes the stored value without retrying the write.""" + entity, _device, cluster, _stored = weekly_schedule_device + command = cluster.command.side_effect + + async def lose_first_ack(command_id, **kwargs): + response = await command(command_id, **kwargs) + if command_id == 1 and kwargs["day_of_week_for_sequence"] == 2: + raise TimeoutError("acknowledgement lost") + return response + + cluster.command.side_effect = lose_first_ack + result = await entity.async_set_weekly_schedule( + {day: [(0, 2000)] for day in _WEEKDAY_BITS} + ) + assert result["complete"] + writes = [item for item in cluster.command.await_args_list if item.args[0] == 1] + assert len(writes) == 7 + + +@pytest.mark.parametrize("reply", ["exception", "unexpected_ack"]) +async def test_weekly_schedule_matching_readback_recovers_invalid_reply( + weekly_schedule_device, reply: str +) -> None: + """Exact read-back confirms a write despite an exception or unknown reply.""" + entity, _device, cluster, _stored = weekly_schedule_device + command = cluster.command.side_effect + + async def invalid_reply(command_id, **kwargs): + response = await command(command_id, **kwargs) + if command_id == 1 and kwargs["day_of_week_for_sequence"] == 2: + if reply == "exception": + return ValueError("response decoding failed") + return zcl_f.DefaultResponse(command_id=3, status=zcl_f.Status.SUCCESS) + return response + + cluster.command.side_effect = invalid_reply + result = await entity.async_set_weekly_schedule( + {day: [(0, 2000)] for day in _WEEKDAY_BITS} + ) + assert result["complete"] + assert ( + len([item for item in cluster.command.await_args_list if item.args[0] == 1]) + == 7 + ) + + +@pytest.mark.parametrize("failure", ["rejected", "mismatched_readback", "transport"]) +async def test_weekly_schedule_stops_after_device_failure( + weekly_schedule_device, failure: str +) -> None: + """A rejection or differing read-back stops subsequent days without rollback.""" + entity, _device, cluster, stored = weekly_schedule_device + command = cluster.command.side_effect + + async def fail_tuesday(command_id, **kwargs): + if command_id == 1 and kwargs["day_of_week_for_sequence"] == 4: + if failure == "rejected": + return zcl_f.DefaultResponse( + command_id=1, status=zcl_f.Status.UNSUP_CLUSTER_COMMAND + ) + if failure == "transport": + raise ValueError("Radio rejected the schedule payload") + stored[4] = [0, 1900] + return zcl_f.DefaultResponse(command_id=1, status=zcl_f.Status.SUCCESS) + return await command(command_id, **kwargs) + + cluster.command.side_effect = fail_tuesday + with pytest.raises(ZHAException) as err: + await entity.async_set_weekly_schedule( + {day: [(0, 2000)] for day in _WEEKDAY_BITS} + ) + assert "Schedule upload stopped on tuesday" in str(err.value) + assert "unknown attempted days: []" in str(err.value) + if failure in ("rejected", "transport"): + expected = ( + "UNSUP_CLUSTER_COMMAND" + if failure == "rejected" + else "Radio rejected the schedule payload" + ) + assert expected in str(err.value) + assert "Observed changed days: ['monday']" in str(err.value) + else: + assert "read-back does not match" in str(err.value) + assert "Observed changed days: ['monday', 'tuesday']" in str(err.value) + writes = [item for item in cluster.command.await_args_list if item.args[0] == 1] + assert len(writes) == 2 + cached = await entity.async_get_weekly_schedule(refresh=False) + assert cached["pre_write_snapshot"]["complete"] + + +@pytest.mark.parametrize("clear_type", ["raw", "managed"]) +async def test_weekly_schedule_serializes_clear( + weekly_schedule_device, clear_type: str +) -> None: + """Clear waits for an in-progress upload on the same endpoint.""" + entity, device, cluster, stored = weekly_schedule_device + command = cluster.command.side_effect + started = asyncio.Event() + resume = asyncio.Event() + + async def pause_first_write(command_id, **kwargs): + if command_id == 1 and kwargs["day_of_week_for_sequence"] == 2: + started.set() + await resume.wait() + return await command(command_id, **kwargs) + + cluster.command.side_effect = pause_first_write + upload = asyncio.create_task( + entity.async_set_weekly_schedule({day: [(0, 2000)] for day in _WEEKDAY_BITS}) + ) + waiting_for_write = asyncio.create_task(started.wait()) + done, _ = await asyncio.wait( + (upload, waiting_for_write), return_when=asyncio.FIRST_COMPLETED + ) + if upload in done: + await upload + assert waiting_for_write in done + clear = asyncio.create_task( + entity.async_clear_weekly_schedule() + if clear_type == "managed" + else device.issue_cluster_command( + 1, Thermostat.cluster_id, 3, "server", None, {} + ) + ) + await asyncio.sleep(0) + assert not clear.done() + assert not any(item.args[0] == 3 for item in cluster.command.await_args_list) + resume.set() + await upload + await clear + assert all(values == [] for values in stored.values()) + cached = await entity.async_get_weekly_schedule(refresh=False) + if clear_type == "raw": + assert all(day["transitions"] is None for day in cached["days"].values()) + else: + assert all(day["transitions"] == [] for day in cached["days"].values()) + assert cached["pre_write_snapshot"]["days"]["monday"]["transitions"] == [ + {"time": "00:00", "temperature": 20.0} + ] + + +async def test_weekly_schedule_invalidates_on_cluster_replacement( + weekly_schedule_device, +) -> None: + """A replacement cluster cannot reuse the previous device's cached schedule.""" + entity, device, _cluster, _stored = weekly_schedule_device + assert (await entity.async_get_weekly_schedule())["complete"] + endpoint = device.device.endpoints[1] + endpoint.in_clusters[Thermostat.cluster_id] = Thermostat(endpoint) + cached = await entity.async_get_weekly_schedule(refresh=False) + assert not cached["complete"] + assert all(day["transitions"] is None for day in cached["days"].values()) + + @pytest.mark.parametrize( ("value", "raw_value"), [(0.3, 3), (-0.3, -3), (0.7, 7), (-1.9, -19), (2.4, 24)], @@ -2001,3 +2894,117 @@ def discover_entities(self) -> Iterator[PlatformEntity]: assert local_temperature_calibration_entity.state.native_max_value == 5.0 assert local_temperature_calibration_entity.state.native_step == 0.1 assert local_temperature_calibration_entity._multiplier == 0.1 + + +async def test_weekly_schedule_requires_exposed_feature(zha_gateway: Gateway) -> None: + """Thermostats without an exposed schedule feature have no provider.""" + device = await device_climate_mock(zha_gateway, CLIMATE, plug={}) + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + assert entity.weekly_schedule is None + with pytest.raises(ZHAException, match="does not support weekly schedules"): + await entity.async_get_weekly_schedule() + + +async def test_bosch_trv1_weekly_schedule_from_diagnostics( + zha_gateway: Gateway, +) -> None: + """The real TRV1 signature discovers the standard schedule provider.""" + zigpy_device = await zigpy_device_from_json( + zha_gateway.application_controller, + "tests/data/devices/bosch-rbsh-trv1-zb-eu-0x11087140.json", + ) + device = await join_zigpy_device(zha_gateway, zigpy_device) + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + + assert THERMOSTAT_WEEKLY_SCHEDULE in device.exposes_features + assert isinstance(entity.weekly_schedule, ZclWeeklySchedule) + assert HVACMode.AUTO in entity.hvac_modes + + +async def test_weekly_schedule_only_changed_days(weekly_schedule_device) -> None: + """Change detection skips days whose fresh read already matches.""" + entity, _device, cluster, stored = weekly_schedule_device + stored.update({bit: [0, 2000] for bit in _WEEKDAY_BITS.values()}) + schedule = {day: [(0, 2000)] for day in _WEEKDAY_BITS} + schedule["wednesday"] = [(0, 1700), (420, 2100)] + + result = await entity.async_set_weekly_schedule(schedule, only_changed=True) + + writes = [ + item.kwargs["day_of_week_for_sequence"] + for item in cluster.command.await_args_list + if item.args[0] == Thermostat.ServerCommandDefs.set_weekly_schedule.id + ] + assert writes == [_WEEKDAY_BITS["wednesday"]] + assert result["written_days"] == ["wednesday"] + assert stored[_WEEKDAY_BITS["wednesday"]] == [0, 1700, 420, 2100] + + cluster.command.reset_mock() + result = await entity.async_set_weekly_schedule(schedule, only_changed=True) + assert result["written_days"] == [] + assert all(item.args[0] == 0x02 for item in cluster.command.await_args_list) + + +async def test_weekly_schedule_custom_provider(zha_gateway: Gateway) -> None: + """Other thermostat families plug in by registering a feature provider.""" + + class MemoryProvider(WeeklyScheduleProvider): + capabilities = WeeklyScheduleCapabilities( + max_transitions_per_day=2, temperature_step=50, supports_clear=False + ) + + def __init__(self, device, endpoint_id) -> None: + super().__init__(device, endpoint_id) + self.days: dict[str, tuple[Transition, ...]] = dict.fromkeys( + _WEEKDAY_BITS, () + ) + + async def _async_read_day(self, day): + return self.days[day] + + async def _async_heat_limits(self): + return 500, 3000 + + def _check_write_support(self) -> None: + pass + + async def _async_write_day(self, day, transitions): + self.days[day] = transitions + return WriteAcknowledgement() + + device = await device_climate_mock(zha_gateway, CLIMATE, plug={}) + device.exposes_features.add("test_memory_schedule") + entity: ThermostatEntity = get_entity( + device, platform=Platform.CLIMATE, entity_type=ThermostatEntity + ) + with patch.dict( + "zha.zigbee.weekly_schedule.WEEKLY_SCHEDULE_PROVIDERS", + {"test_memory_schedule": MemoryProvider}, + ): + provider = entity.weekly_schedule + assert isinstance(provider, MemoryProvider) + + with pytest.raises(ZHAException, match="between 1 and 2 transitions"): + await entity.async_set_weekly_schedule( + {day: [(0, 2000), (60, 2100), (120, 2200)] for day in _WEEKDAY_BITS} + ) + with pytest.raises(ZHAException, match=r"multiples of 0\.5"): + await entity.async_set_weekly_schedule( + {day: [(0, 2010)] for day in _WEEKDAY_BITS} + ) + with pytest.raises(ZHAException, match="does not support schedule clearing"): + await entity.async_clear_weekly_schedule() + + result = await entity.async_set_weekly_schedule( + {day: [(0, 1750), (360, 2100)] for day in _WEEKDAY_BITS} + ) + assert result["complete"] + assert result["days"]["sunday"]["transitions"] == [ + {"time": "00:00", "temperature": 17.5}, + {"time": "06:00", "temperature": 21.0}, + ] + assert provider.days["sunday"] == (Transition(0, 1750), Transition(360, 2100)) diff --git a/zha/application/platforms/climate/__init__.py b/zha/application/platforms/climate/__init__.py index a1cd7fda7..7236d653e 100644 --- a/zha/application/platforms/climate/__init__.py +++ b/zha/application/platforms/climate/__init__.py @@ -55,12 +55,18 @@ Preset, ) from zha.decorators import periodic +from zha.exceptions import ZHAException from zha.quirks import THERMOSTAT_FAN_ONLY_HVAC from zha.units import UnitOfTemperature if TYPE_CHECKING: from zha.zigbee.device import Device from zha.zigbee.endpoint import Endpoint + from zha.zigbee.weekly_schedule import ( + ScheduleInput, + ScheduleResult, + WeeklyScheduleProvider, + ) @dataclass(frozen=True, kw_only=True) @@ -398,6 +404,34 @@ def __init__( self._supported_features = ClimateEntityFeature(0) self.recompute_capabilities() + @property + def weekly_schedule(self) -> WeeklyScheduleProvider | None: + """Return the weekly schedule provider exposed by the device's quirk.""" + return self._device.weekly_schedule(self._endpoint.id) + + def _require_weekly_schedule(self) -> WeeklyScheduleProvider: + if (provider := self.weekly_schedule) is None: + raise ZHAException("This thermostat does not support weekly schedules") + return provider + + async def async_get_weekly_schedule( + self, *, refresh: bool = True + ) -> ScheduleResult: + """Return the thermostat's heat schedule or the in-memory cache.""" + return await self._require_weekly_schedule().async_get(refresh=refresh) + + async def async_set_weekly_schedule( + self, schedule: ScheduleInput, *, only_changed: bool = False + ) -> ScheduleResult: + """Upload and verify a complete heat schedule.""" + return await self._require_weekly_schedule().async_set( + schedule, only_changed=only_changed + ) + + async def async_clear_weekly_schedule(self) -> ScheduleResult: + """Clear the device schedule and verify its heat days.""" + return await self._require_weekly_schedule().async_clear() + @property def _local_temperature(self) -> int | None: return self._cluster.get(ThermostatCluster.AttributeDefs.local_temperature.name) @@ -699,12 +733,27 @@ def _pi_demand_action(self) -> HVACAction | None: @property def hvac_mode(self) -> HVACMode | None: """Return HVAC operation mode.""" - return SYSTEM_MODE_2_HVAC.get(self._system_mode) + mode = SYSTEM_MODE_2_HVAC.get(self._system_mode) + sequence = SEQ_OF_OPERATION.get(self._ctrl_sequence_of_oper, []) + if ( + mode == HVACMode.HEAT_COOL + and HVACMode.HEAT in sequence + and HVACMode.HEAT_COOL not in sequence + and self.weekly_schedule is not None + ): + return HVACMode.AUTO + return mode @property def hvac_modes(self) -> list[HVACMode]: """Return the list of available HVAC operation modes.""" modes = SEQ_OF_OPERATION.get(self._ctrl_sequence_of_oper, [HVACMode.OFF]) + if ( + HVACMode.HEAT in modes + and HVACMode.HEAT_COOL not in modes + and self.weekly_schedule is not None + ): + modes = [*modes, HVACMode.AUTO] if ( self._fan_cluster is not None and THERMOSTAT_FAN_ONLY_HVAC in self._device.exposes_features @@ -737,7 +786,7 @@ def target_temperature(self): temp = self._unoccupied_cooling_setpoint else: temp = self._occupied_cooling_setpoint - elif self.hvac_mode == HVACMode.HEAT: + elif self.hvac_mode in (HVACMode.HEAT, HVACMode.AUTO): if self.preset_mode == Preset.AWAY: temp = self._unoccupied_heating_setpoint else: @@ -939,7 +988,7 @@ async def async_set_temperature( temperature=int(temperature * ZCL_TEMP), is_away=is_away, ) - elif self.hvac_mode == HVACMode.HEAT: + elif self.hvac_mode in (HVACMode.HEAT, HVACMode.AUTO): await self._async_set_heating_setpoint( temperature=int(temperature * ZCL_TEMP), is_away=is_away, diff --git a/zha/application/platforms/climate/const.py b/zha/application/platforms/climate/const.py index c1e5b06bf..3d3400ff0 100644 --- a/zha/application/platforms/climate/const.py +++ b/zha/application/platforms/climate/const.py @@ -205,6 +205,7 @@ class HVACAction(StrEnum): HVAC_MODE_2_SYSTEM = { HVACMode.OFF: SystemMode.Off, HVACMode.HEAT_COOL: SystemMode.Auto, + HVACMode.AUTO: SystemMode.Auto, HVACMode.COOL: SystemMode.Cool, HVACMode.HEAT: SystemMode.Heat, HVACMode.FAN_ONLY: SystemMode.Fan_only, diff --git a/zha/quirks.py b/zha/quirks.py index 2d06135b8..d972fb9cd 100644 --- a/zha/quirks.py +++ b/zha/quirks.py @@ -41,6 +41,7 @@ SE_POLL_SUMMATION = "se_poll_summation" SIREN_BASIC = "siren_basic" THERMOSTAT_FAN_ONLY_HVAC = "thermostat_fan_only_hvac" +THERMOSTAT_WEEKLY_SCHEDULE = "thermostat_weekly_schedule" class ModelInfo(NamedTuple): diff --git a/zha/zigbee/device.py b/zha/zigbee/device.py index ddc8c8cc9..c00a97283 100644 --- a/zha/zigbee/device.py +++ b/zha/zigbee/device.py @@ -30,6 +30,7 @@ import zigpy.zcl from zigpy.zcl.clusters import Cluster from zigpy.zcl.clusters.general import Basic, Groups, Identify, Ota +from zigpy.zcl.clusters.hvac import Thermostat from zigpy.zcl.foundation import ( Status as ZclStatus, WriteAttributesStatusRecord, @@ -99,6 +100,11 @@ initialize_cluster_configs, ) from zha.zigbee.endpoint import Endpoint +from zha.zigbee.weekly_schedule import ( + WEEKLY_SCHEDULE_PROVIDERS, + WeeklyScheduleProvider, + ZclWeeklySchedule, +) if TYPE_CHECKING: from zha.application.gateway import Gateway @@ -1152,6 +1158,8 @@ def _compute_primary_entity(self, entities: Collection[PlatformEntity]) -> None: class ZigbeeDevice(BaseDevice[ZigpyDevice]): """ZHA Zigbee device object.""" + supports_cluster_command_response = True + # Authoring surface for hand-written quirks; `None` marks the unquirked fallback. _device_match: DeviceMatch | None = None _zigpy_device_cls: ReplacingZigpyDeviceFactory | None = None @@ -1176,6 +1184,7 @@ def __init__( ) -> None: """Initialize the Zigbee device.""" self._endpoints: dict[int, Endpoint] = {} + self._weekly_schedules: dict[int, WeeklyScheduleProvider] = {} super().__init__(zigpy_device, _gateway) def _init_from_zigpy_device(self, zigpy_device: ZigpyDevice) -> None: @@ -1597,6 +1606,17 @@ async def write_zigbee_attribute( f"{ATTR_ENDPOINT_ID}: {endpoint_id}" ) from exc + def weekly_schedule(self, endpoint_id: int) -> WeeklyScheduleProvider | None: + """Return the endpoint's schedule provider if a quirk exposes one.""" + if (provider := self._weekly_schedules.get(endpoint_id)) is not None: + return provider + for feature in sorted(self.exposes_features): + if (provider_cls := WEEKLY_SCHEDULE_PROVIDERS.get(feature)) is not None: + provider = provider_cls(self, endpoint_id) + self._weekly_schedules[endpoint_id] = provider + return provider + return None + async def issue_cluster_command( self, endpoint_id: int, @@ -1607,63 +1627,92 @@ async def issue_cluster_command( params: dict[str, Any] | None, cluster_type: str = CLUSTER_TYPE_IN, manufacturer: int | None = None, - ) -> None: + *, + return_response: bool = False, + ) -> Any: """Issue a command against specified zigbee cluster on this device.""" - try: - cluster: Cluster = self.async_get_cluster( - endpoint_id, cluster_id, cluster_type + schedule = ( + self.weekly_schedule(endpoint_id) + if ( + cluster_id == Thermostat.cluster_id + and cluster_type == CLUSTER_TYPE_IN + and command_type == CLUSTER_COMMAND_SERVER + and command in (0x01, 0x02, 0x03) ) - except KeyError as exc: - raise ValueError( - f"Cluster {cluster_id} not found on endpoint {endpoint_id} while" - f" issuing command {command} with args {args}" - ) from exc - commands: dict[int, ZCLCommandDef] = ( - cluster.server_commands - if command_type == CLUSTER_COMMAND_SERVER - else cluster.client_commands + else None ) - if args is not None: - self.warning( - ( - "args [%s] are deprecated and should be passed with the params key." - " The parameter names are: %s" - ), - args, - [field.name for field in commands[command].schema.fields], + if not isinstance(schedule, ZclWeeklySchedule): + schedule = None + async with schedule.lock if schedule is not None else contextlib.nullcontext(): + try: + cluster: Cluster = self.async_get_cluster( + endpoint_id, cluster_id, cluster_type + ) + except KeyError as exc: + raise ValueError( + f"Cluster {cluster_id} not found on endpoint {endpoint_id} while" + f" issuing command {command} with args {args}" + ) from exc + if schedule is not None: + schedule.bind_cluster(cluster) + if command == 0x03: + schedule.invalidate() + elif command == 0x01: + day_bitmap = ( + args[1] + if args is not None and len(args) > 1 + else (params or {}).get("day_of_week_for_sequence") + ) + schedule.invalidate( + day_bitmap + if isinstance(day_bitmap, int) + and not isinstance(day_bitmap, bool) + and 0 < day_bitmap <= 0xFF + else None + ) + + commands: dict[int, ZCLCommandDef] = ( + cluster.server_commands + if command_type == CLUSTER_COMMAND_SERVER + else cluster.client_commands ) - response = await getattr(cluster, commands[command].name)(*args) - else: - assert params is not None - response = await getattr(cluster, commands[command].name)( - **convert_to_zcl_values(params, commands[command].schema) + if args is not None: + self.warning( + ( + "args [%s] are deprecated and should be passed with the params key." + " The parameter names are: %s" + ), + args, + [field.name for field in commands[command].schema.fields], + ) + response = await getattr(cluster, commands[command].name)(*args) + else: + assert params is not None + response = await getattr(cluster, commands[command].name)( + **convert_to_zcl_values(params, commands[command].schema) + ) + self.debug( + "Issued cluster command: %s %s %s %s %s %s %s %s", + f"{ATTR_CLUSTER_ID}: [{cluster_id}]", + f"{ATTR_CLUSTER_TYPE}: [{cluster_type}]", + f"{ATTR_ENDPOINT_ID}: [{endpoint_id}]", + f"{ATTR_COMMAND}: [{command}]", + f"{ATTR_COMMAND_TYPE}: [{command_type}]", + f"{ATTR_ARGS}: [{args}]", + f"{ATTR_PARAMS}: [{params}]", + f"{ATTR_MANUFACTURER}: [{manufacturer}]", ) - self.debug( - "Issued cluster command: %s %s %s %s %s %s %s %s", - f"{ATTR_CLUSTER_ID}: [{cluster_id}]", - f"{ATTR_CLUSTER_TYPE}: [{cluster_type}]", - f"{ATTR_ENDPOINT_ID}: [{endpoint_id}]", - f"{ATTR_COMMAND}: [{command}]", - f"{ATTR_COMMAND_TYPE}: [{command_type}]", - f"{ATTR_ARGS}: [{args}]", - f"{ATTR_PARAMS}: [{params}]", - f"{ATTR_MANUFACTURER}: [{manufacturer}]", - ) - if response is None: - return # client commands don't return a response - if isinstance(response, Exception): - raise ZHAException("Failed to issue cluster command") from response - - # Depending on the command, the reply is either a Default Response - # (`command_id`, `status`) or the cluster-specific response defined for that - # command, whose fields differ per command. A field named `status` means the - # same thing in either kind of reply -- but its position does not carry over: - # indexing blindly into the response reads an unrelated field (e.g. a Groups - # `add_response`'s `group_id`) and reports it as a status. Many cluster-specific - # responses, such as `get_membership_response`, have no `status` field at all. - status = getattr(response, "status", None) - if status is not None and status != ZclStatus.SUCCESS: - raise ZHAException(f"Failed to issue cluster command with status: {status}") + if response is None: + return None + if isinstance(response, Exception): + raise ZHAException("Failed to issue cluster command") from response + + status = getattr(response, "status", None) + if status is not None and status != ZclStatus.SUCCESS: + raise ZHAException( + f"Failed to issue cluster command with status: {status}" + ) + return response if return_response else None async def async_add_to_group(self, group_id: int) -> None: """Add this device to the provided zigbee group.""" diff --git a/zha/zigbee/weekly_schedule.py b/zha/zigbee/weekly_schedule.py new file mode 100644 index 000000000..4ee4cbd3b --- /dev/null +++ b/zha/zigbee/weekly_schedule.py @@ -0,0 +1,651 @@ +"""Heat-only thermostat weekly schedules. + +`WeeklyScheduleProvider` implements validation, caching, snapshots, change +detection and verified per-day writes. A thermostat family only implements the +transport primitives. `ZclWeeklySchedule` uses the standard ZCL Thermostat +cluster commands. Quirks opt in by exposing a feature registered in +`WEEKLY_SCHEDULE_PROVIDERS`. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +import asyncio +from collections.abc import Mapping, Sequence +import copy +from dataclasses import dataclass +from datetime import UTC, datetime +from typing import TYPE_CHECKING, Any, NamedTuple, TypedDict + +import zigpy.exceptions +import zigpy.types as t +from zigpy.zcl import Cluster, foundation +from zigpy.zcl.clusters.hvac import SeqDayOfWeek, SeqMode, Thermostat + +from zha.event import EventBase +from zha.exceptions import ZHAException +from zha.quirks import THERMOSTAT_WEEKLY_SCHEDULE + +if TYPE_CHECKING: + from zha.zigbee.device import ZigbeeDevice + +WEEKDAYS = { + "monday": SeqDayOfWeek.Monday, + "tuesday": SeqDayOfWeek.Tuesday, + "wednesday": SeqDayOfWeek.Wednesday, + "thursday": SeqDayOfWeek.Thursday, + "friday": SeqDayOfWeek.Friday, + "saturday": SeqDayOfWeek.Saturday, + "sunday": SeqDayOfWeek.Sunday, +} + +type ScheduleInput = Mapping[str, Sequence[tuple[int, int]]] + +_TRANSPORT_ERRORS = ( + zigpy.exceptions.ZigbeeException, + TimeoutError, + KeyError, + TypeError, + ValueError, +) + + +class ScheduleTransition(TypedDict): + """A schedule transition in local time and degrees Celsius.""" + + time: str + temperature: float + + +class ScheduleDay(TypedDict): + """A known or unknown day's cached transitions.""" + + transitions: list[ScheduleTransition] | None + updated_at: str | None + + +class ScheduleSnapshot(TypedDict): + """A snapshot of the seven weekdays.""" + + days: dict[str, ScheduleDay] + complete: bool + + +class ScheduleResult(ScheduleSnapshot): + """The current cache, the pre-write snapshot and the days written last.""" + + pre_write_snapshot: ScheduleSnapshot | None + written_days: list[str] + + +@dataclass(frozen=True, kw_only=True) +class WeeklyScheduleCapabilities: + """Limits a provider enforces before communicating with a thermostat. + + `max_transitions_per_day` is `None` when no verified device limit is known. + `temperature_step` is in centi-degrees Celsius. + """ + + max_transitions_per_day: int | None = None + temperature_step: int = 1 + supports_clear: bool = True + + def as_dict(self) -> dict[str, Any]: + """Return a JSON-compatible representation.""" + return { + "max_transitions_per_day": self.max_transitions_per_day, + "temperature_step": self.temperature_step / 100, + "supports_clear": self.supports_clear, + } + + +class Transition(NamedTuple): + """A transition in minutes after local midnight and centi-degrees Celsius.""" + + minute: int + centi_celsius: int + + +class WriteAcknowledgement(NamedTuple): + """The outcome of a day write before it is verified by reading it back. + + `error` describes a missing or unexpected acknowledgement, which a matching + read-back can still recover. `rejected` marks an explicit device failure. + """ + + error: Exception | None = None + rejected: bool = False + + +@dataclass(frozen=True) +class _CachedDay: + transitions: tuple[Transition, ...] + updated_at: datetime + + +class WeeklyScheduleProvider(EventBase, ABC): + """Serialize, cache and verify schedule operations for one device endpoint.""" + + EVENT_VERIFIED_CHANGED = "weekly_schedule_verified_changed" + capabilities = WeeklyScheduleCapabilities() + + def __init__(self, device: ZigbeeDevice, endpoint_id: int) -> None: + """Create an endpoint schedule provider.""" + super().__init__() + self._device = device + self._endpoint_id = endpoint_id + self.lock = asyncio.Lock() + self._days: dict[str, _CachedDay] = {} + self._pre_write_snapshot: ScheduleSnapshot | None = None + self._written_days: list[str] = [] + self._verified_schedule: dict[str, tuple[Transition, ...]] | None = None + + # Device-family primitives. + + def _begin(self) -> None: # noqa: B027 + """Prepare an operation; raise if the device cannot be addressed.""" + + def _ensure_target(self) -> None: # noqa: B027 + """Raise if the addressed device changed during an operation.""" + + @abstractmethod + async def _async_read_day(self, day: str) -> tuple[Transition, ...]: + """Read one heat day from the device.""" + + @abstractmethod + async def _async_heat_limits(self) -> tuple[int, int]: + """Read fresh heat setpoint limits in centi-degrees Celsius.""" + + @abstractmethod + def _check_write_support(self) -> None: + """Raise if the device cannot write schedules.""" + + def _check_encodable( # noqa: B027 + self, day: str, transitions: tuple[Transition, ...] + ) -> None: + """Raise if a day cannot be encoded for the device.""" + + @abstractmethod + async def _async_write_day( + self, day: str, transitions: tuple[Transition, ...] + ) -> WriteAcknowledgement: + """Write one heat day; transport failures are returned, not raised.""" + + def _check_clear_support(self) -> None: + """Raise if the device cannot clear its schedule.""" + if not self.capabilities.supports_clear: + raise ZHAException("The thermostat does not support schedule clearing") + + async def _async_clear_all(self) -> None: + """Clear the device schedule, raising if it is not confirmed.""" + raise ZHAException("The thermostat does not support schedule clearing") + + # Shared behaviour. + + @property + def has_verified_schedule(self) -> bool: + """Return whether a complete uploaded schedule is still verified.""" + return self._verified_schedule is not None + + def _set_verified_schedule( + self, schedule: dict[str, tuple[Transition, ...]] | None + ) -> None: + was_verified = self.has_verified_schedule + self._verified_schedule = schedule + if self.has_verified_schedule != was_verified: + self.emit(self.EVENT_VERIFIED_CHANGED, self.has_verified_schedule) + + def invalidate(self, day_bitmap: int | None = None) -> None: + """Mark selected days unknown without discarding the pre-write snapshot.""" + self._set_verified_schedule(None) + for day, bit in WEEKDAYS.items(): + if day_bitmap is None or day_bitmap & bit: + self._days.pop(day, None) + + def _reset(self) -> None: + self.invalidate() + self._pre_write_snapshot = None + self._written_days = [] + + def _validate_schedule( + self, schedule: ScheduleInput + ) -> dict[str, tuple[Transition, ...]]: + """Validate all days before communicating with a thermostat.""" + if set(schedule) != set(WEEKDAYS): + raise ZHAException( + "A weekly schedule must contain exactly the seven weekdays" + ) + + maximum_count = self.capabilities.max_transitions_per_day or 255 + step = self.capabilities.temperature_step + result: dict[str, tuple[Transition, ...]] = {} + for day in WEEKDAYS: + entries = schedule[day] + if not entries or len(entries) > maximum_count: + raise ZHAException( + f"{day} must contain between 1 and {maximum_count} transitions" + ) + transitions = [] + previous_minute = -1 + for entry in entries: + if not isinstance(entry, (tuple, list)) or len(entry) != 2: + raise ZHAException(f"Invalid transition for {day}: {entry!r}") + minute, temperature = entry + if ( + isinstance(minute, bool) + or not isinstance(minute, int) + or not 0 <= minute < 1440 + or minute <= previous_minute + ): + raise ZHAException( + f"Invalid or duplicate transition time for {day}" + ) + if ( + isinstance(temperature, bool) + or not isinstance(temperature, int) + or not -32767 <= temperature <= 32767 + ): + raise ZHAException(f"Invalid heat setpoint for {day}") + if temperature % step: + raise ZHAException( + f"{day} setpoints must be multiples of {step / 100} °C" + ) + transitions.append(Transition(minute, temperature)) + previous_minute = minute + if transitions[0].minute != 0: + raise ZHAException(f"{day} must begin at 00:00") + result[day] = tuple(transitions) + return result + + def _snapshot(self) -> ScheduleSnapshot: + days: dict[str, ScheduleDay] = {} + for day in WEEKDAYS: + cached = self._days.get(day) + days[day] = { + "transitions": ( + [ + { + "time": f"{item.minute // 60:02}:{item.minute % 60:02}", + "temperature": item.centi_celsius / 100, + } + for item in cached.transitions + ] + if cached is not None + else None + ), + "updated_at": cached.updated_at.isoformat() if cached else None, + } + return {"days": days, "complete": len(self._days) == len(WEEKDAYS)} + + def _result(self) -> ScheduleResult: + return { + **self._snapshot(), + "pre_write_snapshot": copy.deepcopy(self._pre_write_snapshot), + "written_days": list(self._written_days), + } + + async def _read_day(self, day: str) -> tuple[Transition, ...]: + transitions = tuple(await self._async_read_day(day)) + previous_minute = -1 + for minute, temperature in transitions: + if ( + not isinstance(minute, int) + or not 0 <= minute < 1440 + or minute <= previous_minute + or not isinstance(temperature, int) + or not -32767 <= temperature <= 32767 + ): + raise ZHAException(f"Invalid schedule transition returned for {day}") + previous_minute = minute + self._days[day] = _CachedDay(transitions, datetime.now(UTC)) + return transitions + + async def _refresh(self, *, preserve_verification: bool = False) -> None: + verified = self._verified_schedule if preserve_verification else None + if preserve_verification: + self._days.clear() + else: + self.invalidate() + try: + for day in WEEKDAYS: + await self._read_day(day) + finally: + if verified is not None and ( + len(self._days) != len(WEEKDAYS) + or any(self._days[day].transitions != verified[day] for day in WEEKDAYS) + ): + self._set_verified_schedule(None) + + async def async_get(self, *, refresh: bool = True) -> ScheduleResult: + """Return a fresh schedule or the explicitly requested in-memory cache.""" + async with self.lock: + self._begin() + if refresh: + await self._refresh(preserve_verification=True) + return self._result() + + def _partial_failure( + self, + day: str, + attempted: list[str], + before: dict[str, tuple[Transition, ...]], + reason: str, + ) -> ZHAException: + changed = [ + name + for name in attempted + if name in self._days and self._days[name].transitions != before[name] + ] + unknown = [name for name in attempted if name not in self._days] + remaining = [name for name in WEEKDAYS if name not in attempted] + return ZHAException( + f"Schedule upload stopped on {day}: {reason}. " + f"Observed changed days: {changed}; unknown attempted days: {unknown}; " + f"unattempted days: {remaining}. No rollback was attempted." + ) + + async def async_set( + self, schedule: ScheduleInput, *, only_changed: bool = False + ) -> ScheduleResult: + """Upload and verify a complete heat schedule without changing mode or clock. + + With `only_changed`, days whose fresh read already matches are skipped. + """ + validated = self._validate_schedule(schedule) + async with self.lock: + self._begin() + self._pre_write_snapshot = None + self._written_days = [] + minimum, maximum = await self._async_heat_limits() + self._check_write_support() + + for day, transitions in validated.items(): + for item in transitions: + if not minimum <= item.centi_celsius <= maximum: + raise ZHAException( + f"The temperature {item.centi_celsius / 100:g} °C " + f"on {day.capitalize()} at " + f"{item.minute // 60:02}:{item.minute % 60:02} is " + f"{'too low' if item.centi_celsius < minimum else 'too high'}. " + "Choose a temperature within the thermostat's " + f"allowed range of {minimum / 100:g} to {maximum / 100:g} °C." + ) + self._check_encodable(day, transitions) + + await self._refresh() + before = {day: self._days[day].transitions for day in WEEKDAYS} + self._pre_write_snapshot = self._snapshot() + pending = { + day: transitions + for day, transitions in validated.items() + if not only_changed or before[day] != transitions + } + attempted: list[str] = [] + for day, transitions in pending.items(): + try: + self._ensure_target() + except ZHAException as exc: + raise self._partial_failure( + day, attempted, before, str(exc) + ) from exc + attempted.append(day) + self._written_days.append(day) + self.invalidate(WEEKDAYS[day]) + acknowledgement = await self._async_write_day(day, transitions) + + try: + actual = await self._read_day(day) + except ZHAException as exc: + reason = f"read-back failed: {exc}" + if acknowledgement.error is not None: + reason = f"{acknowledgement.error}; {reason}" + raise self._partial_failure(day, attempted, before, reason) from exc + if acknowledgement.rejected or actual != transitions: + reason = "; ".join( + part + for part in ( + str(acknowledgement.error) if acknowledgement.error else "", + ( + "read-back does not match the requested transitions" + if actual != transitions + else "" + ), + ) + if part + ) + raise self._partial_failure(day, attempted, before, reason) from ( + acknowledgement.error + ) + self._set_verified_schedule(validated) + return self._result() + + async def async_clear(self) -> ScheduleResult: + """Clear the entire schedule, snapshotting and verifying heat days.""" + async with self.lock: + self._begin() + self._pre_write_snapshot = None + self._written_days = [] + self._check_clear_support() + + await self._refresh() + self._pre_write_snapshot = self._snapshot() + self._ensure_target() + self.invalidate() + self._written_days = list(WEEKDAYS) + await self._async_clear_all() + + try: + await self._refresh() + except ZHAException as exc: + raise ZHAException( + "Schedule clear was acknowledged, but heat schedule read-back " + "failed. The device schedule may have changed. " + "No rollback was attempted." + ) from exc + remaining = [day for day in WEEKDAYS if self._days[day].transitions] + if remaining: + raise ZHAException( + f"Schedule clear did not remove heat transitions on {remaining}. " + "No rollback was attempted." + ) + return self._result() + + +class ZclWeeklySchedule(WeeklyScheduleProvider): + """Weekly schedules using standard ZCL Thermostat cluster commands.""" + + def __init__(self, device: ZigbeeDevice, endpoint_id: int) -> None: + """Create a ZCL schedule provider.""" + super().__init__(device, endpoint_id) + self._cluster: Cluster | None = None + + def bind_cluster(self, cluster: Cluster) -> None: + """Reset cached values when the endpoint's cluster changes.""" + if cluster is not self._cluster: + self._cluster = cluster + self._reset() + + def _current_cluster(self) -> Cluster: + try: + cluster = self._device.async_get_cluster( + self._endpoint_id, Thermostat.cluster_id + ) + except KeyError as exc: + self._cluster = None + self._reset() + raise ZHAException("The thermostat cluster is no longer available") from exc + self.bind_cluster(cluster) + return cluster + + @property + def _bound_cluster(self) -> Cluster: + assert self._cluster is not None + return self._cluster + + def _begin(self) -> None: + self._current_cluster() + + def _ensure_target(self) -> None: + self._ensure_same_cluster(self._bound_cluster) + + def _ensure_same_cluster(self, cluster: Cluster) -> None: + if self._current_cluster() is not cluster: + raise ZHAException("The thermostat cluster changed during the operation") + + async def _async_read_day(self, day: str) -> tuple[Transition, ...]: + cluster = self._bound_cluster + try: + response = await cluster.command( + Thermostat.ServerCommandDefs.get_weekly_schedule.id, + days_to_return=WEEKDAYS[day], + mode_to_return=SeqMode.Heat, + retries=0, + ) + except _TRANSPORT_ERRORS as exc: + raise ZHAException(f"Unable to read the {day} schedule: {exc}") from exc + self._ensure_same_cluster(cluster) + if isinstance(response, Exception): + raise ZHAException(f"Unable to read the {day} schedule") from response + if isinstance(response, foundation.DefaultResponse): + raise ZHAException( + f"Unable to read the {day} schedule: device returned {response.status}" + ) + if not isinstance(response, t.Struct): + raise ZHAException(f"Unexpected schedule response for {day}: {response!r}") + + fields = response.as_dict() + count = fields.get("num_transitions_for_sequence") + response_days = fields.get("day_of_week_for_sequence") + mode = fields.get("mode_for_sequence") + values = fields.get("values") + if ( + not isinstance(count, int) + or not 0 <= count <= 255 + or response_days != WEEKDAYS[day] + or mode != SeqMode.Heat + or not isinstance(values, (list, tuple)) + or len(values) != count * 2 + ): + raise ZHAException(f"Malformed or unsupported schedule response for {day}") + return tuple( + Transition(*values[index : index + 2]) for index in range(0, len(values), 2) + ) + + async def _async_heat_limits(self) -> tuple[int, int]: + cluster = self._bound_cluster + names = ("min_heat_setpoint_limit", "max_heat_setpoint_limit") + try: + values, failures = await cluster.read_attributes( + list(names), allow_cache=False, retries=0 + ) + except _TRANSPORT_ERRORS as exc: + raise ZHAException( + f"Unable to read the thermostat heat limits: {exc}" + ) from exc + self._ensure_same_cluster(cluster) + minimum, maximum = (values.get(name) for name in names) + if ( + failures + or not isinstance(minimum, int) + or not isinstance(maximum, int) + or not -32767 <= minimum <= maximum <= 32767 + ): + raise ZHAException( + "Fresh thermostat heat limits are unavailable or invalid" + ) + return minimum, maximum + + def _check_write_support(self) -> None: + if ( + Thermostat.ServerCommandDefs.set_weekly_schedule.id + not in self._bound_cluster.server_commands + ): + raise ZHAException("The thermostat does not support schedule writes") + + @staticmethod + def _payload(day: str, transitions: tuple[Transition, ...]) -> dict[str, Any]: + return { + "num_transitions_for_sequence": len(transitions), + "day_of_week_for_sequence": WEEKDAYS[day], + "mode_for_sequence": SeqMode.Heat, + "values": [ + value + for item in transitions + for value in (item.minute, item.centi_celsius) + ], + } + + def _check_encodable(self, day: str, transitions: tuple[Transition, ...]) -> None: + command = self._bound_cluster.server_commands[ + Thermostat.ServerCommandDefs.set_weekly_schedule.id + ] + try: + command.schema(**self._payload(day, transitions)).serialize() + except (ValueError, TypeError, OverflowError) as exc: + raise ZHAException(f"The {day} schedule cannot be encoded: {exc}") from exc + + async def _async_write_day( + self, day: str, transitions: tuple[Transition, ...] + ) -> WriteAcknowledgement: + command_id = Thermostat.ServerCommandDefs.set_weekly_schedule.id + try: + response = await self._bound_cluster.command( + command_id, **self._payload(day, transitions), retries=0 + ) + except _TRANSPORT_ERRORS as exc: + return WriteAcknowledgement(exc) + if isinstance(response, Exception): + return WriteAcknowledgement(response) + if ( + not isinstance(response, foundation.DefaultResponse) + or response.command_id != command_id + ): + return WriteAcknowledgement( + ZHAException(f"Unexpected schedule write acknowledgement: {response!r}") + ) + if response.status != foundation.Status.SUCCESS: + return WriteAcknowledgement( + ZHAException(f"Schedule write returned status {response.status}"), + rejected=True, + ) + return WriteAcknowledgement() + + def _check_clear_support(self) -> None: + if ( + Thermostat.ServerCommandDefs.clear_weekly_schedule.id + not in self._bound_cluster.server_commands + ): + raise ZHAException("The thermostat does not support schedule clearing") + + async def _async_clear_all(self) -> None: + command_id = Thermostat.ServerCommandDefs.clear_weekly_schedule.id + unconfirmed = ( + "Unable to confirm schedule clearing; the device schedule " + "may have changed. No rollback was attempted." + ) + try: + response = await self._bound_cluster.command(command_id, retries=0) + except _TRANSPORT_ERRORS as exc: + raise ZHAException(unconfirmed) from exc + if isinstance(response, Exception): + raise ZHAException(unconfirmed) from response + if ( + not isinstance(response, foundation.DefaultResponse) + or response.command_id != command_id + ): + raise ZHAException( + f"Unexpected schedule clear acknowledgement: {response!r}. " + "The device schedule may have changed. No rollback was attempted." + ) + if response.status != foundation.Status.SUCCESS: + raise ZHAException( + f"Schedule clear returned status {response.status}. " + "The device schedule may have changed. No rollback was attempted." + ) + + +# Exposed quirk feature -> provider. Other thermostat families register their +# own feature and provider here. +WEEKLY_SCHEDULE_PROVIDERS: dict[str, type[WeeklyScheduleProvider]] = { + THERMOSTAT_WEEKLY_SCHEDULE: ZclWeeklySchedule, +}