From 8b20d3f7fd9b90706a553b3727f28f897b54d18b Mon Sep 17 00:00:00 2001 From: Jose Santiago <979630+binarydev@users.noreply.github.com> Date: Sat, 21 Nov 2026 06:15:15 +0000 Subject: [PATCH] feat: add outage/exercise session ledger, event platform, and post-outage summary blueprint --- README.md | 29 +- .../generac_post_outage_summary.yaml | 140 ++++++ custom_components/generac/const.py | 19 +- custom_components/generac/coordinator.py | 52 +- custom_components/generac/event.py | 87 ++++ custom_components/generac/readiness.py | 470 ++++++++++++++++-- custom_components/generac/sensor.py | 60 +++ .../generac/translations/en.json | 1 + .../generac/translations/fr.json | 1 + .../generac/translations/nb.json | 1 + .../generac/translations/pt.json | 1 + info.md | 17 +- tests/test_blueprints.py | 94 ++++ tests/test_config_flow.py | 1 + tests/test_entity_registry.py | 41 +- tests/test_event.py | 284 +++++++++++ tests/test_init.py | 16 +- tests/test_readiness.py | 128 ++++- tests/test_sensor.py | 59 +++ 19 files changed, 1437 insertions(+), 64 deletions(-) create mode 100644 custom_components/generac/blueprints/automation/generac_post_outage_summary.yaml create mode 100644 custom_components/generac/event.py create mode 100644 tests/test_event.py diff --git a/README.md b/README.md index a7becce..5839f44 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,14 @@ **Custom Generac integration component with support for generators and propane tank monitors. It will set up the following platforms.** -| Platform | Entities created for each generator (by `entity_key`) | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | -| `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`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | -| `weather` | conditional `weather` | -| `image` | conditional `hero_image` | +| Platform | Entities created for each generator (by `entity_key`) | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | +| `button` | `reset_service_timer`, `boost_polling` | +| `event` | `activity` | +| `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`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, `last_outage`, `last_exercise`, `last_outage_duration`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | | Platform | Entities created for each propane tank monitor (by `entity_key`) | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -94,14 +95,19 @@ You can also trigger fast polling manually (for example, from an automation trig ### Telemetry, Long-Term Statistics & Diagnostics -- **Long-Term Statistics (LTS)**: Operational numeric sensors expose Home Assistant `state_class` (`total_increasing` on `run_time` and `protection_time`; `measurement` on `battery_voltage`, `exercise_minutes`, `outdoor_temperature`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `signal_strength`, `device_battery_level`, and `hours_until_service`) for history graphs and long-term recorder statistics. +- **Long-Term Statistics (LTS)**: Operational numeric sensors expose Home Assistant `state_class` (`total_increasing` on `run_time` and `protection_time`; `measurement` on `battery_voltage`, `exercise_minutes`, `outdoor_temperature`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `signal_strength`, `device_battery_level`, `hours_until_service`, and `last_outage_duration`) for history graphs and long-term recorder statistics. - **Fault, VPP & Subscription Telemetry**: Generators expose active fault codes via `Error Code` (`error_code`), and—when present in the MobileLink payload—Virtual Power Plant status (`enrolled_in_vpp`, `active_vpp_event`) and subscription billing alerts (`subscription_dunning`). - **Diagnostic Categorization**: Static metadata and diagnostic entities (serial/model/panel ID, device SSID/type, address, dealer contact info, activation/last-seen/connection timestamps, fuel type, tank orientation, signal strength, VPP enrollment, and subscription billing alert) are grouped under Home Assistant's **Diagnostic** entity category to keep primary dashboards uncluttered. -### Readiness Tracking, Maintenance Timer & Repairs Alerts +### Readiness Tracking, Session Ledger, Activity Events & Repairs Alerts -Each generator automatically tracks exercise activity and maintenance runtime baselines using Home Assistant storage (persisting cleanly across restarts without reloading the integration): +Each generator automatically tracks exercise activity, outage/exercise session history, and maintenance runtime baselines using Home Assistant storage (persisting cleanly across restarts without reloading the integration): +- **Outage & Exercise Session Ledger**: + - `Last Outage` (`last_outage`) and `Last Exercise` (`last_exercise`) record UTC timestamps of observed outages (`Running`) and exercises (`Exercising`), staying `unknown` on fresh installs until a real run is observed. Short unobserved `run_time` increases between idle polls are classified as exercises while longer jumps are recorded as inferred outages. + - `Last Outage Duration` (`last_outage_duration`, in minutes) exposes the most recent outage duration along with `started_at`, `ended_at`, `run_hours_delta`, `estimated_fuel_used`, and `inferred` state attributes. +- **Generator Activity Events (`event` platform)**: + - Each generator exposes an `Activity` (`activity`, default entity ID `event._activity`) event entity emitting `outage_started`, `outage_ended`, `exercise_started`, `exercise_completed`, `fault_detected`, and `fault_cleared` with structured metadata for Logbook timelines and event-triggered automations. - **Maintenance Service Timer**: - `Hours Until Service` (`hours_until_service`, default entity ID `sensor._hours_until_service`) shows estimated runtime hours remaining until the configured service interval (default `100` hours, configurable via **Options** -> `service_interval_hours`; set to `0` to disable). - On first setup, the baseline initializes to the generator's current `run_time` to avoid false day-1 alarms. @@ -116,11 +122,12 @@ Each generator automatically tracks exercise activity and maintenance runtime ba ### Bundled Automation Blueprints -When the integration sets up, three ready-to-use automation blueprints are automatically installed to `/blueprints/automation/generac/`: +When the integration sets up, four ready-to-use automation blueprints are automatically installed to `/blueprints/automation/generac/`: 1. **Generac Outage Load Shedding** (`generac_outage_load_shedding.yaml`) — Sheds high-draw entities when status transitions to `Running` (ignoring `Exercising` cycles), waits for `Ready` stabilization, and optionally restores previously active loads with a stagger delay. 2. **Generac Fault & Dealer Contact Alert** (`generac_fault_dealer_alert.yaml`) — Sends a notification populated with generator status, diagnostic `status_text`, optional `error_code`, and your preferred dealer's name and phone number on `Warning`, `Stopped`, `Communication Issue`, warning, or maintenance alerts. 3. **Generac Pre-Storm Readiness Digest** (`generac_storm_readiness_digest.yaml`) — Sends a readiness digest with status, connectivity, battery voltage, hours until service, and optional propane fuel level, remaining fuel, and estimated runtime when a weather alert or trigger entity turns `on`. +4. **Generac Post-Outage Summary** (`generac_post_outage_summary.yaml`) — Waits for a `Running` outage (ignoring `Exercising` cycles) to stabilize back in `Ready` and sends an "All Clear" summary with outage duration, run hours added, estimated fuel used, optional remaining propane runtime, and hours until service. ## Username + Password Authentication diff --git a/custom_components/generac/blueprints/automation/generac_post_outage_summary.yaml b/custom_components/generac/blueprints/automation/generac_post_outage_summary.yaml new file mode 100644 index 0000000..db7fdb8 --- /dev/null +++ b/custom_components/generac/blueprints/automation/generac_post_outage_summary.yaml @@ -0,0 +1,140 @@ +blueprint: + name: Generac Post-Outage Summary + description: >- + Wait for a Generac generator outage ("Running", ignoring scheduled + "Exercising" cycles) to finish and stabilize in "Ready", then send an + All Clear summary with outage duration, estimated fuel used, optional + propane fuel autonomy, and hours until service. + domain: automation + author: ha-generac + input: + generator_status: + name: Generator Status Sensor + description: Generac status sensor for your generator. + selector: + entity: + filter: + - integration: generac + domain: sensor + last_outage_duration_sensor: + name: Last Outage Duration Sensor + description: Generac Last Outage Duration sensor for your generator. + selector: + entity: + filter: + - integration: generac + domain: sensor + hours_until_service_sensor: + name: Hours Until Service Sensor (Optional) + description: Optional Generac Hours Until Service sensor. + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor + remaining_fuel_sensor: + name: Remaining Propane Fuel Sensor (Optional) + description: Optional Generac propane tank remaining fuel sensor (gal). + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor + estimated_runtime_sensor: + name: Estimated Runtime Remaining Sensor (Optional) + description: Optional Generac propane estimated runtime remaining sensor (h). + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor + ready_stabilization_delay: + name: Utility Stabilization Delay + description: >- + Seconds to wait after the generator returns to "Ready" before sending + the post-outage summary. + default: 60 + selector: + number: + min: 0 + max: 600 + unit_of_measurement: seconds + notify_service: + name: Notification Service + description: >- + Home Assistant notify service to call (for example, notify.notify or + notify.mobile_app_your_phone). + default: notify.notify + selector: + text: {} + +mode: single +max_exceeded: silent + +triggers: + - trigger: state + entity_id: !input generator_status + to: "Running" + +variables: + duration_entity: !input last_outage_duration_sensor + service_entity: !input hours_until_service_sensor + remaining_fuel_entity: !input remaining_fuel_sensor + estimated_runtime_entity: !input estimated_runtime_sensor + +actions: + - alias: Wait for generator to stabilize in Ready without flapping back to Running + repeat: + sequence: + - alias: Wait for Ready stabilization or outage restart + wait_for_trigger: + - id: ready + trigger: state + entity_id: !input generator_status + to: "Ready" + for: + seconds: !input ready_stabilization_delay + - id: running_again + trigger: state + entity_id: !input generator_status + to: "Running" + until: + - condition: template + value_template: "{{ wait.trigger is not none and wait.trigger.id == 'ready' }}" + - alias: Send post-outage All Clear summary + action: !input notify_service + data: + title: "Generac Post-Outage Summary (All Clear)" + message: |- + {%- set duration = states(duration_entity) -%} + {%- set fuel_used = state_attr(duration_entity, 'estimated_fuel_used') -%} + {%- set run_delta = state_attr(duration_entity, 'run_hours_delta') -%} + Utility power restored and generator is back in Ready. + Outage Duration: {{ duration if duration not in ['unknown', 'unavailable', ''] else 'Unknown' }}{{ ' min' if duration not in ['unknown', 'unavailable', ''] else '' }} + {%- if run_delta not in [none, ''] %} + Run Hours Added: {{ run_delta }} h + {%- endif %} + {%- if fuel_used not in [none, ''] %} + Estimated Fuel Used: {{ fuel_used }} gal + {%- endif %} + {%- if remaining_fuel_entity not in [none, ''] %} + {%- set remaining_fuel = states(remaining_fuel_entity) %} + {%- if remaining_fuel not in ['unknown', 'unavailable', ''] %} + Remaining Fuel: {{ remaining_fuel }} gal + {%- endif %} + {%- endif %} + {%- if estimated_runtime_entity not in [none, ''] %} + {%- set estimated_runtime = states(estimated_runtime_entity) %} + {%- if estimated_runtime not in ['unknown', 'unavailable', ''] %} + Estimated Runtime Remaining: {{ estimated_runtime }} h + {%- endif %} + {%- endif %} + {%- if service_entity not in [none, ''] %} + {%- set hours_left = states(service_entity) %} + {%- if hours_left not in ['unknown', 'unavailable', ''] %} + Hours Until Service: {{ hours_left }} h + {%- endif %} + {%- endif %} diff --git a/custom_components/generac/const.py b/custom_components/generac/const.py index 13df7f9..341a40b 100644 --- a/custom_components/generac/const.py +++ b/custom_components/generac/const.py @@ -43,7 +43,24 @@ WEATHER = "weather" IMAGE = "image" BUTTON = "button" -PLATFORMS = [BINARY_SENSOR, SENSOR, WEATHER, IMAGE, BUTTON] +EVENT = "event" +PLATFORMS = [BINARY_SENSOR, SENSOR, WEATHER, IMAGE, BUTTON, EVENT] + +# Generator activity event types +EVENT_OUTAGE_STARTED = "outage_started" +EVENT_OUTAGE_ENDED = "outage_ended" +EVENT_EXERCISE_STARTED = "exercise_started" +EVENT_EXERCISE_COMPLETED = "exercise_completed" +EVENT_FAULT_DETECTED = "fault_detected" +EVENT_FAULT_CLEARED = "fault_cleared" +GENERATOR_ACTIVITY_EVENT_TYPES = [ + EVENT_OUTAGE_STARTED, + EVENT_OUTAGE_ENDED, + EVENT_EXERCISE_STARTED, + EVENT_EXERCISE_COMPLETED, + EVENT_FAULT_DETECTED, + EVENT_FAULT_CLEARED, +] # Readiness & maintenance defaults DEFAULT_SERVICE_INTERVAL_HOURS = 100 diff --git a/custom_components/generac/coordinator.py b/custom_components/generac/coordinator.py index 1f54ea9..fa4ae0d 100644 --- a/custom_components/generac/coordinator.py +++ b/custom_components/generac/coordinator.py @@ -3,8 +3,11 @@ import logging import time +from collections import deque from collections.abc import Mapping +from datetime import datetime from datetime import timedelta +from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant @@ -36,6 +39,7 @@ _ACTIVE_GENERATOR_STATUSES = frozenset({2, 3, 4}) _MIN_SCAN_INTERVAL_SECONDS = 10 +_MAX_BUFFERED_EVENTS_PER_DEVICE = 50 def _read_interval(options: Mapping, key: str, default: int) -> int: @@ -82,6 +86,8 @@ def __init__( self.pending_credential_updates: int = 0 self.loaded_platforms: list[str] = [] self.readiness = ReadinessTracker(hass, config_entry) + self._event_seq: int = 0 + self._device_events: dict[str, deque[tuple[int, str, dict[str, Any]]]] = {} options = entry_options(config_entry) self.idle_scan_interval = _read_interval( options, CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL @@ -100,6 +106,32 @@ def __init__( config_entry=config_entry, ) + @property + def event_seq(self) -> int: + """Return the latest monotonic activity event sequence number.""" + return self._event_seq + + def _record_device_events( + self, emitted: dict[str, list[tuple[str, dict[str, Any]]]] + ) -> None: + """Append emitted poll events into the bounded per-device ring buffer.""" + for device_id, events in emitted.items(): + buf = self._device_events.setdefault( + device_id, deque(maxlen=_MAX_BUFFERED_EVENTS_PER_DEVICE) + ) + for event_type, payload in events: + self._event_seq += 1 + buf.append((self._event_seq, event_type, dict(payload))) + + def get_events_since( + self, device_id: str, last_seq: int + ) -> list[tuple[int, str, dict[str, Any]]]: + """Return buffered activity events for a device strictly newer than last_seq.""" + buf = self._device_events.get(device_id) + if not buf: + return [] + return [entry for entry in buf if entry[0] > last_seq] + def hours_since_service(self, device_id: str) -> float | None: """Return runtime hours elapsed since the generator's maintenance baseline.""" return self.readiness.hours_since_service(device_id) @@ -112,6 +144,22 @@ def is_missed_exercise(self, device_id: str, now: float | None = None) -> bool: """Return True if the generator's scheduled exercise window appears missed.""" return self.readiness.is_missed_exercise(device_id, now=now) + def last_outage(self, device_id: str) -> datetime | None: + """Return UTC timestamp of the generator's last observed or inferred outage.""" + return self.readiness.last_outage(device_id) + + def last_exercise(self, device_id: str) -> datetime | None: + """Return UTC timestamp of the generator's last observed or inferred exercise.""" + return self.readiness.last_exercise(device_id) + + def last_outage_duration_minutes(self, device_id: str) -> float | None: + """Return duration in minutes of the generator's last completed outage.""" + return self.readiness.last_outage_duration_minutes(device_id) + + def last_outage_details(self, device_id: str) -> dict[str, Any] | None: + """Return formatted metadata for the generator's last completed outage.""" + return self.readiness.last_outage_details(device_id) + async def async_reset_service_timer(self, device_id: str) -> None: """Reset maintenance baseline to current run time, re-evaluate alerts, and notify.""" item = (self.data or {}).get(device_id) if isinstance(self.data, dict) else None @@ -187,7 +235,9 @@ async def _async_update_data(self): self._apply_polling_interval(mode) await self.readiness.async_load() if isinstance(items, dict): - await self.readiness.async_update_from_items(items) + emitted = await self.readiness.async_update_from_items(items) + if emitted: + self._record_device_events(emitted) async_update_token_expiry_issue(self.hass, self._config_entry) async_update_device_health_issues( self.hass, self._config_entry, items, self.readiness diff --git a/custom_components/generac/event.py b/custom_components/generac/event.py new file mode 100644 index 0000000..6f9e18f --- /dev/null +++ b/custom_components/generac/event.py @@ -0,0 +1,87 @@ +"""Event platform for generac.""" +from __future__ import annotations + +from typing import Type + +from homeassistant.components.event import EventEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import callback +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .const import DEVICE_TYPE_GENERATOR +from .const import DOMAIN +from .const import GENERATOR_ACTIVITY_EVENT_TYPES +from .coordinator import GeneracDataUpdateCoordinator +from .entity import _EMPTY_ITEM +from .entity import GeneracEntity +from .models import Item + + +async def async_setup_entry( + hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback +) -> None: + """Set up event platform.""" + coordinator: GeneracDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] + data = coordinator.data + if isinstance(data, dict): + async_add_entities( + evt(coordinator, entry, device_id, item) + for device_id, item in data.items() + if isinstance(item, Item) + for evt in events(item) + ) + + +def events(item: Item) -> list[Type[GeneracEntity]]: + """Return event entity classes applicable to an item.""" + if item.apparatus.type == DEVICE_TYPE_GENERATOR: + return [GeneracActivityEventEntity] + return [] + + +class GeneracActivityEventEntity(GeneracEntity, EventEntity): + """Event entity emitting generator outage, exercise, and fault lifecycle events.""" + + entity_key = "activity" + entity_label = "Activity" + + _attr_event_types = list(GENERATOR_ACTIVITY_EVENT_TYPES) + _attr_icon = "mdi:generator-stationary" + + def __init__( + self, + coordinator: GeneracDataUpdateCoordinator, + config_entry: ConfigEntry, + device_id: str, + item: Item, + ) -> None: + """Initialize the activity event entity.""" + super().__init__(coordinator, config_entry, device_id, item) + self._last_event_seq: int = 0 + + @callback + def _consume_pending_events(self) -> bool: + """Trigger and write state for every buffered event newer than _last_event_seq.""" + pending = self.coordinator.get_events_since( + self.device_id, self._last_event_seq + ) + if not pending: + return False + for seq, event_type, event_data in pending: + self._last_event_seq = seq + self._trigger_event(event_type, event_data) + self.async_write_ha_state() + return True + + async def async_added_to_hass(self) -> None: + """Restore last event state and replay any transitions from the initial poll.""" + await super().async_added_to_hass() + self._consume_pending_events() + + @callback + def _handle_coordinator_update(self) -> None: + """Handle updated data and emit any new lifecycle transitions.""" + self.item = (self.coordinator.data or {}).get(self.device_id, _EMPTY_ITEM) + if not self._consume_pending_events(): + self.async_write_ha_state() diff --git a/custom_components/generac/readiness.py b/custom_components/generac/readiness.py index 1fb9193..9f8ebc5 100644 --- a/custom_components/generac/readiness.py +++ b/custom_components/generac/readiness.py @@ -1,8 +1,10 @@ -"""Service and exercise readiness persistence and tracking for Generac.""" +"""Service, exercise, and session readiness persistence for Generac.""" from __future__ import annotations import asyncio import time +from datetime import datetime +from datetime import timezone from typing import Any from homeassistant.config_entries import ConfigEntry @@ -10,11 +12,19 @@ from homeassistant.helpers.storage import Store from .const import CONF_EXERCISE_INTERVAL_DAYS +from .const import CONF_FUEL_BURN_RATE from .const import CONF_SERVICE_INTERVAL_HOURS from .const import DEFAULT_EXERCISE_INTERVAL_DAYS +from .const import DEFAULT_FUEL_BURN_RATE from .const import DEFAULT_SERVICE_INTERVAL_HOURS from .const import DEVICE_TYPE_GENERATOR from .const import DOMAIN +from .const import EVENT_EXERCISE_COMPLETED +from .const import EVENT_EXERCISE_STARTED +from .const import EVENT_FAULT_CLEARED +from .const import EVENT_FAULT_DETECTED +from .const import EVENT_OUTAGE_ENDED +from .const import EVENT_OUTAGE_STARTED from .models import Apparatus from .models import ApparatusDetail from .models import Item @@ -23,9 +33,15 @@ from .utils import safe_float from .utils import safe_int_option -STORAGE_VERSION = 1 -_ACTIVE_APPARATUS_STATUSES = (2, 3) # Running (2), Exercising (3) +STORAGE_VERSION = 2 +_STATUS_RUNNING = 2 +_STATUS_EXERCISING = 3 +_FAULT_APPARATUS_STATUSES = frozenset({4, 5, 6}) _SECONDS_PER_DAY = 86400 +_DEFAULT_INFERRED_EXERCISE_MAX_MINUTES = 21.0 +_INFERRED_EXERCISE_BUFFER_MINUTES = 5.0 +_MIN_SINGLE_CYCLE_EXERCISE_MINUTES = 1.0 +_MAX_SINGLE_CYCLE_EXERCISE_MINUTES = 60.0 def readiness_store_key(entry_id: str) -> str: @@ -43,23 +59,166 @@ def get_battery_voltage(item: Item) -> float | None: return safe_float(get_detail_property_value(item, 70), "battery_voltage") +def get_exercise_minutes(item: Item) -> float | None: + """Extract generator exercise duration minutes (detail property 95).""" + return safe_float(get_detail_property_value(item, 95), "exercise_minutes") + + +def get_error_code(detail: ApparatusDetail) -> str | None: + """Return stripped active error code label if present and non-empty.""" + code = detail.eCodeLabel + if not isinstance(code, str): + return None + stripped = code.strip() + return stripped if stripped else None + + +def is_generator_fault(detail: ApparatusDetail) -> bool: + """Return True if the generator detail indicates a fault, warning, or comm issue.""" + return ( + detail.apparatusStatus in _FAULT_APPARATUS_STATUSES + or detail.showWarning is True + or get_error_code(detail) is not None + ) + + +def _active_session_kind(status: int | None) -> str | None: + """Map an active generator status code to 'outage' or 'exercise'.""" + if status == _STATUS_RUNNING: + return "outage" + if status == _STATUS_EXERCISING: + return "exercise" + return None + + +def _inferred_exercise_max_hours(item: Item) -> float: + """Return max unobserved run-time delta (h) classified as an exercise cycle.""" + ex_minutes = get_exercise_minutes(item) + if ( + ex_minutes is not None + and _MIN_SINGLE_CYCLE_EXERCISE_MINUTES + <= ex_minutes + <= _MAX_SINGLE_CYCLE_EXERCISE_MINUTES + ): + return (ex_minutes + _INFERRED_EXERCISE_BUFFER_MINUTES) / 60.0 + return _DEFAULT_INFERRED_EXERCISE_MAX_MINUTES / 60.0 + + +def _fuel_burn_rate(entry: ConfigEntry) -> float: + """Return positive fuel burn rate (gal/h) from config entry options or default.""" + rate = safe_float( + entry_options(entry).get(CONF_FUEL_BURN_RATE, DEFAULT_FUEL_BURN_RATE), + CONF_FUEL_BURN_RATE, + ) + if rate is None or rate <= 0: + return DEFAULT_FUEL_BURN_RATE + return rate + + +def _timestamp_to_utc(ts: float | None) -> datetime | None: + """Convert a unix timestamp to a timezone-aware UTC datetime.""" + if ts is None: + return None + return datetime.fromtimestamp(float(ts), tz=timezone.utc) + + +def _sanitize_active_session(raw: Any) -> dict[str, Any] | None: + """Validate a persisted active session dict.""" + if not isinstance(raw, dict): + return None + kind = raw.get("kind") + started_at = safe_float(raw.get("started_at")) + if kind not in ("outage", "exercise") or started_at is None: + return None + return { + "kind": kind, + "started_at": started_at, + "start_run_time": safe_float(raw.get("start_run_time")), + } + + +def _sanitize_outage_details(raw: Any) -> dict[str, Any] | None: + """Validate a persisted last outage details dict.""" + if not isinstance(raw, dict): + return None + started_at = safe_float(raw.get("started_at")) + ended_at = safe_float(raw.get("ended_at")) + if started_at is None or ended_at is None: + return None + return { + "started_at": started_at, + "ended_at": ended_at, + "run_hours_delta": safe_float(raw.get("run_hours_delta")), + "estimated_fuel_used": safe_float(raw.get("estimated_fuel_used")), + "inferred": bool(raw.get("inferred", False)), + } + + +def _sanitize_device_record(rec: Any) -> dict[str, Any] | None: + """Normalize a v1 or v2 persisted device record into v2 format.""" + if not isinstance(rec, dict): + return None + last_ts = safe_float(rec.get("last_exercise_ts")) + if last_ts is None: + return None + last_rt = safe_float(rec.get("last_run_time")) + baseline = safe_float(rec.get("service_baseline_hours")) + if last_rt is None and baseline == 0.0: + baseline = None + return { + "last_exercise_ts": last_ts, + "last_run_time": last_rt, + "service_baseline_hours": baseline, + "last_outage_ts": safe_float(rec.get("last_outage_ts")), + "last_observed_exercise_ts": safe_float(rec.get("last_observed_exercise_ts")), + "last_outage_duration_minutes": safe_float( + rec.get("last_outage_duration_minutes") + ), + "last_outage_details": _sanitize_outage_details(rec.get("last_outage_details")), + "active_session": _sanitize_active_session(rec.get("active_session")), + "fault_active": bool(rec.get("fault_active", False)), + } + + +class _ReadinessStore(Store[dict[str, Any]]): + """Home Assistant Store subclass supporting v1 -> v2 readiness migration.""" + + async def _async_migrate_func( + self, + old_major_version: int, + old_minor_version: int, + old_data: dict[str, Any], + ) -> dict[str, Any]: + """Migrate persisted readiness records from v1 to v2.""" + devices = old_data.get("devices") if isinstance(old_data, dict) else None + migrated: dict[str, dict[str, Any]] = {} + if isinstance(devices, dict): + for dev_id, rec in devices.items(): + normalized = _sanitize_device_record(rec) + if normalized is not None: + migrated[str(dev_id)] = normalized + return {"devices": migrated} + + async def async_remove_readiness_store(hass: HomeAssistant, entry: ConfigEntry) -> None: """Delete persisted readiness storage when a config entry is removed.""" entry_id = getattr(entry, "entry_id", None) if isinstance(entry_id, str) and hass is not None: - await Store(hass, STORAGE_VERSION, readiness_store_key(entry_id)).async_remove() + await _ReadinessStore( + hass, STORAGE_VERSION, readiness_store_key(entry_id) + ).async_remove() class ReadinessTracker: - """Tracks per-generator exercise activity and maintenance baselines in HA storage.""" + """Tracks per-generator exercise, outage sessions, faults, and maintenance.""" def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize the readiness tracker without mutating entry.data.""" self._hass = hass self._entry = entry entry_id = getattr(entry, "entry_id", None) - self._store: Store[dict[str, Any]] | None = ( - Store(hass, STORAGE_VERSION, readiness_store_key(entry_id)) + self._store: _ReadinessStore | None = ( + _ReadinessStore(hass, STORAGE_VERSION, readiness_store_key(entry_id)) if isinstance(entry_id, str) and hass is not None else None ) @@ -79,20 +238,9 @@ async def async_load(self) -> None: devices = raw.get("devices") if isinstance(raw, dict) else None if isinstance(devices, dict): for dev_id, rec in devices.items(): - if not isinstance(rec, dict): - continue - last_ts = safe_float(rec.get("last_exercise_ts")) - if last_ts is None: - continue - last_rt = safe_float(rec.get("last_run_time")) - baseline = safe_float(rec.get("service_baseline_hours")) - if last_rt is None and baseline == 0.0: - baseline = None - self._devices[str(dev_id)] = { - "last_exercise_ts": last_ts, - "last_run_time": last_rt, - "service_baseline_hours": baseline, - } + normalized = _sanitize_device_record(rec) + if normalized is not None: + self._devices[str(dev_id)] = normalized self._loaded = True async def _async_save(self) -> None: @@ -106,13 +254,86 @@ def get_device_state(self, device_id: str) -> dict[str, Any] | None: record = self._devices.get(device_id) return dict(record) if record is not None else None + def _finalize_active_session( + self, + record: dict[str, Any], + ts: float, + effective_run_time: float | None, + voltage: float | None, + burn_rate: float, + ) -> tuple[str, dict[str, Any]] | None: + """Finalize an active session, update ledger fields, and return its end event.""" + session = record.get("active_session") + if not isinstance(session, dict): + return None + kind = session.get("kind") + started_at = float(session["started_at"]) + start_rt = session.get("start_run_time") + run_hours_delta: float | None = None + if ( + start_rt is not None + and effective_run_time is not None + and effective_run_time >= float(start_rt) + ): + run_hours_delta = round(effective_run_time - float(start_rt), 4) + + wall_minutes = max(0.0, (ts - started_at) / 60.0) + if wall_minutes == 0.0 and run_hours_delta is not None and run_hours_delta > 0: + duration_minutes = round(run_hours_delta * 60.0, 1) + else: + duration_minutes = round(wall_minutes, 1) + + record["active_session"] = None + if kind == "outage": + fuel_hours = ( + run_hours_delta + if (run_hours_delta is not None and run_hours_delta > 0) + else duration_minutes / 60.0 + ) + estimated_fuel_used = round(fuel_hours * burn_rate, 2) + record["last_outage_ts"] = ts + record["last_outage_duration_minutes"] = duration_minutes + record["last_outage_details"] = { + "started_at": started_at, + "ended_at": ts, + "run_hours_delta": run_hours_delta, + "estimated_fuel_used": estimated_fuel_used, + "inferred": False, + } + payload: dict[str, Any] = { + "duration_minutes": duration_minutes, + "inferred": False, + } + if run_hours_delta is not None: + payload["run_hours_delta"] = run_hours_delta + payload["estimated_fuel_used"] = estimated_fuel_used + if voltage is not None: + payload["battery_voltage"] = voltage + return (EVENT_OUTAGE_ENDED, payload) + + if kind == "exercise": + record["last_observed_exercise_ts"] = ts + payload = { + "duration_minutes": duration_minutes, + "inferred": False, + } + if run_hours_delta is not None: + payload["run_hours_delta"] = run_hours_delta + if voltage is not None: + payload["battery_voltage"] = voltage + return (EVENT_EXERCISE_COMPLETED, payload) + + return None + async def async_update_from_items( self, items: dict[str, Any], now: float | None = None - ) -> None: - """Update tracked exercise timestamps and run hours from a coordinator poll.""" + ) -> dict[str, list[tuple[str, dict[str, Any]]]]: + """Update tracked sessions, faults, and run hours; return emitted events.""" await self.async_load() ts = time.time() if now is None else float(now) + burn_rate = _fuel_burn_rate(self._entry) changed = False + emitted: dict[str, list[tuple[str, dict[str, Any]]]] = {} for device_id, item in items.items(): if not isinstance(item, Item): @@ -129,17 +350,40 @@ async def async_update_from_items( else ApparatusDetail() ) current_run_time = get_run_time(item) + voltage = get_battery_voltage(item) + new_kind = _active_session_kind(detail.apparatusStatus) + fault_now = is_generator_fault(detail) if device_id not in self._devices: - # Initialize baseline to current run hours once known to prevent false day-1 alarms. + # Initialize grace/service baselines on first sight without emitting + # synthetic transition events; keep Last Outage / Last Exercise None + # unless the unit is actively Running/Exercising right now. + initial_session = ( + { + "kind": new_kind, + "started_at": ts, + "start_run_time": current_run_time, + } + if new_kind is not None + else None + ) self._devices[device_id] = { "last_exercise_ts": ts, "last_run_time": current_run_time, "service_baseline_hours": current_run_time, + "last_outage_ts": ts if new_kind == "outage" else None, + "last_observed_exercise_ts": ( + ts if new_kind == "exercise" else None + ), + "last_outage_duration_minutes": None, + "last_outage_details": None, + "active_session": initial_session, + "fault_active": fault_now, } changed = True continue + device_events: list[tuple[str, dict[str, Any]]] = [] record = self._devices[device_id] if ( record.get("service_baseline_hours") is None @@ -147,6 +391,7 @@ async def async_update_from_items( ): record["service_baseline_hours"] = current_run_time changed = True + prev_run_time = record.get("last_run_time") is_transient_zero_dip = ( current_run_time is not None @@ -154,15 +399,125 @@ async def async_update_from_items( and prev_run_time is not None and prev_run_time > 0.0 ) - exercised = detail.apparatusStatus in _ACTIVE_APPARATUS_STATUSES or ( - not is_transient_zero_dip - and current_run_time is not None - and prev_run_time is not None - and current_run_time > prev_run_time + effective_run_time = ( + prev_run_time if is_transient_zero_dip else current_run_time + ) + run_delta = ( + round(current_run_time - prev_run_time, 4) + if ( + not is_transient_zero_dip + and current_run_time is not None + and prev_run_time is not None + and current_run_time > prev_run_time + ) + else 0.0 ) - if exercised: + + active_session = record.get("active_session") + active_kind = ( + active_session.get("kind") if isinstance(active_session, dict) else None + ) + + if active_kind is not None and new_kind != active_kind: + end_event = self._finalize_active_session( + record, ts, effective_run_time, voltage, burn_rate + ) + if end_event is not None: + device_events.append(end_event) + record["last_exercise_ts"] = ts + changed = True + active_kind = None + + if new_kind is not None: + if active_kind is None: + session_start_rt = ( + prev_run_time + if prev_run_time is not None + else effective_run_time + ) + record["active_session"] = { + "kind": new_kind, + "started_at": ts, + "start_run_time": session_start_rt, + } + start_payload: dict[str, Any] = {} + if detail.statusText: + start_payload["status_text"] = detail.statusText + if voltage is not None: + start_payload["battery_voltage"] = voltage + if new_kind == "outage": + record["last_outage_ts"] = ts + device_events.append((EVENT_OUTAGE_STARTED, start_payload)) + else: + record["last_observed_exercise_ts"] = ts + device_events.append((EVENT_EXERCISE_STARTED, start_payload)) + record["last_exercise_ts"] = ts + changed = True + elif run_delta > 0.0 and active_session is None: + # Generator ran and finished between idle polls; classify by delta. + duration_minutes = round(run_delta * 60.0, 1) + est_started_at = ts - run_delta * 3600.0 record["last_exercise_ts"] = ts + if run_delta <= _inferred_exercise_max_hours(item): + record["last_observed_exercise_ts"] = ts + ex_payload: dict[str, Any] = { + "duration_minutes": duration_minutes, + "run_hours_delta": run_delta, + "inferred": True, + } + if voltage is not None: + ex_payload["battery_voltage"] = voltage + device_events.append((EVENT_EXERCISE_COMPLETED, ex_payload)) + else: + estimated_fuel_used = round(run_delta * burn_rate, 2) + record["last_outage_ts"] = ts + record["last_outage_duration_minutes"] = duration_minutes + record["last_outage_details"] = { + "started_at": est_started_at, + "ended_at": ts, + "run_hours_delta": run_delta, + "estimated_fuel_used": estimated_fuel_used, + "inferred": True, + } + out_payload: dict[str, Any] = { + "duration_minutes": duration_minutes, + "run_hours_delta": run_delta, + "estimated_fuel_used": estimated_fuel_used, + "inferred": True, + } + if voltage is not None: + out_payload["battery_voltage"] = voltage + device_events.append((EVENT_OUTAGE_ENDED, out_payload)) + changed = True + + # Fault lifecycle transitions + prev_fault = bool(record.get("fault_active", False)) + if not prev_fault and fault_now: + record["fault_active"] = True + fault_payload: dict[str, Any] = {} + error_code = get_error_code(detail) + if error_code is not None: + fault_payload["error_code"] = error_code + if detail.statusLabel: + fault_payload["status_label"] = detail.statusLabel + if detail.statusText: + fault_payload["status_text"] = detail.statusText + if voltage is not None: + fault_payload["battery_voltage"] = voltage + device_events.append((EVENT_FAULT_DETECTED, fault_payload)) changed = True + elif prev_fault and not fault_now: + record["fault_active"] = False + clear_payload: dict[str, Any] = {} + if detail.statusLabel: + clear_payload["status_label"] = detail.statusLabel + if detail.statusText: + clear_payload["status_text"] = detail.statusText + if voltage is not None: + clear_payload["battery_voltage"] = voltage + device_events.append((EVENT_FAULT_CLEARED, clear_payload)) + changed = True + if ( not is_transient_zero_dip and current_run_time is not None @@ -171,9 +526,14 @@ async def async_update_from_items( record["last_run_time"] = current_run_time changed = True + if device_events: + emitted[device_id] = device_events + if changed: await self._async_save() + return emitted + def hours_since_service(self, device_id: str) -> float | None: """Return runtime hours accumulated since the maintenance baseline.""" record = self._devices.get(device_id) @@ -232,6 +592,50 @@ def is_missed_exercise(self, device_id: str, now: float | None = None) -> bool: ts = time.time() if now is None else float(now) return (ts - float(last_ts)) > float(interval_days) * _SECONDS_PER_DAY + def last_outage(self, device_id: str) -> datetime | None: + """Return UTC timestamp of the last observed or inferred outage.""" + record = self._devices.get(device_id) + if record is None: + return None + return _timestamp_to_utc(record.get("last_outage_ts")) + + def last_exercise(self, device_id: str) -> datetime | None: + """Return UTC timestamp of the last observed or inferred exercise.""" + record = self._devices.get(device_id) + if record is None: + return None + return _timestamp_to_utc(record.get("last_observed_exercise_ts")) + + def last_outage_duration_minutes(self, device_id: str) -> float | None: + """Return duration in minutes of the last completed or inferred outage.""" + record = self._devices.get(device_id) + if record is None: + return None + return record.get("last_outage_duration_minutes") + + def last_outage_details(self, device_id: str) -> dict[str, Any] | None: + """Return formatted metadata for the last completed or inferred outage.""" + record = self._devices.get(device_id) + if record is None: + return None + details = record.get("last_outage_details") + if not isinstance(details, dict): + return None + started = _timestamp_to_utc(details.get("started_at")) + ended = _timestamp_to_utc(details.get("ended_at")) + result: dict[str, Any] = { + "inferred": bool(details.get("inferred", False)), + } + if started is not None: + result["started_at"] = started.isoformat() + if ended is not None: + result["ended_at"] = ended.isoformat() + if details.get("run_hours_delta") is not None: + result["run_hours_delta"] = details["run_hours_delta"] + if details.get("estimated_fuel_used") is not None: + result["estimated_fuel_used"] = details["estimated_fuel_used"] + return result + async def async_reset_service_timer( self, device_id: str, @@ -248,6 +652,12 @@ async def async_reset_service_timer( "last_exercise_ts": ts, "last_run_time": current_run_time, "service_baseline_hours": baseline, + "last_outage_ts": None, + "last_observed_exercise_ts": None, + "last_outage_duration_minutes": None, + "last_outage_details": None, + "active_session": None, + "fault_active": False, } else: prev_run_time = record.get("last_run_time") diff --git a/custom_components/generac/sensor.py b/custom_components/generac/sensor.py index f1ccacd..e9a0a08 100644 --- a/custom_components/generac/sensor.py +++ b/custom_components/generac/sensor.py @@ -73,6 +73,9 @@ def sensors(item: Item) -> list[Type[GeneracEntity]]: # never orphaned; it reports unknown when the value is missing. SignalStrengthSensor, HoursUntilServiceSensor, + LastOutageSensor, + LastExerciseSensor, + LastOutageDurationSensor, ] elif item.apparatus.type == DEVICE_TYPE_PROPANE_MONITOR: lst = [ @@ -697,3 +700,60 @@ def extra_state_attributes(self): if hours_since is None or isinstance(hours_since, (int, float)): attrs["hours_since_service"] = hours_since return attrs + + +class LastOutageSensor(GeneracEntity, SensorEntity): + """Timestamp of the generator's last observed or inferred outage.""" + + entity_key = "last_outage" + entity_label = "Last Outage" + + _attr_device_class = SensorDeviceClass.TIMESTAMP + _attr_icon = "mdi:flash-off" + + @property + def native_value(self): + """Return UTC datetime of the last outage, or None if none observed.""" + return self.coordinator.last_outage(self.device_id) + + +class LastExerciseSensor(GeneracEntity, SensorEntity): + """Timestamp of the generator's last observed or inferred exercise.""" + + entity_key = "last_exercise" + entity_label = "Last Exercise" + + _attr_device_class = SensorDeviceClass.TIMESTAMP + _attr_icon = "mdi:calendar-clock" + + @property + def native_value(self): + """Return UTC datetime of the last exercise, or None if none observed.""" + return self.coordinator.last_exercise(self.device_id) + + +class LastOutageDurationSensor(GeneracEntity, SensorEntity): + """Duration in minutes of the generator's last completed or inferred outage.""" + + entity_key = "last_outage_duration" + entity_label = "Last Outage Duration" + + _attr_device_class = SensorDeviceClass.DURATION + _attr_native_unit_of_measurement = UnitOfTime.MINUTES + _attr_state_class = SensorStateClass.MEASUREMENT + _attr_suggested_display_precision = 1 + _attr_icon = "mdi:timer-outline" + + @property + def native_value(self): + """Return duration in minutes of the last completed outage.""" + return self.coordinator.last_outage_duration_minutes(self.device_id) + + @property + def extra_state_attributes(self): + """Include start/end timestamps, run-hour delta, and estimated fuel used.""" + attrs = dict(super().extra_state_attributes) + details = self.coordinator.last_outage_details(self.device_id) + if isinstance(details, dict): + attrs.update(details) + return attrs diff --git a/custom_components/generac/translations/en.json b/custom_components/generac/translations/en.json index 1c3ea77..77b7bd2 100644 --- a/custom_components/generac/translations/en.json +++ b/custom_components/generac/translations/en.json @@ -77,6 +77,7 @@ "active_scan_interval": "Active polling interval (seconds)", "binary_sensor": "Binary sensors enabled", "button": "Buttons enabled", + "event": "Events enabled", "exercise_interval_days": "Missed exercise alert interval (days, 0 to disable)", "fuel_burn_rate": "Estimated fuel burn rate (gal/h)", "image": "Image enabled", diff --git a/custom_components/generac/translations/fr.json b/custom_components/generac/translations/fr.json index c6f85a9..3105a57 100644 --- a/custom_components/generac/translations/fr.json +++ b/custom_components/generac/translations/fr.json @@ -77,6 +77,7 @@ "active_scan_interval": "Intervalle d’interrogation actif en secondes", "binary_sensor": "Capteur binaire activé", "button": "Boutons activés", + "event": "Événements activés", "exercise_interval_days": "Intervalle d’alerte d’exercice manqué (jours, 0 pour désactiver)", "fuel_burn_rate": "Consommation de carburant estimée (gal/h)", "image": "Image activée", diff --git a/custom_components/generac/translations/nb.json b/custom_components/generac/translations/nb.json index 751e1a7..f379741 100644 --- a/custom_components/generac/translations/nb.json +++ b/custom_components/generac/translations/nb.json @@ -77,6 +77,7 @@ "active_scan_interval": "Aktivt avstemningsintervall i sekunder", "binary_sensor": "Binær sensor aktivert", "button": "Knapper aktivert", + "event": "Hendelser aktivert", "exercise_interval_days": "Varselintervall for uteblitt testkjøring (dager, 0 for å deaktivere)", "fuel_burn_rate": "Estimert drivstofforbruk (gal/t)", "image": "Bilde aktivert", diff --git a/custom_components/generac/translations/pt.json b/custom_components/generac/translations/pt.json index ad163fd..67c4bc9 100644 --- a/custom_components/generac/translations/pt.json +++ b/custom_components/generac/translations/pt.json @@ -77,6 +77,7 @@ "active_scan_interval": "Intervalo de sondagem ativo (segundos)", "binary_sensor": "Sensores binários ativados", "button": "Botões ativados", + "event": "Eventos ativados", "exercise_interval_days": "Intervalo de alerta de exercício em falta (dias, 0 para desativar)", "fuel_burn_rate": "Taxa estimada de consumo de combustível (gal/h)", "image": "Imagem ativada", diff --git a/info.md b/info.md index 0922dcc..e8a850f 100644 --- a/info.md +++ b/info.md @@ -4,13 +4,14 @@ **Custom Generac integration component with support for generators and propane tank monitors. It will set up the following platforms.** -| Platform | Entities created for each generator (by `entity_key`) | -| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | -| `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`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | -| `weather` | conditional `weather` | -| `image` | conditional `hero_image` | +| Platform | Entities created for each generator (by `entity_key`) | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `show_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | +| `button` | `reset_service_timer`, `boost_polling` | +| `event` | `activity` | +| `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`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, `last_outage`, `last_exercise`, `last_outage_duration`, plus conditional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | +| `weather` | conditional `weather` | +| `image` | conditional `hero_image` | | Platform | Entities created for each propane tank monitor (by `entity_key`) | | --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -19,7 +20,7 @@ | `weather` | conditional `weather` | | `image` | conditional `hero_image` | -Includes adaptive cloud polling (`900` s idle / `120` s active) with manual outage boost, long-term statistics, propane fuel autonomy estimates, maintenance/exercise readiness tracking with Repairs alerts, and bundled automation blueprints. +Includes adaptive cloud polling (`900` s idle / `120` s active) with manual outage boost, long-term statistics, propane fuel autonomy estimates, outage/exercise session tracking with native activity events, maintenance/exercise readiness alerts, and bundled automation blueprints. ![example][exampleimg] diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 57c9ad0..d1e87e5 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -18,6 +18,7 @@ "generac_outage_load_shedding.yaml", "generac_fault_dealer_alert.yaml", "generac_storm_readiness_digest.yaml", + "generac_post_outage_summary.yaml", } @@ -119,6 +120,21 @@ async def test_bundled_blueprints_instantiate_valid_automations( "notify_service": "notify.notify", }, ], + "generac_post_outage_summary.yaml": [ + { + "generator_status": "sensor.generator_status", + "last_outage_duration_sensor": "sensor.generator_last_outage_duration", + }, + { + "generator_status": "sensor.generator_status", + "last_outage_duration_sensor": "sensor.generator_last_outage_duration", + "hours_until_service_sensor": "sensor.generator_hours_until_service", + "remaining_fuel_sensor": "sensor.propane_tank_remaining_fuel", + "estimated_runtime_sensor": "sensor.propane_tank_estimated_runtime_remaining", + "ready_stabilization_delay": 30, + "notify_service": "notify.notify", + }, + ], } for filename, input_cases in sample_inputs.items(): @@ -343,3 +359,81 @@ async def _notify(call): await hass.async_block_till_done() assert hass.states.get("switch.ev").state == "on" assert hass.states.get("switch.pool").state == "off" + + +async def test_post_outage_summary_blueprint_runtime(hass: HomeAssistant) -> None: + """Post-outage summary ignores Exercising and renders All Clear after Ready.""" + await async_setup_component(hass, "homeassistant", {}) + notifications: list[dict] = [] + + async def _notify(call): + notifications.append(dict(call.data)) + + hass.services.async_register("notify", "notify", _notify) + install_bundled_blueprints(hass.config.path("blueprints", "automation", "generac")) + + hass.states.async_set("sensor.gen_status", "Ready") + hass.states.async_set( + "sensor.gen_outage_dur", + "90.0", + {"run_hours_delta": 1.5, "estimated_fuel_used": 3.3}, + ) + hass.states.async_set("sensor.gen_service", "83.0") + hass.states.async_set("sensor.tank_gal", "321.7") + hass.states.async_set("sensor.tank_rt", "146.2") + + assert await async_setup_component( + hass, + "automation", + { + "automation": [ + { + "id": "post_outage_rt", + "alias": "Post Outage Summary", + "use_blueprint": { + "path": "generac/generac_post_outage_summary.yaml", + "input": { + "generator_status": "sensor.gen_status", + "last_outage_duration_sensor": "sensor.gen_outage_dur", + "hours_until_service_sensor": "sensor.gen_service", + "remaining_fuel_sensor": "sensor.tank_gal", + "estimated_runtime_sensor": "sensor.tank_rt", + "ready_stabilization_delay": 0, + "notify_service": "notify.notify", + }, + }, + } + ] + }, + ) + await hass.async_block_till_done() + + # Scheduled Exercising cycle must NOT trigger post-outage summary + hass.states.async_set("sensor.gen_status", "Exercising") + await hass.async_block_till_done() + hass.states.async_set("sensor.gen_status", "Ready") + await hass.async_block_till_done() + assert notifications == [] + + # Outage (Running -> Warning -> Running -> Ready) sends one All Clear summary + hass.states.async_set("sensor.gen_status", "Running") + await asyncio.sleep(0.05) + hass.states.async_set("sensor.gen_status", "Warning") + await asyncio.sleep(0.05) + hass.states.async_set("sensor.gen_status", "Running") + await asyncio.sleep(0.05) + assert notifications == [] + + hass.states.async_set("sensor.gen_status", "Ready") + await hass.async_block_till_done() + assert len(notifications) == 1 + assert notifications[0]["title"] == "Generac Post-Outage Summary (All Clear)" + assert notifications[0]["message"] == ( + "Utility power restored and generator is back in Ready.\n" + "Outage Duration: 90.0 min\n" + "Run Hours Added: 1.5 h\n" + "Estimated Fuel Used: 3.3 gal\n" + "Remaining Fuel: 321.7 gal\n" + "Estimated Runtime Remaining: 146.2 h\n" + "Hours Until Service: 83.0 h" + ) diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index a6740d6..14ace5e 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -175,6 +175,7 @@ async def test_options_flow(hass: HomeAssistant) -> None: "weather": True, "image": True, "button": True, + "event": True, "scan_interval": 120, "active_scan_interval": 60, "fuel_burn_rate": 2.2, diff --git a/tests/test_entity_registry.py b/tests/test_entity_registry.py index b27cb8c..ec59414 100644 --- a/tests/test_entity_registry.py +++ b/tests/test_entity_registry.py @@ -83,9 +83,17 @@ # Entities this change adds for the fixture payloads below. NEW_SUFFIXES = { GENERATOR_ID: { - "sensor": ["exercise_minutes", "error_code", "hours_until_service"], + "sensor": [ + "exercise_minutes", + "error_code", + "hours_until_service", + "last_outage", + "last_exercise", + "last_outage_duration", + ], "binary_sensor": ["missed_exercise"], "button": ["reset_service_timer", "boost_polling"], + "event": ["activity"], }, PROPANE_ID: { "sensor": [ @@ -291,6 +299,12 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) "button.generator_outage_boost_poll" ), _unique_id(GENERATOR_ID, "error_code"): "sensor.generator_error_code", + _unique_id(GENERATOR_ID, "last_outage"): "sensor.generator_last_outage", + _unique_id(GENERATOR_ID, "last_exercise"): "sensor.generator_last_exercise", + _unique_id(GENERATOR_ID, "last_outage_duration"): ( + "sensor.generator_last_outage_duration" + ), + _unique_id(GENERATOR_ID, "activity"): "event.generator_activity", _unique_id( PROPANE_ID, "signal_strength" ): "sensor.propane_tank_signal_strength", @@ -310,6 +324,10 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) ) assert hass.states.get("button.generator_outage_boost_poll").state == "unknown" assert hass.states.get("sensor.generator_error_code").state == "unknown" + assert hass.states.get("sensor.generator_last_outage").state == "unknown" + assert hass.states.get("sensor.generator_last_exercise").state == "unknown" + assert hass.states.get("sensor.generator_last_outage_duration").state == "unknown" + assert hass.states.get("event.generator_activity").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" remaining_state = hass.states.get("sensor.propane_tank_remaining_fuel") @@ -345,6 +363,22 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) devices[_unique_id(GENERATOR_ID, "error_code")] == devices[_unique_id(GENERATOR_ID, "status")] ) + assert ( + devices[_unique_id(GENERATOR_ID, "last_outage")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) + assert ( + devices[_unique_id(GENERATOR_ID, "last_exercise")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) + assert ( + devices[_unique_id(GENERATOR_ID, "last_outage_duration")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) + assert ( + devices[_unique_id(GENERATOR_ID, "activity")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) assert ( devices[_unique_id(PROPANE_ID, "device_battery_level")] == devices[_unique_id(PROPANE_ID, "status")] @@ -425,6 +459,7 @@ def test_every_entity_class_declares_its_own_stable_key(): """No entity class may inherit or infer its unique_id suffix.""" from custom_components.generac import binary_sensor from custom_components.generac import button + from custom_components.generac import event from custom_components.generac import image from custom_components.generac import sensor from custom_components.generac import weather @@ -432,13 +467,13 @@ def test_every_entity_class_declares_its_own_stable_key(): classes = [ obj - for module in (binary_sensor, button, image, sensor, weather) + for module in (binary_sensor, button, event, image, sensor, weather) for obj in vars(module).values() if isinstance(obj, type) and issubclass(obj, GeneracEntity) and obj is not GeneracEntity ] - assert len(classes) == 44 + assert len(classes) == 48 keys = {} for cls in classes: assert "entity_key" in vars(cls), cls.__name__ diff --git a/tests/test_event.py b/tests/test_event.py new file mode 100644 index 0000000..c994dc1 --- /dev/null +++ b/tests/test_event.py @@ -0,0 +1,284 @@ +"""Tests for the Generac event platform (Generator Activity).""" +from unittest.mock import AsyncMock +from unittest.mock import patch + +from custom_components.generac.auth import DPoPKey +from custom_components.generac.const import CONF_DPOP_PEM +from custom_components.generac.const import CONF_REFRESH_TOKEN +from custom_components.generac.const import CONF_USERNAME +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.const import EVENT_EXERCISE_COMPLETED +from custom_components.generac.const import EVENT_EXERCISE_STARTED +from custom_components.generac.const import EVENT_FAULT_CLEARED +from custom_components.generac.const import EVENT_FAULT_DETECTED +from custom_components.generac.const import EVENT_OUTAGE_ENDED +from custom_components.generac.const import EVENT_OUTAGE_STARTED +from custom_components.generac.const import GENERATOR_ACTIVITY_EVENT_TYPES +from custom_components.generac.event import events +from custom_components.generac.event import GeneracActivityEventEntity +from custom_components.generac.models import Apparatus +from custom_components.generac.models import ApparatusDetail +from custom_components.generac.models import Item +from custom_components.generac.readiness import readiness_store_key +from custom_components.generac.readiness import STORAGE_VERSION +from homeassistant.core import callback +from homeassistant.core import HomeAssistant +from homeassistant.helpers.storage import Store +from pytest_homeassistant_custom_component.common import MockConfigEntry + + +def _make_item( + device_type: int = DEVICE_TYPE_GENERATOR, + apparatus_id: int = 12345, + name: str = "Home Gen", + status: int = 1, + run_time: float | None = 100.0, + battery_voltage: float | None = 13.4, + error_code: str | None = None, + show_warning: bool = False, + status_text: str | None = None, + status_label: str | None = None, +) -> Item: + props = [] + if run_time is not None: + props.append( + ApparatusDetail.Property(name="Run Hours", value=run_time, type=71) + ) + if battery_voltage is not None: + props.append( + ApparatusDetail.Property( + name="Battery Voltage", value=battery_voltage, type=70 + ) + ) + return Item( + apparatus=Apparatus( + apparatusId=apparatus_id, + name=name, + type=device_type, + ), + apparatusDetail=ApparatusDetail( + apparatusId=apparatus_id, + name=name, + apparatusStatus=status, + eCodeLabel=error_code, + showWarning=show_warning, + statusText=status_text, + statusLabel=status_label, + properties=props, + ), + ) + + +def _mock_entry(entry_id: str = "evt_entry") -> MockConfigEntry: + return MockConfigEntry( + domain=DOMAIN, + entry_id=entry_id, + unique_id="user@example.com", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + ) + + +def test_event_selection_generator_only() -> None: + """Activity event entity is created only for generators, not propane monitors.""" + assert events(_make_item(DEVICE_TYPE_GENERATOR)) == [GeneracActivityEventEntity] + assert events(_make_item(DEVICE_TYPE_PROPANE_MONITOR)) == [] + + +async def test_activity_event_lifecycle_and_no_spurious_refire( + hass: HomeAssistant, +) -> None: + """Emit all 6 lifecycle event types and do not re-fire on maintenance reset.""" + entry = _mock_entry("evt_lifecycle") + entry.add_to_hass(hass) + + t0 = 1_700_000_000.0 + polls = [ + {"12345": _make_item(status=1, run_time=100.0)}, + {"12345": _make_item(status=2, run_time=100.0, status_text="Running on load")}, + {"12345": _make_item(status=1, run_time=101.5)}, + {"12345": _make_item(status=3, run_time=101.5, status_text="Weekly test")}, + {"12345": _make_item(status=1, run_time=101.7)}, + { + "12345": _make_item( + status=4, + run_time=101.7, + error_code="E1505", + status_text="Overcrank", + status_label="Warning", + ) + }, + {"12345": _make_item(status=1, run_time=101.7, status_label="Ready")}, + ] + poll_times = [ + t0, + t0 + 600, + t0 + 6000, + t0 + 10000, + t0 + 10720, + t0 + 12000, + t0 + 12600, + ] + clock = [poll_times[0]] + + observed_events: list[tuple[str | None, dict]] = [] + + @callback + def _track(event) -> None: + new_state = event.data.get("new_state") + if new_state is None: + return + if new_state.entity_id == "event.home_gen_activity": + et = new_state.attributes.get("event_type") + if et is not None: + observed_events.append((et, dict(new_state.attributes))) + + hass.bus.async_listen("state_changed", _track) + + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + AsyncMock(side_effect=polls), + ), patch( + "custom_components.generac.readiness.time.time", + side_effect=lambda: clock[0], + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get("event.home_gen_activity") + assert state is not None + assert state.state == "unknown" + assert state.attributes["event_types"] == GENERATOR_ACTIVITY_EVENT_TYPES + assert hass.states.get("sensor.home_gen_last_outage").state == "unknown" + assert hass.states.get("sensor.home_gen_last_exercise").state == "unknown" + assert ( + hass.states.get("sensor.home_gen_last_outage_duration").state == "unknown" + ) + + coordinator = hass.data[DOMAIN][entry.entry_id] + for next_ts in poll_times[1:]: + clock[0] = next_ts + await coordinator.async_refresh() + await hass.async_block_till_done() + + assert [et for et, _ in observed_events] == [ + EVENT_OUTAGE_STARTED, + EVENT_OUTAGE_ENDED, + EVENT_EXERCISE_STARTED, + EVENT_EXERCISE_COMPLETED, + EVENT_FAULT_DETECTED, + EVENT_FAULT_CLEARED, + ] + outage_end_attrs = observed_events[1][1] + assert outage_end_attrs["duration_minutes"] == 90.0 + assert outage_end_attrs["run_hours_delta"] == 1.5 + assert outage_end_attrs["estimated_fuel_used"] == 3.3 + assert outage_end_attrs["inferred"] is False + + fault_attrs = observed_events[4][1] + assert fault_attrs["error_code"] == "E1505" + assert fault_attrs["status_text"] == "Overcrank" + + # Session sensors updated cleanly + duration_state = hass.states.get("sensor.home_gen_last_outage_duration") + assert duration_state.state == "90.0" + assert duration_state.attributes["run_hours_delta"] == 1.5 + assert duration_state.attributes["estimated_fuel_used"] == 3.3 + assert hass.states.get("sensor.home_gen_last_outage").state != "unknown" + assert hass.states.get("sensor.home_gen_last_exercise").state != "unknown" + + # Resetting maintenance timer triggers async_update_listeners without re-firing events + event_state_before = hass.states.get("event.home_gen_activity").state + count_before = len(observed_events) + await coordinator.async_reset_service_timer("12345") + await hass.async_block_till_done() + assert len(observed_events) == count_before + assert hass.states.get("event.home_gen_activity").state == event_state_before + + +async def test_activity_event_replays_offline_transition_and_handles_multi_event_poll( + hass: HomeAssistant, +) -> None: + """Replay transition from initial refresh after restart and emit multi-event polls.""" + entry = _mock_entry("evt_replay") + entry.add_to_hass(hass) + t0 = 1_700_000_000.0 + + # Pre-seed v2 store as if generator was Ready at 50.0 h before HA restarted + await Store(hass, STORAGE_VERSION, readiness_store_key(entry.entry_id)).async_save( + { + "devices": { + "12345": { + "last_exercise_ts": t0, + "last_run_time": 50.0, + "service_baseline_hours": 50.0, + "last_outage_ts": None, + "last_observed_exercise_ts": None, + "last_outage_duration_minutes": None, + "last_outage_details": None, + "active_session": None, + "fault_active": False, + } + } + } + ) + + # First poll after restart shows a 2-hour outage occurred while HA was offline; + # Poll 2 starts Exercising; Poll 3 transitions directly to Running + Warning! + polls = [ + {"12345": _make_item(status=1, run_time=52.0)}, + {"12345": _make_item(status=3, run_time=52.0)}, + { + "12345": _make_item( + status=2, + run_time=52.1, + show_warning=True, + error_code="E1100", + ) + }, + ] + poll_times = [t0 + 10000, t0 + 20000, t0 + 20300] + clock = [poll_times[0]] + recorded: list[str] = [] + + @callback + def _track(event) -> None: + new_state = event.data.get("new_state") + if new_state is not None and new_state.entity_id == "event.home_gen_activity": + et = new_state.attributes.get("event_type") + if et is not None: + recorded.append(et) + + hass.bus.async_listen("state_changed", _track) + + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + AsyncMock(side_effect=polls), + ), patch( + "custom_components.generac.readiness.time.time", + side_effect=lambda: clock[0], + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert recorded == [EVENT_OUTAGE_ENDED] + assert hass.states.get("sensor.home_gen_last_outage_duration").state == "120.0" + + coordinator = hass.data[DOMAIN][entry.entry_id] + for next_ts in poll_times[1:]: + clock[0] = next_ts + await coordinator.async_refresh() + await hass.async_block_till_done() + + assert recorded == [ + EVENT_OUTAGE_ENDED, + EVENT_EXERCISE_STARTED, + EVENT_EXERCISE_COMPLETED, + EVENT_OUTAGE_STARTED, + EVENT_FAULT_DETECTED, + ] diff --git a/tests/test_init.py b/tests/test_init.py index 289c284..4e748dd 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -347,6 +347,7 @@ async def test_setup_entry_installs_bundled_blueprints( assert sorted(p.name for p in bp_dir.glob("*.yaml")) == [ "generac_fault_dealer_alert.yaml", "generac_outage_load_shedding.yaml", + "generac_post_outage_summary.yaml", "generac_storm_readiness_digest.yaml", ] @@ -533,24 +534,31 @@ async def test_platform_toggles_setup_reload_and_unload(hass: HomeAssistant): await hass.async_block_till_done() coordinator = hass.data[DOMAIN][entry.entry_id] - assert coordinator.loaded_platforms == ["binary_sensor", "sensor", "image"] + assert coordinator.loaded_platforms == [ + "binary_sensor", + "sensor", + "image", + "event", + ] registry = er.async_get(hass) domains = { e.domain for e in er.async_entries_for_config_entry(registry, entry.entry_id) } - assert domains == {"binary_sensor", "sensor", "image"} + assert domains == {"binary_sensor", "sensor", "image", "event"} - # Toggling button back on and image off unloads old platforms cleanly and loads new set + # Toggling button back on and image/event off unloads old platforms cleanly hass.config_entries.async_update_entry( entry, - options={"button": True, "weather": False, "image": False}, + options={"button": True, "weather": False, "image": False, "event": False}, ) await hass.async_block_till_done() coordinator2 = hass.data[DOMAIN][entry.entry_id] assert coordinator2.loaded_platforms == ["binary_sensor", "sensor", "button"] assert hass.states.get("button.home_gen_outage_boost_poll") is not None assert hass.states.get("weather.home_gen_weather") is None + unloaded_event = hass.states.get("event.home_gen_activity") + assert unloaded_event is not None and unloaded_event.state == "unavailable" assert await hass.config_entries.async_unload(entry.entry_id) assert entry.entry_id not in hass.data[DOMAIN] diff --git a/tests/test_readiness.py b/tests/test_readiness.py index e1c8806..79297e0 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -68,11 +68,21 @@ async def test_first_sight_prevents_day_1_alarms_and_ignores_propane( "last_exercise_ts": t0, "last_run_time": 250.0, "service_baseline_hours": 250.0, + "last_outage_ts": None, + "last_observed_exercise_ts": None, + "last_outage_duration_minutes": None, + "last_outage_details": None, + "active_session": None, + "fault_active": False, } assert tracker.get_device_state("2") is None assert tracker.hours_since_service("1") == 0.0 assert tracker.hours_until_service("1") == 100.0 assert tracker.is_missed_exercise("1", now=t0) is False + assert tracker.last_outage("1") is None + assert tracker.last_exercise("1") is None + assert tracker.last_outage_duration_minutes("1") is None + assert tracker.last_outage_details("1") is None async def test_exercise_detection_via_status_and_run_time_delta( @@ -135,14 +145,17 @@ async def test_store_persistence_across_restarts_without_mutating_entry_data( await tracker1.async_update_from_items({"1": _gen(run_time=120.0)}, now=t0 + 3600) assert dict(entry.data) == initial_entry_data - # New tracker instance loads persisted baseline and exercise timestamp from Store + # New tracker instance loads persisted baseline, outage ledger, and exercise timestamp tracker2 = ReadinessTracker(hass, entry) await tracker2.async_load() - assert tracker2.get_device_state("1") == { - "last_exercise_ts": t0 + 3600, - "last_run_time": 120.0, - "service_baseline_hours": 100.0, - } + loaded = tracker2.get_device_state("1") + assert loaded["last_exercise_ts"] == t0 + 3600 + assert loaded["last_run_time"] == 120.0 + assert loaded["service_baseline_hours"] == 100.0 + assert loaded["last_outage_ts"] == t0 + 3600 + assert loaded["last_outage_duration_minutes"] == 1200.0 + assert loaded["last_outage_details"]["inferred"] is True + assert loaded["last_outage_details"]["run_hours_delta"] == 20.0 assert tracker2.hours_since_service("1") == 20.0 assert tracker2.hours_until_service("1") == 80.0 @@ -328,3 +341,106 @@ async def slow_load(): assert ( tracker_conc.get_device_state("beta_uninit")["service_baseline_hours"] is None ) + + +async def test_v1_to_v2_migration_and_session_classification( + hass: HomeAssistant, +) -> None: + """v1 store migrates cleanly and unobserved run_time deltas classify accurately.""" + from custom_components.generac.const import CONF_FUEL_BURN_RATE + from custom_components.generac.const import EVENT_EXERCISE_COMPLETED + from custom_components.generac.const import EVENT_FAULT_CLEARED + from custom_components.generac.const import EVENT_FAULT_DETECTED + from custom_components.generac.const import EVENT_OUTAGE_ENDED + from custom_components.generac.const import EVENT_OUTAGE_STARTED + from custom_components.generac.readiness import readiness_store_key + from homeassistant.helpers.storage import Store + + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="v1_migrate_entry", + options={CONF_FUEL_BURN_RATE: 3.0}, + ) + entry.add_to_hass(hass) + t0 = 1_700_000_000.0 + + # Seed v1 store record (no session ledger fields yet) + await Store(hass, 1, readiness_store_key(entry.entry_id)).async_save( + { + "devices": { + "1": { + "last_exercise_ts": t0, + "last_run_time": 100.0, + "service_baseline_hours": 80.0, + } + } + } + ) + + tracker = ReadinessTracker(hass, entry) + await tracker.async_load() + assert tracker.hours_since_service("1") == 20.0 + assert tracker.last_outage("1") is None + assert tracker.last_exercise("1") is None + assert tracker.last_outage_duration_minutes("1") is None + + # 1. Short unobserved run_time jump (+0.2 h = 12 min <= 21 min default) -> exercise + ev1 = await tracker.async_update_from_items( + {"1": _gen(status=1, run_time=100.2)}, now=t0 + 900 + ) + assert [e[0] for e in ev1["1"]] == [EVENT_EXERCISE_COMPLETED] + assert ev1["1"][0][1]["inferred"] is True + assert tracker.last_exercise("1").timestamp() == t0 + 900 + assert tracker.last_outage("1") is None + + # 2. Custom single-cycle exercise_minutes (30 min -> 35 min threshold): + # +0.5 h (30 min) classifies as exercise. + gen_30m = _gen(status=1, run_time=100.7) + gen_30m.apparatusDetail.properties.append( + ApparatusDetail.Property(name="Exercise Minutes", value="30", type=95) + ) + ev2 = await tracker.async_update_from_items({"1": gen_30m}, now=t0 + 3600) + assert [e[0] for e in ev2["1"]] == [EVENT_EXERCISE_COMPLETED] + assert tracker.last_outage("1") is None + + # 3. Bogus cumulative exercise_minutes (1635 > 60) falls back to 21 min threshold: + # +0.5 h (30 min) classifies as an inferred outage (0.5 h * 3.0 gal/h = 1.5 gal). + gen_bogus_ex = _gen(status=1, run_time=101.2) + gen_bogus_ex.apparatusDetail.properties.append( + ApparatusDetail.Property(name="Exercise Minutes", value="1635", type=95) + ) + ev3 = await tracker.async_update_from_items({"1": gen_bogus_ex}, now=t0 + 7200) + assert [e[0] for e in ev3["1"]] == [EVENT_OUTAGE_ENDED] + assert ev3["1"][0][1]["inferred"] is True + assert ev3["1"][0][1]["estimated_fuel_used"] == 1.5 + assert tracker.last_outage_duration_minutes("1") == 30.0 + details = tracker.last_outage_details("1") + assert details["inferred"] is True + assert details["run_hours_delta"] == 0.5 + assert details["estimated_fuel_used"] == 1.5 + assert "started_at" in details and "ended_at" in details + + # 4. Observed outage start -> fault detected -> restart -> fault cleared -> outage ended + ev4 = await tracker.async_update_from_items( + {"1": _gen(status=2, run_time=101.2)}, now=t0 + 10000 + ) + assert [e[0] for e in ev4["1"]] == [EVENT_OUTAGE_STARTED] + + fault_gen = _gen(status=2, run_time=101.5) + fault_gen.apparatusDetail.showWarning = True + fault_gen.apparatusDetail.eCodeLabel = "E2800" + ev5 = await tracker.async_update_from_items({"1": fault_gen}, now=t0 + 10900) + assert [e[0] for e in ev5["1"]] == [EVENT_FAULT_DETECTED] + + # Reload tracker from v2 store: still in fault & active outage -> no duplicate start/fault + tracker2 = ReadinessTracker(hass, entry) + ev6 = await tracker2.async_update_from_items({"1": fault_gen}, now=t0 + 11200) + assert ev6 == {} + + # Clear fault and end outage + ev7 = await tracker2.async_update_from_items( + {"1": _gen(status=1, run_time=102.2)}, now=t0 + 13600 + ) + assert [e[0] for e in ev7["1"]] == [EVENT_OUTAGE_ENDED, EVENT_FAULT_CLEARED] + assert tracker2.last_outage_duration_minutes("1") == 60.0 + assert tracker2.last_outage_details("1")["estimated_fuel_used"] == 3.0 diff --git a/tests/test_sensor.py b/tests/test_sensor.py index bf75115..17132c1 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -28,6 +28,9 @@ from custom_components.generac.sensor import FuelLevelSensor from custom_components.generac.sensor import FuelTypeSensor from custom_components.generac.sensor import HoursUntilServiceSensor +from custom_components.generac.sensor import LastExerciseSensor +from custom_components.generac.sensor import LastOutageDurationSensor +from custom_components.generac.sensor import LastOutageSensor from custom_components.generac.sensor import LastReadingDateSensor from custom_components.generac.sensor import LastSeenSensor from custom_components.generac.sensor import ModelNumberSensor @@ -508,6 +511,7 @@ def test_long_term_statistics_state_classes_and_capacity(): (FuelLevelSensor, propane), (RemainingFuelSensor, propane), (EstimatedRuntimeSensor, propane), + (LastOutageDurationSensor, item), ] for cls, dev_item in measurement_cases: entity = cls(MagicMock(), entry, "1", dev_item) @@ -568,12 +572,67 @@ def test_entity_categories_diagnostic_vs_primary(): LastReadingDateSensor, DeviceBatteryLevelSensor, HoursUntilServiceSensor, + LastOutageSensor, + LastExerciseSensor, + LastOutageDurationSensor, ] for cls in primary_classes: entity = cls(MagicMock(), entry, "1", item) assert entity.entity_category is None, cls.__name__ +def test_session_ledger_sensors(): + """LastOutage, LastExercise, and LastOutageDuration delegate to coordinator.""" + from datetime import datetime + from datetime import timezone + + outage_dt = datetime(2026, 11, 20, 15, 0, tzinfo=timezone.utc) + exercise_dt = datetime(2026, 11, 18, 12, 0, tzinfo=timezone.utc) + coordinator = MagicMock() + coordinator.last_outage.return_value = outage_dt + coordinator.last_exercise.return_value = exercise_dt + coordinator.last_outage_duration_minutes.return_value = 95.5 + coordinator.last_outage_details.return_value = { + "started_at": "2026-11-20T13:24:30+00:00", + "ended_at": "2026-11-20T15:00:00+00:00", + "run_hours_delta": 1.6, + "estimated_fuel_used": 3.52, + "inferred": False, + } + entry = MagicMock() + entry.entry_id = "entry" + + gen = get_mock_item(DEVICE_TYPE_GENERATOR, 1) + propane = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1) + for cls in (LastOutageSensor, LastExerciseSensor, LastOutageDurationSensor): + assert cls in sensors(gen) + assert cls not in sensors(propane) + + last_outage = LastOutageSensor(coordinator, entry, "1", gen) + assert last_outage.device_class == SensorDeviceClass.TIMESTAMP + assert last_outage.icon == "mdi:flash-off" + assert last_outage.native_value == outage_dt + + last_exercise = LastExerciseSensor(coordinator, entry, "1", gen) + assert last_exercise.device_class == SensorDeviceClass.TIMESTAMP + assert last_exercise.icon == "mdi:calendar-clock" + assert last_exercise.native_value == exercise_dt + + duration = LastOutageDurationSensor(coordinator, entry, "1", gen) + assert duration.device_class == SensorDeviceClass.DURATION + assert duration.native_unit_of_measurement == UnitOfTime.MINUTES + assert duration.state_class == SensorStateClass.MEASUREMENT + assert duration.suggested_display_precision == 1 + assert duration.icon == "mdi:timer-outline" + assert duration.native_value == 95.5 + attrs = duration.extra_state_attributes + assert attrs["started_at"] == "2026-11-20T13:24:30+00:00" + assert attrs["ended_at"] == "2026-11-20T15:00:00+00:00" + assert attrs["run_hours_delta"] == 1.6 + assert attrs["estimated_fuel_used"] == 3.52 + assert attrs["inferred"] is False + + def test_remaining_fuel_and_estimated_runtime(): """Propane remaining gallons and runtime handle options and edge cases.""" entry = MagicMock() # entry.options is a MagicMock (non-Mapping) -> default 2.2