From 0b2e62252ca63b915072530f0de1e14e365e9315 Mon Sep 17 00:00:00 2001 From: Neil Sleightholm Date: Sun, 22 Nov 2026 07:12:59 +0000 Subject: [PATCH 1/4] feat: add Hive holiday mode services and sensors Rebased onto master (2026.11.1) as a single commit. - hive.set_holiday_mode (start, end, temperature 7-35) and hive.cancel_holiday_mode services, with catch-up refreshes over the following five minutes and cleanup on unload. - Hub-level Holiday Mode (off/scheduled/active), Holiday Date Start and Holiday Date End sensors sharing one cached fetch, polled every 30 min; a failed fetch leaves them unavailable instead of dropping them. - Requires pyhive-integration 2.0.0b5 (holiday mode API, Pyhive#149, plus the SSO quote fix, Pyhive#169). 2.0.0b5 has no getTargetTemperature alias, so the current-temperature attributes call get_target_temperature. - strings.json, services.yaml and icons.json updated; en.json regenerated. - tests/test_holiday_mode.py; existing sensor tests account for the holiday sensors. 106 passed on pytest-homeassistant 2026.11.2 with pyhive-integration 2.0.0b5; script/lint --check passes. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/__init__.py | 120 +++++++++- custom_components/hive/const.py | 2 + custom_components/hive/icons.json | 6 + custom_components/hive/manifest.json | 2 +- custom_components/hive/sensor.py | 201 +++++++++++++++- custom_components/hive/services.yaml | 21 ++ custom_components/hive/strings.json | 22 ++ custom_components/hive/translations/en.json | 22 ++ tests/conftest.py | 13 +- tests/test_binary_sensor.py | 7 +- tests/test_holiday_mode.py | 251 ++++++++++++++++++++ tests/test_sensor.py | 9 +- 12 files changed, 656 insertions(+), 20 deletions(-) create mode 100644 tests/test_holiday_mode.py diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index cb3cba1..c7d4f0b 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -1,34 +1,66 @@ """Support for the Hive devices and services.""" from collections.abc import Awaitable, Callable, Coroutine +from datetime import datetime, timedelta from functools import wraps from typing import Any, Concatenate from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, HiveInvalidDeviceAuthentication, HiveReauthRequired, ) +import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL, Platform -from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady +from homeassistant.core import HomeAssistant, ServiceCall, callback +from homeassistant.exceptions import ( + ConfigEntryAuthFailed, + ConfigEntryNotReady, + HomeAssistantError, +) from homeassistant.helpers import ( aiohttp_client, config_validation as cv, device_registry as dr, ) from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.typing import ConfigType +from homeassistant.util import dt as dt_util -from .const import DOMAIN, PLATFORM_LOOKUP +from .const import ( + DOMAIN, + PLATFORM_LOOKUP, + SERVICE_CANCEL_HOLIDAY_MODE, + SERVICE_SET_HOLIDAY_MODE, +) from .entity import HiveEntity from .services import async_setup_services type HiveConfigEntry = ConfigEntry[Hive] +# Hive's backend can take a few minutes to actually flip a schedule to +# active/off even after the requested start/cancel has technically taken +# effect, so a single refresh right after the service call (or even right +# at "start") can still catch a stale read. Poll a few extra times over +# the following five minutes to pick up the eventual transition sooner +# than the sensor's normal 30-minute interval would. +HOLIDAY_MODE_CATCHUP_DELAYS = (30, 90, 180, 300) + +SET_HOLIDAY_MODE_SCHEMA = vol.Schema( + { + vol.Required("start"): cv.datetime, + vol.Required("end"): cv.datetime, + vol.Required("temperature"): vol.All( + vol.Coerce(float), vol.Range(min=7, max=35) + ), + } +) + CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) @@ -85,6 +117,88 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> None entry, _platforms_with_devices(devices) ) + @callback + def _async_refresh_holiday_sensor(_now: datetime | None = None) -> None: + async_dispatcher_send(hass, DOMAIN) + + def _schedule_holiday_catchup_refreshes(anchor: datetime) -> None: + """Schedule a few extra refreshes after `anchor`.""" + for delay in HOLIDAY_MODE_CATCHUP_DELAYS: + entry.async_on_unload( + async_track_point_in_utc_time( + hass, + _async_refresh_holiday_sensor, + anchor + timedelta(seconds=delay), + ) + ) + + async def _async_set_holiday_mode(call: ServiceCall) -> None: + """Handle the set_holiday_mode service call.""" + # The Hive app itself only works to minute precision; truncate here + # so every caller (this integration's automations, a manual service + # call, anything else) gets the same clean minute-aligned start/end + # rather than whatever arbitrary seconds happened to be on the + # clock when the caller computed "now". + start = call.data["start"].replace(second=0, microsecond=0) + end = call.data["end"].replace(second=0, microsecond=0) + try: + success = await hive.hub.set_holiday_mode( + start, end, call.data["temperature"] + ) + except (HTTPException, HiveApiError, HiveReauthRequired) as err: + raise HomeAssistantError(f"Failed to set Hive holiday mode: {err}") from err + if not success: + raise HomeAssistantError("Hive rejected the set holiday mode request.") + async_dispatcher_send(hass, DOMAIN) + + # The Holiday Mode sensor otherwise only refreshes on its 30-minute + # poll or after a service call, so a scheduled -> active transition + # that happens purely because "start" has passed can sit stale for + # up to 30 minutes. Refresh right at "start" for a future-dated + # schedule, then run the catch-up burst anchored at whichever of + # "start" or now is later (covers both a future start and a + # start-now request, where Hive's own backend is typically the + # slower part of the transition). + start_utc = dt_util.as_utc(start) + now_utc = dt_util.utcnow() + if start_utc > now_utc: + entry.async_on_unload( + async_track_point_in_utc_time( + hass, _async_refresh_holiday_sensor, start_utc + ) + ) + _schedule_holiday_catchup_refreshes(max(start_utc, now_utc)) + + async def _async_cancel_holiday_mode(call: ServiceCall) -> None: + """Handle the cancel_holiday_mode service call.""" + try: + success = await hive.hub.cancel_holiday_mode() + except (HTTPException, HiveApiError, HiveReauthRequired) as err: + raise HomeAssistantError( + f"Failed to cancel Hive holiday mode: {err}" + ) from err + if not success: + raise HomeAssistantError("Hive rejected the cancel holiday mode request.") + async_dispatcher_send(hass, DOMAIN) + _schedule_holiday_catchup_refreshes(dt_util.utcnow()) + + hass.services.async_register( + DOMAIN, + SERVICE_SET_HOLIDAY_MODE, + _async_set_holiday_mode, + schema=SET_HOLIDAY_MODE_SCHEMA, + ) + hass.services.async_register( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, _async_cancel_holiday_mode + ) + + @callback + def _async_remove_holiday_services() -> None: + hass.services.async_remove(DOMAIN, SERVICE_SET_HOLIDAY_MODE) + hass.services.async_remove(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) + + entry.async_on_unload(_async_remove_holiday_services) + def _platforms_with_devices(devices: dict[str, list[Any]]) -> list[Platform]: """Return the platforms Hive reported devices for. diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 0ed498f..8d0636b 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -29,4 +29,6 @@ SERVICE_BOOST_HOT_WATER = "boost_hot_water" SERVICE_BOOST_HEATING_ON = "boost_heating_on" SERVICE_BOOST_HEATING_OFF = "boost_heating_off" +SERVICE_SET_HOLIDAY_MODE = "set_holiday_mode" +SERVICE_CANCEL_HOLIDAY_MODE = "cancel_holiday_mode" WATER_HEATER_MODES = ["on", "off"] diff --git a/custom_components/hive/icons.json b/custom_components/hive/icons.json index 8b8a785..cc07d55 100644 --- a/custom_components/hive/icons.json +++ b/custom_components/hive/icons.json @@ -26,6 +26,12 @@ }, "boost_hot_water": { "service": "mdi:water-boiler" + }, + "set_holiday_mode": { + "service": "mdi:palm-tree" + }, + "cancel_holiday_mode": { + "service": "mdi:palm-tree-outline" } } } diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index fbb6e66..3580f31 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -17,6 +17,6 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", "loggers": ["apyhiveapi"], - "requirements": ["pyhive-integration==1.0.10"], + "requirements": ["pyhive-integration==2.0.0b5"], "version": "2026.11.1" } diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index bf1775b..fce483c 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,11 +1,16 @@ """Support for the Hive sensors.""" +import asyncio from collections.abc import Callable from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta +import logging +import time from typing import Any +from aiohttp import ClientError from apyhiveapi import Hive +from apyhiveapi.helper.hive_exceptions import HiveApiError from homeassistant.components.sensor import ( SensorDeviceClass, @@ -19,14 +24,22 @@ UnitOfPower, UnitOfTemperature, ) -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers.dispatcher import async_dispatcher_connect +from homeassistant.helpers.entity import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.typing import StateType from homeassistant.util import dt as dt_util from . import HiveConfigEntry +from .const import DOMAIN from .entity import HiveEntity +_LOGGER = logging.getLogger(__name__) + +HOLIDAY_MODE_SCAN_INTERVAL = timedelta(minutes=30) + PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) @@ -107,20 +120,31 @@ async def async_setup_entry( """Set up Hive thermostat based on a config entry.""" hive = entry.runtime_data devices = hive.session.deviceList.get("sensor") - if not devices: - return entities: list[SensorEntity] = [ HiveSensorEntity(hass, entry, hive, dev, description) - for dev in devices + for dev in devices or [] for description in SENSOR_TYPES if dev["hiveType"] == description.key ] entities.extend( HiveBoostEndSensorEntity(hass, entry, hive, dev) - for dev in devices + for dev in devices or [] if dev["hiveType"] in BOOST_TYPES ) - async_add_entities(entities, True) + + hub_id = hive.session.hub_id + if hub_id: + holiday_data = _HiveHolidayModeData(hive) + entities.extend( + [ + HiveHolidayModeSensor(holiday_data, hub_id), + HiveHolidayStartSensor(holiday_data, hub_id), + HiveHolidayEndSensor(holiday_data, hub_id), + ] + ) + + if entities: + async_add_entities(entities, True) class HiveSensorEntity(HiveEntity, SensorEntity): @@ -189,7 +213,7 @@ async def get_current_temp_sa(self): # This sensor's own state is the current temperature (getSensor reads it). temp_current = self.device.get("status", {}).get("state") - temperature_target = await self.hive.heating.getTargetTemperature(self.device) + temperature_target = await self.hive.heating.get_target_temperature(self.device) if ( isinstance(temp_current, (int, float)) @@ -315,6 +339,167 @@ async def get_hotwater_state_sa(self): return s_a +class _HiveHolidayModeData: + """Shares a single Hive Holiday Mode API fetch across its sensors. + + get_holiday_mode() always makes a fresh cloud API call, so without this + the status/start/end sensors below would each fetch independently and + triple the calls every time they're refreshed together (dispatcher + signal, or their shared poll interval). Short-lived cache: refreshes + together resolve to a single fetch. + """ + + _CACHE_SECONDS = 5 + + def __init__(self, hive) -> None: + """Initialise the shared fetch cache.""" + self._hive = hive + self._data: dict | None = None + self._fetched_at: float | None = None + self._lock = asyncio.Lock() + + async def async_get(self) -> dict | None: + """Return the latest holiday mode data, fetching if the cache is stale.""" + async with self._lock: + now = time.monotonic() + if self._fetched_at is None or now - self._fetched_at > self._CACHE_SECONDS: + self._data = await self._hive.hub.get_holiday_mode() + self._fetched_at = now + return self._data + + +class _HiveHolidayModeSensorBase(SensorEntity): + """Base for the Hive whole-home Holiday Mode sensors. + + Unlike the other sensors in this platform, Holiday Mode is a hub-level + feature (no per-device Hive product backs it), and get_holiday_mode() + always makes a fresh API call rather than going through the + rate-limited device polling cache — so these entities manage their own, + much longer, poll interval instead of relying on the module-level + SCAN_INTERVAL the other sensors use. + """ + + _attr_should_poll = False + + def __init__(self, data: _HiveHolidayModeData, hub_id: str, key: str) -> None: + """Initialise the sensor.""" + self._data = data + self._attr_unique_id = f"{hub_id}-Holiday{key}" + self._attr_device_info = DeviceInfo(identifiers={(DOMAIN, hub_id)}) + + async def async_added_to_hass(self) -> None: + """Subscribe to updates and start polling once added.""" + self.async_on_remove( + async_dispatcher_connect(self.hass, DOMAIN, self._async_schedule_refresh) + ) + self.async_on_remove( + async_track_time_interval( + self.hass, self._async_schedule_refresh, HOLIDAY_MODE_SCAN_INTERVAL + ) + ) + await self.async_update_ha_state(force_refresh=True) + + @callback + def _async_schedule_refresh(self, _now: datetime | None = None) -> None: + """Schedule a state refresh.""" + self.async_schedule_update_ha_state(force_refresh=True) + + async def async_update(self) -> None: + """Fetch the latest Holiday Mode status from Hive.""" + # The platform adds these with update_before_add, so an exception here + # (e.g. Hive's cloud timing out at boot) would stop the entity being + # added at all until the next restart. Go unavailable instead; the poll + # interval and dispatcher refreshes bring it back. + try: + result = await self._data.async_get() + except (TimeoutError, ClientError, HiveApiError) as err: + _LOGGER.warning("Failed to fetch Hive holiday mode: %r", err) + result = None + if result is None: + self._attr_available = False + return + self._attr_available = True + self._update_from_result(result) + + def _update_from_result(self, result: dict) -> None: + """Update entity state from the fetched holiday mode data.""" + raise NotImplementedError + + +class HiveHolidayModeSensor(_HiveHolidayModeSensorBase): + """Sensor exposing Hive's whole-home Holiday Mode status.""" + + _attr_device_class = SensorDeviceClass.ENUM + _attr_options = ["off", "scheduled", "active"] + _attr_icon = "mdi:palm-tree" + _attr_name = "Holiday Mode" + + def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + """Initialise the Holiday Mode sensor.""" + super().__init__(data, hub_id, "Mode") + + def _update_from_result(self, result: dict) -> None: + if result.get("active"): + self._attr_native_value = "active" + elif result.get("enabled"): + self._attr_native_value = "scheduled" + else: + self._attr_native_value = "off" + + # Hive's API intermittently omits start/end/temperature from an + # otherwise-valid response, even while active/enabled are reported + # correctly. Retain the last known value for a field rather than + # blanking it out, so a partial response doesn't cause the + # attributes to flicker empty between refreshes. + attrs = dict(getattr(self, "_attr_extra_state_attributes", None) or {}) + for key in ("start", "end"): + epoch_ms = result.get(key) + if epoch_ms is not None: + attrs[key] = datetime.fromtimestamp(epoch_ms / 1000, tz=UTC).isoformat() + if result.get("temperature") is not None: + attrs["temperature"] = result["temperature"] + self._attr_extra_state_attributes = attrs + + +class _HiveHolidayModeDateSensor(_HiveHolidayModeSensorBase): + """Base for the Holiday Mode start/end timestamp sensors.""" + + _attr_device_class = SensorDeviceClass.TIMESTAMP + _result_key: str + + def _update_from_result(self, result: dict) -> None: + # As with the attributes on HiveHolidayModeSensor, Hive's API can + # omit this field from an otherwise-valid response — retain the + # last known value rather than flickering to unknown. + epoch_ms = result.get(self._result_key) + if epoch_ms is not None: + self._attr_native_value = datetime.fromtimestamp(epoch_ms / 1000, tz=UTC) + + +class HiveHolidayStartSensor(_HiveHolidayModeDateSensor): + """Sensor exposing Hive's Holiday Mode start date/time.""" + + _attr_name = "Holiday Date Start" + _attr_icon = "mdi:calendar-start" + _result_key = "start" + + def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + """Initialise the Holiday Date Start sensor.""" + super().__init__(data, hub_id, "DateStart") + + +class HiveHolidayEndSensor(_HiveHolidayModeDateSensor): + """Sensor exposing Hive's Holiday Mode end date/time.""" + + _attr_name = "Holiday Date End" + _attr_icon = "mdi:calendar-end" + _result_key = "end" + + def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + """Initialise the Holiday Date End sensor.""" + super().__init__(data, hub_id, "DateEnd") + + class HiveBoostEndSensorEntity(HiveEntity, SensorEntity): """When a heating or hot water boost ends (unknown when no boost is on).""" diff --git a/custom_components/hive/services.yaml b/custom_components/hive/services.yaml index e2ad598..ed1c933 100755 --- a/custom_components/hive/services.yaml +++ b/custom_components/hive/services.yaml @@ -45,3 +45,24 @@ boost_hot_water: options: - "on" - "off" +set_holiday_mode: + fields: + start: + required: true + selector: + datetime: + end: + required: true + selector: + datetime: + temperature: + required: true + default: 15.0 + selector: + number: + min: 7 + max: 35 + step: 0.5 + unit_of_measurement: ° +cancel_holiday_mode: + fields: {} diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 2bca947..44af0ce 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -101,6 +101,28 @@ "description": "Set the boost function on or off." } } + }, + "set_holiday_mode": { + "name": "Set holiday mode", + "description": "Schedules Hive's whole-home holiday mode, holding a frost-protection temperature for the given period.", + "fields": { + "start": { + "name": "Start", + "description": "When holiday mode should begin." + }, + "end": { + "name": "End", + "description": "When holiday mode should end." + }, + "temperature": { + "name": "Temperature", + "description": "The frost-protection temperature to hold during holiday mode." + } + } + }, + "cancel_holiday_mode": { + "name": "Cancel holiday mode", + "description": "Cancels any scheduled or currently active Hive holiday mode." } }, "entity": { diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 90c237a..84ddf87 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -101,6 +101,28 @@ "description": "Set the boost function on or off." } } + }, + "set_holiday_mode": { + "name": "Set holiday mode", + "description": "Schedules Hive's whole-home holiday mode, holding a frost-protection temperature for the given period.", + "fields": { + "start": { + "name": "Start", + "description": "When holiday mode should begin." + }, + "end": { + "name": "End", + "description": "When holiday mode should end." + }, + "temperature": { + "name": "Temperature", + "description": "The frost-protection temperature to hold during holiday mode." + } + } + }, + "cancel_holiday_mode": { + "name": "Cancel holiday mode", + "description": "Cancels any scheduled or currently active Hive holiday mode." } }, "entity": { diff --git a/tests/conftest.py b/tests/conftest.py index f180f38..2685479 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -39,6 +39,13 @@ } } DEVICE_DATA = ["device-group-key", "device-key", "device-password"] +HOLIDAY_MODE_OFF = {"enabled": False, "active": False} +# Hub-level sensors added whenever Hive reports a hub. +HOLIDAY_SENSORS = { + "sensor.hive_hub_holiday_mode", + "sensor.hive_hub_holiday_date_start", + "sensor.hive_hub_holiday_date_end", +} # pytest-homeassistant's hass fixture enables custom integrations by default, so # custom_components/hive loads instead of the core hive integration. @@ -134,12 +141,16 @@ def mock_hive( hive = MagicMock() hive.session.startSession = AsyncMock(return_value=devices) hive.session.deviceList = devices + hive.session.hub_id = HUB_ID + hive.hub.get_holiday_mode = AsyncMock(return_value=HOLIDAY_MODE_OFF) + hive.hub.set_holiday_mode = AsyncMock(return_value=True) + hive.hub.cancel_holiday_mode = AsyncMock(return_value=True) hive.session.updateData = AsyncMock() hive.sensor.getSensor = AsyncMock(side_effect=_echo) hive.heating.getClimate = AsyncMock(side_effect=_echo) # Extra attributes on the heating sensors (min/max, boost end); no data by default. hive.heating.minmaxTemperature = AsyncMock(return_value=None) - hive.heating.getTargetTemperature = AsyncMock(return_value=None) + hive.heating.get_target_temperature = AsyncMock(return_value=None) hive.heating.getBoostStatus = AsyncMock(return_value="OFF") hive.heating.getBoostTime = AsyncMock(return_value=None) hive.hotwater.getBoost = AsyncMock(return_value="OFF") diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py index 7de620d..4dfd6b2 100644 --- a/tests/test_binary_sensor.py +++ b/tests/test_binary_sensor.py @@ -8,7 +8,7 @@ from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant -from .conftest import make_device +from .conftest import HOLIDAY_SENSORS, make_device CONTACT = make_device( "contactsensor", @@ -83,7 +83,8 @@ async def test_heating_and_hot_water_state_sensors( hass.states.get("binary_sensor.hot_water_hotwater_boost").state == STATE_UNAVAILABLE ) - assert sorted(hass.states.async_entity_ids("sensor")) == [ + assert set(hass.states.async_entity_ids("sensor")) == { "sensor.hot_water_hotwater_boost_ends", "sensor.thermostat_heating_boost_ends", - ] + *HOLIDAY_SENSORS, + } diff --git a/tests/test_holiday_mode.py b/tests/test_holiday_mode.py new file mode 100644 index 0000000..dbb29f4 --- /dev/null +++ b/tests/test_holiday_mode.py @@ -0,0 +1,251 @@ +"""Tests for the Hive Holiday Mode sensors and services.""" + +from datetime import UTC, datetime +from unittest.mock import AsyncMock, MagicMock + +from apyhiveapi.helper.hive_exceptions import HiveApiError +import pytest +from pytest_homeassistant.common import MockConfigEntry + +from homeassistant.const import STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.dispatcher import async_dispatcher_send + +from custom_components.hive import sensor +from custom_components.hive.const import ( + DOMAIN, + SERVICE_CANCEL_HOLIDAY_MODE, + SERVICE_SET_HOLIDAY_MODE, +) + +from .conftest import HUB_ID + +START = datetime(2026, 12, 20, 10, 15, tzinfo=UTC) +END = datetime(2027, 1, 3, 18, 30, tzinfo=UTC) +START_MS = int(START.timestamp() * 1000) +END_MS = int(END.timestamp() * 1000) +SCHEDULED = { + "enabled": True, + "active": False, + "start": START_MS, + "end": END_MS, + "temperature": 12.0, +} + + +@pytest.fixture(autouse=True) +def no_holiday_cache(monkeypatch: pytest.MonkeyPatch) -> None: + """Fetch fresh holiday data on every refresh so tests can change it.""" + monkeypatch.setattr(sensor._HiveHolidayModeData, "_CACHE_SECONDS", -1) + + +def _entity_id(hass: HomeAssistant, key: str) -> str: + entity_id = er.async_get(hass).async_get_entity_id( + "sensor", DOMAIN, f"{HUB_ID}-Holiday{key}" + ) + assert entity_id is not None + return entity_id + + +async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +async def _refresh(hass: HomeAssistant) -> None: + async_dispatcher_send(hass, DOMAIN) + await hass.async_block_till_done() + + +async def test_holiday_sensors_off( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The hub gets Holiday Mode, Start and End sensors; off has no dates.""" + await _setup(hass, mock_config_entry) + + assert hass.states.get(_entity_id(hass, "Mode")).state == "off" + assert hass.states.get(_entity_id(hass, "DateStart")).state == "unknown" + assert hass.states.get(_entity_id(hass, "DateEnd")).state == "unknown" + + +async def test_holiday_sensors_scheduled_then_active( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Status, attributes and dates follow the Hive response.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _setup(hass, mock_config_entry) + + mode = hass.states.get(_entity_id(hass, "Mode")) + assert mode.state == "scheduled" + assert mode.attributes["start"] == START.isoformat() + assert mode.attributes["end"] == END.isoformat() + assert mode.attributes["temperature"] == 12.0 + assert hass.states.get(_entity_id(hass, "DateStart")).state == START.isoformat() + assert hass.states.get(_entity_id(hass, "DateEnd")).state == END.isoformat() + + mock_hive.hub.get_holiday_mode.return_value = {**SCHEDULED, "active": True} + await _refresh(hass) + + assert hass.states.get(_entity_id(hass, "Mode")).state == "active" + + +async def test_holiday_sensors_keep_values_on_partial_response( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """A response missing start/end/temperature keeps the last known values.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _setup(hass, mock_config_entry) + + mock_hive.hub.get_holiday_mode.return_value = {"enabled": True, "active": True} + await _refresh(hass) + + mode = hass.states.get(_entity_id(hass, "Mode")) + assert mode.state == "active" + assert mode.attributes["start"] == START.isoformat() + assert mode.attributes["temperature"] == 12.0 + assert hass.states.get(_entity_id(hass, "DateEnd")).state == END.isoformat() + + +async def test_holiday_sensors_unavailable_without_data( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The sensors go unavailable when Hive returns no holiday data.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=None) + await _setup(hass, mock_config_entry) + + for key in ("Mode", "DateStart", "DateEnd"): + assert hass.states.get(_entity_id(hass, key)).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize("error", [TimeoutError(), HiveApiError()]) +async def test_holiday_sensors_survive_fetch_error_at_setup( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + error: Exception, +) -> None: + """A failed first fetch still adds the sensors, unavailable, and they recover.""" + mock_hive.hub.get_holiday_mode = AsyncMock(side_effect=error) + await _setup(hass, mock_config_entry) + + for key in ("Mode", "DateStart", "DateEnd"): + assert hass.states.get(_entity_id(hass, key)).state == STATE_UNAVAILABLE + + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _refresh(hass) + + assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" + assert hass.states.get(_entity_id(hass, "DateStart")).state == START.isoformat() + + +async def test_set_holiday_mode( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The service truncates to the minute and refreshes the sensors.""" + await _setup(hass, mock_config_entry) + mock_hive.hub.get_holiday_mode.return_value = SCHEDULED + + await hass.services.async_call( + DOMAIN, + SERVICE_SET_HOLIDAY_MODE, + { + "start": "2026-12-20T10:15:42+00:00", + "end": "2027-01-03T18:30:59.5+00:00", + "temperature": "12", + }, + blocking=True, + ) + await hass.async_block_till_done() + + mock_hive.hub.set_holiday_mode.assert_awaited_once_with(START, END, 12.0) + assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" + + # Unloading cancels the pending catch-up refreshes and removes the services. + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + assert not hass.services.has_service(DOMAIN, SERVICE_SET_HOLIDAY_MODE) + assert not hass.services.has_service(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) + + +async def test_cancel_holiday_mode( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The cancel service calls Hive and refreshes the sensors.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _setup(hass, mock_config_entry) + mock_hive.hub.get_holiday_mode.return_value = {"enabled": False, "active": False} + + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + await hass.async_block_till_done() + + mock_hive.hub.cancel_holiday_mode.assert_awaited_once_with() + assert hass.states.get(_entity_id(hass, "Mode")).state == "off" + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + ("service", "data", "method"), + [ + ( + SERVICE_SET_HOLIDAY_MODE, + {"start": START.isoformat(), "end": END.isoformat(), "temperature": 12}, + "set_holiday_mode", + ), + (SERVICE_CANCEL_HOLIDAY_MODE, {}, "cancel_holiday_mode"), + ], +) +@pytest.mark.parametrize( + "outcome", + [AsyncMock(return_value=False), AsyncMock(side_effect=HiveApiError)], + ids=["rejected", "api_error"], +) +async def test_holiday_service_failures( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + service: str, + data: dict, + method: str, + outcome: AsyncMock, +) -> None: + """A rejected request or an API error surfaces as HomeAssistantError.""" + await _setup(hass, mock_config_entry) + setattr(mock_hive.hub, method, outcome) + + with pytest.raises(HomeAssistantError): + await hass.services.async_call(DOMAIN, service, data, blocking=True) + + +async def test_set_holiday_mode_rejects_bad_temperature( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Temperatures outside Hive's 7-35 range are rejected before calling Hive.""" + await _setup(hass, mock_config_entry) + + with pytest.raises(Exception, match="temperature"): + await hass.services.async_call( + DOMAIN, + SERVICE_SET_HOLIDAY_MODE, + {"start": START.isoformat(), "end": END.isoformat(), "temperature": 40}, + blocking=True, + ) + mock_hive.hub.set_holiday_mode.assert_not_awaited() + + +async def test_no_holiday_sensors_without_hub( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Without a hub, only the device sensors are added.""" + hive = MagicMock() + hive.session.deviceList = {"sensor": []} + hive.session.hub_id = None + mock_config_entry.runtime_data = hive + add_entities = MagicMock() + + await sensor.async_setup_entry(hass, mock_config_entry, add_entities) + + add_entities.assert_not_called() diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 97b06d1..bd4051e 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -13,7 +13,7 @@ from custom_components.hive import sensor -from .conftest import make_device +from .conftest import HOLIDAY_SENSORS, make_device async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: @@ -112,7 +112,7 @@ async def test_unknown_sensor_type_is_ignored( """Device types without a description don't create entities.""" await _setup(hass, mock_config_entry) - assert hass.states.async_entity_ids("sensor") == [] + assert set(hass.states.async_entity_ids("sensor")) == HOLIDAY_SENSORS @pytest.mark.parametrize( @@ -295,9 +295,10 @@ async def test_mode_sensor_without_state( async def test_sensor_platform_without_devices( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: - """The sensor platform adds nothing when Hive reports no sensors.""" + """The sensor platform adds nothing when Hive reports no sensors or hub.""" hive = MagicMock() hive.session.deviceList = {"sensor": []} + hive.session.hub_id = None mock_config_entry.runtime_data = hive add_entities = MagicMock() @@ -322,7 +323,7 @@ async def test_current_temperature_attributes( "RestartMax": 22.0, } ) - mock_hive.heating.getTargetTemperature = AsyncMock(return_value=21.0) + mock_hive.heating.get_target_temperature = AsyncMock(return_value=21.0) await _setup(hass, mock_config_entry) From 15cf3dbef476979f56ef3847eb599cfd53bbb1cc Mon Sep 17 00:00:00 2001 From: Neil Sleightholm Date: Mon, 23 Nov 2026 02:09:46 +0000 Subject: [PATCH 2/4] refactor: move holiday mode services into services.py Addresses review on #222: - Holiday services now live in services.py, below core's import, and are registered once from async_setup alongside core's boost services instead of per entry. Unloading one entry no longer removes them; with several Hive accounts the optional config_entry_id picks one. - set_holiday_mode rejects an end before (or in the same minute as) the start, or in the past. Naive times use Home Assistant's time zone. - Shared holiday state moves to holiday.py: the fetch cache is dropped after a service call, the catch-up timers replace the previous call's instead of piling up, and the sensors refresh on their own signal rather than every Hive entity's. - Errors: catch ClientError/TimeoutError as well; HiveReauthRequired starts a reauth flow from both the services and the sensors. Messages use translation keys. - Sensor names, icons and states move to strings.json/icons.json via translation_key; _update_from_result is an abstractmethod. - Pin pyhive-integration==1.0.11 (holiday mode backport, Pyhass/Pyhive 1.0.x) and go back to getTargetTemperature, which 1.0.x provides. - Tests for two entries, the date checks, naive times, reauth, the cache and timer replacement. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/__init__.py | 120 +--------- custom_components/hive/holiday.py | 120 ++++++++++ custom_components/hive/icons.json | 9 + custom_components/hive/manifest.json | 2 +- custom_components/hive/sensor.py | 79 ++----- custom_components/hive/services.py | 161 ++++++++++++- custom_components/hive/services.yaml | 10 +- custom_components/hive/strings.json | 72 +++++- custom_components/hive/translations/en.json | 72 +++++- tests/conftest.py | 2 +- tests/test_holiday_mode.py | 246 ++++++++++++++++++-- tests/test_sensor.py | 2 +- 12 files changed, 698 insertions(+), 197 deletions(-) create mode 100644 custom_components/hive/holiday.py diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index c7d4f0b..cb3cba1 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -1,66 +1,34 @@ """Support for the Hive devices and services.""" from collections.abc import Awaitable, Callable, Coroutine -from datetime import datetime, timedelta from functools import wraps from typing import Any, Concatenate from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive from apyhiveapi.helper.hive_exceptions import ( - HiveApiError, HiveInvalidDeviceAuthentication, HiveReauthRequired, ) -import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL, Platform -from homeassistant.core import HomeAssistant, ServiceCall, callback -from homeassistant.exceptions import ( - ConfigEntryAuthFailed, - ConfigEntryNotReady, - HomeAssistantError, -) +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import ( aiohttp_client, config_validation as cv, device_registry as dr, ) from homeassistant.helpers.dispatcher import async_dispatcher_send -from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.typing import ConfigType -from homeassistant.util import dt as dt_util -from .const import ( - DOMAIN, - PLATFORM_LOOKUP, - SERVICE_CANCEL_HOLIDAY_MODE, - SERVICE_SET_HOLIDAY_MODE, -) +from .const import DOMAIN, PLATFORM_LOOKUP from .entity import HiveEntity from .services import async_setup_services type HiveConfigEntry = ConfigEntry[Hive] -# Hive's backend can take a few minutes to actually flip a schedule to -# active/off even after the requested start/cancel has technically taken -# effect, so a single refresh right after the service call (or even right -# at "start") can still catch a stale read. Poll a few extra times over -# the following five minutes to pick up the eventual transition sooner -# than the sensor's normal 30-minute interval would. -HOLIDAY_MODE_CATCHUP_DELAYS = (30, 90, 180, 300) - -SET_HOLIDAY_MODE_SCHEMA = vol.Schema( - { - vol.Required("start"): cv.datetime, - vol.Required("end"): cv.datetime, - vol.Required("temperature"): vol.All( - vol.Coerce(float), vol.Range(min=7, max=35) - ), - } -) - CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) @@ -117,88 +85,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> None entry, _platforms_with_devices(devices) ) - @callback - def _async_refresh_holiday_sensor(_now: datetime | None = None) -> None: - async_dispatcher_send(hass, DOMAIN) - - def _schedule_holiday_catchup_refreshes(anchor: datetime) -> None: - """Schedule a few extra refreshes after `anchor`.""" - for delay in HOLIDAY_MODE_CATCHUP_DELAYS: - entry.async_on_unload( - async_track_point_in_utc_time( - hass, - _async_refresh_holiday_sensor, - anchor + timedelta(seconds=delay), - ) - ) - - async def _async_set_holiday_mode(call: ServiceCall) -> None: - """Handle the set_holiday_mode service call.""" - # The Hive app itself only works to minute precision; truncate here - # so every caller (this integration's automations, a manual service - # call, anything else) gets the same clean minute-aligned start/end - # rather than whatever arbitrary seconds happened to be on the - # clock when the caller computed "now". - start = call.data["start"].replace(second=0, microsecond=0) - end = call.data["end"].replace(second=0, microsecond=0) - try: - success = await hive.hub.set_holiday_mode( - start, end, call.data["temperature"] - ) - except (HTTPException, HiveApiError, HiveReauthRequired) as err: - raise HomeAssistantError(f"Failed to set Hive holiday mode: {err}") from err - if not success: - raise HomeAssistantError("Hive rejected the set holiday mode request.") - async_dispatcher_send(hass, DOMAIN) - - # The Holiday Mode sensor otherwise only refreshes on its 30-minute - # poll or after a service call, so a scheduled -> active transition - # that happens purely because "start" has passed can sit stale for - # up to 30 minutes. Refresh right at "start" for a future-dated - # schedule, then run the catch-up burst anchored at whichever of - # "start" or now is later (covers both a future start and a - # start-now request, where Hive's own backend is typically the - # slower part of the transition). - start_utc = dt_util.as_utc(start) - now_utc = dt_util.utcnow() - if start_utc > now_utc: - entry.async_on_unload( - async_track_point_in_utc_time( - hass, _async_refresh_holiday_sensor, start_utc - ) - ) - _schedule_holiday_catchup_refreshes(max(start_utc, now_utc)) - - async def _async_cancel_holiday_mode(call: ServiceCall) -> None: - """Handle the cancel_holiday_mode service call.""" - try: - success = await hive.hub.cancel_holiday_mode() - except (HTTPException, HiveApiError, HiveReauthRequired) as err: - raise HomeAssistantError( - f"Failed to cancel Hive holiday mode: {err}" - ) from err - if not success: - raise HomeAssistantError("Hive rejected the cancel holiday mode request.") - async_dispatcher_send(hass, DOMAIN) - _schedule_holiday_catchup_refreshes(dt_util.utcnow()) - - hass.services.async_register( - DOMAIN, - SERVICE_SET_HOLIDAY_MODE, - _async_set_holiday_mode, - schema=SET_HOLIDAY_MODE_SCHEMA, - ) - hass.services.async_register( - DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, _async_cancel_holiday_mode - ) - - @callback - def _async_remove_holiday_services() -> None: - hass.services.async_remove(DOMAIN, SERVICE_SET_HOLIDAY_MODE) - hass.services.async_remove(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) - - entry.async_on_unload(_async_remove_holiday_services) - def _platforms_with_devices(devices: dict[str, list[Any]]) -> list[Platform]: """Return the platforms Hive reported devices for. diff --git a/custom_components/hive/holiday.py b/custom_components/hive/holiday.py new file mode 100644 index 0000000..d1d9ca0 --- /dev/null +++ b/custom_components/hive/holiday.py @@ -0,0 +1,120 @@ +"""Holiday mode state shared by the Hive sensors and services.""" + +import asyncio +from datetime import datetime, timedelta +import time + +from aiohttp import ClientError +from aiohttp.web_exceptions import HTTPException +from apyhiveapi.helper.hive_exceptions import HiveApiError, NoApiToken + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback +from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.helpers.event import async_track_point_in_utc_time +from homeassistant.util import dt as dt_util +from homeassistant.util.hass_dict import HassKey + +from .const import DOMAIN + +# What a holiday mode call can raise apart from HiveReauthRequired, which +# callers handle separately so they can start a reauth flow. pyhive raises +# aiohttp.web_exceptions.HTTPError when a request fails outright. +HIVE_HOLIDAY_ERRORS = ( + TimeoutError, + ClientError, + HTTPException, + HiveApiError, + NoApiToken, +) + +# Hive's backend can take a few minutes to flip holiday mode to active or off +# after a change, so a single refresh straight after a service call (or at +# "start") can still read the old state. Refresh a few more times over the +# next five minutes rather than waiting for the 30-minute poll. +CATCHUP_DELAYS = tuple(timedelta(seconds=s) for s in (30, 90, 180, 300)) + + +class HiveHolidayModeData: + """One config entry's holiday mode data, refresh signal and timers. + + get_holiday_mode() always makes a cloud API call, so the status, start and + end sensors share one fetch: refreshes within a few seconds of each other + use the cached result. + """ + + _CACHE_SECONDS = 5 + + def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: + """Initialise the holiday mode data.""" + self.hass = hass + self.hive = entry.runtime_data + self.signal = f"{DOMAIN}_holiday_{entry.entry_id}" + self._data: dict | None = None + self._fetched_at: float | None = None + self._lock = asyncio.Lock() + self._timers: list[CALLBACK_TYPE] = [] + + async def async_get(self) -> dict | None: + """Return the holiday mode data, fetching it if the cache is stale.""" + async with self._lock: + now = time.monotonic() + if self._fetched_at is None or now - self._fetched_at > self._CACHE_SECONDS: + self._data = await self.hive.hub.get_holiday_mode() + self._fetched_at = now + return self._data + + @callback + def async_refresh(self, _now: datetime | None = None) -> None: + """Ask the holiday mode sensors to refresh.""" + async_dispatcher_send(self.hass, self.signal) + + @callback + def async_changed(self, start: datetime | None = None) -> None: + """Refresh after holiday mode was set or cancelled. + + Drops the cached result so the next fetch sees the change, refreshes + now, at a future start, and a few times after whichever is later. + Replaces the timers from any earlier call. + """ + self._fetched_at = None + self.async_cancel_timers() + anchor = now = dt_util.utcnow() + if start is not None and (start := dt_util.as_utc(start)) > now: + self._track(start) + anchor = start + for delay in CATCHUP_DELAYS: + self._track(anchor + delay) + self.async_refresh() + + @callback + def async_cancel_timers(self) -> None: + """Cancel pending refreshes.""" + while self._timers: + self._timers.pop()() + + def _track(self, when: datetime) -> None: + self._timers.append( + async_track_point_in_utc_time(self.hass, self.async_refresh, when) + ) + + +DATA_HOLIDAY: HassKey[dict[str, HiveHolidayModeData]] = HassKey(f"{DOMAIN}_holiday") + + +@callback +def async_get_holiday_data( + hass: HomeAssistant, entry: ConfigEntry +) -> HiveHolidayModeData: + """Return the holiday mode data for a config entry, creating it once.""" + entries = hass.data.setdefault(DATA_HOLIDAY, {}) + if (data := entries.get(entry.entry_id)) is None: + data = entries[entry.entry_id] = HiveHolidayModeData(hass, entry) + + @callback + def _async_unload() -> None: + data.async_cancel_timers() + entries.pop(entry.entry_id, None) + + entry.async_on_unload(_async_unload) + return data diff --git a/custom_components/hive/icons.json b/custom_components/hive/icons.json index cc07d55..98ac3b5 100644 --- a/custom_components/hive/icons.json +++ b/custom_components/hive/icons.json @@ -14,6 +14,15 @@ }, "hot_water": { "default": "mdi:hand-water" + }, + "holiday_mode": { + "default": "mdi:palm-tree" + }, + "holiday_start": { + "default": "mdi:calendar-start" + }, + "holiday_end": { + "default": "mdi:calendar-end" } } }, diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 3580f31..7849d64 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -17,6 +17,6 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", "loggers": ["apyhiveapi"], - "requirements": ["pyhive-integration==2.0.0b5"], + "requirements": ["pyhive-integration==1.0.11"], "version": "2026.11.1" } diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index fce483c..3996c95 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,16 +1,14 @@ """Support for the Hive sensors.""" -import asyncio +from abc import abstractmethod from collections.abc import Callable from dataclasses import dataclass from datetime import UTC, datetime, timedelta import logging -import time from typing import Any -from aiohttp import ClientError from apyhiveapi import Hive -from apyhiveapi.helper.hive_exceptions import HiveApiError +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired from homeassistant.components.sensor import ( SensorDeviceClass, @@ -35,6 +33,7 @@ from . import HiveConfigEntry from .const import DOMAIN from .entity import HiveEntity +from .holiday import HIVE_HOLIDAY_ERRORS, HiveHolidayModeData, async_get_holiday_data _LOGGER = logging.getLogger(__name__) @@ -134,7 +133,7 @@ async def async_setup_entry( hub_id = hive.session.hub_id if hub_id: - holiday_data = _HiveHolidayModeData(hive) + holiday_data = async_get_holiday_data(hass, entry) entities.extend( [ HiveHolidayModeSensor(holiday_data, hub_id), @@ -213,7 +212,7 @@ async def get_current_temp_sa(self): # This sensor's own state is the current temperature (getSensor reads it). temp_current = self.device.get("status", {}).get("state") - temperature_target = await self.hive.heating.get_target_temperature(self.device) + temperature_target = await self.hive.heating.getTargetTemperature(self.device) if ( isinstance(temp_current, (int, float)) @@ -339,49 +338,19 @@ async def get_hotwater_state_sa(self): return s_a -class _HiveHolidayModeData: - """Shares a single Hive Holiday Mode API fetch across its sensors. - - get_holiday_mode() always makes a fresh cloud API call, so without this - the status/start/end sensors below would each fetch independently and - triple the calls every time they're refreshed together (dispatcher - signal, or their shared poll interval). Short-lived cache: refreshes - together resolve to a single fetch. - """ - - _CACHE_SECONDS = 5 - - def __init__(self, hive) -> None: - """Initialise the shared fetch cache.""" - self._hive = hive - self._data: dict | None = None - self._fetched_at: float | None = None - self._lock = asyncio.Lock() - - async def async_get(self) -> dict | None: - """Return the latest holiday mode data, fetching if the cache is stale.""" - async with self._lock: - now = time.monotonic() - if self._fetched_at is None or now - self._fetched_at > self._CACHE_SECONDS: - self._data = await self._hive.hub.get_holiday_mode() - self._fetched_at = now - return self._data - - class _HiveHolidayModeSensorBase(SensorEntity): """Base for the Hive whole-home Holiday Mode sensors. - Unlike the other sensors in this platform, Holiday Mode is a hub-level - feature (no per-device Hive product backs it), and get_holiday_mode() - always makes a fresh API call rather than going through the - rate-limited device polling cache — so these entities manage their own, - much longer, poll interval instead of relying on the module-level - SCAN_INTERVAL the other sensors use. + Holiday Mode is a hub-level setting with no Hive product behind it, and + get_holiday_mode() always calls the cloud API rather than going through + the device polling cache. So these sensors poll on their own, much longer, + interval and refresh on the holiday services' signal, not on SCAN_INTERVAL. """ + _attr_has_entity_name = True _attr_should_poll = False - def __init__(self, data: _HiveHolidayModeData, hub_id: str, key: str) -> None: + def __init__(self, data: HiveHolidayModeData, hub_id: str, key: str) -> None: """Initialise the sensor.""" self._data = data self._attr_unique_id = f"{hub_id}-Holiday{key}" @@ -390,7 +359,9 @@ def __init__(self, data: _HiveHolidayModeData, hub_id: str, key: str) -> None: async def async_added_to_hass(self) -> None: """Subscribe to updates and start polling once added.""" self.async_on_remove( - async_dispatcher_connect(self.hass, DOMAIN, self._async_schedule_refresh) + async_dispatcher_connect( + self.hass, self._data.signal, self._async_schedule_refresh + ) ) self.async_on_remove( async_track_time_interval( @@ -412,7 +383,10 @@ async def async_update(self) -> None: # interval and dispatcher refreshes bring it back. try: result = await self._data.async_get() - except (TimeoutError, ClientError, HiveApiError) as err: + except HiveReauthRequired: + self.platform.config_entry.async_start_reauth(self.hass) + result = None + except HIVE_HOLIDAY_ERRORS as err: _LOGGER.warning("Failed to fetch Hive holiday mode: %r", err) result = None if result is None: @@ -421,9 +395,9 @@ async def async_update(self) -> None: self._attr_available = True self._update_from_result(result) + @abstractmethod def _update_from_result(self, result: dict) -> None: """Update entity state from the fetched holiday mode data.""" - raise NotImplementedError class HiveHolidayModeSensor(_HiveHolidayModeSensorBase): @@ -431,10 +405,9 @@ class HiveHolidayModeSensor(_HiveHolidayModeSensorBase): _attr_device_class = SensorDeviceClass.ENUM _attr_options = ["off", "scheduled", "active"] - _attr_icon = "mdi:palm-tree" - _attr_name = "Holiday Mode" + _attr_translation_key = "holiday_mode" - def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + def __init__(self, data: HiveHolidayModeData, hub_id: str) -> None: """Initialise the Holiday Mode sensor.""" super().__init__(data, hub_id, "Mode") @@ -479,11 +452,10 @@ def _update_from_result(self, result: dict) -> None: class HiveHolidayStartSensor(_HiveHolidayModeDateSensor): """Sensor exposing Hive's Holiday Mode start date/time.""" - _attr_name = "Holiday Date Start" - _attr_icon = "mdi:calendar-start" + _attr_translation_key = "holiday_start" _result_key = "start" - def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + def __init__(self, data: HiveHolidayModeData, hub_id: str) -> None: """Initialise the Holiday Date Start sensor.""" super().__init__(data, hub_id, "DateStart") @@ -491,11 +463,10 @@ def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: class HiveHolidayEndSensor(_HiveHolidayModeDateSensor): """Sensor exposing Hive's Holiday Mode end date/time.""" - _attr_name = "Holiday Date End" - _attr_icon = "mdi:calendar-end" + _attr_translation_key = "holiday_end" _result_key = "end" - def __init__(self, data: _HiveHolidayModeData, hub_id: str) -> None: + def __init__(self, data: HiveHolidayModeData, hub_id: str) -> None: """Initialise the Holiday Date End sensor.""" super().__init__(data, hub_id, "DateEnd") diff --git a/custom_components/hive/services.py b/custom_components/hive/services.py index 0d33f40..050d8a0 100644 --- a/custom_components/hive/services.py +++ b/custom_components/hive/services.py @@ -1 +1,160 @@ -from homeassistant.components.hive.services import * +"""Services for the Hive integration.""" + +from typing import TYPE_CHECKING + +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +import probatio + +from homeassistant.components.hive.services import * # noqa: F403 +from homeassistant.components.hive.services import ( + async_setup_services as async_setup_core_services, +) +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import ATTR_CONFIG_ENTRY_ID +from homeassistant.core import HomeAssistant, ServiceCall, callback +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import config_validation as cv +from homeassistant.util import dt as dt_util + +from .const import DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, SERVICE_SET_HOLIDAY_MODE +from .holiday import HIVE_HOLIDAY_ERRORS, async_get_holiday_data + +if TYPE_CHECKING: + from . import HiveConfigEntry + +ATTR_START = "start" +ATTR_END = "end" +ATTR_TEMPERATURE = "temperature" + +CONFIG_ENTRY_SCHEMA = {probatio.Optional(ATTR_CONFIG_ENTRY_ID): cv.string} + +SET_HOLIDAY_MODE_SCHEMA = probatio.Schema( + { + **CONFIG_ENTRY_SCHEMA, + probatio.Required(ATTR_START): cv.datetime, + probatio.Required(ATTR_END): cv.datetime, + probatio.Required(ATTR_TEMPERATURE): probatio.All( + probatio.Coerce(float), probatio.Range(min=7, max=35) + ), + } +) +CANCEL_HOLIDAY_MODE_SCHEMA = probatio.Schema(CONFIG_ENTRY_SCHEMA) + + +@callback +def async_setup_services(hass: HomeAssistant) -> None: + """Set up the services for the Hive integration. + + Core's services (the boost_* entity services) are registered unchanged; + the holiday mode services are added alongside them. + """ + async_setup_core_services(hass) + + hass.services.async_register( + DOMAIN, + SERVICE_SET_HOLIDAY_MODE, + _async_set_holiday_mode, + schema=SET_HOLIDAY_MODE_SCHEMA, + ) + hass.services.async_register( + DOMAIN, + SERVICE_CANCEL_HOLIDAY_MODE, + _async_cancel_holiday_mode, + schema=CANCEL_HOLIDAY_MODE_SCHEMA, + ) + + +def _get_entry(call: ServiceCall) -> HiveConfigEntry: + """Return the loaded Hive entry the call is for. + + The entry can be given; with only one Hive account loaded it is optional. + """ + hass = call.hass + if entry_id := call.data.get(ATTR_CONFIG_ENTRY_ID): + entry = hass.config_entries.async_get_entry(entry_id) + if entry is None or entry.domain != DOMAIN: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="entry_not_found", + translation_placeholders={"entry_id": entry_id}, + ) + if entry.state is not ConfigEntryState.LOADED: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="entry_not_loaded", + translation_placeholders={"title": entry.title}, + ) + return entry + + entries = hass.config_entries.async_loaded_entries(DOMAIN) + if not entries: + raise ServiceValidationError( + translation_domain=DOMAIN, translation_key="no_entry_loaded" + ) + if len(entries) > 1: + raise ServiceValidationError( + translation_domain=DOMAIN, translation_key="multiple_entries" + ) + return entries[0] + + +async def _async_set_holiday_mode(call: ServiceCall) -> None: + """Schedule holiday mode.""" + entry = _get_entry(call) + # The Hive app works to the minute, so drop seconds here: every caller + # gets the same minute-aligned window. Naive times are Home Assistant's + # local time (pyhive would otherwise use the host's time zone). + start = dt_util.as_local(call.data[ATTR_START]).replace(second=0, microsecond=0) + end = dt_util.as_local(call.data[ATTR_END]).replace(second=0, microsecond=0) + if end <= start: + raise ServiceValidationError( + translation_domain=DOMAIN, translation_key="end_before_start" + ) + if end <= dt_util.now(): + raise ServiceValidationError( + translation_domain=DOMAIN, translation_key="end_in_past" + ) + + try: + success = await entry.runtime_data.hub.set_holiday_mode( + start, end, call.data[ATTR_TEMPERATURE] + ) + except HiveReauthRequired as err: + entry.async_start_reauth(call.hass) + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="reauth_required" + ) from err + except HIVE_HOLIDAY_ERRORS as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="set_holiday_mode_failed", + translation_placeholders={"error": repr(err)}, + ) from err + if not success: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="set_holiday_mode_rejected" + ) + async_get_holiday_data(call.hass, entry).async_changed(start) + + +async def _async_cancel_holiday_mode(call: ServiceCall) -> None: + """Cancel scheduled or active holiday mode.""" + entry = _get_entry(call) + try: + success = await entry.runtime_data.hub.cancel_holiday_mode() + except HiveReauthRequired as err: + entry.async_start_reauth(call.hass) + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="reauth_required" + ) from err + except HIVE_HOLIDAY_ERRORS as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="cancel_holiday_mode_failed", + translation_placeholders={"error": repr(err)}, + ) from err + if not success: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="cancel_holiday_mode_rejected" + ) + async_get_holiday_data(call.hass, entry).async_changed() diff --git a/custom_components/hive/services.yaml b/custom_components/hive/services.yaml index ed1c933..e8462ce 100755 --- a/custom_components/hive/services.yaml +++ b/custom_components/hive/services.yaml @@ -47,6 +47,10 @@ boost_hot_water: - "off" set_holiday_mode: fields: + config_entry_id: + selector: + config_entry: + integration: hive start: required: true selector: @@ -65,4 +69,8 @@ set_holiday_mode: step: 0.5 unit_of_measurement: ° cancel_holiday_mode: - fields: {} + fields: + config_entry_id: + selector: + config_entry: + integration: hive diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 44af0ce..625b7a8 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -106,6 +106,10 @@ "name": "Set holiday mode", "description": "Schedules Hive's whole-home holiday mode, holding a frost-protection temperature for the given period.", "fields": { + "config_entry_id": { + "name": "Hive account", + "description": "The Hive account to use. Only needed when more than one is set up." + }, "start": { "name": "Start", "description": "When holiday mode should begin." @@ -122,7 +126,13 @@ }, "cancel_holiday_mode": { "name": "Cancel holiday mode", - "description": "Cancels any scheduled or currently active Hive holiday mode." + "description": "Cancels any scheduled or currently active Hive holiday mode.", + "fields": { + "config_entry_id": { + "name": "[%key:component::hive::services::set_holiday_mode::fields::config_entry_id::name%]", + "description": "[%key:component::hive::services::set_holiday_mode::fields::config_entry_id::description%]" + } + } } }, "entity": { @@ -140,7 +150,67 @@ "off": "[%key:common::state::off%]", "schedule": "[%key:component::hive::entity::sensor::heating::state::schedule%]" } + }, + "holiday_mode": { + "name": "Holiday mode", + "state": { + "off": "[%key:common::state::off%]", + "scheduled": "Scheduled", + "active": "[%key:common::state::active%]" + }, + "state_attributes": { + "start": { + "name": "Start" + }, + "end": { + "name": "End" + }, + "temperature": { + "name": "[%key:component::hive::services::set_holiday_mode::fields::temperature::name%]" + } + } + }, + "holiday_start": { + "name": "Holiday date start" + }, + "holiday_end": { + "name": "Holiday date end" } } + }, + "exceptions": { + "entry_not_found": { + "message": "No Hive account with config entry ID {entry_id} was found." + }, + "entry_not_loaded": { + "message": "The Hive account {title} is not loaded." + }, + "no_entry_loaded": { + "message": "No Hive account is loaded." + }, + "multiple_entries": { + "message": "More than one Hive account is set up. Choose which one to use." + }, + "end_before_start": { + "message": "The holiday mode end must be after its start." + }, + "end_in_past": { + "message": "The holiday mode end must be in the future." + }, + "reauth_required": { + "message": "Hive needs you to sign in again. Reauthenticate the integration, then try again." + }, + "set_holiday_mode_failed": { + "message": "Failed to set Hive holiday mode: {error}" + }, + "set_holiday_mode_rejected": { + "message": "Hive rejected the set holiday mode request." + }, + "cancel_holiday_mode_failed": { + "message": "Failed to cancel Hive holiday mode: {error}" + }, + "cancel_holiday_mode_rejected": { + "message": "Hive rejected the cancel holiday mode request." + } } } diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 84ddf87..7e7d789 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -106,6 +106,10 @@ "name": "Set holiday mode", "description": "Schedules Hive's whole-home holiday mode, holding a frost-protection temperature for the given period.", "fields": { + "config_entry_id": { + "name": "Hive account", + "description": "The Hive account to use. Only needed when more than one is set up." + }, "start": { "name": "Start", "description": "When holiday mode should begin." @@ -122,7 +126,13 @@ }, "cancel_holiday_mode": { "name": "Cancel holiday mode", - "description": "Cancels any scheduled or currently active Hive holiday mode." + "description": "Cancels any scheduled or currently active Hive holiday mode.", + "fields": { + "config_entry_id": { + "name": "Hive account", + "description": "The Hive account to use. Only needed when more than one is set up." + } + } } }, "entity": { @@ -140,7 +150,67 @@ "off": "Off", "schedule": "Schedule" } + }, + "holiday_mode": { + "name": "Holiday mode", + "state": { + "off": "Off", + "scheduled": "Scheduled", + "active": "Active" + }, + "state_attributes": { + "start": { + "name": "Start" + }, + "end": { + "name": "End" + }, + "temperature": { + "name": "Temperature" + } + } + }, + "holiday_start": { + "name": "Holiday date start" + }, + "holiday_end": { + "name": "Holiday date end" } } + }, + "exceptions": { + "entry_not_found": { + "message": "No Hive account with config entry ID {entry_id} was found." + }, + "entry_not_loaded": { + "message": "The Hive account {title} is not loaded." + }, + "no_entry_loaded": { + "message": "No Hive account is loaded." + }, + "multiple_entries": { + "message": "More than one Hive account is set up. Choose which one to use." + }, + "end_before_start": { + "message": "The holiday mode end must be after its start." + }, + "end_in_past": { + "message": "The holiday mode end must be in the future." + }, + "reauth_required": { + "message": "Hive needs you to sign in again. Reauthenticate the integration, then try again." + }, + "set_holiday_mode_failed": { + "message": "Failed to set Hive holiday mode: {error}" + }, + "set_holiday_mode_rejected": { + "message": "Hive rejected the set holiday mode request." + }, + "cancel_holiday_mode_failed": { + "message": "Failed to cancel Hive holiday mode: {error}" + }, + "cancel_holiday_mode_rejected": { + "message": "Hive rejected the cancel holiday mode request." + } } } diff --git a/tests/conftest.py b/tests/conftest.py index 2685479..285d9a7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -150,7 +150,7 @@ def mock_hive( hive.heating.getClimate = AsyncMock(side_effect=_echo) # Extra attributes on the heating sensors (min/max, boost end); no data by default. hive.heating.minmaxTemperature = AsyncMock(return_value=None) - hive.heating.get_target_temperature = AsyncMock(return_value=None) + hive.heating.getTargetTemperature = AsyncMock(return_value=None) hive.heating.getBoostStatus = AsyncMock(return_value="OFF") hive.heating.getBoostTime = AsyncMock(return_value=None) hive.hotwater.getBoost = AsyncMock(return_value="OFF") diff --git a/tests/test_holiday_mode.py b/tests/test_holiday_mode.py index dbb29f4..13b197d 100644 --- a/tests/test_holiday_mode.py +++ b/tests/test_holiday_mode.py @@ -1,26 +1,28 @@ """Tests for the Hive Holiday Mode sensors and services.""" -from datetime import UTC, datetime -from unittest.mock import AsyncMock, MagicMock +from datetime import UTC, datetime, timedelta +from unittest.mock import AsyncMock, MagicMock, patch -from apyhiveapi.helper.hive_exceptions import HiveApiError +from aiohttp import ClientError +from apyhiveapi.helper.hive_exceptions import HiveApiError, HiveReauthRequired +from freezegun.api import FrozenDateTimeFactory import pytest -from pytest_homeassistant.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry, async_fire_time_changed from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import entity_registry as er from homeassistant.helpers.dispatcher import async_dispatcher_send -from custom_components.hive import sensor +from custom_components.hive import holiday, sensor from custom_components.hive.const import ( DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, SERVICE_SET_HOLIDAY_MODE, ) -from .conftest import HUB_ID +from .conftest import DEVICE_DATA, HUB_ID, PASSWORD, TOKENS START = datetime(2026, 12, 20, 10, 15, tzinfo=UTC) END = datetime(2027, 1, 3, 18, 30, tzinfo=UTC) @@ -38,7 +40,7 @@ @pytest.fixture(autouse=True) def no_holiday_cache(monkeypatch: pytest.MonkeyPatch) -> None: """Fetch fresh holiday data on every refresh so tests can change it.""" - monkeypatch.setattr(sensor._HiveHolidayModeData, "_CACHE_SECONDS", -1) + monkeypatch.setattr(holiday.HiveHolidayModeData, "_CACHE_SECONDS", -1) def _entity_id(hass: HomeAssistant, key: str) -> str: @@ -55,8 +57,8 @@ async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: await hass.async_block_till_done() -async def _refresh(hass: HomeAssistant) -> None: - async_dispatcher_send(hass, DOMAIN) +async def _refresh(hass: HomeAssistant, entry: MockConfigEntry) -> None: + async_dispatcher_send(hass, f"{DOMAIN}_holiday_{entry.entry_id}") await hass.async_block_till_done() @@ -87,7 +89,7 @@ async def test_holiday_sensors_scheduled_then_active( assert hass.states.get(_entity_id(hass, "DateEnd")).state == END.isoformat() mock_hive.hub.get_holiday_mode.return_value = {**SCHEDULED, "active": True} - await _refresh(hass) + await _refresh(hass, mock_config_entry) assert hass.states.get(_entity_id(hass, "Mode")).state == "active" @@ -100,7 +102,7 @@ async def test_holiday_sensors_keep_values_on_partial_response( await _setup(hass, mock_config_entry) mock_hive.hub.get_holiday_mode.return_value = {"enabled": True, "active": True} - await _refresh(hass) + await _refresh(hass, mock_config_entry) mode = hass.states.get(_entity_id(hass, "Mode")) assert mode.state == "active" @@ -120,7 +122,7 @@ async def test_holiday_sensors_unavailable_without_data( assert hass.states.get(_entity_id(hass, key)).state == STATE_UNAVAILABLE -@pytest.mark.parametrize("error", [TimeoutError(), HiveApiError()]) +@pytest.mark.parametrize("error", [TimeoutError(), HiveApiError(), ClientError()]) async def test_holiday_sensors_survive_fetch_error_at_setup( hass: HomeAssistant, mock_hive: MagicMock, @@ -135,7 +137,7 @@ async def test_holiday_sensors_survive_fetch_error_at_setup( assert hass.states.get(_entity_id(hass, key)).state == STATE_UNAVAILABLE mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) - await _refresh(hass) + await _refresh(hass, mock_config_entry) assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" assert hass.states.get(_entity_id(hass, "DateStart")).state == START.isoformat() @@ -163,10 +165,12 @@ async def test_set_holiday_mode( mock_hive.hub.set_holiday_mode.assert_awaited_once_with(START, END, 12.0) assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" - # Unloading cancels the pending catch-up refreshes and removes the services. + # Unloading cancels the pending catch-up refreshes; the services stay + # registered (they belong to the integration, not the entry). assert await hass.config_entries.async_unload(mock_config_entry.entry_id) - assert not hass.services.has_service(DOMAIN, SERVICE_SET_HOLIDAY_MODE) - assert not hass.services.has_service(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) + assert hass.services.has_service(DOMAIN, SERVICE_SET_HOLIDAY_MODE) + assert hass.services.has_service(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) + assert not hass.data.get(holiday.DATA_HOLIDAY) async def test_cancel_holiday_mode( @@ -200,8 +204,13 @@ async def test_cancel_holiday_mode( ) @pytest.mark.parametrize( "outcome", - [AsyncMock(return_value=False), AsyncMock(side_effect=HiveApiError)], - ids=["rejected", "api_error"], + [ + AsyncMock(return_value=False), + AsyncMock(side_effect=HiveApiError), + AsyncMock(side_effect=ClientError), + AsyncMock(side_effect=TimeoutError), + ], + ids=["rejected", "api_error", "client_error", "timeout"], ) async def test_holiday_service_failures( hass: HomeAssistant, @@ -249,3 +258,202 @@ async def test_no_holiday_sensors_without_hub( await sensor.async_setup_entry(hass, mock_config_entry, add_entities) add_entities.assert_not_called() + + +async def _set(hass: HomeAssistant, **data) -> None: + await hass.services.async_call( + DOMAIN, + SERVICE_SET_HOLIDAY_MODE, + {"start": START.isoformat(), "end": END.isoformat(), "temperature": 12, **data}, + blocking=True, + ) + + +@pytest.mark.freeze_time("2026-12-01 12:00:00+00:00") +@pytest.mark.parametrize( + ("start", "end", "key"), + [ + (END, START, "end_before_start"), + (START, START + timedelta(seconds=30), "end_before_start"), + ( + datetime(2026, 11, 1, tzinfo=UTC), + datetime(2026, 11, 30, tzinfo=UTC), + "end_in_past", + ), + ], +) +async def test_set_holiday_mode_validates_window( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + start: datetime, + end: datetime, + key: str, +) -> None: + """An end before (or in the same minute as) the start, or in the past, is rejected.""" + await _setup(hass, mock_config_entry) + + with pytest.raises(ServiceValidationError) as err: + await _set(hass, start=start.isoformat(), end=end.isoformat()) + assert err.value.translation_key == key + mock_hive.hub.set_holiday_mode.assert_not_awaited() + + +async def test_set_holiday_mode_naive_times_are_local( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Times without an offset use Home Assistant's time zone.""" + await hass.config.async_set_time_zone("Europe/London") + await _setup(hass, mock_config_entry) + + # 20 June is BST (UTC+1). + await _set(hass, start="2027-06-20 10:15:00", end="2027-06-27 18:30:00") + + start, end, _ = mock_hive.hub.set_holiday_mode.await_args.args + assert start == datetime(2027, 6, 20, 9, 15, tzinfo=UTC) + assert end == datetime(2027, 6, 27, 17, 30, tzinfo=UTC) + assert start.utcoffset() == timedelta(hours=1) + + +@pytest.mark.parametrize( + "service", [SERVICE_SET_HOLIDAY_MODE, SERVICE_CANCEL_HOLIDAY_MODE] +) +async def test_holiday_service_reauth( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + service: str, +) -> None: + """A reauth-required error starts the reauth flow.""" + await _setup(hass, mock_config_entry) + mock_hive.hub.set_holiday_mode.side_effect = HiveReauthRequired + mock_hive.hub.cancel_holiday_mode.side_effect = HiveReauthRequired + data = ( + {"start": START.isoformat(), "end": END.isoformat(), "temperature": 12} + if service == SERVICE_SET_HOLIDAY_MODE + else {} + ) + + with ( + patch.object(mock_config_entry, "async_start_reauth") as start_reauth, + pytest.raises(HomeAssistantError) as err, + ): + await hass.services.async_call(DOMAIN, service, data, blocking=True) + assert err.value.translation_key == "reauth_required" + start_reauth.assert_called_once_with(hass) + + +async def test_holiday_sensor_reauth( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """A reauth-required error while polling starts reauth and goes unavailable.""" + mock_hive.hub.get_holiday_mode = AsyncMock(side_effect=HiveReauthRequired) + with patch.object(mock_config_entry, "async_start_reauth") as start_reauth: + await _setup(hass, mock_config_entry) + + assert hass.states.get(_entity_id(hass, "Mode")).state == STATE_UNAVAILABLE + start_reauth.assert_called_with(hass) + + +async def test_service_call_skips_stale_cache( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A service call straight after a poll still shows the new state.""" + monkeypatch.setattr(holiday.HiveHolidayModeData, "_CACHE_SECONDS", 3600) + await _setup(hass, mock_config_entry) + assert hass.states.get(_entity_id(hass, "Mode")).state == "off" + + mock_hive.hub.get_holiday_mode.return_value = SCHEDULED + await _set(hass) + await hass.async_block_till_done() + + assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" + + +@pytest.mark.freeze_time("2026-12-01 12:00:00+00:00") +async def test_catch_up_refreshes_replace_earlier_ones( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Each call replaces the previous call's timers instead of adding more.""" + await _setup(hass, mock_config_entry) + data = hass.data[holiday.DATA_HOLIDAY][mock_config_entry.entry_id] + + await _set(hass) + # Refresh at the future start plus four catch-ups after it. + assert len(data._timers) == 5 + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + assert len(data._timers) == 4 + + calls = mock_hive.hub.get_holiday_mode.await_count + freezer.tick(timedelta(seconds=31)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + # One fetch per sensor (the cache is off in these tests). + assert mock_hive.hub.get_holiday_mode.await_count == calls + 3 + + +async def test_holiday_services_with_two_entries( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """With two accounts the entry must be chosen; unloading one keeps the services.""" + second = MockConfigEntry( + domain=DOMAIN, + title="other@example.com", + unique_id="other@example.com", + data={ + "username": "other@example.com", + "password": PASSWORD, + "tokens": TOKENS, + "device_data": DEVICE_DATA, + }, + ) + await _setup(hass, mock_config_entry) + await _setup(hass, second) + + with pytest.raises(ServiceValidationError) as err: + await _set(hass) + assert err.value.translation_key == "multiple_entries" + + await _set(hass, config_entry_id=second.entry_id) + mock_hive.hub.set_holiday_mode.assert_awaited_once() + + assert await hass.config_entries.async_unload(second.entry_id) + assert hass.services.has_service(DOMAIN, SERVICE_SET_HOLIDAY_MODE) + assert hass.services.has_service(DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE) + + with pytest.raises(ServiceValidationError) as err: + await _set(hass, config_entry_id=second.entry_id) + assert err.value.translation_key == "entry_not_loaded" + + # With one account left, the entry is optional again. + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + mock_hive.hub.cancel_holiday_mode.assert_awaited_once() + + +async def test_holiday_services_without_loaded_entry( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The services report a clear error when no account is loaded.""" + await _setup(hass, mock_config_entry) + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + + with pytest.raises(ServiceValidationError) as err: + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + assert err.value.translation_key == "no_entry_loaded" + with pytest.raises(ServiceValidationError) as err: + await _set(hass, config_entry_id="missing") + assert err.value.translation_key == "entry_not_found" diff --git a/tests/test_sensor.py b/tests/test_sensor.py index bd4051e..9d3acbc 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -323,7 +323,7 @@ async def test_current_temperature_attributes( "RestartMax": 22.0, } ) - mock_hive.heating.get_target_temperature = AsyncMock(return_value=21.0) + mock_hive.heating.getTargetTemperature = AsyncMock(return_value=21.0) await _setup(hass, mock_config_entry) From e175a508039933a63b86ea736a37b40fdf42ad0d Mon Sep 17 00:00:00 2001 From: Neil Sleightholm Date: Mon, 23 Nov 2026 03:46:16 +0000 Subject: [PATCH 3/4] fix: refresh holiday sensors at the holiday's start and end The sensors only refreshed around a service call, so a holiday ending (or starting after a restart, or set from the Hive app) showed the old state until the 30-minute poll. Each fetch that finds holiday mode scheduled or active now sets a refresh for its start and end; once either has passed, the catch-up refreshes run, because Hive can take a while to flip. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/holiday.py | 86 ++++++++++++++++++++++-------- custom_components/hive/services.py | 2 +- tests/test_holiday_mode.py | 68 +++++++++++++++++++++-- 3 files changed, 129 insertions(+), 27 deletions(-) diff --git a/custom_components/hive/holiday.py b/custom_components/hive/holiday.py index d1d9ca0..0696e72 100644 --- a/custom_components/hive/holiday.py +++ b/custom_components/hive/holiday.py @@ -29,9 +29,9 @@ ) # Hive's backend can take a few minutes to flip holiday mode to active or off -# after a change, so a single refresh straight after a service call (or at -# "start") can still read the old state. Refresh a few more times over the -# next five minutes rather than waiting for the 30-minute poll. +# after a change, at its start or at its end, so a single refresh at that +# moment can still read the old state. Refresh a few more times over the next +# five minutes rather than waiting for the 30-minute poll. CATCHUP_DELAYS = tuple(timedelta(seconds=s) for s in (30, 90, 180, 300)) @@ -41,6 +41,11 @@ class HiveHolidayModeData: get_holiday_mode() always makes a cloud API call, so the status, start and end sensors share one fetch: refreshes within a few seconds of each other use the cached result. + + Whenever a fetch shows holiday mode scheduled or active, a refresh is set + for its start and end, followed by catch-up refreshes once it has passed, + so the sensors follow the transitions however the holiday was set (these + services, the Hive app) and across restarts. """ _CACHE_SECONDS = 5 @@ -53,7 +58,8 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: self._data: dict | None = None self._fetched_at: float | None = None self._lock = asyncio.Lock() - self._timers: list[CALLBACK_TYPE] = [] + self._catch_up: list[CALLBACK_TYPE] = [] + self._transitions: dict[str, tuple[datetime, CALLBACK_TYPE]] = {} async def async_get(self) -> dict | None: """Return the holiday mode data, fetching it if the cache is stale.""" @@ -62,6 +68,7 @@ async def async_get(self) -> dict | None: if self._fetched_at is None or now - self._fetched_at > self._CACHE_SECONDS: self._data = await self.hive.hub.get_holiday_mode() self._fetched_at = now + self._track_transitions(self._data) return self._data @callback @@ -70,33 +77,70 @@ def async_refresh(self, _now: datetime | None = None) -> None: async_dispatcher_send(self.hass, self.signal) @callback - def async_changed(self, start: datetime | None = None) -> None: + def async_changed(self) -> None: """Refresh after holiday mode was set or cancelled. - Drops the cached result so the next fetch sees the change, refreshes - now, at a future start, and a few times after whichever is later. - Replaces the timers from any earlier call. + Drops the cached result so the next fetch sees the change, then + refreshes now and a few times over the next few minutes. A future + start or end is picked up from the fetched data. """ self._fetched_at = None - self.async_cancel_timers() - anchor = now = dt_util.utcnow() - if start is not None and (start := dt_util.as_utc(start)) > now: - self._track(start) - anchor = start - for delay in CATCHUP_DELAYS: - self._track(anchor + delay) - self.async_refresh() + self._async_catch_up() @callback def async_cancel_timers(self) -> None: """Cancel pending refreshes.""" - while self._timers: - self._timers.pop()() + self._cancel_catch_up() + while self._transitions: + self._transitions.popitem()[1][1]() - def _track(self, when: datetime) -> None: - self._timers.append( - async_track_point_in_utc_time(self.hass, self.async_refresh, when) + @callback + def _async_catch_up(self, _now: datetime | None = None) -> None: + """Refresh now and at each catch-up delay, replacing earlier ones.""" + self._cancel_catch_up() + now = dt_util.utcnow() + self._catch_up.extend( + async_track_point_in_utc_time(self.hass, self.async_refresh, now + delay) + for delay in CATCHUP_DELAYS ) + self.async_refresh() + + def _cancel_catch_up(self) -> None: + while self._catch_up: + self._catch_up.pop()() + + def _track_transitions(self, data: dict | None) -> None: + """Keep a refresh set for a scheduled or active holiday's start and end.""" + if not data: + # Failed fetch: keep what we have until the next good one. + return + on = data.get("enabled") or data.get("active") + now = dt_util.utcnow() + for key in ("start", "end"): + when: datetime | None = None + if on: + if (epoch_ms := data.get(key)) is None: + # Hive sometimes leaves fields out; keep the timer we have. + continue + when = dt_util.utc_from_timestamp(epoch_ms / 1000) + if when <= now: + when = None + current = self._transitions.get(key) + if current is not None and current[0] == when: + continue + if current is not None: + reached, cancel = self._transitions.pop(key) + cancel() + if reached <= now: + # The start or end has passed, whether its timer or another + # refresh got here first. Hive may not have caught up yet, + # so keep refreshing for a few minutes. + self._async_catch_up() + if when is not None: + self._transitions[key] = ( + when, + async_track_point_in_utc_time(self.hass, self.async_refresh, when), + ) DATA_HOLIDAY: HassKey[dict[str, HiveHolidayModeData]] = HassKey(f"{DOMAIN}_holiday") diff --git a/custom_components/hive/services.py b/custom_components/hive/services.py index 050d8a0..4635ab0 100644 --- a/custom_components/hive/services.py +++ b/custom_components/hive/services.py @@ -134,7 +134,7 @@ async def _async_set_holiday_mode(call: ServiceCall) -> None: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_holiday_mode_rejected" ) - async_get_holiday_data(call.hass, entry).async_changed(start) + async_get_holiday_data(call.hass, entry).async_changed() async def _async_cancel_holiday_mode(call: ServiceCall) -> None: diff --git a/tests/test_holiday_mode.py b/tests/test_holiday_mode.py index 13b197d..a3463f8 100644 --- a/tests/test_holiday_mode.py +++ b/tests/test_holiday_mode.py @@ -14,6 +14,7 @@ from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import entity_registry as er from homeassistant.helpers.dispatcher import async_dispatcher_send +from homeassistant.util import dt as dt_util from custom_components.hive import holiday, sensor from custom_components.hive.const import ( @@ -387,21 +388,78 @@ async def test_catch_up_refreshes_replace_earlier_ones( data = hass.data[holiday.DATA_HOLIDAY][mock_config_entry.entry_id] await _set(hass) - # Refresh at the future start plus four catch-ups after it. - assert len(data._timers) == 5 + assert len(data._catch_up) == 4 await hass.services.async_call( DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True ) - assert len(data._timers) == 4 + assert len(data._catch_up) == 4 calls = mock_hive.hub.get_holiday_mode.await_count - freezer.tick(timedelta(seconds=31)) - async_fire_time_changed(hass) + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=31)) await hass.async_block_till_done() # One fetch per sensor (the cache is off in these tests). assert mock_hive.hub.get_holiday_mode.await_count == calls + 3 +@pytest.mark.freeze_time("2026-12-20 10:00:00+00:00") +async def test_refreshes_at_start_and_end( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """A scheduled holiday found at setup (e.g. after a restart) refreshes at its edges.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _setup(hass, mock_config_entry) + data = hass.data[holiday.DATA_HOLIDAY][mock_config_entry.entry_id] + assert {key: when for key, (when, _) in data._transitions.items()} == { + "start": START, + "end": END, + } + assert hass.states.get(_entity_id(hass, "Mode")).state == "scheduled" + + # At the start Hive reports active; the sensors follow without a poll. + mock_hive.hub.get_holiday_mode.return_value = {**SCHEDULED, "active": True} + freezer.move_to(START) + async_fire_time_changed(hass, dt_util.utcnow()) + await hass.async_block_till_done() + assert hass.states.get(_entity_id(hass, "Mode")).state == "active" + assert set(data._transitions) == {"end"} + + # Hive is still catching up at the end; a catch-up refresh sees it off. + freezer.move_to(END) + async_fire_time_changed(hass, dt_util.utcnow()) + await hass.async_block_till_done() + assert hass.states.get(_entity_id(hass, "Mode")).state == "active" + + mock_hive.hub.get_holiday_mode.return_value = { + **SCHEDULED, + "enabled": False, + "active": False, + } + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=31)) + await hass.async_block_till_done() + assert hass.states.get(_entity_id(hass, "Mode")).state == "off" + assert not data._transitions + + +async def test_cancel_clears_transition_refreshes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Once Hive reports holiday mode off, the start/end refreshes are dropped.""" + mock_hive.hub.get_holiday_mode = AsyncMock(return_value=SCHEDULED) + await _setup(hass, mock_config_entry) + data = hass.data[holiday.DATA_HOLIDAY][mock_config_entry.entry_id] + assert set(data._transitions) == {"start", "end"} + + mock_hive.hub.get_holiday_mode.return_value = {"enabled": False, "active": False} + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + await hass.async_block_till_done() + assert not data._transitions + + async def test_holiday_services_with_two_entries( hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry ) -> None: From dbc106875e3359613588d5d6588cad523a31d0cf Mon Sep 17 00:00:00 2001 From: root Date: Mon, 23 Nov 2026 07:19:07 +0000 Subject: [PATCH 4/4] Holiday mode: say which time zone naive start/end times use Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/strings.json | 4 ++-- custom_components/hive/translations/en.json | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 625b7a8..28791e4 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -112,11 +112,11 @@ }, "start": { "name": "Start", - "description": "When holiday mode should begin." + "description": "When holiday mode should begin. A time without a UTC offset is read in Home Assistant's time zone." }, "end": { "name": "End", - "description": "When holiday mode should end." + "description": "When holiday mode should end. A time without a UTC offset is read in Home Assistant's time zone." }, "temperature": { "name": "Temperature", diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 7e7d789..ee07fdf 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -112,11 +112,11 @@ }, "start": { "name": "Start", - "description": "When holiday mode should begin." + "description": "When holiday mode should begin. A time without a UTC offset is read in Home Assistant's time zone." }, "end": { "name": "End", - "description": "When holiday mode should end." + "description": "When holiday mode should end. A time without a UTC offset is read in Home Assistant's time zone." }, "temperature": { "name": "Temperature",