Skip to content
Merged
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
16 changes: 15 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------ |
Expand Down Expand Up @@ -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.<device>_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):
Expand Down
60 changes: 60 additions & 0 deletions custom_components/generac/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand All @@ -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."""
Expand Down Expand Up @@ -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


Expand All @@ -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


Expand Down
15 changes: 14 additions & 1 deletion custom_components/generac/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ 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)
)


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 []


Expand All @@ -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()
25 changes: 22 additions & 3 deletions custom_components/generac/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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

Expand All @@ -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(
Expand All @@ -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)),
Expand All @@ -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"])
Expand All @@ -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
Expand Down
6 changes: 6 additions & 0 deletions custom_components/generac/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand All @@ -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,
Expand Down
Loading
Loading