From 4bce73a6fc2e10385ad5b38e2a1fd17cd837a210 Mon Sep 17 00:00:00 2001 From: Jose Santiago Date: Wed, 18 Nov 2026 01:23:12 -0500 Subject: [PATCH] Add proactive readiness alerts, maintenance timer, and bundled blueprints --- .pre-commit-config.yaml | 1 + README.md | 33 ++- custom_components/generac/__init__.py | 20 +- custom_components/generac/binary_sensor.py | 28 +- custom_components/generac/blueprints.py | 33 +++ .../generac_fault_dealer_alert.yaml | 105 ++++++++ .../generac_outage_load_shedding.yaml | 96 +++++++ .../generac_storm_readiness_digest.yaml | 91 +++++++ custom_components/generac/button.py | 51 ++++ custom_components/generac/config_flow.py | 24 +- custom_components/generac/const.py | 25 +- custom_components/generac/coordinator.py | 42 ++- custom_components/generac/issues.py | 217 +++++++++++++++- custom_components/generac/readiness.py | 238 +++++++++++++++++ custom_components/generac/sensor.py | 67 +++-- .../generac/translations/en.json | 20 ++ .../generac/translations/fr.json | 4 + .../generac/translations/nb.json | 4 + .../generac/translations/pt.json | 4 + custom_components/generac/utils.py | 52 +++- tests/test_binary_sensor.py | 34 +++ tests/test_blueprints.py | 136 ++++++++++ tests/test_button.py | 142 +++++++++++ tests/test_config_flow.py | 36 +++ tests/test_entity_registry.py | 37 ++- tests/test_init.py | 40 +++ tests/test_issues.py | 238 ++++++++++++++++- tests/test_readiness.py | 241 ++++++++++++++++++ tests/test_sensor.py | 25 ++ 29 files changed, 2017 insertions(+), 67 deletions(-) create mode 100644 custom_components/generac/blueprints.py create mode 100644 custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml create mode 100644 custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml create mode 100644 custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml create mode 100644 custom_components/generac/button.py create mode 100644 custom_components/generac/readiness.py create mode 100644 tests/test_blueprints.py create mode 100644 tests/test_button.py create mode 100644 tests/test_readiness.py diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7b1e0fb..59a4d0b 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,6 +4,7 @@ repos: hooks: - id: check-added-large-files - id: check-yaml + args: [--unsafe] - id: end-of-file-fixer - id: trailing-whitespace - repo: local diff --git a/README.md b/README.md index 3a7de0b..083646c 100644 --- a/README.md +++ b/README.md @@ -9,10 +9,11 @@ **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 | -| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning` | -| `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` | +| Platform | Entities created for each generator | +| --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, `missed_exercise` | +| `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 | | --------------- | ------------------------------------------------------------------------------------------------------------------------------ | @@ -65,6 +66,30 @@ Click this button to skip steps 1 and 2 below: [![Open your Home Assistant insta ## Configuration is done in the UI +### 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): + +- **Maintenance Service Timer**: + - `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. + - After completing maintenance (oil change, filter, etc.), press **Reset Maintenance Timer** (`button._reset_maintenance_timer`) on the device page to reset the baseline to the current run hours and clear any timer-based Repairs issue immediately. +- **Exercise Readiness Tracking**: + - `binary_sensor._missed_exercise` turns `on` if no `Running`/`Exercising` status or run-hour increase is observed within `exercise_interval_days` (default `16` days to cover weekly and biweekly schedules; set to `0` to disable). +- **Proactive Home Assistant Repairs Alerts**: + - `low_battery_voltage`: raised when generator starting battery voltage drops below `low_battery_threshold` (default `12.2` V). + - `missed_exercise`: raised when the generator exceeds `exercise_interval_days` without observed activity. + - `maintenance_due`: raised when runtime since the last service reset reaches `service_interval_hours` or Mobile Link reports a maintenance alert. + - `subscription_dunning`: raised when Mobile Link reports a past-due/dunning subscription status. + +### Bundled Automation Blueprints + +When the integration sets up, three 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 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`, 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 when a weather alert or trigger entity turns `on`. + ## Username + Password Authentication This integration previously used a cookie-fishing authentication workflow. As of PR #267, it has now been replaced by a standard OAuth workflow similar to the mobile app, using your username and password, with auto-refreshing token retrieval. You no longer need to enter your cookie's string! diff --git a/custom_components/generac/__init__.py b/custom_components/generac/__init__.py index 509676c..0cb4d55 100644 --- a/custom_components/generac/__init__.py +++ b/custom_components/generac/__init__.py @@ -16,6 +16,7 @@ from .api import InvalidCredentialsException from .auth import GeneracAuth from .auth import InvalidGrantError +from .blueprints import install_bundled_blueprints from .const import CONF_DPOP_PEM from .const import CONF_PASSWORD from .const import CONF_REFRESH_TOKEN @@ -25,8 +26,10 @@ from .const import PLATFORMS from .const import STARTUP_MESSAGE from .coordinator import GeneracDataUpdateCoordinator -from .issues import async_delete_token_expiry_issue +from .issues import async_delete_all_entry_issues +from .readiness import async_remove_readiness_store from .utils import async_client_session +from .utils import entry_options _LOGGER: logging.Logger = logging.getLogger(__package__) @@ -37,7 +40,7 @@ def _reload_signature(entry: ConfigEntry) -> tuple[dict, dict]: """Snapshot of entry options and non-token data that require a reload on change.""" return ( - dict(entry.options), + dict(entry_options(entry)), {k: v for k, v in entry.data.items() if k not in _TOKEN_KEYS}, ) @@ -114,6 +117,14 @@ async def _persist_relogin(fresh: GeneracAuth) -> None: if not coordinator.last_update_success: raise ConfigEntryNotReady + try: + await hass.async_add_executor_job( + install_bundled_blueprints, + hass.config.path("blueprints", "automation", DOMAIN), + ) + except OSError as ex: + _LOGGER.warning("Could not install bundled Generac blueprints: %s", ex) + hass.data[DOMAIN][entry.entry_id] = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) @@ -153,5 +164,6 @@ async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: async def async_remove_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: - """Clean up the expiry Repairs issue when the entry is deleted.""" - async_delete_token_expiry_issue(hass, entry) + """Clean up Repairs issues and readiness storage when the entry is deleted.""" + async_delete_all_entry_issues(hass, entry) + await async_remove_readiness_store(hass, entry) diff --git a/custom_components/generac/binary_sensor.py b/custom_components/generac/binary_sensor.py index 40b6a60..79e8794 100644 --- a/custom_components/generac/binary_sensor.py +++ b/custom_components/generac/binary_sensor.py @@ -1,4 +1,6 @@ """Binary sensor platform for generac.""" +from __future__ import annotations + from typing import Type from homeassistant.components.binary_sensor import BinarySensorDeviceClass @@ -7,9 +9,11 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback +from .const import DEVICE_TYPE_GENERATOR from .const import DOMAIN from .coordinator import GeneracDataUpdateCoordinator from .entity import GeneracEntity +from .models import Item async def async_setup_entry( @@ -22,17 +26,21 @@ async def async_setup_entry( async_add_entities( sensor(coordinator, entry, device_id, item) for device_id, item in data.items() - for sensor in sensors() + for sensor in sensors(item) ) -def sensors() -> Type[GeneracEntity]: - return [ +def sensors(item: Item | None = None) -> list[Type[GeneracEntity]]: + """Return binary sensor entity classes applicable to an item.""" + lst: list[Type[GeneracEntity]] = [ GeneracConnectedSensor, GeneracConnectingSensor, GeneracMaintenanceAlertSensor, GeneracWarningSensor, ] + if item is not None and item.apparatus.type == DEVICE_TYPE_GENERATOR: + lst.append(GeneracMissedExerciseSensor) + return lst class GeneracConnectedSensor(GeneracEntity, BinarySensorEntity): @@ -101,3 +109,17 @@ def device_class(self): def is_on(self): """Return true if the binary_sensor is on.""" return self.aparatus_detail.showWarning + + +class GeneracMissedExerciseSensor(GeneracEntity, BinarySensorEntity): + """Binary sensor indicating whether scheduled exercise appears overdue.""" + + entity_key = "missed_exercise" + entity_label = "Missed Exercise" + + _attr_device_class = BinarySensorDeviceClass.PROBLEM + + @property + def is_on(self) -> bool: + """Return True if the generator has missed its exercise window.""" + return bool(self.coordinator.is_missed_exercise(self.device_id)) diff --git a/custom_components/generac/blueprints.py b/custom_components/generac/blueprints.py new file mode 100644 index 0000000..468324a --- /dev/null +++ b/custom_components/generac/blueprints.py @@ -0,0 +1,33 @@ +"""Installer for bundled Generac Home Assistant automation blueprints.""" +from __future__ import annotations + +from pathlib import Path + +BUNDLED_BLUEPRINTS_DIR = Path(__file__).resolve().parent / "blueprints" / "automation" + + +def list_bundled_blueprints() -> list[Path]: + """Return sorted paths to bundled automation blueprint YAML files.""" + if not BUNDLED_BLUEPRINTS_DIR.is_dir(): + return [] + return sorted(BUNDLED_BLUEPRINTS_DIR.glob("*.yaml")) + + +def install_bundled_blueprints(target_dir: str | Path) -> list[Path]: + """Copy bundled automation blueprints into ``target_dir`` if missing or changed. + + Idempotent and safe to run inside ``hass.async_add_executor_job``. + Returns the list of destination paths written. + """ + dest_dir = Path(target_dir) + dest_dir.mkdir(parents=True, exist_ok=True) + + written: list[Path] = [] + for src in list_bundled_blueprints(): + content = src.read_bytes() + dest = dest_dir / src.name + if dest.exists() and dest.read_bytes() == content: + continue + dest.write_bytes(content) + written.append(dest) + return written diff --git a/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml b/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml new file mode 100644 index 0000000..26a0408 --- /dev/null +++ b/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml @@ -0,0 +1,105 @@ +blueprint: + name: Generac Fault & Dealer Contact Alert + description: >- + Send a detailed notification including generator status, diagnostic text, + and your preferred dealer's name and phone number when a fault, stop, + communication issue, warning, or maintenance alert occurs. + domain: automation + author: ha-generac + input: + status_sensor: + name: Generator Status Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + status_text_sensor: + name: Generator Status Text Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + warning_sensor: + name: Generator Warning Binary Sensor + selector: + entity: + filter: + - integration: generac + domain: binary_sensor + maintenance_sensor: + name: Generator Maintenance Alert Binary Sensor + selector: + entity: + filter: + - integration: generac + domain: binary_sensor + dealer_name_sensor: + name: Dealer Name Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + dealer_phone_sensor: + name: Dealer Phone Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + 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: queued +max: 10 + +triggers: + - trigger: state + entity_id: !input status_sensor + to: + - "Warning" + - "Stopped" + - "Communication Issue" + - trigger: state + entity_id: !input warning_sensor + to: "on" + - trigger: state + entity_id: !input maintenance_sensor + to: "on" + +variables: + status_entity: !input status_sensor + status_text_entity: !input status_text_sensor + maintenance_entity: !input maintenance_sensor + dealer_name_entity: !input dealer_name_sensor + dealer_phone_entity: !input dealer_phone_sensor + +actions: + - alias: Send fault and dealer contact notification + action: !input notify_service + data: + title: >- + {% if trigger.entity_id == maintenance_entity %} + Generac Maintenance Alert ({{ states(status_entity) }}) + {% else %} + Generac Alert: {{ states(status_entity) }} + {% endif %} + message: >- + {% set status = states(status_entity) %} + {% set details = states(status_text_entity) %} + {% set dealer = states(dealer_name_entity) %} + {% set phone = states(dealer_phone_entity) %} + Status: {{ status }} + {% if details not in ['unknown', 'unavailable', ''] %} + Details: {{ details }} + {% endif %} + Dealer: {{ dealer if dealer not in ['unknown', 'unavailable', ''] else 'Not configured' }} + Phone: {{ phone if phone not in ['unknown', 'unavailable', ''] else 'Not configured' }} diff --git a/custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml b/custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml new file mode 100644 index 0000000..be5d90f --- /dev/null +++ b/custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml @@ -0,0 +1,96 @@ +blueprint: + name: Generac Outage Load Shedding + description: >- + Automatically turn off high-draw appliances or circuits when a Generac + generator transitions to "Running" (ignoring scheduled "Exercising" + cycles), wait for utility power to stabilize in "Ready", and optionally + restore shed loads with a stagger delay. + 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 + shed_entities: + name: High-Draw Entities to Shed + description: >- + Entities (switches, climates, water heaters, EV chargers, etc.) to + turn off while running on generator power. + selector: + entity: + multiple: true + ready_stabilization_delay: + name: Utility Stabilization Delay + description: >- + Seconds to wait after the generator returns to "Ready" before + restoring loads. + default: 60 + selector: + number: + min: 0 + max: 600 + unit_of_measurement: seconds + restore_loads: + name: Restore Shed Loads + description: Turn shed entities back on after utility power stabilizes. + default: true + selector: + boolean: {} + restore_stagger_delay: + name: Restore Stagger Delay + description: >- + Optional delay between turning each shed entity back on to avoid + inrush spikes (0 restores all entities without pausing). + default: 5 + selector: + number: + min: 0 + max: 120 + unit_of_measurement: seconds + +mode: restart +max_exceeded: silent + +triggers: + - trigger: state + entity_id: !input generator_status + to: "Running" + +variables: + restore_loads: !input restore_loads + restore_stagger_delay: !input restore_stagger_delay + +actions: + - alias: Shed high-draw loads + action: homeassistant.turn_off + target: + entity_id: !input shed_entities + - alias: Wait for generator to return to Ready + wait_for_trigger: + - trigger: state + entity_id: !input generator_status + to: "Ready" + for: + seconds: !input ready_stabilization_delay + - if: + - condition: template + value_template: "{{ restore_loads }}" + then: + - alias: Restore shed loads + repeat: + for_each: !input shed_entities + sequence: + - action: homeassistant.turn_on + target: + entity_id: "{{ repeat.item }}" + - if: + - condition: template + value_template: "{{ (restore_stagger_delay | int(0)) > 0 and not repeat.last }}" + then: + - delay: + seconds: !input restore_stagger_delay diff --git a/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml b/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml new file mode 100644 index 0000000..8c8a002 --- /dev/null +++ b/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml @@ -0,0 +1,91 @@ +blueprint: + name: Generac Pre-Storm Readiness Digest + description: >- + When a weather alert or storm readiness trigger turns on, send a summary of + your generator's readiness including status, connectivity, battery voltage, + hours until service, and optional propane tank fuel level. + domain: automation + author: ha-generac + input: + weather_alert_entity: + name: Weather Alert / Trigger Entity + description: Binary sensor or input boolean that turns on ahead of severe weather. + selector: + entity: + filter: + - domain: binary_sensor + - domain: input_boolean + status_sensor: + name: Generator Status Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + battery_voltage_sensor: + name: Generator Battery Voltage Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + is_connected_sensor: + name: Generator Connected Binary Sensor + selector: + entity: + filter: + - integration: generac + domain: binary_sensor + hours_until_service_sensor: + name: Hours Until Service Sensor + selector: + entity: + filter: + - integration: generac + domain: sensor + fuel_level_sensor: + name: Propane Fuel Level Sensor (Optional) + description: Optional Generac propane tank monitor fuel level sensor. + default: "" + selector: + entity: + filter: + - integration: generac + domain: sensor + 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 + +triggers: + - trigger: state + entity_id: !input weather_alert_entity + to: "on" + +variables: + status_entity: !input status_sensor + battery_entity: !input battery_voltage_sensor + connected_entity: !input is_connected_sensor + service_entity: !input hours_until_service_sensor + fuel_entity: !input fuel_level_sensor + +actions: + - alias: Send pre-storm generator readiness digest + action: !input notify_service + data: + title: "Generac Pre-Storm Readiness Digest" + message: >- + {% set connected = is_state(connected_entity, 'on') %} + Status: {{ states(status_entity) }} + Connected: {{ 'Online' if connected else 'Offline' }} + Battery Voltage: {{ states(battery_entity) }} V + Hours Until Service: {{ states(service_entity) }} h + {% if fuel_entity %} + Propane Fuel Level: {{ states(fuel_entity) }}% + {% endif %} diff --git a/custom_components/generac/button.py b/custom_components/generac/button.py new file mode 100644 index 0000000..c9afcb6 --- /dev/null +++ b/custom_components/generac/button.py @@ -0,0 +1,51 @@ +"""Button platform for generac.""" +from __future__ import annotations + +from typing import Type + +from homeassistant.components.button import ButtonEntity +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddEntitiesCallback + +from .const import DEVICE_TYPE_GENERATOR +from .const import DOMAIN +from .coordinator import GeneracDataUpdateCoordinator +from .entity import GeneracEntity +from .models import Item + + +async def async_setup_entry( + hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback +) -> None: + """Set up button platform.""" + coordinator: GeneracDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] + data = coordinator.data + if isinstance(data, dict): + async_add_entities( + btn(coordinator, entry, device_id, item) + for device_id, item in data.items() + 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 [] + + +class ResetServiceTimerButton(GeneracEntity, ButtonEntity): + """Button to reset the generator's maintenance service interval baseline.""" + + entity_key = "reset_service_timer" + entity_label = "Reset Maintenance Timer" + + _attr_icon = "mdi:wrench-check" + + async def async_press(self) -> None: + """Reset service baseline hours to current run time and re-evaluate alerts.""" + 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() diff --git a/custom_components/generac/config_flow.py b/custom_components/generac/config_flow.py index 3f6721c..c1a19fa 100644 --- a/custom_components/generac/config_flow.py +++ b/custom_components/generac/config_flow.py @@ -37,17 +37,20 @@ from .auth import MfaRequiredError from .auth import MfaUnsupportedError from .const import CONF_DPOP_PEM +from .const import CONF_EXERCISE_INTERVAL_DAYS from .const import CONF_MFA_CODE from .const import CONF_OPTIONS from .const import CONF_PASSWORD from .const import CONF_REFRESH_TOKEN from .const import CONF_REMEMBER_PASSWORD from .const import CONF_SCAN_INTERVAL +from .const import CONF_SERVICE_INTERVAL_HOURS from .const import CONF_TOKEN_ISSUED_AT from .const import CONF_USERNAME from .const import DEFAULT_SCAN_INTERVAL from .const import DOMAIN from .utils import async_client_session +from .utils import entry_options _LOGGER: logging.Logger = logging.getLogger(__package__) @@ -242,7 +245,7 @@ async def async_step_reconfigure(self, user_input=None): default_email = entry.data.get(CONF_USERNAME, "") if entry else "" default_scan_interval = ( - (entry.options or {}).get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) + entry_options(entry).get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) if entry else DEFAULT_SCAN_INTERVAL ) @@ -277,7 +280,7 @@ async def _finish_reconfigure(self, entry_data: dict): # Persist polling interval into entry.options so the coordinator # picks it up the same way the OptionsFlow does. new_options = { - **(entry.options or {}), + **entry_options(entry), CONF_SCAN_INTERVAL: int(self._pending_scan_interval), } # Update the stored data/options. When the entry is already loaded the @@ -459,11 +462,20 @@ def async_get_options_flow(config_entry): return GeneracOptionsFlowHandler(config_entry) +def _option_validator(key: str, option_type: type): + """Build a Voluptuous validator for an integration option.""" + if option_type is float: + return vol.All(vol.Coerce(float), vol.Range(min=0.0)) + if key in (CONF_SERVICE_INTERVAL_HOURS, CONF_EXERCISE_INTERVAL_DAYS): + return vol.All(int, vol.Range(min=0)) + return option_type + + class GeneracOptionsFlowHandler(config_entries.OptionsFlow): """Config flow options handler for generac.""" def __init__(self, config_entry): - self.options = dict(config_entry.options) + self.options = dict(entry_options(config_entry)) async def async_step_init(self, user_input=None): # pylint: disable=unused-argument return await self.async_step_user() @@ -477,9 +489,9 @@ async def async_step_user(self, user_input=None): step_id="user", data_schema=vol.Schema( { - vol.Required(k, default=self.options.get(k, v["default"])): v[ - "type" - ] + vol.Required( + k, default=self.options.get(k, v["default"]) + ): _option_validator(k, v["type"]) for k, v in CONF_OPTIONS.items() } ), diff --git a/custom_components/generac/const.py b/custom_components/generac/const.py index 3a2073d..47f99cb 100644 --- a/custom_components/generac/const.py +++ b/custom_components/generac/const.py @@ -37,7 +37,15 @@ SENSOR = "sensor" WEATHER = "weather" IMAGE = "image" -PLATFORMS = [BINARY_SENSOR, SENSOR, WEATHER, IMAGE] +BUTTON = "button" +PLATFORMS = [BINARY_SENSOR, SENSOR, WEATHER, IMAGE, BUTTON] + +# Readiness & maintenance defaults +DEFAULT_SERVICE_INTERVAL_HOURS = 100 +# 16 days covers weekly & biweekly exercise schedules with a grace buffer; +# 0 disables missed-exercise alerts. +DEFAULT_EXERCISE_INTERVAL_DAYS = 16 +DEFAULT_LOW_BATTERY_THRESHOLD = 12.2 # Configuration labels CONF_ENABLED = "enabled" @@ -52,6 +60,9 @@ CONF_REFRESH_TOKEN = "refresh_token" CONF_DPOP_PEM = "dpop_pem" CONF_SCAN_INTERVAL = "scan_interval" +CONF_SERVICE_INTERVAL_HOURS = "service_interval_hours" +CONF_EXERCISE_INTERVAL_DAYS = "exercise_interval_days" +CONF_LOW_BATTERY_THRESHOLD = "low_battery_threshold" # Opt-in: keep the password in entry.data so an expired refresh token can be # replaced by a silent re-login instead of a manual reauth. CONF_REMEMBER_PASSWORD = "remember_password" @@ -73,6 +84,18 @@ CONF_OPTIONS = { **bool_opts, CONF_SCAN_INTERVAL: {"type": int, "default": DEFAULT_SCAN_INTERVAL}, + CONF_SERVICE_INTERVAL_HOURS: { + "type": int, + "default": DEFAULT_SERVICE_INTERVAL_HOURS, + }, + CONF_EXERCISE_INTERVAL_DAYS: { + "type": int, + "default": DEFAULT_EXERCISE_INTERVAL_DAYS, + }, + CONF_LOW_BATTERY_THRESHOLD: { + "type": float, + "default": DEFAULT_LOW_BATTERY_THRESHOLD, + }, } STARTUP_MESSAGE = f""" diff --git a/custom_components/generac/coordinator.py b/custom_components/generac/coordinator.py index 1f27eb1..94e4639 100644 --- a/custom_components/generac/coordinator.py +++ b/custom_components/generac/coordinator.py @@ -1,3 +1,6 @@ +"""DataUpdateCoordinator for the Generac MobileLink integration.""" +from __future__ import annotations + import logging from datetime import timedelta @@ -14,8 +17,12 @@ from .const import CONF_SCAN_INTERVAL from .const import DEFAULT_SCAN_INTERVAL from .const import DOMAIN +from .issues import async_update_device_health_issues from .issues import async_update_token_expiry_issue from .models import Item +from .readiness import get_run_time +from .readiness import ReadinessTracker +from .utils import entry_options _LOGGER: logging.Logger = logging.getLogger(__package__) @@ -34,8 +41,11 @@ def __init__( self.reload_signature: tuple[dict, dict] | None = None self.persisted_credentials: tuple[str | None, str | None] | None = None self.pending_credential_updates: int = 0 + self.readiness = ReadinessTracker(hass, config_entry) scan_interval = timedelta( - seconds=config_entry.options.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) + seconds=entry_options(config_entry).get( + CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL + ) ) super().__init__( hass, @@ -45,6 +55,30 @@ def __init__( config_entry=config_entry, ) + 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) + + def hours_until_service(self, device_id: str) -> float | None: + """Return estimated runtime hours remaining until scheduled maintenance.""" + return self.readiness.hours_until_service(device_id) + + 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) + + 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 + current_run_time = get_run_time(item) if isinstance(item, Item) else None + await self.readiness.async_reset_service_timer( + device_id, current_run_time=current_run_time + ) + async_update_device_health_issues( + self.hass, self._config_entry, self.data, self.readiness + ) + self.async_update_listeners() + async def _async_update_data(self): """Update data via library.""" try: @@ -52,7 +86,13 @@ async def _async_update_data(self): items = await self.api.async_get_data() self.is_online = items is not None _LOGGER.info("Generac poll OK: %d device(s)", len(items) if items else 0) + await self.readiness.async_load() + if isinstance(items, dict): + await self.readiness.async_update_from_items(items) async_update_token_expiry_issue(self.hass, self._config_entry) + async_update_device_health_issues( + self.hass, self._config_entry, items, self.readiness + ) return items except (InvalidCredentialsException, InvalidGrantError) as ex: # Refresh token / login no longer valid — trigger HA reauth flow. diff --git a/custom_components/generac/issues.py b/custom_components/generac/issues.py index bad0f17..1a3dbef 100644 --- a/custom_components/generac/issues.py +++ b/custom_components/generac/issues.py @@ -1,28 +1,65 @@ -"""Repairs issue warning that the refresh token is about to expire.""" +"""Repairs issues for Generac sign-in expiry and proactive hardware readiness.""" from __future__ import annotations import time from datetime import datetime from datetime import timezone +from typing import Any from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir +from .const import CONF_EXERCISE_INTERVAL_DAYS +from .const import CONF_LOW_BATTERY_THRESHOLD from .const import CONF_PASSWORD +from .const import CONF_SERVICE_INTERVAL_HOURS from .const import CONF_TOKEN_ISSUED_AT from .const import CONF_USERNAME +from .const import DEFAULT_EXERCISE_INTERVAL_DAYS +from .const import DEFAULT_LOW_BATTERY_THRESHOLD +from .const import DEFAULT_SERVICE_INTERVAL_HOURS +from .const import DEVICE_TYPE_GENERATOR from .const import DOMAIN from .const import REFRESH_TOKEN_LIFETIME_DAYS from .const import REFRESH_TOKEN_WARN_DAYS +from .models import Apparatus +from .models import ApparatusDetail +from .models import Item +from .readiness import get_battery_voltage +from .readiness import ReadinessTracker +from .utils import entry_options _DAY = 86400 +ISSUE_LOW_BATTERY_VOLTAGE = "low_battery_voltage" +ISSUE_MISSED_EXERCISE = "missed_exercise" +ISSUE_MAINTENANCE_DUE = "maintenance_due" +ISSUE_SUBSCRIPTION_DUNNING = "subscription_dunning" + +_DEVICE_ISSUE_KEYS = ( + ISSUE_LOW_BATTERY_VOLTAGE, + ISSUE_MISSED_EXERCISE, + ISSUE_MAINTENANCE_DUE, + ISSUE_SUBSCRIPTION_DUNNING, +) + def _issue_id(entry: ConfigEntry) -> str: return f"refresh_token_expiring_{entry.entry_id}" +def _device_issue_id(issue_key: str, entry_id: str, device_id: str) -> str: + return f"{issue_key}_{entry_id}_{device_id}" + + +def _belongs_to_entry(issue: ir.IssueEntry, entry_id: str) -> bool: + if isinstance(issue.data, dict) and "entry_id" in issue.data: + return issue.data.get("entry_id") == entry_id + prefixes = tuple(f"{key}_{entry_id}_" for key in _DEVICE_ISSUE_KEYS) + return issue.issue_id.startswith(prefixes) + + def async_update_token_expiry_issue(hass: HomeAssistant, entry: ConfigEntry) -> None: """Create or clear the "sign in again soon" Repairs issue for an entry. @@ -58,5 +95,181 @@ def async_update_token_expiry_issue(hass: HomeAssistant, entry: ConfigEntry) -> def async_delete_token_expiry_issue(hass: HomeAssistant, entry: ConfigEntry) -> None: - """Remove the issue (entry deleted).""" + """Remove the token-expiry issue (entry deleted).""" ir.async_delete_issue(hass, DOMAIN, _issue_id(entry)) + + +def async_update_device_health_issues( + hass: HomeAssistant, + entry: ConfigEntry, + items: dict[str, Any] | None, + readiness: ReadinessTracker | None = None, + now: float | None = None, +) -> None: + """Create or clear per-device hardware, exercise, maintenance, and billing issues.""" + entry_id = getattr(entry, "entry_id", None) + if not isinstance(entry_id, str) or not isinstance(items, dict): + return + + options = entry_options(entry) + low_battery_threshold = float( + options.get(CONF_LOW_BATTERY_THRESHOLD, DEFAULT_LOW_BATTERY_THRESHOLD) + ) + exercise_interval_days = int( + options.get(CONF_EXERCISE_INTERVAL_DAYS, DEFAULT_EXERCISE_INTERVAL_DAYS) + ) + service_interval_hours = int( + options.get(CONF_SERVICE_INTERVAL_HOURS, DEFAULT_SERVICE_INTERVAL_HOURS) + ) + + active_issue_ids: set[str] = set() + + def _sync_issue( + issue_key: str, + device_id: str, + active: bool, + placeholders: dict[str, str] | None = None, + ) -> None: + issue_id = _device_issue_id(issue_key, entry_id, device_id) + if active: + active_issue_ids.add(issue_id) + ir.async_create_issue( + hass, + DOMAIN, + issue_id, + data={"entry_id": entry_id, "device_id": device_id}, + is_fixable=False, + is_persistent=False, + severity=ir.IssueSeverity.WARNING, + translation_key=issue_key, + translation_placeholders=placeholders or {}, + ) + else: + ir.async_delete_issue(hass, DOMAIN, issue_id) + + for device_id, item in items.items(): + if not isinstance(item, Item): + continue + apparatus = ( + item.apparatus if isinstance(item.apparatus, Apparatus) else Apparatus() + ) + detail = ( + item.apparatusDetail + if isinstance(item.apparatusDetail, ApparatusDetail) + else ApparatusDetail() + ) + is_generator = apparatus.type == DEVICE_TYPE_GENERATOR + device_name = apparatus.name or detail.name or str(device_id) + + # 1. Low battery voltage (generator detail property 70) + voltage = get_battery_voltage(item) if is_generator else None + low_battery = voltage is not None and 0 < voltage < low_battery_threshold + _sync_issue( + ISSUE_LOW_BATTERY_VOLTAGE, + device_id, + low_battery, + ( + { + "device_name": device_name, + "voltage": f"{voltage:.1f}", + "threshold": f"{low_battery_threshold:.1f}", + } + if low_battery + else None + ), + ) + + # 2. Missed scheduled exercise + missed = bool( + is_generator + and readiness is not None + and readiness.is_missed_exercise(device_id, now=now) + ) + if missed and readiness is not None: + days_since = readiness.days_since_exercise(device_id, now=now) or 0.0 + _sync_issue( + ISSUE_MISSED_EXERCISE, + device_id, + True, + { + "device_name": device_name, + "interval_days": str(exercise_interval_days), + "days_since": f"{days_since:.1f}", + }, + ) + else: + _sync_issue(ISSUE_MISSED_EXERCISE, device_id, False) + + # 3. Maintenance due (runtime timer or Mobile Link maintenance alert) + hours_since = ( + readiness.hours_since_service(device_id) + if (is_generator and readiness is not None) + else None + ) + timer_due = bool( + is_generator + and service_interval_hours > 0 + and hours_since is not None + and hours_since >= service_interval_hours + ) + api_alert = detail.hasMaintenanceAlert is True + maint_due = timer_due or api_alert + if maint_due: + if timer_due and api_alert and hours_since is not None: + reason = ( + f"Mobile Link maintenance alert is active and {hours_since:.1f} h " + f"logged since last service (interval: {service_interval_hours} h)" + ) + elif timer_due and hours_since is not None: + reason = ( + f"{hours_since:.1f} h logged since last service " + f"(interval: {service_interval_hours} h)" + ) + else: + reason = "Mobile Link maintenance alert is active" + _sync_issue( + ISSUE_MAINTENANCE_DUE, + device_id, + True, + {"device_name": device_name, "reason": reason}, + ) + else: + _sync_issue(ISSUE_MAINTENANCE_DUE, device_id, False) + + # 4. Mobile Link subscription dunning + dunning = ( + detail.subscription is not None and detail.subscription.isDunning is True + ) + _sync_issue( + ISSUE_SUBSCRIPTION_DUNNING, + device_id, + dunning, + {"device_name": device_name} if dunning else None, + ) + + # Clear any stale device issues for devices no longer returned by the API + registry = ir.async_get(hass) + for (domain, issue_id), issue in list(registry.issues.items()): + if ( + domain == DOMAIN + and issue_id not in active_issue_ids + and issue_id != _issue_id(entry) + and _belongs_to_entry(issue, entry_id) + ): + ir.async_delete_issue(hass, DOMAIN, issue_id) + + +def async_delete_all_entry_issues(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Remove all Repairs issues belonging to an entry (token expiry + device health).""" + async_delete_token_expiry_issue(hass, entry) + entry_id = getattr(entry, "entry_id", None) + if not isinstance(entry_id, str): + return + registry = ir.async_get(hass) + to_delete = [ + issue_id + for (domain, issue_id), issue in list(registry.issues.items()) + if domain == DOMAIN and _belongs_to_entry(issue, entry_id) + ] + for issue_id in to_delete: + ir.async_delete_issue(hass, DOMAIN, issue_id) diff --git a/custom_components/generac/readiness.py b/custom_components/generac/readiness.py new file mode 100644 index 0000000..f12ea5b --- /dev/null +++ b/custom_components/generac/readiness.py @@ -0,0 +1,238 @@ +"""Service and exercise readiness persistence and tracking for Generac.""" +from __future__ import annotations + +import time +from typing import Any + +from homeassistant.config_entries import ConfigEntry +from homeassistant.core import HomeAssistant +from homeassistant.helpers.storage import Store + +from .const import CONF_EXERCISE_INTERVAL_DAYS +from .const import CONF_SERVICE_INTERVAL_HOURS +from .const import DEFAULT_EXERCISE_INTERVAL_DAYS +from .const import DEFAULT_SERVICE_INTERVAL_HOURS +from .const import DEVICE_TYPE_GENERATOR +from .const import DOMAIN +from .models import Apparatus +from .models import ApparatusDetail +from .models import Item +from .utils import entry_options +from .utils import get_detail_property_value +from .utils import safe_float + +STORAGE_VERSION = 1 +_ACTIVE_APPARATUS_STATUSES = (2, 3) # Running (2), Exercising (3) +_SECONDS_PER_DAY = 86400 + + +def readiness_store_key(entry_id: str) -> str: + """Return the Home Assistant storage key for an entry's readiness state.""" + return f"{DOMAIN}.{entry_id}.readiness" + + +def get_run_time(item: Item) -> float | None: + """Extract generator cumulative runtime hours (detail property 71).""" + return safe_float(get_detail_property_value(item, 71), "run_time") + + +def get_battery_voltage(item: Item) -> float | None: + """Extract generator battery voltage (detail property 70).""" + return safe_float(get_detail_property_value(item, 70), "battery_voltage") + + +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() + + +class ReadinessTracker: + """Tracks per-generator exercise activity and maintenance baselines in HA storage.""" + + 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)) + if isinstance(entry_id, str) and hass is not None + else None + ) + self._devices: dict[str, dict[str, Any]] = {} + self._loaded = False + + async def async_load(self) -> None: + """Load persisted readiness records once.""" + if self._loaded: + return + self._loaded = True + if self._store is None: + return + raw = await self._store.async_load() + if not isinstance(raw, dict): + return + devices = raw.get("devices") + if not isinstance(devices, dict): + return + 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")) + self._devices[str(dev_id)] = { + "last_exercise_ts": last_ts, + "last_run_time": last_rt, + "service_baseline_hours": baseline if baseline is not None else 0.0, + } + + async def _async_save(self) -> None: + """Persist current readiness state to Store.""" + if self._store is None: + return + await self._store.async_save({"devices": self._devices}) + + def get_device_state(self, device_id: str) -> dict[str, Any] | None: + """Return a shallow copy of the readiness record for a generator.""" + record = self._devices.get(device_id) + return dict(record) if record is not None else 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.""" + await self.async_load() + ts = time.time() if now is None else float(now) + changed = False + + for device_id, item in items.items(): + if not isinstance(item, Item): + continue + apparatus = item.apparatus + if ( + not isinstance(apparatus, Apparatus) + or apparatus.type != DEVICE_TYPE_GENERATOR + ): + continue + detail = ( + item.apparatusDetail + if isinstance(item.apparatusDetail, ApparatusDetail) + else ApparatusDetail() + ) + current_run_time = get_run_time(item) + + if device_id not in self._devices: + # Initialize baseline to current run hours to prevent false day-1 alarms. + self._devices[device_id] = { + "last_exercise_ts": ts, + "last_run_time": current_run_time, + "service_baseline_hours": ( + current_run_time if current_run_time is not None else 0.0 + ), + } + changed = True + continue + + record = self._devices[device_id] + prev_run_time = record.get("last_run_time") + exercised = detail.apparatusStatus in _ACTIVE_APPARATUS_STATUSES or ( + current_run_time is not None + and prev_run_time is not None + and current_run_time > prev_run_time + ) + if exercised: + record["last_exercise_ts"] = ts + changed = True + if current_run_time is not None and current_run_time != prev_run_time: + record["last_run_time"] = current_run_time + changed = True + + if changed: + await self._async_save() + + def hours_since_service(self, device_id: str) -> float | None: + """Return runtime hours accumulated since the maintenance baseline.""" + record = self._devices.get(device_id) + if record is None: + return None + last_run_time = record.get("last_run_time") + if last_run_time is None: + return None + baseline = float(record.get("service_baseline_hours") or 0.0) + return round(max(0.0, float(last_run_time) - baseline), 4) + + def hours_until_service(self, device_id: str) -> float | None: + """Return estimated runtime hours remaining until scheduled maintenance.""" + interval = entry_options(self._entry).get( + CONF_SERVICE_INTERVAL_HOURS, DEFAULT_SERVICE_INTERVAL_HOURS + ) + if interval is None or interval <= 0: + return None + since = self.hours_since_service(device_id) + if since is None: + return None + return round(max(0.0, float(interval) - since), 4) + + def days_since_exercise( + self, device_id: str, now: float | None = None + ) -> float | None: + """Return elapsed days since last observed exercise or run activity.""" + record = self._devices.get(device_id) + if record is None: + return None + last_ts = record.get("last_exercise_ts") + if last_ts is None: + return None + ts = time.time() if now is None else float(now) + return round(max(0.0, (ts - float(last_ts)) / _SECONDS_PER_DAY), 1) + + def is_missed_exercise(self, device_id: str, now: float | None = None) -> bool: + """Return True if elapsed time since last exercise exceeds the configured window.""" + interval_days = entry_options(self._entry).get( + CONF_EXERCISE_INTERVAL_DAYS, DEFAULT_EXERCISE_INTERVAL_DAYS + ) + if interval_days is None or interval_days <= 0: + return False + record = self._devices.get(device_id) + if record is None: + return False + last_ts = record.get("last_exercise_ts") + if last_ts is None: + return False + ts = time.time() if now is None else float(now) + return (ts - float(last_ts)) > float(interval_days) * _SECONDS_PER_DAY + + async def async_reset_service_timer( + self, + device_id: str, + current_run_time: float | None = None, + now: float | None = None, + ) -> None: + """Reset service baseline hours to current run time and persist immediately.""" + await self.async_load() + ts = time.time() if now is None else float(now) + record = self._devices.get(device_id) + if record is None: + baseline = float(current_run_time) if current_run_time is not None else 0.0 + self._devices[device_id] = { + "last_exercise_ts": ts, + "last_run_time": current_run_time, + "service_baseline_hours": baseline, + } + else: + effective_run_time = ( + current_run_time + if current_run_time is not None + else record.get("last_run_time") + ) + record["service_baseline_hours"] = ( + float(effective_run_time) if effective_run_time is not None else 0.0 + ) + if current_run_time is not None: + record["last_run_time"] = current_run_time + await self._async_save() diff --git a/custom_components/generac/sensor.py b/custom_components/generac/sensor.py index a5bb6ae..1b222a5 100644 --- a/custom_components/generac/sensor.py +++ b/custom_components/generac/sensor.py @@ -1,5 +1,4 @@ """Sensor platform for generac.""" -import logging from datetime import datetime from typing import Type @@ -10,6 +9,7 @@ from homeassistant.const import PERCENTAGE from homeassistant.const import UnitOfElectricPotential from homeassistant.const import UnitOfTemperature +from homeassistant.const import UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback @@ -19,6 +19,8 @@ from .coordinator import GeneracDataUpdateCoordinator from .entity import GeneracEntity from .models import Item +from .utils import get_detail_property_value +from .utils import safe_float as _safe_float async def async_setup_entry( @@ -64,6 +66,7 @@ def sensors(item: Item) -> list[Type[GeneracEntity]]: # Always created for generators so existing registry entries are # never orphaned; it reports unknown when the value is missing. SignalStrengthSensor, + HoursUntilServiceSensor, ] elif item.apparatus.type == DEVICE_TYPE_PROPANE_MONITOR: lst = [ @@ -117,20 +120,6 @@ def get_prop_value(props, type_num: int, default_val): return val -def get_detail_property_value(item: Item, property_type: int): - """Return a detail property value by its Mobile Link type code.""" - if item.apparatusDetail.properties is None: - return None - return next( - ( - prop.value - for prop in item.apparatusDetail.properties - if prop.type == property_type - ), - None, - ) - - def get_apparatus_property_value(item: Item, field: str): """Return a scalar field from the apparatus property payload.""" if item.apparatus.properties is None: @@ -145,27 +134,6 @@ def get_apparatus_property_value(item: Item, field: str): return None -_LOGGER = logging.getLogger(__name__) - - -def _safe_float(val, label: str = ""): - """Best-effort float conversion; return None on bad data so the - sensor reports ``unknown`` instead of crashing native_value.""" - if val is None: - return None - if isinstance(val, (int, float)): - return float(val) - if isinstance(val, str) and val.strip().endswith("%"): - val = val.strip()[:-1].strip() - try: - return float(val) - except (TypeError, ValueError) as ex: - _LOGGER.debug( - "Could not convert %s sensor value %r to float: %s", label, val, ex - ) - return None - - class StatusSensor(GeneracEntity, SensorEntity): """generac Sensor class.""" @@ -573,3 +541,30 @@ def native_value(self): get_apparatus_property_value(self.item, "batteryLevel"), "device_battery_level", ) + + +class HoursUntilServiceSensor(GeneracEntity, SensorEntity): + """Estimated runtime hours remaining until scheduled generator service.""" + + entity_key = "hours_until_service" + entity_label = "Hours Until Service" + + _attr_device_class = SensorDeviceClass.DURATION + _attr_native_unit_of_measurement = UnitOfTime.HOURS + _attr_state_class = SensorStateClass.MEASUREMENT + _attr_icon = "mdi:wrench-clock" + _attr_suggested_display_precision = 1 + + @property + def native_value(self): + """Return remaining runtime hours until maintenance is due.""" + return self.coordinator.hours_until_service(self.device_id) + + @property + def extra_state_attributes(self): + """Include hours logged since the last maintenance baseline.""" + attrs = dict(super().extra_state_attributes) + hours_since = self.coordinator.hours_since_service(self.device_id) + if hours_since is None or isinstance(hours_since, (int, float)): + attrs["hours_since_service"] = hours_since + return attrs diff --git a/custom_components/generac/translations/en.json b/custom_components/generac/translations/en.json index 4e006d7..da0361d 100644 --- a/custom_components/generac/translations/en.json +++ b/custom_components/generac/translations/en.json @@ -72,9 +72,13 @@ "user": { "data": { "binary_sensor": "Binary sensors enabled", + "button": "Buttons enabled", + "exercise_interval_days": "Missed exercise alert interval (days, 0 to disable)", "image": "Image enabled", + "low_battery_threshold": "Low battery voltage alert threshold (V)", "scan_interval": "Cloud polling interval (seconds)", "sensor": "Non-binary sensors enabled", + "service_interval_hours": "Maintenance service interval (hours, 0 to disable)", "switch": "Switch enabled", "weather": "Weather sensor enabled" } @@ -85,6 +89,22 @@ "refresh_token_expiring": { "title": "Generac sign-in for {username} expires soon", "description": "Generac sessions expire 90 days after sign-in. The session for {username} expires around {expires}, after which your Generac devices will stop updating.\n\nTo renew it, go to Settings → Devices & services → Generac MobileLink, open the ⋮ menu, choose **Reconfigure** and sign in again. Tick **Remember password** to have the integration renew the session automatically from now on." + }, + "low_battery_voltage": { + "title": "Low battery voltage on {device_name}", + "description": "Generator {device_name} reported a battery voltage of {voltage} V, below the configured threshold of {threshold} V. Inspect the battery, charger, and terminals to ensure reliable starting during an outage." + }, + "missed_exercise": { + "title": "Generator {device_name} missed its scheduled exercise", + "description": "Generator {device_name} has not recorded a run or exercise cycle in {days_since} days (alert interval: {interval_days} days). Verify the generator is in Auto mode and inspect its exercise schedule and Mobile Link connection." + }, + "maintenance_due": { + "title": "Maintenance due for {device_name}", + "description": "Generator {device_name} requires scheduled maintenance ({reason}). After servicing the generator, press **Reset Maintenance Timer** on the device page to reset the countdown." + }, + "subscription_dunning": { + "title": "Mobile Link subscription billing issue for {device_name}", + "description": "Generac Mobile Link reports a past-due or dunning subscription status for {device_name}. Update your payment method in the Mobile Link portal to avoid remote monitoring interruption." } } } diff --git a/custom_components/generac/translations/fr.json b/custom_components/generac/translations/fr.json index 929b59a..d364d35 100644 --- a/custom_components/generac/translations/fr.json +++ b/custom_components/generac/translations/fr.json @@ -60,9 +60,13 @@ "user": { "data": { "binary_sensor": "Capteur binaire activé", + "button": "Boutons activés", + "exercise_interval_days": "Intervalle d’alerte d’exercice manqué (jours, 0 pour désactiver)", "image": "Image activé", + "low_battery_threshold": "Seuil d’alerte de tension batterie faible (V)", "scan_interval": "Intervalle d’interrogation en secondes", "sensor": "Capteur activé", + "service_interval_hours": "Intervalle d’entretien (heures, 0 pour désactiver)", "switch": "Interrupteur activé", "weather": "Capteur météo activé" } diff --git a/custom_components/generac/translations/nb.json b/custom_components/generac/translations/nb.json index a66fb09..cfa309a 100644 --- a/custom_components/generac/translations/nb.json +++ b/custom_components/generac/translations/nb.json @@ -60,9 +60,13 @@ "user": { "data": { "binary_sensor": "Binær sensor aktivert", + "button": "Knapper aktivert", + "exercise_interval_days": "Varselintervall for uteblitt testkjøring (dager, 0 for å deaktivere)", "image": "Bilde aktivert", + "low_battery_threshold": "Terskel for varsel om lav batterispenning (V)", "scan_interval": "Avstemningsintervall i sekunder", "sensor": "Sensor aktivert", + "service_interval_hours": "Serviceintervall for vedlikehold (timer, 0 for å deaktivere)", "switch": "Bryter aktivert", "weather": "Værsensor aktivert" } diff --git a/custom_components/generac/translations/pt.json b/custom_components/generac/translations/pt.json index a1cdfc2..00e11bf 100644 --- a/custom_components/generac/translations/pt.json +++ b/custom_components/generac/translations/pt.json @@ -60,9 +60,13 @@ "user": { "data": { "binary_sensor": "Sensores binários ativados", + "button": "Botões ativados", + "exercise_interval_days": "Intervalo de alerta de exercício em falta (dias, 0 para desativar)", "image": "Imagem ativada", + "low_battery_threshold": "Limite de alerta de tensão baixa da bateria (V)", "scan_interval": "Intervalo de sondagem (segundos)", "sensor": "Sensores não binários ativados", + "service_interval_hours": "Intervalo de manutenção (horas, 0 para desativar)", "switch": "Interruptor ativado", "weather": "Sensor meteorológico ativado" } diff --git a/custom_components/generac/utils.py b/custom_components/generac/utils.py index 4b48267..8246ed3 100644 --- a/custom_components/generac/utils.py +++ b/custom_components/generac/utils.py @@ -1,12 +1,62 @@ -"""Helper to create an aiohttp client session for the Generac API.""" +"""Shared helpers for the Generac integration.""" +from __future__ import annotations + +import logging +import math +from collections.abc import Mapping +from typing import Any + from aiohttp import ClientSession from aiohttp import CookieJar +from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import aiohttp_client +from .models import Item + +_LOGGER = logging.getLogger(__package__) + async def async_client_session(hass: HomeAssistant) -> ClientSession: """Return a new aiohttp session.""" return aiohttp_client.async_create_clientsession( hass, cookie_jar=CookieJar(unsafe=True, quote_cookie=False) ) + + +def entry_options(entry: ConfigEntry | None) -> Mapping[str, Any]: + """Return ConfigEntry options as a Mapping, tolerating MagicMock entries in tests.""" + options = getattr(entry, "options", None) + return options if isinstance(options, Mapping) else {} + + +def get_detail_property_value(item: Item, property_type: int) -> Any: + """Return a detail property value by its Mobile Link type code.""" + props = getattr(getattr(item, "apparatusDetail", None), "properties", None) + if props is None: + return None + return next( + (prop.value for prop in props if prop.type == property_type), + None, + ) + + +def safe_float(val: Any, label: str = "") -> float | None: + """Best-effort float conversion; return None on bad or non-finite data.""" + if val is None or isinstance(val, bool): + return None + if isinstance(val, (int, float)): + result = float(val) + else: + if isinstance(val, str) and val.strip().endswith("%"): + val = val.strip()[:-1].strip() + try: + result = float(val) + except (TypeError, ValueError) as ex: + _LOGGER.debug( + "Could not convert %s sensor value %r to float: %s", label, val, ex + ) + return None + if not math.isfinite(result): + return None + return result diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py index acec67f..eeb3db2 100644 --- a/tests/test_binary_sensor.py +++ b/tests/test_binary_sensor.py @@ -4,7 +4,11 @@ from custom_components.generac.binary_sensor import GeneracConnectedSensor from custom_components.generac.binary_sensor import GeneracConnectingSensor from custom_components.generac.binary_sensor import GeneracMaintenanceAlertSensor +from custom_components.generac.binary_sensor import GeneracMissedExerciseSensor from custom_components.generac.binary_sensor import GeneracWarningSensor +from custom_components.generac.binary_sensor import sensors +from custom_components.generac.const import DEVICE_TYPE_GENERATOR +from custom_components.generac.const import DEVICE_TYPE_PROPANE_MONITOR from custom_components.generac.models import Apparatus from custom_components.generac.models import ApparatusDetail from custom_components.generac.models import Item @@ -98,3 +102,33 @@ async def test_warning_sensor(hass): item = get_mock_item(False, False, False, False) sensor = GeneracWarningSensor(coordinator, entry, "12345", item) assert sensor.is_on is False + + +async def test_missed_exercise_sensor(hass): + """Test the missed exercise binary sensor and generator-only selection.""" + coordinator = MagicMock() + coordinator.is_missed_exercise.return_value = True + entry = MagicMock() + entry.entry_id = "entry" + + gen = Item( + apparatus=Apparatus(type=DEVICE_TYPE_GENERATOR), + apparatusDetail=ApparatusDetail(), + ) + propane = Item( + apparatus=Apparatus(type=DEVICE_TYPE_PROPANE_MONITOR), + apparatusDetail=ApparatusDetail(), + ) + + assert GeneracMissedExerciseSensor in sensors(gen) + assert GeneracMissedExerciseSensor not in sensors(propane) + assert GeneracMissedExerciseSensor not in sensors() + + sensor = GeneracMissedExerciseSensor(coordinator, entry, "12345", gen) + assert sensor.entity_key == "missed_exercise" + assert sensor.name == "Missed Exercise" + assert sensor.device_class == "problem" + assert sensor.is_on is True + + coordinator.is_missed_exercise.return_value = False + assert sensor.is_on is False diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py new file mode 100644 index 0000000..9a92985 --- /dev/null +++ b/tests/test_blueprints.py @@ -0,0 +1,136 @@ +"""Tests for bundled Generac automation blueprints and auto-installer.""" +from pathlib import Path + +from custom_components.generac.blueprints import BUNDLED_BLUEPRINTS_DIR +from custom_components.generac.blueprints import install_bundled_blueprints +from custom_components.generac.blueprints import list_bundled_blueprints +from homeassistant.components.automation.config import _async_validate_config_item +from homeassistant.components.automation.config import AUTOMATION_BLUEPRINT_SCHEMA +from homeassistant.components.automation.config import ValidationStatus +from homeassistant.components.blueprint.models import Blueprint +from homeassistant.components.blueprint.models import BlueprintInputs +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component +from homeassistant.util.yaml import load_yaml + +EXPECTED_BLUEPRINTS = { + "generac_outage_load_shedding.yaml", + "generac_fault_dealer_alert.yaml", + "generac_storm_readiness_digest.yaml", +} + + +def test_bundled_blueprints_valid_against_ha_schema() -> None: + """Every bundled YAML file validates cleanly as an HA automation blueprint.""" + paths = list_bundled_blueprints() + assert {p.name for p in paths} == EXPECTED_BLUEPRINTS + + for path in paths: + raw = load_yaml(str(path)) + assert isinstance(raw, dict), path.name + bp = Blueprint( + raw, + path=str(path), + expected_domain="automation", + schema=AUTOMATION_BLUEPRINT_SCHEMA, + ) + assert bp.validate() is None + assert bp.domain == "automation" + + +async def test_bundled_blueprints_instantiate_valid_automations( + hass: HomeAssistant, +) -> None: + """Instantiating every blueprint with sample inputs yields valid HA automations.""" + await async_setup_component(hass, "homeassistant", {}) + + sample_inputs = { + "generac_outage_load_shedding.yaml": [ + { + "generator_status": "sensor.generator_status", + "shed_entities": ["switch.ev_charger", "climate.upstairs"], + "ready_stabilization_delay": 60, + "restore_loads": True, + "restore_stagger_delay": 5, + }, + { + "generator_status": "sensor.generator_status", + "shed_entities": ["switch.ev_charger"], + "ready_stabilization_delay": 0, + "restore_loads": False, + "restore_stagger_delay": 0, + }, + ], + "generac_fault_dealer_alert.yaml": [ + { + "status_sensor": "sensor.generator_status", + "status_text_sensor": "sensor.generator_status_text", + "warning_sensor": "binary_sensor.generator_warning", + "maintenance_sensor": "binary_sensor.generator_maintenance_alert", + "dealer_name_sensor": "sensor.generator_dealer_name", + "dealer_phone_sensor": "sensor.generator_dealer_phone", + "notify_service": "notify.mobile_app_phone", + } + ], + "generac_storm_readiness_digest.yaml": [ + { + "weather_alert_entity": "binary_sensor.nws_storm_alert", + "status_sensor": "sensor.generator_status", + "battery_voltage_sensor": "sensor.generator_battery_voltage", + "is_connected_sensor": "binary_sensor.generator_connected", + "hours_until_service_sensor": "sensor.generator_hours_until_service", + }, + { + "weather_alert_entity": "input_boolean.storm_prep", + "status_sensor": "sensor.generator_status", + "battery_voltage_sensor": "sensor.generator_battery_voltage", + "is_connected_sensor": "binary_sensor.generator_connected", + "hours_until_service_sensor": "sensor.generator_hours_until_service", + "fuel_level_sensor": "sensor.propane_tank_fuel_level", + "notify_service": "notify.notify", + }, + ], + } + + for filename, input_cases in sample_inputs.items(): + bp_path = BUNDLED_BLUEPRINTS_DIR / filename + raw = load_yaml(str(bp_path)) + bp = Blueprint( + raw, + path=str(bp_path), + expected_domain="automation", + schema=AUTOMATION_BLUEPRINT_SCHEMA, + ) + for idx, inputs in enumerate(input_cases): + bi = BlueprintInputs( + bp, {"use_blueprint": {"path": f"generac/{filename}", "input": inputs}} + ) + bi.validate() + substituted = bi.async_substitute() + substituted["alias"] = f"test_{filename}_{idx}" + result = await _async_validate_config_item(hass, substituted, True, False) + assert result.validation_status == ValidationStatus.OK, filename + + +def test_install_bundled_blueprints_is_idempotent(tmp_path: Path) -> None: + """Installer copies blueprints once, skips unchanged files, and repairs modified ones.""" + dest = tmp_path / "blueprints" / "automation" / "generac" + + written_first = install_bundled_blueprints(dest) + assert {p.name for p in written_first} == EXPECTED_BLUEPRINTS + for p in written_first: + assert p.read_bytes() == (BUNDLED_BLUEPRINTS_DIR / p.name).read_bytes() + + # Second run writes nothing + written_second = install_bundled_blueprints(dest) + assert written_second == [] + + # Modifying one file restores only that file + target = dest / "generac_outage_load_shedding.yaml" + target.write_text("# modified", encoding="utf-8") + written_third = install_bundled_blueprints(dest) + assert written_third == [target] + assert ( + target.read_bytes() + == (BUNDLED_BLUEPRINTS_DIR / "generac_outage_load_shedding.yaml").read_bytes() + ) diff --git a/tests/test_button.py b/tests/test_button.py new file mode 100644 index 0000000..7400bb2 --- /dev/null +++ b/tests/test_button.py @@ -0,0 +1,142 @@ +"""Tests for the Generac button platform and service reset flow.""" +from unittest.mock import AsyncMock +from unittest.mock import MagicMock +from unittest.mock import patch + +from custom_components.generac.auth import DPoPKey +from custom_components.generac.button import buttons +from custom_components.generac.button import ResetServiceTimerButton +from custom_components.generac.const import CONF_DPOP_PEM +from custom_components.generac.const import CONF_REFRESH_TOKEN +from custom_components.generac.const import CONF_SERVICE_INTERVAL_HOURS +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.models import Apparatus +from custom_components.generac.models import ApparatusDetail +from custom_components.generac.models import Item +from homeassistant.core import HomeAssistant +from homeassistant.helpers import issue_registry as ir +from pytest_homeassistant_custom_component.common import MockConfigEntry + + +def _make_item(device_type: int, run_time: float = 100.0) -> Item: + return Item( + apparatus=Apparatus( + apparatusId=12345, + name="Generator", + type=device_type, + ), + apparatusDetail=ApparatusDetail( + apparatusId=12345, + name="Generator", + apparatusStatus=1, + properties=[ + ApparatusDetail.Property(name="Run Hours", value=run_time, type=71), + ApparatusDetail.Property(name="Battery Voltage", value=13.4, type=70), + ], + ), + ) + + +def test_button_selection() -> None: + """ResetServiceTimerButton is registered only for generators.""" + gen = _make_item(DEVICE_TYPE_GENERATOR) + propane = _make_item(DEVICE_TYPE_PROPANE_MONITOR) + assert buttons(gen) == [ResetServiceTimerButton] + assert buttons(propane) == [] + + +async def test_reset_service_timer_button_unit() -> None: + """Unit test ResetServiceTimerButton properties and async_press delegation.""" + coordinator = MagicMock() + coordinator.async_reset_service_timer = AsyncMock() + entry = MagicMock() + entry.entry_id = "entry1" + btn = ResetServiceTimerButton( + coordinator, entry, "12345", _make_item(DEVICE_TYPE_GENERATOR) + ) + + assert btn.entity_key == "reset_service_timer" + assert btn.name == "Reset Maintenance Timer" + assert btn.icon == "mdi:wrench-check" + assert btn.unique_id == "entry1_12345_generac_12345_reset_service_timer" + + await btn.async_press() + coordinator.async_reset_service_timer.assert_awaited_once_with("12345") + + +async def test_reset_service_timer_button_end_to_end(hass: HomeAssistant) -> None: + """Pressing the button resets hours_until_service, clears Repairs issue, and persists without reloading.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="btn_entry", + unique_id="user@example.com", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + options={CONF_SERVICE_INTERVAL_HOURS: 100}, + ) + entry.add_to_hass(hass) + + initial_data = {"12345": _make_item(DEVICE_TYPE_GENERATOR, run_time=50.0)} + overdue_data = {"12345": _make_item(DEVICE_TYPE_GENERATOR, run_time=155.0)} + mock_get_data = AsyncMock(side_effect=[initial_data, overdue_data]) + + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + mock_get_data, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get("sensor.generator_hours_until_service").state == "100.0" + assert ( + ir.async_get(hass).async_get_issue( + DOMAIN, f"maintenance_due_{entry.entry_id}_12345" + ) + is None + ) + + # Advance runtime past 100h service interval + coordinator = hass.data[DOMAIN][entry.entry_id] + await coordinator.async_refresh() + await hass.async_block_till_done() + + assert hass.states.get("sensor.generator_hours_until_service").state == "0.0" + assert ( + ir.async_get(hass).async_get_issue( + DOMAIN, f"maintenance_due_{entry.entry_id}_12345" + ) + is not None + ) + + # Press the Reset Maintenance Timer button; entry.data must stay untouched & no reload + original_data = dict(entry.data) + with patch.object( + hass.config_entries, "async_reload", wraps=hass.config_entries.async_reload + ) as mock_reload: + await hass.services.async_call( + "button", + "press", + {"entity_id": "button.generator_reset_maintenance_timer"}, + blocking=True, + ) + await hass.async_block_till_done() + mock_reload.assert_not_called() + + assert dict(entry.data) == original_data + assert hass.states.get("sensor.generator_hours_until_service").state == "100.0" + assert ( + ir.async_get(hass).async_get_issue( + DOMAIN, f"maintenance_due_{entry.entry_id}_12345" + ) + is None + ) + assert ( + coordinator.readiness.get_device_state("12345")["service_baseline_hours"] + == 155.0 + ) diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 8aec197..af21753 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -144,7 +144,11 @@ async def test_options_flow(hass: HomeAssistant) -> None: "sensor": True, "weather": True, "image": True, + "button": True, "scan_interval": 120, + "service_interval_hours": 100, + "exercise_interval_days": 16, + "low_battery_threshold": 12.2, }, ) entry.add_to_hass(hass) @@ -166,10 +170,42 @@ async def test_options_flow(hass: HomeAssistant) -> None: "sensor": True, "weather": True, "image": True, + "button": True, "scan_interval": 120, + "service_interval_hours": 100, + "exercise_interval_days": 16, + "low_battery_threshold": 12.2, } +@pytest.mark.asyncio +async def test_options_flow_readiness_thresholds(hass: HomeAssistant) -> None: + """Test configuring readiness thresholds and disabling alerts with 0.""" + from custom_components.generac.const import CONF_EXERCISE_INTERVAL_DAYS + from custom_components.generac.const import CONF_LOW_BATTERY_THRESHOLD + from custom_components.generac.const import CONF_SERVICE_INTERVAL_HOURS + + entry = MockConfigEntry(domain=DOMAIN, data={}, options={}) + entry.add_to_hass(hass) + + result = await hass.config_entries.options.async_init(entry.entry_id) + assert result["type"] == "form" + + result2 = await hass.config_entries.options.async_configure( + result["flow_id"], + user_input={ + CONF_SERVICE_INTERVAL_HOURS: 50, + CONF_EXERCISE_INTERVAL_DAYS: 0, + CONF_LOW_BATTERY_THRESHOLD: 12, + }, + ) + assert result2["type"] == "create_entry" + assert entry.options[CONF_SERVICE_INTERVAL_HOURS] == 50 + assert entry.options[CONF_EXERCISE_INTERVAL_DAYS] == 0 + assert entry.options[CONF_LOW_BATTERY_THRESHOLD] == 12.0 + assert isinstance(entry.options[CONF_LOW_BATTERY_THRESHOLD], float) + + @pytest.mark.asyncio async def test_reconfigure_flow(hass: HomeAssistant) -> None: """Reconfigure should re-run login and update entry data.""" diff --git a/tests/test_entity_registry.py b/tests/test_entity_registry.py index dd64550..fe20c88 100644 --- a/tests/test_entity_registry.py +++ b/tests/test_entity_registry.py @@ -80,7 +80,11 @@ # Entities this change adds for the fixture payloads below. NEW_SUFFIXES = { - GENERATOR_ID: {"sensor": ["exercise_minutes"]}, + GENERATOR_ID: { + "sensor": ["exercise_minutes", "hours_until_service"], + "binary_sensor": ["missed_exercise"], + "button": ["reset_service_timer"], + }, PROPANE_ID: {"sensor": ["signal_strength", "device_battery_level"]}, } @@ -265,6 +269,15 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) _unique_id(GENERATOR_ID, "exercise_minutes"): ( "sensor.generator_exercise_duration" ), + _unique_id(GENERATOR_ID, "hours_until_service"): ( + "sensor.generator_hours_until_service" + ), + _unique_id(GENERATOR_ID, "missed_exercise"): ( + "binary_sensor.generator_missed_exercise" + ), + _unique_id(GENERATOR_ID, "reset_service_timer"): ( + "button.generator_reset_maintenance_timer" + ), _unique_id( PROPANE_ID, "signal_strength" ): "sensor.propane_tank_signal_strength", @@ -273,6 +286,11 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) ), } assert hass.states.get("sensor.generator_exercise_duration").state == "12.0" + assert hass.states.get("sensor.generator_hours_until_service").state == "100.0" + assert hass.states.get("binary_sensor.generator_missed_exercise").state == "off" + assert ( + hass.states.get("button.generator_reset_maintenance_timer").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" @@ -281,6 +299,18 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) devices[_unique_id(GENERATOR_ID, "exercise_minutes")] == devices[_unique_id(GENERATOR_ID, "status")] ) + assert ( + devices[_unique_id(GENERATOR_ID, "hours_until_service")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) + assert ( + devices[_unique_id(GENERATOR_ID, "missed_exercise")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) + assert ( + devices[_unique_id(GENERATOR_ID, "reset_service_timer")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) assert ( devices[_unique_id(PROPANE_ID, "device_battery_level")] == devices[_unique_id(PROPANE_ID, "status")] @@ -290,6 +320,7 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) 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 image from custom_components.generac import sensor from custom_components.generac import weather @@ -297,13 +328,13 @@ def test_every_entity_class_declares_its_own_stable_key(): classes = [ obj - for module in (binary_sensor, image, sensor, weather) + for module in (binary_sensor, button, 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) == 34 + assert len(classes) == 37 keys = {} for cls in classes: assert "entity_key" in vars(cls), cls.__name__ diff --git a/tests/test_init.py b/tests/test_init.py index 30860bb..f26160c 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -315,3 +315,43 @@ async def rotate_on_first_refresh(self): await hass.async_block_till_done() mock_reload.assert_called_once_with(config_entry.entry_id) + + +async def test_setup_entry_installs_bundled_blueprints( + hass: HomeAssistant, bypass_get_data +): + """Setup copies bundled automation blueprints into HA config blueprints dir.""" + from pathlib import Path + + config_entry = MockConfigEntry( + domain=DOMAIN, data=_make_mock_config(), entry_id="bp_setup_test" + ) + config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + bp_dir = Path(hass.config.path("blueprints", "automation", DOMAIN)) + assert sorted(p.name for p in bp_dir.glob("*.yaml")) == [ + "generac_fault_dealer_alert.yaml", + "generac_outage_load_shedding.yaml", + "generac_storm_readiness_digest.yaml", + ] + + +async def test_setup_entry_survives_blueprint_install_oserror( + hass: HomeAssistant, bypass_get_data +): + """Read-only config blueprint dirs log a warning rather than aborting setup.""" + config_entry = MockConfigEntry( + domain=DOMAIN, data=_make_mock_config(), entry_id="bp_oserror_test" + ) + config_entry.add_to_hass(hass) + + with patch( + "custom_components.generac.install_bundled_blueprints", + side_effect=OSError("read-only filesystem"), + ): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.entry_id in hass.data[DOMAIN] diff --git a/tests/test_issues.py b/tests/test_issues.py index 2514494..562e488 100644 --- a/tests/test_issues.py +++ b/tests/test_issues.py @@ -1,11 +1,23 @@ -"""Tests for the refresh-token expiry Repairs issue.""" +"""Tests for Generac Repairs issues (token expiry and device health).""" import time +from custom_components.generac.const import CONF_EXERCISE_INTERVAL_DAYS +from custom_components.generac.const import CONF_LOW_BATTERY_THRESHOLD from custom_components.generac.const import CONF_PASSWORD +from custom_components.generac.const import CONF_SERVICE_INTERVAL_HOURS from custom_components.generac.const import CONF_TOKEN_ISSUED_AT 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.issues import async_delete_all_entry_issues +from custom_components.generac.issues import async_update_device_health_issues from custom_components.generac.issues import async_update_token_expiry_issue +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.models import Subscription +from custom_components.generac.readiness import ReadinessTracker from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -13,20 +25,73 @@ _DAY = 86400 -def _entry(hass, **data) -> MockConfigEntry: - entry = MockConfigEntry( - domain=DOMAIN, data={CONF_USERNAME: "user@example.com", **data} - ) +def _entry( + hass: HomeAssistant, entry_id: str | None = None, options=None, **data +) -> MockConfigEntry: + kwargs = { + "domain": DOMAIN, + "data": {CONF_USERNAME: "user@example.com", **data}, + "options": options or {}, + } + if entry_id is not None: + kwargs["entry_id"] = entry_id + entry = MockConfigEntry(**kwargs) entry.add_to_hass(hass) return entry -def _issue(hass, entry): +def _issue(hass: HomeAssistant, entry: MockConfigEntry): return ir.async_get(hass).async_get_issue( DOMAIN, f"refresh_token_expiring_{entry.entry_id}" ) +def _device_issue( + hass: HomeAssistant, issue_key: str, entry: MockConfigEntry, device_id: str +): + return ir.async_get(hass).async_get_issue( + DOMAIN, f"{issue_key}_{entry.entry_id}_{device_id}" + ) + + +def _make_generator( + *, + name: str = "Home Gen", + status: int = 1, + battery_voltage: float | str | None = 13.4, + run_time: float | str | None = 120.0, + has_maintenance_alert: bool = False, + is_dunning: bool | None = None, +) -> Item: + props = [] + if battery_voltage is not None: + props.append( + ApparatusDetail.Property( + name="Battery Voltage", value=battery_voltage, type=70 + ) + ) + if run_time is not None: + props.append( + ApparatusDetail.Property(name="Run Hours", value=run_time, type=71) + ) + subscription = ( + Subscription(type=1, status=1, isLegacy=False, isDunning=is_dunning) + if is_dunning is not None + else None + ) + return Item( + apparatus=Apparatus(apparatusId=101, name=name, type=DEVICE_TYPE_GENERATOR), + apparatusDetail=ApparatusDetail( + apparatusId=101, + name=name, + apparatusStatus=status, + hasMaintenanceAlert=has_maintenance_alert, + properties=props, + subscription=subscription, + ), + ) + + async def test_issue_raised_near_expiry_and_cleared_after_relogin( hass: HomeAssistant, ) -> None: @@ -55,3 +120,164 @@ async def test_no_issue_when_young_password_stored_or_age_unknown( for entry in (young, with_pw, legacy): async_update_token_expiry_issue(hass, entry) assert _issue(hass, entry) is None + + +async def test_low_battery_voltage_issue_lifecycle(hass: HomeAssistant) -> None: + """Low battery voltage (< threshold and > 0) raises and clears automatically.""" + entry = _entry(hass, options={CONF_LOW_BATTERY_THRESHOLD: 12.2}) + gen_low = _make_generator(battery_voltage="11.8") + gen_zero = _make_generator(battery_voltage="0") + gen_none = _make_generator(battery_voltage=None) + gen_ok = _make_generator(battery_voltage="12.2") + propane = Item( + apparatus=Apparatus( + apparatusId=202, name="Propane", type=DEVICE_TYPE_PROPANE_MONITOR + ), + apparatusDetail=ApparatusDetail( + properties=[ApparatusDetail.Property(name="Battery", value="10.0", type=70)] + ), + ) + + async_update_device_health_issues(hass, entry, {"101": gen_low, "202": propane}) + issue = _device_issue(hass, "low_battery_voltage", entry, "101") + assert issue is not None + assert issue.translation_key == "low_battery_voltage" + assert issue.translation_placeholders == { + "device_name": "Home Gen", + "voltage": "11.8", + "threshold": "12.2", + } + assert _device_issue(hass, "low_battery_voltage", entry, "202") is None + + # 0 V (unreported) clears the issue + async_update_device_health_issues(hass, entry, {"101": gen_zero}) + assert _device_issue(hass, "low_battery_voltage", entry, "101") is None + + # Back below threshold -> raised, then >= threshold -> cleared + async_update_device_health_issues(hass, entry, {"101": gen_low}) + assert _device_issue(hass, "low_battery_voltage", entry, "101") is not None + async_update_device_health_issues(hass, entry, {"101": gen_ok}) + assert _device_issue(hass, "low_battery_voltage", entry, "101") is None + + # None voltage -> cleared + async_update_device_health_issues(hass, entry, {"101": gen_low}) + async_update_device_health_issues(hass, entry, {"101": gen_none}) + assert _device_issue(hass, "low_battery_voltage", entry, "101") is None + + +async def test_missed_exercise_issue_lifecycle(hass: HomeAssistant) -> None: + """Missed exercise alert respects exercise_interval_days and clears on activity.""" + entry = _entry(hass, options={CONF_EXERCISE_INTERVAL_DAYS: 16}) + tracker = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + gen = _make_generator(status=1, run_time=50.0) + + await tracker.async_update_from_items({"101": gen}, now=t0) + async_update_device_health_issues(hass, entry, {"101": gen}, tracker, now=t0) + assert _device_issue(hass, "missed_exercise", entry, "101") is None + + # 17 days without exercise or run_time increase -> raises issue + t_late = t0 + 17 * _DAY + await tracker.async_update_from_items({"101": gen}, now=t_late) + async_update_device_health_issues(hass, entry, {"101": gen}, tracker, now=t_late) + issue = _device_issue(hass, "missed_exercise", entry, "101") + assert issue is not None + assert issue.translation_key == "missed_exercise" + assert issue.translation_placeholders["interval_days"] == "16" + + # Short exercise caught via run_time increase -> clears issue + gen_ran = _make_generator(status=1, run_time=50.2) + await tracker.async_update_from_items({"101": gen_ran}, now=t_late + 600) + async_update_device_health_issues( + hass, entry, {"101": gen_ran}, tracker, now=t_late + 600 + ) + assert _device_issue(hass, "missed_exercise", entry, "101") is None + + # Disabling missed exercise (0 days) clears any active issue + t_much_later = t_late + 20 * _DAY + async_update_device_health_issues( + hass, entry, {"101": gen_ran}, tracker, now=t_much_later + ) + assert _device_issue(hass, "missed_exercise", entry, "101") is not None + hass.config_entries.async_update_entry( + entry, options={CONF_EXERCISE_INTERVAL_DAYS: 0} + ) + async_update_device_health_issues( + hass, entry, {"101": gen_ran}, tracker, now=t_much_later + ) + assert _device_issue(hass, "missed_exercise", entry, "101") is None + + +async def test_maintenance_due_issue_lifecycle(hass: HomeAssistant) -> None: + """Maintenance due fires from service hours or API flag and clears on reset.""" + entry = _entry(hass, options={CONF_SERVICE_INTERVAL_HOURS: 100}) + tracker = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + gen_initial = _make_generator(run_time=10.0) + await tracker.async_update_from_items({"101": gen_initial}, now=t0) + async_update_device_health_issues(hass, entry, {"101": gen_initial}, tracker) + assert _device_issue(hass, "maintenance_due", entry, "101") is None + + # Run 100+ hours -> maintenance_due raised + gen_due = _make_generator(run_time=112.5) + await tracker.async_update_from_items({"101": gen_due}, now=t0 + 1000) + async_update_device_health_issues(hass, entry, {"101": gen_due}, tracker) + issue = _device_issue(hass, "maintenance_due", entry, "101") + assert issue is not None + assert issue.translation_key == "maintenance_due" + + # Both timer_due and API hasMaintenanceAlert active simultaneously + gen_both = _make_generator(run_time=112.5, has_maintenance_alert=True) + async_update_device_health_issues(hass, entry, {"101": gen_both}, tracker) + issue_both = _device_issue(hass, "maintenance_due", entry, "101") + assert issue_both is not None + assert ( + "Mobile Link maintenance alert" in issue_both.translation_placeholders["reason"] + ) + assert "102.5 h" in issue_both.translation_placeholders["reason"] + + # Reset timer while hasMaintenanceAlert is still True -> stays raised + await tracker.async_reset_service_timer("101", current_run_time=112.5) + gen_api_flag = _make_generator(run_time=112.5, has_maintenance_alert=True) + async_update_device_health_issues(hass, entry, {"101": gen_api_flag}, tracker) + assert _device_issue(hass, "maintenance_due", entry, "101") is not None + + # Clear hasMaintenanceAlert -> issue clears + async_update_device_health_issues(hass, entry, {"101": gen_due}, tracker) + assert _device_issue(hass, "maintenance_due", entry, "101") is None + + +async def test_subscription_dunning_and_entry_cleanup(hass: HomeAssistant) -> None: + """Subscription dunning raises/clears, and entry deletion removes all entry issues.""" + entry = _entry( + hass, entry_id="entry", **{CONF_TOKEN_ISSUED_AT: time.time() - 85 * _DAY} + ) + other_entry = _entry(hass, entry_id="entry_2") + + gen_dunning = _make_generator(battery_voltage="11.5", is_dunning=True) + gen_other = _make_generator(battery_voltage="11.5", is_dunning=True) + + async_update_token_expiry_issue(hass, entry) + async_update_device_health_issues(hass, entry, {"101": gen_dunning}) + async_update_device_health_issues(hass, other_entry, {"101": gen_other}) + + assert _device_issue(hass, "subscription_dunning", entry, "101") is not None + assert _device_issue(hass, "low_battery_voltage", entry, "101") is not None + assert _device_issue(hass, "low_battery_voltage", other_entry, "101") is not None + + # Clearing dunning removes subscription_dunning + gen_paid = _make_generator(battery_voltage="11.5", is_dunning=False) + async_update_device_health_issues(hass, entry, {"101": gen_paid}) + assert _device_issue(hass, "subscription_dunning", entry, "101") is None + + # Stale device removal sweeps orphaned device issue + async_update_device_health_issues(hass, entry, {}) + assert _device_issue(hass, "low_battery_voltage", entry, "101") is None + + # Re-create issues then delete all for entry -> does NOT affect entry_2 + async_update_device_health_issues(hass, entry, {"101": gen_dunning}) + async_delete_all_entry_issues(hass, entry) + assert _issue(hass, entry) is None + assert _device_issue(hass, "low_battery_voltage", entry, "101") is None + assert _device_issue(hass, "subscription_dunning", entry, "101") is None + assert _device_issue(hass, "low_battery_voltage", other_entry, "101") is not None diff --git a/tests/test_readiness.py b/tests/test_readiness.py new file mode 100644 index 0000000..94d125c --- /dev/null +++ b/tests/test_readiness.py @@ -0,0 +1,241 @@ +"""Tests for Generac readiness tracking, persistence, and reload-free updates.""" +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_EXERCISE_INTERVAL_DAYS +from custom_components.generac.const import CONF_REFRESH_TOKEN +from custom_components.generac.const import CONF_SERVICE_INTERVAL_HOURS +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.models import Apparatus +from custom_components.generac.models import ApparatusDetail +from custom_components.generac.models import Item +from custom_components.generac.readiness import ReadinessTracker +from homeassistant.core import HomeAssistant +from homeassistant.helpers import issue_registry as ir +from pytest_homeassistant_custom_component.common import MockConfigEntry + +_DAY = 86400 + + +def _gen(status: int = 1, run_time: float | None = 100.0) -> Item: + props = [] + if run_time is not None: + props.append( + ApparatusDetail.Property(name="Run Hours", value=run_time, type=71) + ) + return Item( + apparatus=Apparatus(apparatusId=1, name="Gen", type=DEVICE_TYPE_GENERATOR), + apparatusDetail=ApparatusDetail( + apparatusId=1, + name="Gen", + apparatusStatus=status, + properties=props, + ), + ) + + +async def test_first_sight_prevents_day_1_alarms_and_ignores_propane( + hass: HomeAssistant, +) -> None: + """First sight sets service_baseline_hours = run_time and ignores propane tanks.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="r_entry_1", + options={CONF_SERVICE_INTERVAL_HOURS: 100, CONF_EXERCISE_INTERVAL_DAYS: 16}, + ) + entry.add_to_hass(hass) + tracker = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + + propane = Item( + apparatus=Apparatus( + apparatusId=2, name="Tank", type=DEVICE_TYPE_PROPANE_MONITOR + ), + apparatusDetail=ApparatusDetail(apparatusId=2), + ) + await tracker.async_update_from_items( + {"1": _gen(run_time=250.0), "2": propane}, now=t0 + ) + + state = tracker.get_device_state("1") + assert state == { + "last_exercise_ts": t0, + "last_run_time": 250.0, + "service_baseline_hours": 250.0, + } + 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 + + +async def test_exercise_detection_via_status_and_run_time_delta( + hass: HomeAssistant, +) -> None: + """Detects exercises both during Running/Exercising polls and via run_time delta.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="r_entry_2", + options={CONF_EXERCISE_INTERVAL_DAYS: 16}, + ) + entry.add_to_hass(hass) + tracker = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + + await tracker.async_update_from_items({"1": _gen(status=1, run_time=10.0)}, now=t0) + + # 10 days later: active Exercising status (3) updates last_exercise_ts even before run_time increments + t1 = t0 + 10 * _DAY + await tracker.async_update_from_items({"1": _gen(status=3, run_time=10.0)}, now=t1) + assert tracker.get_device_state("1")["last_exercise_ts"] == t1 + + # 10 more days later: short 10-min exercise finished between 15-min polls (status back to 1, run_time 10.0 -> 10.2) + t2 = t1 + 10 * _DAY + await tracker.async_update_from_items({"1": _gen(status=1, run_time=10.2)}, now=t2) + assert tracker.get_device_state("1")["last_exercise_ts"] == t2 + assert tracker.is_missed_exercise("1", now=t2) is False + + # Transient None run_time preserves last_run_time + await tracker.async_update_from_items( + {"1": _gen(status=1, run_time=None)}, now=t2 + 900 + ) + assert tracker.get_device_state("1")["last_run_time"] == 10.2 + + # 17 days after t2 without activity -> missed exercise + assert tracker.is_missed_exercise("1", now=t2 + 17 * _DAY) is True + + +async def test_store_persistence_across_restarts_without_mutating_entry_data( + hass: HomeAssistant, +) -> None: + """Readiness state persists in HA Store across restarts and never modifies entry.data.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="persist_entry", + unique_id="user@example.com", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + options={CONF_SERVICE_INTERVAL_HOURS: 100}, + ) + entry.add_to_hass(hass) + initial_entry_data = dict(entry.data) + + tracker1 = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + await tracker1.async_update_from_items({"1": _gen(run_time=100.0)}, now=t0) + 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 + 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, + } + assert tracker2.hours_since_service("1") == 20.0 + assert tracker2.hours_until_service("1") == 80.0 + + +async def test_coordinator_poll_persists_readiness_without_reloading_entry( + hass: HomeAssistant, +) -> None: + """Full coordinator poll updates readiness store without triggering ConfigEntry reload.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="coord_persist", + unique_id="user@example.com", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + ) + entry.add_to_hass(hass) + + poll1 = {"1": _gen(run_time=50.0)} + poll2 = {"1": _gen(run_time=65.0)} + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + AsyncMock(side_effect=[poll1, poll2]), + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + coordinator = hass.data[DOMAIN][entry.entry_id] + with patch.object( + hass.config_entries, "async_reload", wraps=hass.config_entries.async_reload + ) as mock_reload: + await coordinator.async_refresh() + await hass.async_block_till_done() + mock_reload.assert_not_called() + + assert coordinator.hours_since_service("1") == 15.0 + assert coordinator.hours_until_service("1") == 85.0 + + # Removing the entry cleans up Repairs issues too + assert await hass.config_entries.async_remove(entry.entry_id) + await hass.async_block_till_done() + assert ir.async_get(hass).issues == {} + + +async def test_readiness_edge_cases_and_disabled_interval(hass: HomeAssistant) -> None: + """Edge cases: unknown device, disabled service interval, reset unseen device, NaN/bool values.""" + from custom_components.generac.readiness import readiness_store_key + from custom_components.generac.utils import safe_float + from homeassistant.helpers.storage import Store + + assert safe_float(True, "bool") is None + assert safe_float("nan", "nan") is None + assert safe_float("inf", "inf") is None + + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="edge_entry", + options={CONF_SERVICE_INTERVAL_HOURS: 0, CONF_EXERCISE_INTERVAL_DAYS: 0}, + ) + entry.add_to_hass(hass) + + # Pre-seed Store with partially corrupted entries to verify defensive loading + await Store(hass, 1, readiness_store_key(entry.entry_id)).async_save( + { + "devices": { + "bad_type": "not-a-dict", + "missing_ts": {"last_run_time": 10.0}, + "valid": { + "last_exercise_ts": 1_700_000_000.0, + "last_run_time": 42.0, + "service_baseline_hours": 30.0, + }, + } + } + ) + + tracker = ReadinessTracker(hass, entry) + await tracker.async_load() + assert tracker.get_device_state("bad_type") is None + assert tracker.get_device_state("missing_ts") is None + assert tracker.hours_since_service("valid") == 12.0 + # Service interval 0 disables hours_until_service + assert tracker.hours_until_service("valid") is None + # Exercise interval 0 disables missed exercise + assert tracker.is_missed_exercise("valid", now=1_800_000_000.0) is False + # Unknown device returns None / False safely + assert tracker.hours_since_service("unknown") is None + assert tracker.days_since_exercise("unknown") is None + assert tracker.is_missed_exercise("unknown") is False + + # Resetting an unseen device initializes its record cleanly + await tracker.async_reset_service_timer( + "new_gen", current_run_time=15.0, now=1_700_000_100.0 + ) + assert tracker.hours_since_service("new_gen") == 0.0 diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 0eb5696..2be257f 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -23,6 +23,7 @@ from custom_components.generac.sensor import ExerciseMinutesSensor 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 LastReadingDateSensor from custom_components.generac.sensor import LastSeenSensor from custom_components.generac.sensor import ModelNumberSensor @@ -422,3 +423,27 @@ def test_friendly_names_and_stable_unique_ids(): assert sensor.has_entity_name is True assert sensor.name == label assert sensor.unique_id == f"entry_9_generac_9_{suffix}" + + +async def test_hours_until_service_sensor(hass): + """HoursUntilServiceSensor reports remaining hours and selection is generator-only.""" + coordinator = MagicMock() + coordinator.hours_until_service.return_value = 72.5 + coordinator.hours_since_service.return_value = 27.5 + entry = MagicMock() + entry.entry_id = "entry" + + gen = get_mock_item(DEVICE_TYPE_GENERATOR, 1) + propane = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1) + assert HoursUntilServiceSensor in sensors(gen) + assert HoursUntilServiceSensor not in sensors(propane) + + sensor = HoursUntilServiceSensor(coordinator, entry, "12345", gen) + assert sensor.entity_key == "hours_until_service" + assert sensor.name == "Hours Until Service" + assert sensor.device_class == "duration" + assert sensor.native_unit_of_measurement == "h" + assert sensor.state_class == "measurement" + assert sensor.icon == "mdi:wrench-clock" + assert sensor.native_value == 72.5 + assert sensor.extra_state_attributes["hours_since_service"] == 27.5