From 53dd3d36d2d220fca61034df99b918f8026df705 Mon Sep 17 00:00:00 2001 From: Neil Sleightholm Date: Wed, 21 Oct 2026 09:28:46 +0100 Subject: [PATCH 1/2] feat: add Hive holiday mode services and sensors Adds whole-home holiday mode support on top of pyhive-integration's hub holiday API (Pyhass/Pyhive#149, first released in 2.0.0b4): - hive.set_holiday_mode (start, end, temperature 7-35) and hive.cancel_holiday_mode services. Start/end are truncated to the minute, matching the Hive app; failures raise HomeAssistantError. - Holiday Mode (off/scheduled/active), Holiday Date Start and Holiday Date End sensors on the hub. They share one cached fetch, poll every 30 minutes, refresh at a scheduled start, and run a short catch-up burst after set/cancel because Hive's backend lags the request. A partial API response keeps the last known start/end/temperature. - Services, and any pending catch-up refreshes, are removed on unload. - Requires pyhive-integration==2.0.0b4. Every hive.. call the integration makes was checked to exist in 2.0.0b4. Tests: new tests/test_holiday_mode.py; the mocked Hive now has a hub and holiday response, and two "no sensors" assertions now allow the hub's holiday sensors. The 4 failures that already occur on master (test_setup_failures x2, test_translations x2) are unchanged. Ported from nsleigh/Hive-Custom-Component feature/vendor-apyhiveapi-dev (a2ac9b9, 1e4e88a, 4ae6cba, fe2d5a9, b24c3da, 57c1ff3), without the vendored library or unrelated fixes. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/__init__.py | 130 ++++++++++++++- custom_components/hive/const.py | 2 + custom_components/hive/icons.json | 6 + custom_components/hive/manifest.json | 2 +- custom_components/hive/sensor.py | 196 +++++++++++++++++++++-- custom_components/hive/services.yaml | 23 ++- custom_components/hive/strings.json | 22 +++ tests/conftest.py | 11 ++ tests/test_binary_sensor.py | 4 +- tests/test_holiday_mode.py | 230 +++++++++++++++++++++++++++ tests/test_sensor.py | 7 +- 11 files changed, 607 insertions(+), 26 deletions(-) create mode 100644 tests/test_holiday_mode.py diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index 5c2527a..821237c 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -3,28 +3,64 @@ from __future__ import annotations from collections.abc import Awaitable, Callable, Coroutine +from datetime import datetime, timedelta from functools import wraps import logging from typing import Any, Concatenate from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive -from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +from apyhiveapi.helper.hive_exceptions import HiveApiError, HiveReauthRequired +import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL -from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady -from homeassistant.helpers import aiohttp_client, device_registry as dr +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 .const import DOMAIN, PLATFORM_LOOKUP, PLATFORMS +from homeassistant.helpers.event import async_track_point_in_utc_time +from homeassistant.util import dt as dt_util + +from .const import ( + DOMAIN, + PLATFORM_LOOKUP, + PLATFORMS, + SERVICE_CANCEL_HOLIDAY_MODE, + SERVICE_SET_HOLIDAY_MODE, +) from .entity import HiveEntity _LOGGER = logging.getLogger(__name__) 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) + ), + } +) + async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool: """Set up Hive from a config entry.""" @@ -65,6 +101,88 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool ], ) + @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) + return True diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 0caf965..cfe57b4 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 d955e01..5028d57 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" } } } \ No newline at end of file diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index ac3c013..060fd8a 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -11,6 +11,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.0b4"], "version": "2026.10.1b2" } diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index 0c3030c..49fd32f 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,8 +1,10 @@ """Support for the Hive sensors.""" +import asyncio from collections.abc import Callable from dataclasses import dataclass -from datetime import timedelta +from datetime import UTC, datetime, timedelta +import time from typing import Any from homeassistant.components.sensor import ( @@ -17,14 +19,20 @@ 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 . import HiveConfigEntry +from .const import DOMAIN from .entity import HiveEntity from apyhiveapi import Hive +HOLIDAY_MODE_SCAN_INTERVAL = timedelta(minutes=30) + PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) @@ -101,17 +109,26 @@ 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 - async_add_entities( - ( - HiveSensorEntity(hass, entry, hive, dev, description) - for dev in devices - for description in SENSOR_TYPES - if dev["hiveType"] == description.key - ), - True, - ) + entities = [ + HiveSensorEntity(hass, entry, hive, dev, description) + for dev in devices or [] + for description in SENSOR_TYPES + if dev["hiveType"] == description.key + ] + + 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): @@ -314,3 +331,156 @@ async def get_hotwater_state_sa(self): s_a.update({"Schedule not active": ""}) 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.""" + result = await self._data.async_get() + 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") diff --git a/custom_components/hive/services.yaml b/custom_components/hive/services.yaml index 15c4b7f..66bab7e 100755 --- a/custom_components/hive/services.yaml +++ b/custom_components/hive/services.yaml @@ -44,4 +44,25 @@ boost_hot_water: select: options: - "on" - - "off" \ No newline at end of file + - "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: {} \ No newline at end of file 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/tests/conftest.py b/tests/conftest.py index b0b8d9d..4878f5f 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -23,6 +23,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.fixture(autouse=True) @@ -120,6 +127,10 @@ 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) diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py index 759f76e..10286df 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", @@ -82,4 +82,4 @@ async def test_heating_and_hot_water_state_sensors( hass.states.get("binary_sensor.hot_water_hotwater_boost").state == STATE_UNAVAILABLE ) - assert hass.states.async_entity_ids("sensor") == [] + assert set(hass.states.async_entity_ids("sensor")) == HOLIDAY_SENSORS diff --git a/tests/test_holiday_mode.py b/tests/test_holiday_mode.py new file mode 100644 index 0000000..848e343 --- /dev/null +++ b/tests/test_holiday_mode.py @@ -0,0 +1,230 @@ +"""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_custom_component.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 + + +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 db644eb..4e8ffa6 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: @@ -111,7 +111,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( @@ -294,9 +294,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() From f8848452e20c094770ef2667a01ea87768bf7d7e Mon Sep 17 00:00:00 2001 From: Neil Sleightholm Date: Wed, 4 Nov 2026 20:22:37 +0000 Subject: [PATCH 2/2] fix: keep holiday sensors when the first fetch fails The holiday mode sensors are added with update_before_add, so an exception from get_holiday_mode() during setup (e.g. Hive's cloud timing out at boot) stopped HA adding them at all until the next restart. Catch TimeoutError, aiohttp ClientError and HiveApiError in async_update and go unavailable instead; the 30-minute poll and dispatcher refreshes bring them back. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/sensor.py | 16 +++++++++++++++- tests/test_holiday_mode.py | 21 +++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index 49fd32f..62e4d5c 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -4,9 +4,13 @@ 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.helper.hive_exceptions import HiveApiError + from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -31,6 +35,8 @@ from .entity import HiveEntity from apyhiveapi import Hive +_LOGGER = logging.getLogger(__name__) + HOLIDAY_MODE_SCAN_INTERVAL = timedelta(minutes=30) PARALLEL_UPDATES = 0 @@ -400,7 +406,15 @@ def _async_schedule_refresh(self, _now: datetime | None = None) -> None: async def async_update(self) -> None: """Fetch the latest Holiday Mode status from Hive.""" - result = await self._data.async_get() + # 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 diff --git a/tests/test_holiday_mode.py b/tests/test_holiday_mode.py index 848e343..0378c89 100644 --- a/tests/test_holiday_mode.py +++ b/tests/test_holiday_mode.py @@ -120,6 +120,27 @@ 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()]) +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: