diff --git a/README.md b/README.md index 083646c..4564ab7 100644 --- a/README.md +++ b/README.md @@ -12,8 +12,8 @@ | Platform | Entities created for each generator | | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, `missed_exercise` | +| `button` | `reset_service_timer`, `boost_polling` | | `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `hours_until_service` | -| `button` | `reset_service_timer` | | Platform | Entities created for each propane tank monitor | | --------------- | ------------------------------------------------------------------------------------------------------------------------------ | @@ -66,6 +66,20 @@ Click this button to skip steps 1 and 2 below: [![Open your Home Assistant insta ## Configuration is done in the UI +### Adaptive Polling & Outage Boost + +To stay gentle on Generac's rate-limited cloud API during normal standby while reacting quickly during exercises, outages, and warnings, polling adapts automatically between two configurable intervals (both clamped to at least `10` seconds): + +- **Idle polling interval (`scan_interval`)**: Default `900` seconds (15 minutes). Used when all devices are idle/ready. +- **Active polling interval (`active_scan_interval`)**: Default `120` seconds (2 minutes), capped at `min(scan_interval, active_scan_interval)` so fast polling never slows down a shorter idle interval. + +Fast polling activates automatically whenever any generator is **Running**, **Exercising**, **Warning**, or **Stopped**, or when any device reports `isConnecting`, `showWarning`, or `isRunning`. After the fleet returns to idle, fast polling remains active for a `300`-second (5-minute) cooldown before returning to the idle interval. + +You can also trigger fast polling manually (for example, from an automation triggered by a utility power-loss sensor) using either: + +- **Outage Boost Poll button (`button._outage_boost_poll`)**: Created for each generator; pressing it immediately refreshes data and enables boost polling for `30` minutes. +- **`generac.boost_polling` action (service)**: Switches loaded entries into boost polling and triggers an immediate refresh. Accepts optional `duration_minutes` (`1`–`120`, default `30`) and optional `entry_id` (targets all loaded Generac entries if omitted). + ### Readiness Tracking, Maintenance Timer & Repairs Alerts Each generator automatically tracks exercise activity and maintenance runtime baselines using Home Assistant storage (persisting cleanly across restarts without reloading the integration): diff --git a/custom_components/generac/__init__.py b/custom_components/generac/__init__.py index 0cb4d55..7edec35 100644 --- a/custom_components/generac/__init__.py +++ b/custom_components/generac/__init__.py @@ -7,8 +7,10 @@ import logging import time +import voluptuous as vol from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant +from homeassistant.core import ServiceCall from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.exceptions import ConfigEntryNotReady @@ -22,8 +24,10 @@ from .const import CONF_REFRESH_TOKEN from .const import CONF_TOKEN_ISSUED_AT from .const import CONF_USERNAME +from .const import DEFAULT_BOOST_DURATION_MINUTES from .const import DOMAIN from .const import PLATFORMS +from .const import SERVICE_BOOST_POLLING from .const import STARTUP_MESSAGE from .coordinator import GeneracDataUpdateCoordinator from .issues import async_delete_all_entry_issues @@ -36,6 +40,50 @@ # Keys rewritten in-place during background token rotation / auto-relogin. _TOKEN_KEYS = frozenset({CONF_REFRESH_TOKEN, CONF_DPOP_PEM, CONF_TOKEN_ISSUED_AT}) +BOOST_POLLING_SCHEMA = vol.Schema( + { + vol.Optional( + "duration_minutes", default=DEFAULT_BOOST_DURATION_MINUTES + ): vol.All(vol.Coerce(int), vol.Range(min=1, max=120)), + vol.Optional("entry_id"): str, + } +) + + +def _matching_coordinators( + hass: HomeAssistant, entry_id: str | None +) -> list[GeneracDataUpdateCoordinator]: + """Return loaded coordinators matching an optional config entry ID.""" + domain_data = hass.data.get(DOMAIN, {}) + coordinators: list[GeneracDataUpdateCoordinator] = [] + for key, value in domain_data.items(): + if not isinstance(value, GeneracDataUpdateCoordinator): + continue + if entry_id is None: + coordinators.append(value) + continue + coord_entry_id = getattr(value._config_entry, "entry_id", None) + if key == entry_id or ( + isinstance(coord_entry_id, str) and coord_entry_id == entry_id + ): + coordinators.append(value) + return coordinators + + +async def _async_handle_boost_polling(call: ServiceCall) -> None: + """Handle the generac.boost_polling service call.""" + duration_minutes: int = call.data["duration_minutes"] + entry_id: str | None = call.data.get("entry_id") + coordinators = _matching_coordinators(call.hass, entry_id) + if entry_id is not None and not coordinators: + _LOGGER.warning( + "No loaded Generac config entry found for entry_id=%s", entry_id + ) + return + duration_seconds = duration_minutes * 60 + for coordinator in coordinators: + await coordinator.async_trigger_boost(duration_seconds) + def _reload_signature(entry: ConfigEntry) -> tuple[dict, dict]: """Snapshot of entry options and non-token data that require a reload on change.""" @@ -130,6 +178,13 @@ async def _persist_relogin(fresh: GeneracAuth) -> None: await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) coordinator.reload_signature = _reload_signature(entry) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) + if not hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING): + hass.services.async_register( + DOMAIN, + SERVICE_BOOST_POLLING, + _async_handle_boost_polling, + schema=BOOST_POLLING_SCHEMA, + ) return True @@ -140,6 +195,11 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: # Defensive default: if a previous reload already popped the # coordinator (e.g. mid-reconfigure race), don't KeyError. hass.data[DOMAIN].pop(entry.entry_id, None) + if not any( + isinstance(v, GeneracDataUpdateCoordinator) + for v in hass.data.get(DOMAIN, {}).values() + ) and hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING): + hass.services.async_remove(DOMAIN, SERVICE_BOOST_POLLING) return unloaded diff --git a/custom_components/generac/button.py b/custom_components/generac/button.py index c9afcb6..db4ff71 100644 --- a/custom_components/generac/button.py +++ b/custom_components/generac/button.py @@ -25,6 +25,7 @@ async def async_setup_entry( async_add_entities( btn(coordinator, entry, device_id, item) for device_id, item in data.items() + if isinstance(item, Item) for btn in buttons(item) ) @@ -32,7 +33,7 @@ async def async_setup_entry( def buttons(item: Item) -> list[Type[GeneracEntity]]: """Return button entity classes applicable to an item.""" if item.apparatus.type == DEVICE_TYPE_GENERATOR: - return [ResetServiceTimerButton] + return [ResetServiceTimerButton, OutageBoostButton] return [] @@ -49,3 +50,15 @@ async def async_press(self) -> None: await self.coordinator.async_reset_service_timer(self.device_id) if self.hass is not None and self.entity_id is not None: self.async_write_ha_state() + + +class OutageBoostButton(GeneracEntity, ButtonEntity): + """Button entity to manually trigger outage boost polling.""" + + entity_key = "boost_polling" + entity_label = "Outage Boost Poll" + _attr_icon = "mdi:lightning-bolt-circle" + + async def async_press(self) -> None: + """Handle the button press.""" + await self.coordinator.async_trigger_boost() diff --git a/custom_components/generac/config_flow.py b/custom_components/generac/config_flow.py index c1a19fa..31d634f 100644 --- a/custom_components/generac/config_flow.py +++ b/custom_components/generac/config_flow.py @@ -36,6 +36,7 @@ from .auth import InvalidMfaCodeError from .auth import MfaRequiredError from .auth import MfaUnsupportedError +from .const import CONF_ACTIVE_SCAN_INTERVAL from .const import CONF_DPOP_PEM from .const import CONF_EXERCISE_INTERVAL_DAYS from .const import CONF_MFA_CODE @@ -47,6 +48,7 @@ from .const import CONF_SERVICE_INTERVAL_HOURS from .const import CONF_TOKEN_ISSUED_AT from .const import CONF_USERNAME +from .const import DEFAULT_ACTIVE_SCAN_INTERVAL from .const import DEFAULT_SCAN_INTERVAL from .const import DOMAIN from .utils import async_client_session @@ -98,6 +100,7 @@ def __init__(self): self._mfa_origin: str | None = None self._pending_email: str | None = None self._pending_scan_interval: int | None = None + self._pending_active_scan_interval: int | None = None @staticmethod def _entry_data(auth: GeneracAuth, email: str, password: str | None) -> dict: @@ -227,6 +230,9 @@ async def async_step_reconfigure(self, user_input=None): email = user_input[CONF_USERNAME].strip() password = user_input[CONF_PASSWORD] scan_interval = user_input.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) + active_scan_interval = user_input.get( + CONF_ACTIVE_SCAN_INTERVAL, DEFAULT_ACTIVE_SCAN_INTERVAL + ) remember = user_input.get(CONF_REMEMBER_PASSWORD, False) try: @@ -236,10 +242,12 @@ async def async_step_reconfigure(self, user_input=None): self._mfa_origin = "reconfigure" self._pending_email = email self._pending_scan_interval = int(scan_interval) + self._pending_active_scan_interval = int(active_scan_interval) return await self.async_step_mfa() if error is None: self._pending_scan_interval = int(scan_interval) + self._pending_active_scan_interval = int(active_scan_interval) return await self._finish_reconfigure(entry_data) errors["base"] = error @@ -249,6 +257,13 @@ async def async_step_reconfigure(self, user_input=None): if entry else DEFAULT_SCAN_INTERVAL ) + default_active_scan_interval = ( + entry_options(entry).get( + CONF_ACTIVE_SCAN_INTERVAL, DEFAULT_ACTIVE_SCAN_INTERVAL + ) + if entry + else DEFAULT_ACTIVE_SCAN_INTERVAL + ) return self.async_show_form( step_id="reconfigure", data_schema=vol.Schema( @@ -258,6 +273,9 @@ async def async_step_reconfigure(self, user_input=None): vol.Required( CONF_SCAN_INTERVAL, default=default_scan_interval ): int, + vol.Required( + CONF_ACTIVE_SCAN_INTERVAL, default=default_active_scan_interval + ): int, vol.Optional( CONF_REMEMBER_PASSWORD, default=bool(entry and entry.data.get(CONF_PASSWORD)), @@ -268,7 +286,7 @@ async def async_step_reconfigure(self, user_input=None): ) async def _finish_reconfigure(self, entry_data: dict): - """Terminal action for a reconfigure: persist creds + scan interval.""" + """Terminal action for a reconfigure: persist creds + scan intervals.""" # Re-fetch the entry at finish time rather than caching it across the # (possible) MFA round-trip — the registry can change underneath us. entry = self.hass.config_entries.async_get_entry(self.context["entry_id"]) @@ -277,11 +295,12 @@ async def _finish_reconfigure(self, entry_data: dict): # MFA form). Nothing left to update — abort cleanly instead of # dereferencing None. return self.async_abort(reason="entry_not_found") - # Persist polling interval into entry.options so the coordinator - # picks it up the same way the OptionsFlow does. + # Persist polling intervals into entry.options so the coordinator + # picks them up the same way the OptionsFlow does. new_options = { **entry_options(entry), CONF_SCAN_INTERVAL: int(self._pending_scan_interval), + CONF_ACTIVE_SCAN_INTERVAL: int(self._pending_active_scan_interval), } # Update the stored data/options. When the entry is already loaded the # update listener registered in async_setup_entry reloads it exactly diff --git a/custom_components/generac/const.py b/custom_components/generac/const.py index 47f99cb..ade7ce3 100644 --- a/custom_components/generac/const.py +++ b/custom_components/generac/const.py @@ -31,6 +31,10 @@ # faster than this provides little benefit and risks hitting their # throttles. DEFAULT_SCAN_INTERVAL = 900 +DEFAULT_ACTIVE_SCAN_INTERVAL = 120 +ACTIVE_COOLDOWN_SECONDS = 300 +DEFAULT_BOOST_DURATION_MINUTES = 30 +SERVICE_BOOST_POLLING = "boost_polling" # Platforms BINARY_SENSOR = "binary_sensor" @@ -60,6 +64,7 @@ CONF_REFRESH_TOKEN = "refresh_token" CONF_DPOP_PEM = "dpop_pem" CONF_SCAN_INTERVAL = "scan_interval" +CONF_ACTIVE_SCAN_INTERVAL = "active_scan_interval" CONF_SERVICE_INTERVAL_HOURS = "service_interval_hours" CONF_EXERCISE_INTERVAL_DAYS = "exercise_interval_days" CONF_LOW_BATTERY_THRESHOLD = "low_battery_threshold" @@ -84,6 +89,7 @@ CONF_OPTIONS = { **bool_opts, CONF_SCAN_INTERVAL: {"type": int, "default": DEFAULT_SCAN_INTERVAL}, + CONF_ACTIVE_SCAN_INTERVAL: {"type": int, "default": DEFAULT_ACTIVE_SCAN_INTERVAL}, CONF_SERVICE_INTERVAL_HOURS: { "type": int, "default": DEFAULT_SERVICE_INTERVAL_HOURS, diff --git a/custom_components/generac/coordinator.py b/custom_components/generac/coordinator.py index 94e4639..a2e92d8 100644 --- a/custom_components/generac/coordinator.py +++ b/custom_components/generac/coordinator.py @@ -2,6 +2,8 @@ from __future__ import annotations import logging +import time +from collections.abc import Mapping from datetime import timedelta from homeassistant.config_entries import ConfigEntry @@ -14,8 +16,13 @@ from .api import InvalidCredentialsException from .api import SessionExpiredException from .auth import InvalidGrantError +from .const import ACTIVE_COOLDOWN_SECONDS +from .const import CONF_ACTIVE_SCAN_INTERVAL from .const import CONF_SCAN_INTERVAL +from .const import DEFAULT_ACTIVE_SCAN_INTERVAL +from .const import DEFAULT_BOOST_DURATION_MINUTES from .const import DEFAULT_SCAN_INTERVAL +from .const import DEVICE_TYPE_GENERATOR from .const import DOMAIN from .issues import async_update_device_health_issues from .issues import async_update_token_expiry_issue @@ -26,6 +33,40 @@ _LOGGER: logging.Logger = logging.getLogger(__package__) +_ACTIVE_GENERATOR_STATUSES = frozenset({2, 3, 4, 5}) +_MIN_SCAN_INTERVAL_SECONDS = 10 + + +def _read_interval(options: Mapping, key: str, default: int) -> int: + """Read an integer polling interval from options and clamp to >= 10 s.""" + raw = options.get(key, default) + if raw is None: + raw = default + return max(_MIN_SCAN_INTERVAL_SECONDS, int(raw)) + + +def _is_fleet_active(items: dict[str, Item] | None) -> bool: + """Return True if any device is running, exercising, warning, or connecting.""" + if not isinstance(items, dict): + return False + for item in items.values(): + if not isinstance(item, Item): + continue + if ( + item.apparatus.type == DEVICE_TYPE_GENERATOR + and item.apparatusDetail.apparatusStatus in _ACTIVE_GENERATOR_STATUSES + ): + return True + if ( + item.apparatusDetail.isConnecting is True + or item.apparatusDetail.showWarning is True + ): + return True + for prop in item.apparatus.properties or []: + if getattr(prop.value, "isRunning", False) is True: + return True + return False + class GeneracDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Item]]): """Class to manage fetching data from the API.""" @@ -42,16 +83,21 @@ def __init__( self.persisted_credentials: tuple[str | None, str | None] | None = None self.pending_credential_updates: int = 0 self.readiness = ReadinessTracker(hass, config_entry) - scan_interval = timedelta( - seconds=entry_options(config_entry).get( - CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL - ) + options = entry_options(config_entry) + self.idle_scan_interval = _read_interval( + options, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL ) + self.active_scan_interval = _read_interval( + options, CONF_ACTIVE_SCAN_INTERVAL, DEFAULT_ACTIVE_SCAN_INTERVAL + ) + self._cooldown_until: float = 0.0 + self._boost_until: float = 0.0 + self._fleet_active: bool = False super().__init__( hass, _LOGGER, name=DOMAIN, - update_interval=scan_interval, + update_interval=timedelta(seconds=self.idle_scan_interval), config_entry=config_entry, ) @@ -79,6 +125,53 @@ async def async_reset_service_timer(self, device_id: str) -> None: ) self.async_update_listeners() + @property + def fast_scan_interval(self) -> int: + """Return the effective fast polling interval in seconds.""" + return min(self.idle_scan_interval, self.active_scan_interval) + + def _compute_polling_mode(self, now: float, fleet_active: bool) -> str: + """Compute the polling mode for a point in time and fleet state.""" + if now < self._boost_until: + return "boost" + if fleet_active: + return "active" + if now < self._cooldown_until: + return "cooldown" + return "idle" + + @property + def polling_mode(self) -> str: + """Return the current adaptive polling mode.""" + return self._compute_polling_mode(time.monotonic(), self._fleet_active) + + @property + def is_fast_polling(self) -> bool: + """Return True when adaptive polling is faster than the idle interval.""" + return self.polling_mode != "idle" + + def _apply_polling_interval(self, mode: str) -> None: + """Update update_interval to match the given adaptive polling mode.""" + target_seconds = ( + self.idle_scan_interval if mode == "idle" else self.fast_scan_interval + ) + target_interval = timedelta(seconds=target_seconds) + if self.update_interval != target_interval: + _LOGGER.debug( + "Adaptive polling switching to %s mode (%s s)", + mode, + target_seconds, + ) + self.update_interval = target_interval + + async def async_trigger_boost( + self, duration_seconds: int = DEFAULT_BOOST_DURATION_MINUTES * 60 + ) -> None: + """Switch to fast boost polling and immediately request a refresh.""" + self._boost_until = max(self._boost_until, time.monotonic() + duration_seconds) + self._apply_polling_interval("boost") + await self.async_request_refresh() + async def _async_update_data(self): """Update data via library.""" try: @@ -86,6 +179,13 @@ async def _async_update_data(self): items = await self.api.async_get_data() self.is_online = items is not None _LOGGER.info("Generac poll OK: %d device(s)", len(items) if items else 0) + now = time.monotonic() + fleet_active = _is_fleet_active(items) + self._fleet_active = fleet_active + if fleet_active: + self._cooldown_until = now + ACTIVE_COOLDOWN_SECONDS + mode = self._compute_polling_mode(now, fleet_active) + self._apply_polling_interval(mode) await self.readiness.async_load() if isinstance(items, dict): await self.readiness.async_update_from_items(items) diff --git a/custom_components/generac/services.yaml b/custom_components/generac/services.yaml new file mode 100644 index 0000000..4b81278 --- /dev/null +++ b/custom_components/generac/services.yaml @@ -0,0 +1,17 @@ +boost_polling: + fields: + duration_minutes: + required: false + default: 30 + example: 30 + selector: + number: + min: 1 + max: 120 + unit_of_measurement: min + mode: box + entry_id: + required: false + selector: + config_entry: + integration: generac diff --git a/custom_components/generac/translations/en.json b/custom_components/generac/translations/en.json index ed0f0cc..fe41859 100644 --- a/custom_components/generac/translations/en.json +++ b/custom_components/generac/translations/en.json @@ -20,9 +20,12 @@ "username": "Email", "password": "Password", "scan_interval": "Cloud polling interval (seconds)", + "active_scan_interval": "Active polling interval (seconds)", "remember_password": "Remember password" }, "data_description": { + "scan_interval": "Idle cloud polling interval when all devices are ready (minimum 10 seconds).", + "active_scan_interval": "Fast polling interval used while a generator is running, exercising, warning, connecting, or boosted (minimum 10 seconds).", "remember_password": "Generac sessions expire about every 90 days. If enabled, the password is stored in Home Assistant so the integration can sign in again on its own. Not used for accounts that require a verification code." } }, @@ -71,6 +74,7 @@ "step": { "user": { "data": { + "active_scan_interval": "Active polling interval (seconds)", "binary_sensor": "Binary sensors enabled", "button": "Buttons enabled", "exercise_interval_days": "Missed exercise alert interval (days, 0 to disable)", @@ -81,6 +85,26 @@ "service_interval_hours": "Maintenance service interval (hours, 0 to disable)", "switch": "Switch enabled", "weather": "Weather sensor enabled" + }, + "data_description": { + "scan_interval": "Idle cloud polling interval when all devices are ready (minimum 10 seconds).", + "active_scan_interval": "Fast polling interval used while a generator is running, exercising, warning, connecting, or boosted (minimum 10 seconds)." + } + } + } + }, + "services": { + "boost_polling": { + "name": "Boost polling", + "description": "Temporarily switch Generac cloud polling to the active polling interval and refresh immediately.", + "fields": { + "duration_minutes": { + "name": "Duration", + "description": "How long to maintain fast boost polling, in minutes (1 to 120)." + }, + "entry_id": { + "name": "Config entry", + "description": "Optional Generac config entry to boost. If omitted, all loaded Generac entries are boosted." } } } diff --git a/custom_components/generac/translations/fr.json b/custom_components/generac/translations/fr.json index f42ff9b..4f731d8 100644 --- a/custom_components/generac/translations/fr.json +++ b/custom_components/generac/translations/fr.json @@ -15,7 +15,8 @@ "data": { "username": "E-mail", "password": "Mot de passe", - "scan_interval": "Intervalle d'interrogation du cloud (secondes)" + "scan_interval": "Intervalle d'interrogation du cloud (secondes)", + "active_scan_interval": "Intervalle d'interrogation actif (secondes)" } }, "reauth_confirm": { @@ -59,6 +60,7 @@ "step": { "user": { "data": { + "active_scan_interval": "Intervalle d’interrogation actif en secondes", "binary_sensor": "Capteur binaire activé", "button": "Boutons activés", "exercise_interval_days": "Intervalle d’alerte d’exercice manqué (jours, 0 pour désactiver)", diff --git a/custom_components/generac/translations/nb.json b/custom_components/generac/translations/nb.json index 7ac378c..e230c4a 100644 --- a/custom_components/generac/translations/nb.json +++ b/custom_components/generac/translations/nb.json @@ -15,7 +15,8 @@ "data": { "username": "E-post", "password": "Passord", - "scan_interval": "Intervall for skyavstemning (sekunder)" + "scan_interval": "Intervall for skyavstemning (sekunder)", + "active_scan_interval": "Aktivt avstemningsintervall (sekunder)" } }, "reauth_confirm": { @@ -59,6 +60,7 @@ "step": { "user": { "data": { + "active_scan_interval": "Aktivt avstemningsintervall i sekunder", "binary_sensor": "Binær sensor aktivert", "button": "Knapper aktivert", "exercise_interval_days": "Varselintervall for uteblitt testkjøring (dager, 0 for å deaktivere)", diff --git a/custom_components/generac/translations/pt.json b/custom_components/generac/translations/pt.json index 9028420..d5c6c9b 100644 --- a/custom_components/generac/translations/pt.json +++ b/custom_components/generac/translations/pt.json @@ -15,7 +15,8 @@ "data": { "username": "Email", "password": "Palavra-passe", - "scan_interval": "Intervalo de sondagem à cloud (segundos)" + "scan_interval": "Intervalo de sondagem à cloud (segundos)", + "active_scan_interval": "Intervalo de sondagem ativo (segundos)" } }, "reauth_confirm": { @@ -59,6 +60,7 @@ "step": { "user": { "data": { + "active_scan_interval": "Intervalo de sondagem ativo (segundos)", "binary_sensor": "Sensores binários ativados", "button": "Botões ativados", "exercise_interval_days": "Intervalo de alerta de exercício em falta (dias, 0 para desativar)", diff --git a/tests/test_button.py b/tests/test_button.py index 7400bb2..861831f 100644 --- a/tests/test_button.py +++ b/tests/test_button.py @@ -1,10 +1,12 @@ -"""Tests for the Generac button platform and service reset flow.""" +"""Tests for the Generac button platform, service reset flow, and boost trigger.""" from unittest.mock import AsyncMock from unittest.mock import MagicMock from unittest.mock import patch +from custom_components.generac import button as button_platform from custom_components.generac.auth import DPoPKey from custom_components.generac.button import buttons +from custom_components.generac.button import OutageBoostButton from custom_components.generac.button import ResetServiceTimerButton from custom_components.generac.const import CONF_DPOP_PEM from custom_components.generac.const import CONF_REFRESH_TOKEN @@ -13,6 +15,7 @@ from custom_components.generac.const import DEVICE_TYPE_GENERATOR from custom_components.generac.const import DEVICE_TYPE_PROPANE_MONITOR from custom_components.generac.const import DOMAIN +from custom_components.generac.coordinator import GeneracDataUpdateCoordinator from custom_components.generac.models import Apparatus from custom_components.generac.models import ApparatusDetail from custom_components.generac.models import Item @@ -41,10 +44,10 @@ def _make_item(device_type: int, run_time: float = 100.0) -> Item: def test_button_selection() -> None: - """ResetServiceTimerButton is registered only for generators.""" + """Button entities are registered only for generators.""" gen = _make_item(DEVICE_TYPE_GENERATOR) propane = _make_item(DEVICE_TYPE_PROPANE_MONITOR) - assert buttons(gen) == [ResetServiceTimerButton] + assert buttons(gen) == [ResetServiceTimerButton, OutageBoostButton] assert buttons(propane) == [] @@ -67,6 +70,48 @@ async def test_reset_service_timer_button_unit() -> None: coordinator.async_reset_service_timer.assert_awaited_once_with("12345") +async def test_outage_boost_button_metadata_and_press(hass: HomeAssistant) -> None: + """OutageBoostButton exposes expected attributes and triggers boost on press.""" + coordinator = MagicMock() + coordinator.async_trigger_boost = AsyncMock() + entry = MagicMock() + entry.entry_id = "entry1" + item = _make_item(DEVICE_TYPE_GENERATOR) + + btn = OutageBoostButton(coordinator, entry, "12345", item) + assert btn.entity_key == "boost_polling" + assert btn.name == "Outage Boost Poll" + assert btn.icon == "mdi:lightning-bolt-circle" + assert btn.unique_id == "entry1_12345_generac_12345_boost_polling" + + await btn.async_press() + coordinator.async_trigger_boost.assert_awaited_once_with() + + +async def test_button_setup_creates_only_generator_entities( + hass: HomeAssistant, +) -> None: + """Button setup creates generator buttons only for generators.""" + coordinator = MagicMock() + coordinator.data = { + "gen1": _make_item(DEVICE_TYPE_GENERATOR), + "tank1": _make_item(DEVICE_TYPE_PROPANE_MONITOR), + } + entry = MagicMock() + entry.entry_id = "entry1" + hass.data[DOMAIN] = {"entry1": coordinator} + + added: list = [] + await button_platform.async_setup_entry(hass, entry, added.extend) + assert [type(b) for b in added] == [ResetServiceTimerButton, OutageBoostButton] + assert all(b.device_id == "gen1" for b in added) + + coordinator.data = None + added_empty: list = [] + await button_platform.async_setup_entry(hass, entry, added_empty.extend) + assert added_empty == [] + + async def test_reset_service_timer_button_end_to_end(hass: HomeAssistant) -> None: """Pressing the button resets hours_until_service, clears Repairs issue, and persists without reloading.""" entry = MockConfigEntry( @@ -140,3 +185,39 @@ async def test_reset_service_timer_button_end_to_end(hass: HomeAssistant) -> Non coordinator.readiness.get_device_state("12345")["service_baseline_hours"] == 155.0 ) + + +async def test_button_press_service_triggers_boost(hass: HomeAssistant) -> None: + """Pressing the registered Outage Boost Poll entity via HA invokes async_trigger_boost.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="entry1", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + ) + entry.add_to_hass(hass) + + data = {"12345": _make_item(DEVICE_TYPE_GENERATOR)} + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + return_value=data, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + with patch.object( + GeneracDataUpdateCoordinator, + "async_trigger_boost", + new_callable=AsyncMock, + ) as mock_boost: + await hass.services.async_call( + "button", + "press", + {"entity_id": "button.generator_outage_boost_poll"}, + blocking=True, + ) + + mock_boost.assert_awaited_once_with() diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index af21753..17d9a21 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -7,6 +7,7 @@ from custom_components.generac.auth import DPoPKey from custom_components.generac.auth import InvalidCredentialsError from custom_components.generac.auth import MfaRequiredError +from custom_components.generac.const import CONF_ACTIVE_SCAN_INTERVAL from custom_components.generac.const import CONF_DPOP_PEM from custom_components.generac.const import CONF_PASSWORD from custom_components.generac.const import CONF_REFRESH_TOKEN @@ -14,6 +15,7 @@ from custom_components.generac.const import CONF_SCAN_INTERVAL from custom_components.generac.const import CONF_TOKEN_ISSUED_AT from custom_components.generac.const import CONF_USERNAME +from custom_components.generac.const import DEFAULT_ACTIVE_SCAN_INTERVAL from custom_components.generac.const import DOMAIN from homeassistant import config_entries from homeassistant import setup @@ -146,6 +148,7 @@ async def test_options_flow(hass: HomeAssistant) -> None: "image": True, "button": True, "scan_interval": 120, + "active_scan_interval": 120, "service_interval_hours": 100, "exercise_interval_days": 16, "low_battery_threshold": 12.2, @@ -161,7 +164,8 @@ async def test_options_flow(hass: HomeAssistant) -> None: assert result["step_id"] == "user" result = await hass.config_entries.options.async_configure( - result["flow_id"], user_input={"binary_sensor": False} + result["flow_id"], + user_input={"binary_sensor": False, "active_scan_interval": 60}, ) assert result["type"] == "create_entry" @@ -172,6 +176,7 @@ async def test_options_flow(hass: HomeAssistant) -> None: "image": True, "button": True, "scan_interval": 120, + "active_scan_interval": 60, "service_interval_hours": 100, "exercise_interval_days": 16, "low_battery_threshold": 12.2, @@ -734,7 +739,10 @@ async def test_reconfigure_unchanged_options_reloads_loaded_entry( CONF_REFRESH_TOKEN: "old-rt", CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), }, - options={CONF_SCAN_INTERVAL: 900}, + options={ + CONF_SCAN_INTERVAL: 900, + CONF_ACTIVE_SCAN_INTERVAL: DEFAULT_ACTIVE_SCAN_INTERVAL, + }, ) entry.add_to_hass(hass) @@ -760,6 +768,7 @@ async def test_reconfigure_unchanged_options_reloads_loaded_entry( CONF_USERNAME: "user@example.com", CONF_PASSWORD: "new-pw", CONF_SCAN_INTERVAL: 900, + CONF_ACTIVE_SCAN_INTERVAL: DEFAULT_ACTIVE_SCAN_INTERVAL, CONF_REMEMBER_PASSWORD: False, }, ) @@ -771,3 +780,112 @@ async def test_reconfigure_unchanged_options_reloads_loaded_entry( assert new_coordinator is not old_coordinator assert new_coordinator.api._auth.refresh_token == "new-rt" assert new_coordinator.api._auth.pem_str == new_auth.pem_str + + +async def test_reconfigure_persists_active_scan_interval_with_mfa( + hass: HomeAssistant, +) -> None: + """Reconfigure preserves both scan_interval and active_scan_interval across MFA.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "old-rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + options={}, + ) + entry.add_to_hass(hass) + + with patch("custom_components.generac.async_setup_entry", return_value=True): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": "reconfigure", "entry_id": entry.entry_id}, + ) + login_flow = MagicMock() + login_flow.mfa_type = "otp" + login_flow.submit_mfa_code = AsyncMock( + return_value=_mock_auth(refresh_token="mfa-rt") + ) + + with patch( + "custom_components.generac.config_flow.GeneracAuth.login", + AsyncMock( + side_effect=MfaRequiredError(login_flow, "otp", "https://x", "state") + ), + ): + result2 = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_USERNAME: "user@example.com", + CONF_PASSWORD: "new-pw", + CONF_SCAN_INTERVAL: 600, + CONF_ACTIVE_SCAN_INTERVAL: 45, + }, + ) + assert result2["type"] == "form" + assert result2["step_id"] == "mfa" + + with patch("custom_components.generac.async_setup_entry", return_value=True), patch( + "custom_components.generac.async_unload_entry", return_value=True + ): + result3 = await hass.config_entries.flow.async_configure( + result2["flow_id"], {"mfa_code": "123456"} + ) + await hass.async_block_till_done() + + assert result3["type"] == "abort" + assert result3["reason"] == "reconfigure_successful" + assert entry.options[CONF_SCAN_INTERVAL] == 600 + assert entry.options[CONF_ACTIVE_SCAN_INTERVAL] == 45 + assert entry.data[CONF_REFRESH_TOKEN] == "mfa-rt" + + +async def test_reconfigure_flow_persists_active_scan_interval( + hass: HomeAssistant, +) -> None: + """Active scan interval supplied during reconfigure ends up in entry.options.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "old-rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + options={}, + ) + entry.add_to_hass(hass) + + with patch("custom_components.generac.async_setup_entry", return_value=True): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": "reconfigure", "entry_id": entry.entry_id}, + ) + assert result["step_id"] == "reconfigure" + + new_auth = _mock_auth(refresh_token="new-rt") + with patch( + "custom_components.generac.config_flow.GeneracAuth.login", + AsyncMock(return_value=new_auth), + ), patch("custom_components.generac.async_setup_entry", return_value=True), patch( + "custom_components.generac.async_unload_entry", return_value=True + ): + await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_USERNAME: "user@example.com", + CONF_PASSWORD: "new-pw", + CONF_SCAN_INTERVAL: 600, + CONF_ACTIVE_SCAN_INTERVAL: 90, + }, + ) + await hass.async_block_till_done() + + assert entry.options.get(CONF_SCAN_INTERVAL) == 600 + assert entry.options.get(CONF_ACTIVE_SCAN_INTERVAL) == 90 diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py index b88c0bb..cc80e36 100644 --- a/tests/test_coordinator.py +++ b/tests/test_coordinator.py @@ -4,6 +4,7 @@ from datetime import timedelta from unittest.mock import AsyncMock from unittest.mock import MagicMock +from unittest.mock import patch import pytest from custom_components.generac.api import GeneracApiClient @@ -11,9 +12,18 @@ from custom_components.generac.auth import DPoPKey from custom_components.generac.auth import GeneracAuth from custom_components.generac.auth import InvalidGrantError +from custom_components.generac.const import ACTIVE_COOLDOWN_SECONDS +from custom_components.generac.const import CONF_ACTIVE_SCAN_INTERVAL from custom_components.generac.const import CONF_SCAN_INTERVAL +from custom_components.generac.const import DEFAULT_ACTIVE_SCAN_INTERVAL from custom_components.generac.const import DEFAULT_SCAN_INTERVAL +from custom_components.generac.const import DEVICE_TYPE_GENERATOR +from custom_components.generac.const import DEVICE_TYPE_PROPANE_MONITOR +from custom_components.generac.coordinator import _is_fleet_active from custom_components.generac.coordinator import GeneracDataUpdateCoordinator +from custom_components.generac.models import Apparatus +from custom_components.generac.models import ApparatusDetail +from custom_components.generac.models import Item from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import UpdateFailed @@ -155,3 +165,169 @@ async def test_api_401_with_revoked_refresh_token_starts_reauth(hass): await coordinator._async_update_data() assert not coordinator.is_online session.post.assert_called_once() + + +def _item( + device_type: int = DEVICE_TYPE_GENERATOR, + status: int = 1, + is_connecting: bool = False, + show_warning: bool = False, + is_running_prop: bool = False, +) -> Item: + props = ( + [ + Apparatus.Property(name="ignored", value=[], type=1), + Apparatus.Property( + name="status", + value=Apparatus.Property.Value( + type=3, + status=None, + isLegacy=None, + isRunning=is_running_prop, + deviceId=None, + deviceType=None, + signalStrength=None, + batteryLevel=None, + ), + type=3, + ), + ] + if is_running_prop + else None + ) + return Item( + apparatus=Apparatus(type=device_type, properties=props), + apparatusDetail=ApparatusDetail( + apparatusStatus=status, + isConnecting=is_connecting, + showWarning=show_warning, + ), + ) + + +async def test_coordinator_clamps_intervals_and_tolerates_mock_options(hass): + """Intervals clamp >= 10, fast interval uses min(idle, active), non-Mapping options ignored.""" + mock_entry = MagicMock() + coord_mock = GeneracDataUpdateCoordinator(hass, MagicMock(), mock_entry) + assert coord_mock.idle_scan_interval == DEFAULT_SCAN_INTERVAL + assert coord_mock.active_scan_interval == DEFAULT_ACTIVE_SCAN_INTERVAL + assert coord_mock.fast_scan_interval == DEFAULT_ACTIVE_SCAN_INTERVAL + + entry_clamped = MagicMock() + entry_clamped.options = {CONF_SCAN_INTERVAL: 5, CONF_ACTIVE_SCAN_INTERVAL: None} + coord_clamped = GeneracDataUpdateCoordinator(hass, MagicMock(), entry_clamped) + assert coord_clamped.idle_scan_interval == 10 + assert coord_clamped.active_scan_interval == DEFAULT_ACTIVE_SCAN_INTERVAL + assert coord_clamped.fast_scan_interval == 10 + assert coord_clamped.update_interval == timedelta(seconds=10) + + entry_short = MagicMock() + entry_short.options = {CONF_SCAN_INTERVAL: 60, CONF_ACTIVE_SCAN_INTERVAL: 120} + coord_short = GeneracDataUpdateCoordinator(hass, MagicMock(), entry_short) + assert coord_short.idle_scan_interval == 60 + assert coord_short.active_scan_interval == 120 + assert coord_short.fast_scan_interval == 60 + + +def test_is_fleet_active_variants(): + """Verify _is_fleet_active across device types, statuses, flags, and malformed inputs.""" + assert _is_fleet_active(None) is False + assert _is_fleet_active({"foo": "bar"}) is False + assert _is_fleet_active({"g": _item(DEVICE_TYPE_GENERATOR, status=1)}) is False + for active_status in (2, 3, 4, 5): + assert ( + _is_fleet_active({"g": _item(DEVICE_TYPE_GENERATOR, status=active_status)}) + is True + ) + assert ( + _is_fleet_active({"p": _item(DEVICE_TYPE_PROPANE_MONITOR, status=2)}) is False + ) + assert _is_fleet_active({"g": _item(is_connecting=True)}) is True + assert _is_fleet_active({"g": _item(show_warning=True)}) is True + assert _is_fleet_active({"g": _item(is_running_prop=True)}) is True + + +async def test_coordinator_adaptive_polling_transitions(hass): + """Coordinator transitions idle -> active -> cooldown -> idle with dynamic update_interval.""" + entry = MagicMock() + entry.options = {CONF_SCAN_INTERVAL: 900, CONF_ACTIVE_SCAN_INTERVAL: 120} + client = MagicMock() + coordinator = GeneracDataUpdateCoordinator(hass, client, entry) + + clock = {"now": 1000.0} + with patch( + "custom_components.generac.coordinator.time.monotonic", + side_effect=lambda: clock["now"], + ): + assert coordinator.polling_mode == "idle" + assert coordinator.is_fast_polling is False + assert coordinator.update_interval == timedelta(seconds=900) + + # Idle poll keeps idle interval. + client.async_get_data = AsyncMock(return_value={"g": _item(status=1)}) + await coordinator._async_update_data() + assert coordinator.polling_mode == "idle" + assert coordinator.is_fast_polling is False + assert coordinator.update_interval == timedelta(seconds=900) + + # Active generator switches immediately to fast interval and sets cooldown. + clock["now"] = 1010.0 + client.async_get_data = AsyncMock(return_value={"g": _item(status=2)}) + await coordinator._async_update_data() + assert coordinator.polling_mode == "active" + assert coordinator.is_fast_polling is True + assert coordinator.update_interval == timedelta(seconds=120) + + # Returning to Ready stays in cooldown (fast) until ACTIVE_COOLDOWN_SECONDS elapse. + clock["now"] = 1010.0 + ACTIVE_COOLDOWN_SECONDS - 10 + client.async_get_data = AsyncMock(return_value={"g": _item(status=1)}) + await coordinator._async_update_data() + assert coordinator.polling_mode == "cooldown" + assert coordinator.is_fast_polling is True + assert coordinator.update_interval == timedelta(seconds=120) + + # After cooldown expires, polling returns to idle interval. + clock["now"] = 1010.0 + ACTIVE_COOLDOWN_SECONDS + await coordinator._async_update_data() + assert coordinator.polling_mode == "idle" + assert coordinator.is_fast_polling is False + assert coordinator.update_interval == timedelta(seconds=900) + + +async def test_coordinator_boost_polling_lifecycle(hass): + """async_trigger_boost switches to fast interval, refreshes, and respects max duration.""" + entry = MagicMock() + entry.options = {CONF_SCAN_INTERVAL: 900, CONF_ACTIVE_SCAN_INTERVAL: 90} + client = MagicMock() + client.async_get_data = AsyncMock(return_value={"g": _item(status=1)}) + coordinator = GeneracDataUpdateCoordinator(hass, client, entry) + coordinator.async_request_refresh = AsyncMock() + + clock = {"now": 2000.0} + with patch( + "custom_components.generac.coordinator.time.monotonic", + side_effect=lambda: clock["now"], + ): + await coordinator.async_trigger_boost(1800) + assert coordinator.polling_mode == "boost" + assert coordinator.is_fast_polling is True + assert coordinator.update_interval == timedelta(seconds=90) + coordinator.async_request_refresh.assert_awaited_once() + + # Shorter boost does not shorten an active longer boost. + clock["now"] = 2010.0 + await coordinator.async_trigger_boost(60) + assert coordinator._boost_until == 3800.0 + + # Subsequent idle poll while boosted keeps boost mode and fast interval. + clock["now"] = 2100.0 + await coordinator._async_update_data() + assert coordinator.polling_mode == "boost" + assert coordinator.update_interval == timedelta(seconds=90) + + # After boost expires, next idle poll drops back to idle interval. + clock["now"] = 3800.0 + await coordinator._async_update_data() + assert coordinator.polling_mode == "idle" + assert coordinator.is_fast_polling is False + assert coordinator.update_interval == timedelta(seconds=900) diff --git a/tests/test_entity_registry.py b/tests/test_entity_registry.py index fe20c88..7647872 100644 --- a/tests/test_entity_registry.py +++ b/tests/test_entity_registry.py @@ -83,7 +83,7 @@ GENERATOR_ID: { "sensor": ["exercise_minutes", "hours_until_service"], "binary_sensor": ["missed_exercise"], - "button": ["reset_service_timer"], + "button": ["reset_service_timer", "boost_polling"], }, PROPANE_ID: {"sensor": ["signal_strength", "device_battery_level"]}, } @@ -278,6 +278,9 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) _unique_id(GENERATOR_ID, "reset_service_timer"): ( "button.generator_reset_maintenance_timer" ), + _unique_id(GENERATOR_ID, "boost_polling"): ( + "button.generator_outage_boost_poll" + ), _unique_id( PROPANE_ID, "signal_strength" ): "sensor.propane_tank_signal_strength", @@ -291,6 +294,7 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) assert ( hass.states.get("button.generator_reset_maintenance_timer").state == "unknown" ) + assert hass.states.get("button.generator_outage_boost_poll").state == "unknown" assert hass.states.get("sensor.propane_tank_signal_strength").state == "60.0" assert hass.states.get("sensor.propane_tank_device_battery_level").state == "80.0" @@ -311,6 +315,10 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) devices[_unique_id(GENERATOR_ID, "reset_service_timer")] == devices[_unique_id(GENERATOR_ID, "status")] ) + assert ( + devices[_unique_id(GENERATOR_ID, "boost_polling")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) assert ( devices[_unique_id(PROPANE_ID, "device_battery_level")] == devices[_unique_id(PROPANE_ID, "status")] @@ -334,7 +342,7 @@ def test_every_entity_class_declares_its_own_stable_key(): and issubclass(obj, GeneracEntity) and obj is not GeneracEntity ] - assert len(classes) == 37 + assert len(classes) == 38 keys = {} for cls in classes: assert "entity_key" in vars(cls), cls.__name__ diff --git a/tests/test_init.py b/tests/test_init.py index f26160c..98887b8 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -1,7 +1,10 @@ """Test generac setup process.""" +from pathlib import Path +from unittest.mock import AsyncMock from unittest.mock import patch import pytest +import voluptuous as vol from custom_components.generac import async_reload_entry from custom_components.generac import async_setup_entry from custom_components.generac import async_unload_entry @@ -12,11 +15,15 @@ from custom_components.generac.const import CONF_REFRESH_TOKEN from custom_components.generac.const import CONF_TOKEN_ISSUED_AT from custom_components.generac.const import CONF_USERNAME +from custom_components.generac.const import DEFAULT_BOOST_DURATION_MINUTES from custom_components.generac.const import DOMAIN +from custom_components.generac.const import SERVICE_BOOST_POLLING from custom_components.generac.coordinator import GeneracDataUpdateCoordinator from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers import service as ha_service +from homeassistant.util.yaml import load_yaml_dict from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -321,8 +328,6 @@ async def test_setup_entry_installs_bundled_blueprints( hass: HomeAssistant, bypass_get_data ): """Setup copies bundled automation blueprints into HA config blueprints dir.""" - from pathlib import Path - config_entry = MockConfigEntry( domain=DOMAIN, data=_make_mock_config(), entry_id="bp_setup_test" ) @@ -355,3 +360,123 @@ async def test_setup_entry_survives_blueprint_install_oserror( assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.entry_id in hass.data[DOMAIN] + + +async def test_boost_polling_service_registration_targeting_and_unload( + hass: HomeAssistant, bypass_get_data +): + """boost_polling service registers idempotently, targets entries, and unloads cleanly.""" + hass.data[DOMAIN] = {"existing_entry": "data"} + entry1 = MockConfigEntry( + domain=DOMAIN, + data=_make_mock_config(), + entry_id="entry_one", + unique_id="one@example.com", + ) + entry2 = MockConfigEntry( + domain=DOMAIN, + data=_make_mock_config(), + entry_id="entry_two", + unique_id="two@example.com", + ) + entry1.add_to_hass(hass) + + assert await hass.config_entries.async_setup(entry1.entry_id) + assert hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING) + + # Second entry setup on same domain is idempotent. + entry2.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry2.entry_id) + assert hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING) + + coord1 = hass.data[DOMAIN][entry1.entry_id] + coord2 = hass.data[DOMAIN][entry2.entry_id] + + with patch.object( + coord1, "async_trigger_boost", new_callable=AsyncMock + ) as boost1, patch.object( + coord2, "async_trigger_boost", new_callable=AsyncMock + ) as boost2: + # Without entry_id: boosts all loaded coordinators with default duration. + await hass.services.async_call(DOMAIN, SERVICE_BOOST_POLLING, {}, blocking=True) + boost1.assert_awaited_once_with(DEFAULT_BOOST_DURATION_MINUTES * 60) + boost2.assert_awaited_once_with(DEFAULT_BOOST_DURATION_MINUTES * 60) + + boost1.reset_mock() + boost2.reset_mock() + + # With entry_id + duration_minutes: boosts only matching entry. + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_POLLING, + {"entry_id": entry1.entry_id, "duration_minutes": 15}, + blocking=True, + ) + boost1.assert_awaited_once_with(15 * 60) + boost2.assert_not_called() + + boost1.reset_mock() + + # Unknown entry_id: no coordinators boosted and no crash. + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_POLLING, + {"entry_id": "missing_entry"}, + blocking=True, + ) + boost1.assert_not_called() + boost2.assert_not_called() + + # Schema validation rejects out-of-range duration_minutes. + with pytest.raises(vol.Invalid): + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_POLLING, + {"duration_minutes": 0}, + blocking=True, + ) + with pytest.raises(vol.Invalid): + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_POLLING, + {"duration_minutes": 121}, + blocking=True, + ) + + # Unloading one entry keeps the service registered while the other remains. + assert await hass.config_entries.async_unload(entry1.entry_id) + assert hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING) + + # Unloading the last coordinator removes the service despite non-coordinator domain keys. + assert await hass.config_entries.async_unload(entry2.entry_id) + assert not hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING) + assert hass.data[DOMAIN]["existing_entry"] == "data" + + +async def test_services_yaml_schema_and_descriptions( + hass: HomeAssistant, bypass_get_data +): + """services.yaml validates cleanly against Home Assistant's service schema.""" + services_path = ( + Path(__file__).resolve().parents[1] + / "custom_components" + / "generac" + / "services.yaml" + ) + raw = load_yaml_dict(str(services_path)) + parsed = ha_service._SERVICES_SCHEMA(raw) + assert SERVICE_BOOST_POLLING in parsed + assert set(parsed[SERVICE_BOOST_POLLING]["fields"]) == { + "duration_minutes", + "entry_id", + } + + entry = MockConfigEntry(domain=DOMAIN, data=_make_mock_config(), entry_id="test") + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + descriptions = await ha_service.async_get_all_descriptions(hass) + assert SERVICE_BOOST_POLLING in descriptions[DOMAIN] + assert set(descriptions[DOMAIN][SERVICE_BOOST_POLLING]["fields"]) == { + "duration_minutes", + "entry_id", + }