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/holiday.py b/custom_components/hive/holiday.py new file mode 100644 index 0000000..0696e72 --- /dev/null +++ b/custom_components/hive/holiday.py @@ -0,0 +1,164 @@ +"""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, 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)) + + +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. + + 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 + + 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._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.""" + 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 + self._track_transitions(self._data) + 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) -> None: + """Refresh after holiday mode was set or cancelled. + + 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_catch_up() + + @callback + def async_cancel_timers(self) -> None: + """Cancel pending refreshes.""" + self._cancel_catch_up() + while self._transitions: + self._transitions.popitem()[1][1]() + + @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") + + +@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 8b8a785..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" } } }, @@ -26,6 +35,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..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==1.0.10"], + "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 bf1775b..3996c95 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,11 +1,14 @@ """Support for the Hive sensors.""" +from abc import abstractmethod from collections.abc import Callable from dataclasses import dataclass -from datetime import datetime, timedelta +from datetime import UTC, datetime, timedelta +import logging from typing import Any from apyhiveapi import Hive +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired from homeassistant.components.sensor import ( SensorDeviceClass, @@ -19,13 +22,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 +from .holiday import HIVE_HOLIDAY_ERRORS, HiveHolidayModeData, async_get_holiday_data + +_LOGGER = logging.getLogger(__name__) + +HOLIDAY_MODE_SCAN_INTERVAL = timedelta(minutes=30) PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) @@ -107,20 +119,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 = async_get_holiday_data(hass, entry) + 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): @@ -315,6 +338,139 @@ async def get_hotwater_state_sa(self): return s_a +class _HiveHolidayModeSensorBase(SensorEntity): + """Base for the Hive whole-home Holiday Mode sensors. + + 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: + """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, self._data.signal, 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 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: + self._attr_available = False + return + 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.""" + + +class HiveHolidayModeSensor(_HiveHolidayModeSensorBase): + """Sensor exposing Hive's whole-home Holiday Mode status.""" + + _attr_device_class = SensorDeviceClass.ENUM + _attr_options = ["off", "scheduled", "active"] + _attr_translation_key = "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_translation_key = "holiday_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_translation_key = "holiday_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.py b/custom_components/hive/services.py index 0d33f40..4635ab0 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() + + +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 e2ad598..e8462ce 100755 --- a/custom_components/hive/services.yaml +++ b/custom_components/hive/services.yaml @@ -45,3 +45,32 @@ boost_hot_water: options: - "on" - "off" +set_holiday_mode: + fields: + config_entry_id: + selector: + config_entry: + integration: hive + 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: + config_entry_id: + selector: + config_entry: + integration: hive diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 2bca947..28791e4 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -101,6 +101,38 @@ "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": { + "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. A time without a UTC offset is read in Home Assistant's time zone." + }, + "end": { + "name": "End", + "description": "When holiday mode should end. A time without a UTC offset is read in Home Assistant's time zone." + }, + "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.", + "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": { @@ -118,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 90c237a..ee07fdf 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -101,6 +101,38 @@ "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": { + "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. A time without a UTC offset is read in Home Assistant's time zone." + }, + "end": { + "name": "End", + "description": "When holiday mode should end. A time without a UTC offset is read in Home Assistant's time zone." + }, + "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.", + "fields": { + "config_entry_id": { + "name": "Hive account", + "description": "The Hive account to use. Only needed when more than one is set up." + } + } } }, "entity": { @@ -118,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 f180f38..285d9a7 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,6 +141,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 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..a3463f8 --- /dev/null +++ b/tests/test_holiday_mode.py @@ -0,0 +1,517 @@ +"""Tests for the Hive Holiday Mode sensors and services.""" + +from datetime import UTC, datetime, timedelta +from unittest.mock import AsyncMock, MagicMock, patch + +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, async_fire_time_changed + +from homeassistant.const import STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant +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 ( + DOMAIN, + SERVICE_CANCEL_HOLIDAY_MODE, + SERVICE_SET_HOLIDAY_MODE, +) + +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) +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(holiday.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, entry: MockConfigEntry) -> None: + async_dispatcher_send(hass, f"{DOMAIN}_holiday_{entry.entry_id}") + 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, mock_config_entry) + + 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, mock_config_entry) + + 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(), ClientError()]) +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, mock_config_entry) + + 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; 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 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( + 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), + AsyncMock(side_effect=ClientError), + AsyncMock(side_effect=TimeoutError), + ], + ids=["rejected", "api_error", "client_error", "timeout"], +) +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() + + +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) + assert len(data._catch_up) == 4 + await hass.services.async_call( + DOMAIN, SERVICE_CANCEL_HOLIDAY_MODE, {}, blocking=True + ) + assert len(data._catch_up) == 4 + + calls = mock_hive.hub.get_holiday_mode.await_count + 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: + """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 97b06d1..9d3acbc 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()