Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
130 changes: 124 additions & 6 deletions custom_components/hive/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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


Expand Down
2 changes: 2 additions & 0 deletions custom_components/hive/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
6 changes: 6 additions & 0 deletions custom_components/hive/icons.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
}
}
2 changes: 1 addition & 1 deletion custom_components/hive/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Loading