From d00cc19aa6fec1b460f7114fa01fd9091b918057 Mon Sep 17 00:00:00 2001 From: Jose Santiago Date: Fri, 20 Nov 2026 18:31:39 -0500 Subject: [PATCH 1/2] Harden v0.6 sensors, readiness tracking, platform toggles, validation, and blueprints --- README.md | 8 +- custom_components/generac/__init__.py | 29 ++- .../generac_fault_dealer_alert.yaml | 40 +++- .../generac_outage_load_shedding.yaml | 48 ++-- .../generac_storm_readiness_digest.yaml | 50 ++++- custom_components/generac/config_flow.py | 73 ++++-- custom_components/generac/coordinator.py | 9 +- custom_components/generac/issues.py | 25 ++- custom_components/generac/readiness.py | 122 ++++++---- custom_components/generac/sensor.py | 10 +- custom_components/generac/utils.py | 40 ++++ custom_components/generac/weather.py | 2 +- tests/test_blueprints.py | 211 +++++++++++++++++- tests/test_config_flow.py | 104 +++++++++ tests/test_coordinator.py | 9 +- tests/test_init.py | 81 +++++++ tests/test_issues.py | 31 +++ tests/test_readiness.py | 89 ++++++++ tests/test_sensor.py | 82 +++++++ tests/test_weather.py | 13 ++ 20 files changed, 954 insertions(+), 122 deletions(-) diff --git a/README.md b/README.md index b6fb1c7..dbcc0e4 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ To stay gentle on Generac's rate-limited cloud API during normal standby while r - **Idle polling interval (`scan_interval`)**: Default `900` seconds (15 minutes). Used when all devices are idle/ready. - **Active polling interval (`active_scan_interval`)**: Default `120` seconds (2 minutes), capped at `min(scan_interval, active_scan_interval)` so fast polling never slows down a shorter idle interval. -Fast polling activates automatically whenever any generator is **Running**, **Exercising**, **Warning**, or **Stopped**, or when any device reports `isConnecting`, `showWarning`, or `isRunning`. After the fleet returns to idle, fast polling remains active for a `300`-second (5-minute) cooldown before returning to the idle interval. +Fast polling activates automatically whenever any generator is **Running**, **Exercising**, or **Warning**, or when any device reports `isConnecting`, `showWarning`, or `isRunning`. After the fleet returns to idle, fast polling remains active for a `300`-second (5-minute) cooldown before returning to the idle interval. You can also trigger fast polling manually (for example, from an automation triggered by a utility power-loss sensor) using either: @@ -112,9 +112,9 @@ Each generator automatically tracks exercise activity and maintenance runtime ba 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`. +1. **Generac Outage Load Shedding** (`generac_outage_load_shedding.yaml`) — Sheds high-draw entities when status transitions to `Running` (ignoring `Exercising` cycles), waits for `Ready` stabilization, and optionally restores previously active loads with a stagger delay. +2. **Generac Fault & Dealer Contact Alert** (`generac_fault_dealer_alert.yaml`) — Sends a notification populated with generator status, diagnostic `status_text`, optional `error_code`, and your preferred dealer's name and phone number on `Warning`, `Stopped`, `Communication Issue`, warning, or maintenance alerts. +3. **Generac Pre-Storm Readiness Digest** (`generac_storm_readiness_digest.yaml`) — Sends a readiness digest with status, connectivity, battery voltage, hours until service, and optional propane fuel level, remaining fuel, and estimated runtime when a weather alert or trigger entity turns `on`. ## Username + Password Authentication diff --git a/custom_components/generac/__init__.py b/custom_components/generac/__init__.py index 7edec35..1fca184 100644 --- a/custom_components/generac/__init__.py +++ b/custom_components/generac/__init__.py @@ -85,6 +85,16 @@ async def _async_handle_boost_polling(call: ServiceCall) -> None: await coordinator.async_trigger_boost(duration_seconds) +def _enabled_platforms(entry: ConfigEntry) -> list[str]: + """Return platforms enabled in entry options (all enabled by default).""" + options = entry_options(entry) + return [ + platform + for platform in PLATFORMS + if (options.get(platform) if isinstance(options.get(platform), bool) else True) + ] + + def _reload_signature(entry: ConfigEntry) -> tuple[dict, dict]: """Snapshot of entry options and non-token data that require a reload on change.""" return ( @@ -175,7 +185,10 @@ async def _persist_relogin(fresh: GeneracAuth) -> None: hass.data[DOMAIN][entry.entry_id] = coordinator - await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + enabled_platforms = _enabled_platforms(entry) + coordinator.loaded_platforms = list(enabled_platforms) + if enabled_platforms: + await hass.config_entries.async_forward_entry_setups(entry, enabled_platforms) coordinator.reload_signature = _reload_signature(entry) entry.async_on_unload(entry.add_update_listener(async_reload_entry)) if not hass.services.has_service(DOMAIN, SERVICE_BOOST_POLLING): @@ -190,7 +203,19 @@ async def _persist_relogin(fresh: GeneracAuth) -> None: async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Handle removal of an entry.""" - unloaded = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + coordinator: GeneracDataUpdateCoordinator | None = hass.data.get(DOMAIN, {}).get( + entry.entry_id + ) + platforms_to_unload = ( + list(coordinator.loaded_platforms) + if isinstance(coordinator, GeneracDataUpdateCoordinator) + else _enabled_platforms(entry) + ) + unloaded = ( + await hass.config_entries.async_unload_platforms(entry, platforms_to_unload) + if platforms_to_unload + else True + ) if unloaded: # Defensive default: if a previous reload already popped the # coordinator (e.g. mid-reconfigure race), don't KeyError. diff --git a/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml b/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml index 26a0408..c76d8fa 100644 --- a/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml +++ b/custom_components/generac/blueprints/automation/generac_fault_dealer_alert.yaml @@ -2,8 +2,8 @@ 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. + optional error code, 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: @@ -49,6 +49,15 @@ blueprint: filter: - integration: generac domain: sensor + error_code_sensor: + name: Generator Error Code Sensor (Optional) + description: Optional Generac error code sensor for active fault diagnostics. + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor notify_service: name: Notification Service description: >- @@ -78,6 +87,7 @@ triggers: variables: status_entity: !input status_sensor status_text_entity: !input status_text_sensor + error_code_entity: !input error_code_sensor maintenance_entity: !input maintenance_sensor dealer_name_entity: !input dealer_name_sensor dealer_phone_entity: !input dealer_phone_sensor @@ -87,19 +97,25 @@ actions: action: !input notify_service data: title: >- - {% if trigger.entity_id == maintenance_entity %} + {%- if trigger.entity_id == maintenance_entity -%} Generac Maintenance Alert ({{ states(status_entity) }}) - {% else %} + {%- 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) %} + {%- 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', ''] %} + {%- if error_code_entity not in [none, ''] %} + {%- set error_code = states(error_code_entity) %} + {%- if error_code not in ['unknown', 'unavailable', ''] %} + Error Code: {{ error_code }} + {%- endif %} + {%- endif %} + {%- if details not in ['unknown', 'unavailable', ''] %} Details: {{ details }} - {% endif %} + {%- 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 index be5d90f..480f313 100644 --- a/custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml +++ b/custom_components/generac/blueprints/automation/generac_outage_load_shedding.yaml @@ -37,7 +37,9 @@ blueprint: unit_of_measurement: seconds restore_loads: name: Restore Shed Loads - description: Turn shed entities back on after utility power stabilizes. + description: >- + Turn previously active shed entities (not already off, unavailable, or + unknown) back on after utility power stabilizes. default: true selector: boolean: {} @@ -53,7 +55,7 @@ blueprint: max: 120 unit_of_measurement: seconds -mode: restart +mode: single max_exceeded: silent triggers: @@ -62,28 +64,44 @@ triggers: to: "Running" variables: + shed_entities: !input shed_entities 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 + - variables: + shed_list: "{{ [shed_entities] if shed_entities is string else shed_entities }}" + entities_to_restore: >- + {{ shed_list | select('has_value') | reject('is_state', 'off') | list }} + - alias: Keep high-draw loads shed until generator stabilizes in Ready + repeat: + sequence: + - alias: Shed high-draw loads + action: homeassistant.turn_off + target: + entity_id: !input shed_entities + - alias: Wait for generator to stabilize in Ready or re-enter Running + wait_for_trigger: + - id: ready + trigger: state + entity_id: !input generator_status + to: "Ready" + for: + seconds: !input ready_stabilization_delay + - id: running_again + trigger: state + entity_id: !input generator_status + to: "Running" + until: + - condition: template + value_template: "{{ wait.trigger is not none and wait.trigger.id == 'ready' }}" - if: - condition: template - value_template: "{{ restore_loads }}" + value_template: "{{ restore_loads and (entities_to_restore | length > 0) }}" then: - alias: Restore shed loads repeat: - for_each: !input shed_entities + for_each: "{{ entities_to_restore }}" sequence: - action: homeassistant.turn_on target: diff --git a/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml b/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml index 8c8a002..255b3c7 100644 --- a/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml +++ b/custom_components/generac/blueprints/automation/generac_storm_readiness_digest.yaml @@ -3,7 +3,8 @@ blueprint: 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. + hours until service, and optional propane tank fuel level, remaining fuel, + and estimated runtime. domain: automation author: ha-generac input: @@ -46,7 +47,25 @@ blueprint: fuel_level_sensor: name: Propane Fuel Level Sensor (Optional) description: Optional Generac propane tank monitor fuel level sensor. - default: "" + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor + remaining_fuel_sensor: + name: Remaining Propane Fuel Sensor (Optional) + description: Optional Generac propane tank remaining fuel sensor (gal). + default: null + selector: + entity: + filter: + - integration: generac + domain: sensor + estimated_runtime_sensor: + name: Estimated Runtime Remaining Sensor (Optional) + description: Optional Generac propane estimated runtime remaining sensor (h). + default: null selector: entity: filter: @@ -74,18 +93,35 @@ variables: connected_entity: !input is_connected_sensor service_entity: !input hours_until_service_sensor fuel_entity: !input fuel_level_sensor + remaining_fuel_entity: !input remaining_fuel_sensor + estimated_runtime_entity: !input estimated_runtime_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') %} + 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 %} + {%- if fuel_entity not in [none, ''] %} + {%- set fuel_level = states(fuel_entity) %} + {%- if fuel_level not in ['unknown', 'unavailable', ''] %} + Propane Fuel Level: {{ fuel_level }}% + {%- endif %} + {%- endif %} + {%- if remaining_fuel_entity not in [none, ''] %} + {%- set remaining_fuel = states(remaining_fuel_entity) %} + {%- if remaining_fuel not in ['unknown', 'unavailable', ''] %} + Remaining Fuel: {{ remaining_fuel }} gal + {%- endif %} + {%- endif %} + {%- if estimated_runtime_entity not in [none, ''] %} + {%- set estimated_runtime = states(estimated_runtime_entity) %} + {%- if estimated_runtime not in ['unknown', 'unavailable', ''] %} + Estimated Runtime: {{ estimated_runtime }} h + {%- endif %} + {%- endif %} diff --git a/custom_components/generac/config_flow.py b/custom_components/generac/config_flow.py index 5173d6b..553f2f6 100644 --- a/custom_components/generac/config_flow.py +++ b/custom_components/generac/config_flow.py @@ -22,7 +22,6 @@ """ import asyncio import logging -import math import time import aiohttp @@ -56,9 +55,17 @@ from .const import DOMAIN from .utils import async_client_session from .utils import entry_options +from .utils import safe_float +from .utils import safe_int_option _LOGGER: logging.Logger = logging.getLogger(__package__) +_MIN_SCAN_INTERVAL_SECONDS = 10 +_MAX_FLOAT_OPTION_VALUE = 1000.0 +_SCAN_INTERVAL_VALIDATOR = vol.All( + vol.Coerce(int), vol.Range(min=_MIN_SCAN_INTERVAL_SECONDS) +) + # Where the one-time code comes from, keyed by the factor that # GeneracLoginFlow detected. Fills the {method} placeholder in the MFA # step's prompt so the user knows where to look. @@ -256,13 +263,21 @@ async def async_step_reconfigure(self, user_input=None): default_email = entry.data.get(CONF_USERNAME, "") if entry else "" default_scan_interval = ( - entry_options(entry).get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) + safe_int_option( + entry_options(entry), + CONF_SCAN_INTERVAL, + DEFAULT_SCAN_INTERVAL, + min_value=_MIN_SCAN_INTERVAL_SECONDS, + ) if entry else DEFAULT_SCAN_INTERVAL ) default_active_scan_interval = ( - entry_options(entry).get( - CONF_ACTIVE_SCAN_INTERVAL, DEFAULT_ACTIVE_SCAN_INTERVAL + safe_int_option( + entry_options(entry), + CONF_ACTIVE_SCAN_INTERVAL, + DEFAULT_ACTIVE_SCAN_INTERVAL, + min_value=_MIN_SCAN_INTERVAL_SECONDS, ) if entry else DEFAULT_ACTIVE_SCAN_INTERVAL @@ -275,10 +290,10 @@ async def async_step_reconfigure(self, user_input=None): vol.Required(CONF_PASSWORD): str, vol.Required( CONF_SCAN_INTERVAL, default=default_scan_interval - ): int, + ): _SCAN_INTERVAL_VALIDATOR, vol.Required( CONF_ACTIVE_SCAN_INTERVAL, default=default_active_scan_interval - ): int, + ): _SCAN_INTERVAL_VALIDATOR, vol.Optional( CONF_REMEMBER_PASSWORD, default=bool(entry and entry.data.get(CONF_PASSWORD)), @@ -486,12 +501,20 @@ def async_get_options_flow(config_entry): def _option_validator(key: str, option_type: type): """Build a Voluptuous validator for an integration option.""" + if key in (CONF_SCAN_INTERVAL, CONF_ACTIVE_SCAN_INTERVAL): + return _SCAN_INTERVAL_VALIDATOR if key == CONF_FUEL_BURN_RATE: - return vol.All(vol.Coerce(float), vol.Range(min=0.0, min_included=False)) + return vol.All( + vol.Coerce(float), + vol.Range(min=0.0, max=_MAX_FLOAT_OPTION_VALUE, min_included=False), + ) if option_type is float: - return vol.All(vol.Coerce(float), vol.Range(min=0.0)) + return vol.All( + vol.Coerce(float), + vol.Range(min=0.0, max=_MAX_FLOAT_OPTION_VALUE), + ) if key in (CONF_SERVICE_INTERVAL_HOURS, CONF_EXERCISE_INTERVAL_DAYS): - return vol.All(int, vol.Range(min=0)) + return vol.All(vol.Coerce(int), vol.Range(min=0)) return option_type @@ -504,16 +527,30 @@ def __init__(self, config_entry): @staticmethod def _option_default(key: str, opt: dict, current: dict): """Return a safe form default for an option key.""" - default = current.get(key, opt["default"]) + if key in (CONF_SCAN_INTERVAL, CONF_ACTIVE_SCAN_INTERVAL): + return safe_int_option( + current, key, opt["default"], min_value=_MIN_SCAN_INTERVAL_SECONDS + ) + if key in (CONF_SERVICE_INTERVAL_HOURS, CONF_EXERCISE_INTERVAL_DAYS): + return safe_int_option(current, key, opt["default"], min_value=0) if key == CONF_FUEL_BURN_RATE: - if isinstance(default, bool): - return DEFAULT_FUEL_BURN_RATE - try: - rate = float(default) - except (TypeError, ValueError): - return DEFAULT_FUEL_BURN_RATE - return rate if math.isfinite(rate) and rate > 0 else DEFAULT_FUEL_BURN_RATE - return default + rate = safe_float(current.get(key, opt["default"]), key) + return ( + rate + if rate is not None and 0.0 < rate <= _MAX_FLOAT_OPTION_VALUE + else DEFAULT_FUEL_BURN_RATE + ) + if opt["type"] is float: + val = safe_float(current.get(key, opt["default"]), key) + return ( + val + if val is not None and 0.0 <= val <= _MAX_FLOAT_OPTION_VALUE + else opt["default"] + ) + if opt["type"] is bool: + val = current.get(key, opt["default"]) + return val if isinstance(val, bool) else opt["default"] + return current.get(key, opt["default"]) async def async_step_init(self, user_input=None): # pylint: disable=unused-argument return await self.async_step_user() diff --git a/custom_components/generac/coordinator.py b/custom_components/generac/coordinator.py index a2e92d8..1f54ea9 100644 --- a/custom_components/generac/coordinator.py +++ b/custom_components/generac/coordinator.py @@ -30,19 +30,17 @@ from .readiness import get_run_time from .readiness import ReadinessTracker from .utils import entry_options +from .utils import safe_int_option _LOGGER: logging.Logger = logging.getLogger(__package__) -_ACTIVE_GENERATOR_STATUSES = frozenset({2, 3, 4, 5}) +_ACTIVE_GENERATOR_STATUSES = frozenset({2, 3, 4}) _MIN_SCAN_INTERVAL_SECONDS = 10 def _read_interval(options: Mapping, key: str, default: int) -> int: """Read an integer polling interval from options and clamp to >= 10 s.""" - raw = options.get(key, default) - if raw is None: - raw = default - return max(_MIN_SCAN_INTERVAL_SECONDS, int(raw)) + return safe_int_option(options, key, default, min_value=_MIN_SCAN_INTERVAL_SECONDS) def _is_fleet_active(items: dict[str, Item] | None) -> bool: @@ -82,6 +80,7 @@ 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.loaded_platforms: list[str] = [] self.readiness = ReadinessTracker(hass, config_entry) options = entry_options(config_entry) self.idle_scan_interval = _read_interval( diff --git a/custom_components/generac/issues.py b/custom_components/generac/issues.py index 1a3dbef..651b4ca 100644 --- a/custom_components/generac/issues.py +++ b/custom_components/generac/issues.py @@ -29,6 +29,8 @@ from .readiness import get_battery_voltage from .readiness import ReadinessTracker from .utils import entry_options +from .utils import safe_float_option +from .utils import safe_int_option _DAY = 86400 @@ -112,14 +114,23 @@ def async_update_device_health_issues( return options = entry_options(entry) - low_battery_threshold = float( - options.get(CONF_LOW_BATTERY_THRESHOLD, DEFAULT_LOW_BATTERY_THRESHOLD) + low_battery_threshold = safe_float_option( + options, + CONF_LOW_BATTERY_THRESHOLD, + DEFAULT_LOW_BATTERY_THRESHOLD, + min_value=0.0, ) - exercise_interval_days = int( - options.get(CONF_EXERCISE_INTERVAL_DAYS, DEFAULT_EXERCISE_INTERVAL_DAYS) + exercise_interval_days = safe_int_option( + options, + CONF_EXERCISE_INTERVAL_DAYS, + DEFAULT_EXERCISE_INTERVAL_DAYS, + min_value=0, ) - service_interval_hours = int( - options.get(CONF_SERVICE_INTERVAL_HOURS, DEFAULT_SERVICE_INTERVAL_HOURS) + service_interval_hours = safe_int_option( + options, + CONF_SERVICE_INTERVAL_HOURS, + DEFAULT_SERVICE_INTERVAL_HOURS, + min_value=0, ) active_issue_ids: set[str] = set() @@ -212,7 +223,7 @@ def _sync_issue( and hours_since is not None and hours_since >= service_interval_hours ) - api_alert = detail.hasMaintenanceAlert is True + api_alert = is_generator and 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: diff --git a/custom_components/generac/readiness.py b/custom_components/generac/readiness.py index f12ea5b..1fb9193 100644 --- a/custom_components/generac/readiness.py +++ b/custom_components/generac/readiness.py @@ -1,6 +1,7 @@ """Service and exercise readiness persistence and tracking for Generac.""" from __future__ import annotations +import asyncio import time from typing import Any @@ -20,6 +21,7 @@ from .utils import entry_options from .utils import get_detail_property_value from .utils import safe_float +from .utils import safe_int_option STORAGE_VERSION = 1 _ACTIVE_APPARATUS_STATUSES = (2, 3) # Running (2), Exercising (3) @@ -63,33 +65,35 @@ def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: ) self._devices: dict[str, dict[str, Any]] = {} self._loaded = False + self._load_lock = asyncio.Lock() 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 with self._load_lock: + if self._loaded: + return + if self._store is not None: + raw = await self._store.async_load() + devices = raw.get("devices") if isinstance(raw, dict) else None + if isinstance(devices, dict): + for dev_id, rec in devices.items(): + if not isinstance(rec, dict): + continue + last_ts = safe_float(rec.get("last_exercise_ts")) + if last_ts is None: + continue + last_rt = safe_float(rec.get("last_run_time")) + baseline = safe_float(rec.get("service_baseline_hours")) + if last_rt is None and baseline == 0.0: + baseline = None + self._devices[str(dev_id)] = { + "last_exercise_ts": last_ts, + "last_run_time": last_rt, + "service_baseline_hours": baseline, + } + self._loaded = True async def _async_save(self) -> None: """Persist current readiness state to Store.""" @@ -127,28 +131,43 @@ async def async_update_from_items( 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. + # Initialize baseline to current run hours once known 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 - ), + "service_baseline_hours": current_run_time, } changed = True continue record = self._devices[device_id] + if ( + record.get("service_baseline_hours") is None + and current_run_time is not None + ): + record["service_baseline_hours"] = current_run_time + changed = True prev_run_time = record.get("last_run_time") - exercised = detail.apparatusStatus in _ACTIVE_APPARATUS_STATUSES or ( + is_transient_zero_dip = ( current_run_time is not None + and current_run_time == 0.0 + and prev_run_time is not None + and prev_run_time > 0.0 + ) + exercised = detail.apparatusStatus in _ACTIVE_APPARATUS_STATUSES or ( + not is_transient_zero_dip + and current_run_time is not None and prev_run_time is not None and current_run_time > prev_run_time ) if exercised: record["last_exercise_ts"] = ts changed = True - if current_run_time is not None and current_run_time != prev_run_time: + if ( + not is_transient_zero_dip + and current_run_time is not None + and current_run_time != prev_run_time + ): record["last_run_time"] = current_run_time changed = True @@ -161,17 +180,20 @@ def hours_since_service(self, device_id: str) -> float | None: if record is None: return None last_run_time = record.get("last_run_time") - if last_run_time is None: + baseline = record.get("service_baseline_hours") + if last_run_time is None or baseline 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) + return round(max(0.0, float(last_run_time) - float(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 + interval = safe_int_option( + entry_options(self._entry), + CONF_SERVICE_INTERVAL_HOURS, + DEFAULT_SERVICE_INTERVAL_HOURS, + min_value=0, ) - if interval is None or interval <= 0: + if interval <= 0: return None since = self.hours_since_service(device_id) if since is None: @@ -193,10 +215,13 @@ def days_since_exercise( 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 + interval_days = safe_int_option( + entry_options(self._entry), + CONF_EXERCISE_INTERVAL_DAYS, + DEFAULT_EXERCISE_INTERVAL_DAYS, + min_value=0, ) - if interval_days is None or interval_days <= 0: + if interval_days <= 0: return False record = self._devices.get(device_id) if record is None: @@ -218,21 +243,30 @@ async def async_reset_service_timer( 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 + baseline = float(current_run_time) if current_run_time is not None else None self._devices[device_id] = { "last_exercise_ts": ts, "last_run_time": current_run_time, "service_baseline_hours": baseline, } else: + prev_run_time = record.get("last_run_time") + usable_run_time = ( + None + if ( + current_run_time is not None + and current_run_time == 0.0 + and prev_run_time is not None + and prev_run_time > 0.0 + ) + else current_run_time + ) effective_run_time = ( - current_run_time - if current_run_time is not None - else record.get("last_run_time") + usable_run_time if usable_run_time is not None else prev_run_time ) record["service_baseline_hours"] = ( - float(effective_run_time) if effective_run_time is not None else 0.0 + float(effective_run_time) if effective_run_time is not None else None ) - if current_run_time is not None: - record["last_run_time"] = current_run_time + if usable_run_time is not None: + record["last_run_time"] = usable_run_time await self._async_save() diff --git a/custom_components/generac/sensor.py b/custom_components/generac/sensor.py index 22b5688..b0acb4d 100644 --- a/custom_components/generac/sensor.py +++ b/custom_components/generac/sensor.py @@ -249,7 +249,7 @@ class RunTimeSensor(GeneracEntity, SensorEntity): @property def native_value(self): """Return the state of the sensor.""" - val = get_prop_value(self.aparatus_detail.properties, 71, 0) + val = get_prop_value(self.aparatus_detail.properties, 71, None) return _safe_float(val, "run_time") @@ -265,7 +265,7 @@ class ProtectionTimeSensor(GeneracEntity, SensorEntity): @property def native_value(self): """Return the state of the sensor.""" - val = get_prop_value(self.aparatus_detail.properties, 32, 0) + val = get_prop_value(self.aparatus_detail.properties, 32, None) return _safe_float(val, "protection_time") @@ -333,7 +333,7 @@ class BatteryVoltageSensor(GeneracEntity, SensorEntity): @property def native_value(self): """Return the state of the sensor.""" - val = get_prop_value(self.aparatus_detail.properties, 70, 0) + val = get_prop_value(self.aparatus_detail.properties, 70, None) return _safe_float(val, "battery_voltage") @@ -381,7 +381,7 @@ def native_value(self): or self.aparatus_detail.weather.temperature is None or self.aparatus_detail.weather.temperature.value is None ): - return 0 + return None return self.aparatus_detail.weather.temperature.value @@ -522,7 +522,7 @@ class CapacitySensor(GeneracEntity, SensorEntity): @property def native_value(self): """Return the state of the sensor.""" - val = get_prop_value(self.aparatus_detail.tuProperties, 1, 0) + val = get_prop_value(self.aparatus_detail.tuProperties, 1, None) return _safe_float(val, "capacity") diff --git a/custom_components/generac/utils.py b/custom_components/generac/utils.py index 8246ed3..d02f686 100644 --- a/custom_components/generac/utils.py +++ b/custom_components/generac/utils.py @@ -60,3 +60,43 @@ def safe_float(val: Any, label: str = "") -> float | None: if not math.isfinite(result): return None return result + + +def safe_int_option( + options: Mapping[str, Any], + key: str, + default: int, + *, + min_value: int | None = None, +) -> int: + """Read an integer option defensively, falling back to default on bad values.""" + raw = options.get(key, default) + if ( + raw is None + or isinstance(raw, bool) + or (isinstance(raw, float) and not math.isfinite(raw)) + ): + value = default + else: + try: + value = int(raw) + except (TypeError, ValueError): + value = default + if min_value is not None: + return max(min_value, value) + return value + + +def safe_float_option( + options: Mapping[str, Any], + key: str, + default: float, + *, + min_value: float | None = None, +) -> float: + """Read a finite float option defensively, falling back to default on bad values.""" + parsed = safe_float(options.get(key, default), key) + value = default if parsed is None else parsed + if min_value is not None: + return max(min_value, value) + return value diff --git a/custom_components/generac/weather.py b/custom_components/generac/weather.py index 44c7600..d9772b2 100644 --- a/custom_components/generac/weather.py +++ b/custom_components/generac/weather.py @@ -172,5 +172,5 @@ def native_temperature(self): or self.aparatus.weather.temperature is None or self.aparatus.weather.temperature.value is None ): - return 0 + return None return self.aparatus.weather.temperature.value diff --git a/tests/test_blueprints.py b/tests/test_blueprints.py index 9a92985..57c9ad0 100644 --- a/tests/test_blueprints.py +++ b/tests/test_blueprints.py @@ -1,4 +1,5 @@ """Tests for bundled Generac automation blueprints and auto-installer.""" +import asyncio from pathlib import Path from custom_components.generac.blueprints import BUNDLED_BLUEPRINTS_DIR @@ -60,6 +61,13 @@ async def test_bundled_blueprints_instantiate_valid_automations( "restore_loads": False, "restore_stagger_delay": 0, }, + { + "generator_status": "sensor.generator_status", + "shed_entities": "switch.ev_charger", + "ready_stabilization_delay": 30, + "restore_loads": True, + "restore_stagger_delay": 0, + }, ], "generac_fault_dealer_alert.yaml": [ { @@ -70,7 +78,17 @@ async def test_bundled_blueprints_instantiate_valid_automations( "dealer_name_sensor": "sensor.generator_dealer_name", "dealer_phone_sensor": "sensor.generator_dealer_phone", "notify_service": "notify.mobile_app_phone", - } + }, + { + "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", + "error_code_sensor": "sensor.generator_error_code", + "notify_service": "notify.mobile_app_phone", + }, ], "generac_storm_readiness_digest.yaml": [ { @@ -89,6 +107,17 @@ async def test_bundled_blueprints_instantiate_valid_automations( "fuel_level_sensor": "sensor.propane_tank_fuel_level", "notify_service": "notify.notify", }, + { + "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", + "remaining_fuel_sensor": "sensor.propane_tank_remaining_fuel", + "estimated_runtime_sensor": "sensor.propane_tank_estimated_runtime_remaining", + "notify_service": "notify.notify", + }, ], } @@ -134,3 +163,183 @@ def test_install_bundled_blueprints_is_idempotent(tmp_path: Path) -> None: target.read_bytes() == (BUNDLED_BLUEPRINTS_DIR / "generac_outage_load_shedding.yaml").read_bytes() ) + + +async def test_bundled_blueprints_runtime_execution(hass: HomeAssistant) -> None: + """Verify multi-line notification rendering and flap-safe load shedding.""" + await async_setup_component(hass, "homeassistant", {}) + + async def _turn_off(call): + eids = call.data.get("entity_id") + for eid in [eids] if isinstance(eids, str) else (eids or []): + hass.states.async_set(eid, "off") + + async def _turn_on(call): + eids = call.data.get("entity_id") + for eid in [eids] if isinstance(eids, str) else (eids or []): + hass.states.async_set(eid, "on") + + notifications: list[dict] = [] + + async def _notify(call): + notifications.append(dict(call.data)) + + hass.services.async_register("switch", "turn_off", _turn_off) + hass.services.async_register("switch", "turn_on", _turn_on) + hass.services.async_register("notify", "notify", _notify) + + hass.states.async_set("sensor.gen_status", "Ready") + hass.states.async_set("sensor.gen_status_text", "RPM Sense Loss") + hass.states.async_set("sensor.gen_error_code", "E1505") + hass.states.async_set("binary_sensor.gen_warning", "off") + hass.states.async_set("binary_sensor.gen_maint", "off") + hass.states.async_set("binary_sensor.gen_conn", "on") + hass.states.async_set("sensor.gen_batt", "13.2") + hass.states.async_set("sensor.gen_service", "84.5") + hass.states.async_set("sensor.dealer_name", "Acme Gen") + hass.states.async_set("sensor.dealer_phone", "555-0199") + hass.states.async_set("sensor.tank_level", "65") + hass.states.async_set("sensor.tank_gal", "325.0") + hass.states.async_set("sensor.tank_rt", "147.7") + hass.states.async_set("binary_sensor.storm_full", "off") + hass.states.async_set("binary_sensor.storm_min", "off") + hass.states.async_set("switch.ev", "on") + hass.states.async_set("switch.pool", "off") + + install_bundled_blueprints(hass.config.path("blueprints", "automation", "generac")) + + assert await async_setup_component( + hass, + "automation", + { + "automation": [ + { + "id": "shed_rt", + "alias": "Shed Runtime", + "use_blueprint": { + "path": "generac/generac_outage_load_shedding.yaml", + "input": { + "generator_status": "sensor.gen_status", + "shed_entities": ["switch.ev", "switch.pool"], + "ready_stabilization_delay": 0, + "restore_loads": True, + "restore_stagger_delay": 0, + }, + }, + }, + { + "id": "fault_rt", + "alias": "Fault Runtime", + "use_blueprint": { + "path": "generac/generac_fault_dealer_alert.yaml", + "input": { + "status_sensor": "sensor.gen_status", + "status_text_sensor": "sensor.gen_status_text", + "error_code_sensor": "sensor.gen_error_code", + "warning_sensor": "binary_sensor.gen_warning", + "maintenance_sensor": "binary_sensor.gen_maint", + "dealer_name_sensor": "sensor.dealer_name", + "dealer_phone_sensor": "sensor.dealer_phone", + "notify_service": "notify.notify", + }, + }, + }, + { + "id": "storm_full_rt", + "alias": "Storm Full Runtime", + "use_blueprint": { + "path": "generac/generac_storm_readiness_digest.yaml", + "input": { + "weather_alert_entity": "binary_sensor.storm_full", + "status_sensor": "sensor.gen_status", + "battery_voltage_sensor": "sensor.gen_batt", + "is_connected_sensor": "binary_sensor.gen_conn", + "hours_until_service_sensor": "sensor.gen_service", + "fuel_level_sensor": "sensor.tank_level", + "remaining_fuel_sensor": "sensor.tank_gal", + "estimated_runtime_sensor": "sensor.tank_rt", + "notify_service": "notify.notify", + }, + }, + }, + { + "id": "storm_min_rt", + "alias": "Storm Min Runtime", + "use_blueprint": { + "path": "generac/generac_storm_readiness_digest.yaml", + "input": { + "weather_alert_entity": "binary_sensor.storm_min", + "status_sensor": "sensor.gen_status", + "battery_voltage_sensor": "sensor.gen_batt", + "is_connected_sensor": "binary_sensor.gen_conn", + "hours_until_service_sensor": "sensor.gen_service", + "notify_service": "notify.notify", + }, + }, + }, + ] + }, + ) + await hass.async_block_till_done() + + # 1. Storm readiness notifications format cleanly across lines + hass.states.async_set("binary_sensor.storm_full", "on") + await hass.async_block_till_done() + assert notifications[-1]["message"] == ( + "Status: Ready\n" + "Connected: Online\n" + "Battery Voltage: 13.2 V\n" + "Hours Until Service: 84.5 h\n" + "Propane Fuel Level: 65%\n" + "Remaining Fuel: 325.0 gal\n" + "Estimated Runtime: 147.7 h" + ) + + hass.states.async_set("binary_sensor.storm_min", "on") + await hass.async_block_till_done() + assert notifications[-1]["message"] == ( + "Status: Ready\n" + "Connected: Online\n" + "Battery Voltage: 13.2 V\n" + "Hours Until Service: 84.5 h" + ) + + # 2. Fault alert formats optional error code cleanly with and without details + hass.states.async_set("sensor.gen_status", "Stopped") + await hass.async_block_till_done() + assert notifications[-1]["title"] == "Generac Alert: Stopped" + assert notifications[-1]["message"] == ( + "Status: Stopped\n" + "Error Code: E1505\n" + "Details: RPM Sense Loss\n" + "Dealer: Acme Gen\n" + "Phone: 555-0199" + ) + + hass.states.async_set("sensor.gen_error_code", "unknown") + hass.states.async_set("sensor.gen_status_text", "unknown") + hass.states.async_set("binary_sensor.gen_maint", "on") + await hass.async_block_till_done() + assert notifications[-1]["title"] == "Generac Maintenance Alert (Stopped)" + assert notifications[-1]["message"] == ( + "Status: Stopped\nDealer: Acme Gen\nPhone: 555-0199" + ) + + # 3. Load shedding sheds active + idle loads, survives Running->Warning->Running + # flaps, and restores only loads that were active before the outage. + hass.states.async_set("sensor.gen_status", "Running") + await asyncio.sleep(0.05) + assert hass.states.get("switch.ev").state == "off" + assert hass.states.get("switch.pool").state == "off" + + hass.states.async_set("sensor.gen_status", "Warning") + await asyncio.sleep(0.05) + hass.states.async_set("switch.ev", "on") + hass.states.async_set("sensor.gen_status", "Running") + await asyncio.sleep(0.05) + assert hass.states.get("switch.ev").state == "off" + + hass.states.async_set("sensor.gen_status", "Ready") + await hass.async_block_till_done() + assert hass.states.get("switch.ev").state == "on" + assert hass.states.get("switch.pool").state == "off" diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 0fe17c5..48d2b15 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -941,3 +941,107 @@ async def test_reconfigure_flow_persists_active_scan_interval( assert entry.options.get(CONF_SCAN_INTERVAL) == 600 assert entry.options.get(CONF_ACTIVE_SCAN_INTERVAL) == 90 + + +async def test_options_flow_and_reconfigure_schema_bounds_and_serialization( + hass: HomeAssistant, +) -> None: + """Options and Reconfigure validate bounds, reject non-finite floats, and serialize cleanly.""" + import voluptuous_serialize + from custom_components.generac.const import CONF_EXERCISE_INTERVAL_DAYS + from custom_components.generac.const import CONF_FUEL_BURN_RATE + from custom_components.generac.const import CONF_LOW_BATTERY_THRESHOLD + from custom_components.generac.const import CONF_SERVICE_INTERVAL_HOURS + from custom_components.generac.const import DEFAULT_EXERCISE_INTERVAL_DAYS + from custom_components.generac.const import DEFAULT_LOW_BATTERY_THRESHOLD + from custom_components.generac.const import DEFAULT_SCAN_INTERVAL + from custom_components.generac.const import DEFAULT_SERVICE_INTERVAL_HOURS + from homeassistant.data_entry_flow import InvalidData + from homeassistant.helpers import config_validation as cv + + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "old-rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + options={ + "button": None, + CONF_SCAN_INTERVAL: "bad", + CONF_ACTIVE_SCAN_INTERVAL: 3, + CONF_SERVICE_INTERVAL_HOURS: True, + CONF_EXERCISE_INTERVAL_DAYS: "oops", + CONF_LOW_BATTERY_THRESHOLD: float("inf"), + }, + ) + entry.add_to_hass(hass) + + with patch("custom_components.generac.async_setup_entry", return_value=True): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + # OptionsFlow: schema serializes for HA UI and recovers corrupted defaults cleanly + opt_res = await hass.config_entries.options.async_init(entry.entry_id) + assert opt_res["type"] == "form" + serialized_opts = voluptuous_serialize.convert( + opt_res["data_schema"], custom_serializer=cv.custom_serializer + ) + assert any(field["name"] == CONF_SCAN_INTERVAL for field in serialized_opts) + + for bad_input in ( + {CONF_SCAN_INTERVAL: 5}, + {CONF_ACTIVE_SCAN_INTERVAL: 0}, + {CONF_FUEL_BURN_RATE: float("inf")}, + {CONF_FUEL_BURN_RATE: float("nan")}, + {CONF_LOW_BATTERY_THRESHOLD: float("inf")}, + {CONF_LOW_BATTERY_THRESHOLD: float("nan")}, + {CONF_LOW_BATTERY_THRESHOLD: -1.0}, + ): + with pytest.raises(InvalidData): + await hass.config_entries.options.async_configure( + opt_res["flow_id"], user_input=bad_input + ) + + opt_done = await hass.config_entries.options.async_configure( + opt_res["flow_id"], user_input={} + ) + assert opt_done["type"] == "create_entry" + assert entry.options["button"] is True + assert entry.options[CONF_SCAN_INTERVAL] == DEFAULT_SCAN_INTERVAL + assert entry.options[CONF_ACTIVE_SCAN_INTERVAL] == 10 + assert entry.options[CONF_SERVICE_INTERVAL_HOURS] == DEFAULT_SERVICE_INTERVAL_HOURS + assert entry.options[CONF_EXERCISE_INTERVAL_DAYS] == DEFAULT_EXERCISE_INTERVAL_DAYS + assert entry.options[CONF_LOW_BATTERY_THRESHOLD] == DEFAULT_LOW_BATTERY_THRESHOLD + + # Reconfigure: schema serializes cleanly and enforces >= 10s intervals + rec_res = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": "reconfigure", "entry_id": entry.entry_id}, + ) + assert rec_res["type"] == "form" + serialized_rec = voluptuous_serialize.convert( + rec_res["data_schema"], custom_serializer=cv.custom_serializer + ) + assert any(field["name"] == CONF_ACTIVE_SCAN_INTERVAL for field in serialized_rec) + + with pytest.raises(InvalidData): + await hass.config_entries.flow.async_configure( + rec_res["flow_id"], + { + CONF_USERNAME: "user@example.com", + CONF_PASSWORD: "new-pw", + CONF_SCAN_INTERVAL: 9, + CONF_ACTIVE_SCAN_INTERVAL: 120, + }, + ) + with pytest.raises(InvalidData): + await hass.config_entries.flow.async_configure( + rec_res["flow_id"], + { + CONF_USERNAME: "user@example.com", + CONF_PASSWORD: "new-pw", + CONF_SCAN_INTERVAL: 900, + CONF_ACTIVE_SCAN_INTERVAL: 0, + }, + ) diff --git a/tests/test_coordinator.py b/tests/test_coordinator.py index cc80e36..0c0c91b 100644 --- a/tests/test_coordinator.py +++ b/tests/test_coordinator.py @@ -228,13 +228,20 @@ async def test_coordinator_clamps_intervals_and_tolerates_mock_options(hass): assert coord_short.active_scan_interval == 120 assert coord_short.fast_scan_interval == 60 + entry_bad = MagicMock() + entry_bad.options = {CONF_SCAN_INTERVAL: "bad", CONF_ACTIVE_SCAN_INTERVAL: True} + coord_bad = GeneracDataUpdateCoordinator(hass, MagicMock(), entry_bad) + assert coord_bad.idle_scan_interval == DEFAULT_SCAN_INTERVAL + assert coord_bad.active_scan_interval == DEFAULT_ACTIVE_SCAN_INTERVAL + def test_is_fleet_active_variants(): """Verify _is_fleet_active across device types, statuses, flags, and malformed inputs.""" assert _is_fleet_active(None) is False assert _is_fleet_active({"foo": "bar"}) is False assert _is_fleet_active({"g": _item(DEVICE_TYPE_GENERATOR, status=1)}) is False - for active_status in (2, 3, 4, 5): + assert _is_fleet_active({"g": _item(DEVICE_TYPE_GENERATOR, status=5)}) is False + for active_status in (2, 3, 4): assert ( _is_fleet_active({"g": _item(DEVICE_TYPE_GENERATOR, status=active_status)}) is True diff --git a/tests/test_init.py b/tests/test_init.py index 98887b8..7881767 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -480,3 +480,84 @@ async def test_services_yaml_schema_and_descriptions( "duration_minutes", "entry_id", } + + +async def test_platform_toggles_setup_reload_and_unload(hass: HomeAssistant): + """Platform checkboxes filter forwarded platforms and toggle cleanly on reload.""" + from custom_components.generac.const import DEVICE_TYPE_GENERATOR + from custom_components.generac.const import PLATFORMS + 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 Weather + from homeassistant.helpers import entity_registry as er + + gen_item = Item( + apparatus=Apparatus( + apparatusId=12345, + name="Home Gen", + type=DEVICE_TYPE_GENERATOR, + weather=Weather( + iconCode=1, + temperature=Weather.Temperature(value=70.0, unit="F", unitType=1), + ), + ), + apparatusDetail=ApparatusDetail( + apparatusId=12345, + name="Home Gen", + apparatusStatus=1, + heroImageUrl="https://example.com/gen.png", + ), + ) + + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + AsyncMock(return_value={"12345": gen_item}), + ): + entry = MockConfigEntry( + domain=DOMAIN, + data=_make_mock_config(), + options={"button": False, "weather": False, "sensor": None}, + entry_id="platform_toggle_test", + ) + entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + coordinator = hass.data[DOMAIN][entry.entry_id] + assert coordinator.loaded_platforms == ["binary_sensor", "sensor", "image"] + registry = er.async_get(hass) + domains = { + e.domain + for e in er.async_entries_for_config_entry(registry, entry.entry_id) + } + assert domains == {"binary_sensor", "sensor", "image"} + + # Toggling button back on and image off unloads old platforms cleanly and loads new set + hass.config_entries.async_update_entry( + entry, + options={"button": True, "weather": False, "image": False}, + ) + await hass.async_block_till_done() + coordinator2 = hass.data[DOMAIN][entry.entry_id] + assert coordinator2.loaded_platforms == ["binary_sensor", "sensor", "button"] + assert hass.states.get("button.home_gen_outage_boost_poll") is not None + assert hass.states.get("weather.home_gen_weather") is None + + assert await hass.config_entries.async_unload(entry.entry_id) + assert entry.entry_id not in hass.data[DOMAIN] + + # All platforms disabled still sets up and unloads cleanly without errors + all_disabled_entry = MockConfigEntry( + domain=DOMAIN, + data=_make_mock_config(), + options={platform: False for platform in PLATFORMS}, + entry_id="all_disabled_test", + ) + all_disabled_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(all_disabled_entry.entry_id) + await hass.async_block_till_done() + assert hass.data[DOMAIN][all_disabled_entry.entry_id].loaded_platforms == [] + assert await hass.config_entries.async_unload(all_disabled_entry.entry_id) + assert all_disabled_entry.entry_id not in hass.data[DOMAIN] diff --git a/tests/test_issues.py b/tests/test_issues.py index 562e488..95eb31f 100644 --- a/tests/test_issues.py +++ b/tests/test_issues.py @@ -281,3 +281,34 @@ async def test_subscription_dunning_and_entry_cleanup(hass: HomeAssistant) -> No 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 + + +async def test_propane_maintenance_alert_ignored_and_bad_options_tolerated( + hass: HomeAssistant, +) -> None: + """Propane monitors do not raise generator-worded maintenance_due, and bad options do not crash.""" + entry = _entry( + hass, + entry_id="edge_issues", + options={ + CONF_LOW_BATTERY_THRESHOLD: None, + CONF_EXERCISE_INTERVAL_DAYS: "not-an-int", + CONF_SERVICE_INTERVAL_HOURS: True, + }, + ) + propane = Item( + apparatus=Apparatus( + apparatusId=202, name="Propane Tank", type=DEVICE_TYPE_PROPANE_MONITOR + ), + apparatusDetail=ApparatusDetail( + apparatusId=202, name="Propane Tank", hasMaintenanceAlert=True + ), + ) + gen_low_batt = _make_generator(battery_voltage="11.5") + + async_update_device_health_issues( + hass, entry, {"202": propane, "101": gen_low_batt} + ) + + assert _device_issue(hass, "maintenance_due", entry, "202") is None + assert _device_issue(hass, "low_battery_voltage", entry, "101") is not None diff --git a/tests/test_readiness.py b/tests/test_readiness.py index 94d125c..e1c8806 100644 --- a/tests/test_readiness.py +++ b/tests/test_readiness.py @@ -1,4 +1,5 @@ """Tests for Generac readiness tracking, persistence, and reload-free updates.""" +import asyncio from unittest.mock import AsyncMock from unittest.mock import patch @@ -239,3 +240,91 @@ async def test_readiness_edge_cases_and_disabled_interval(hass: HomeAssistant) - "new_gen", current_run_time=15.0, now=1_700_000_100.0 ) assert tracker.hours_since_service("new_gen") == 0.0 + + +async def test_readiness_missing_initial_runtime_transient_zero_and_concurrent_load( + hass: HomeAssistant, +) -> None: + """Verify baseline waits for valid run_time, ignores 0-dips, locks load, and tolerates bad options.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id="hardening_entry", + options={CONF_SERVICE_INTERVAL_HOURS: None, CONF_EXERCISE_INTERVAL_DAYS: "bad"}, + ) + entry.add_to_hass(hass) + tracker = ReadinessTracker(hass, entry) + t0 = 1_700_000_000.0 + + # 1. First poll lacks run_time (None): baseline stays None so poll 2 does not false-alarm + await tracker.async_update_from_items({"1": _gen(status=1, run_time=None)}, now=t0) + assert tracker.get_device_state("1")["service_baseline_hours"] is None + assert tracker.hours_since_service("1") is None + assert tracker.hours_until_service("1") is None + + await tracker.async_update_from_items( + {"1": _gen(status=1, run_time=500.0)}, now=t0 + 900 + ) + assert tracker.get_device_state("1")["service_baseline_hours"] == 500.0 + assert tracker.hours_since_service("1") == 0.0 + # Malformed None/str options fall back safely to defaults (100 h / 16 days) + assert tracker.hours_until_service("1") == 100.0 + assert tracker.is_missed_exercise("1", now=t0 + 900) is False + + # 2. Transient 0.0 runtime dip (500.0 -> 0.0 -> 500.0) must not drop last_run_time + # or falsely advance last_exercise_ts. + await tracker.async_update_from_items( + {"1": _gen(status=1, run_time=0.0)}, now=t0 + 1800 + ) + assert tracker.get_device_state("1")["last_run_time"] == 500.0 + await tracker.async_update_from_items( + {"1": _gen(status=1, run_time=500.0)}, now=t0 + 2700 + ) + assert tracker.get_device_state("1")["last_run_time"] == 500.0 + assert tracker.get_device_state("1")["last_exercise_ts"] == t0 + + # Resetting the maintenance timer during a transient 0.0 dip keeps 500.0 baseline + await tracker.async_reset_service_timer("1", current_run_time=0.0, now=t0 + 3000) + assert tracker.get_device_state("1")["last_run_time"] == 500.0 + assert tracker.get_device_state("1")["service_baseline_hours"] == 500.0 + assert tracker.hours_since_service("1") == 0.0 + + # 3. Concurrent async_load calls wait on the load lock, load once, and heal beta stores + from custom_components.generac.readiness import readiness_store_key + from homeassistant.helpers.storage import Store + + concurrent_entry = MockConfigEntry(domain=DOMAIN, entry_id="concurrent_entry") + concurrent_entry.add_to_hass(hass) + await Store(hass, 1, readiness_store_key(concurrent_entry.entry_id)).async_save( + { + "devices": { + "1": { + "last_exercise_ts": t0, + "last_run_time": 42.0, + "service_baseline_hours": 30.0, + }, + "beta_uninit": { + "last_exercise_ts": t0, + "last_run_time": None, + "service_baseline_hours": 0.0, + }, + } + } + ) + + tracker_conc = ReadinessTracker(hass, concurrent_entry) + orig_load = tracker_conc._store.async_load + + async def slow_load(): + await asyncio.sleep(0.01) + return await orig_load() + + with patch.object( + tracker_conc._store, "async_load", side_effect=slow_load + ) as mock_load: + await asyncio.gather(tracker_conc.async_load(), tracker_conc.async_load()) + + mock_load.assert_awaited_once() + assert tracker_conc.hours_since_service("1") == 12.0 + assert ( + tracker_conc.get_device_state("beta_uninit")["service_baseline_hours"] is None + ) diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 646777d..fb6cc70 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -653,3 +653,85 @@ def test_error_code_sensor(): for empty_val in ("", " ", None, 123): item.apparatusDetail.eCodeLabel = empty_val assert sensor.native_value is None + + +def test_missing_properties_return_none_while_explicit_zero_preserved(): + """Missing properties/weather return None to avoid LTS spikes, while explicit 0 is kept.""" + entry = MagicMock() + + # Empty/missing properties on generator & propane monitor must return None + missing_gen = Item( + apparatus=Apparatus(apparatusId=1, type=DEVICE_TYPE_GENERATOR), + apparatusDetail=ApparatusDetail(apparatusId=1, properties=None, weather=None), + ) + assert RunTimeSensor(MagicMock(), entry, "1", missing_gen).native_value is None + assert ( + ProtectionTimeSensor(MagicMock(), entry, "1", missing_gen).native_value is None + ) + assert ( + BatteryVoltageSensor(MagicMock(), entry, "1", missing_gen).native_value is None + ) + assert ( + OutdoorTemperatureSensor(MagicMock(), entry, "1", missing_gen).native_value + is None + ) + + missing_gen_empty_props = Item( + apparatus=Apparatus(apparatusId=1, type=DEVICE_TYPE_GENERATOR), + apparatusDetail=ApparatusDetail( + apparatusId=1, + properties=[], + weather=Weather( + temperature=Weather.Temperature(value=None, unit="F", unitType=1), + iconCode=1, + ), + ), + ) + assert ( + RunTimeSensor(MagicMock(), entry, "1", missing_gen_empty_props).native_value + is None + ) + assert ( + ProtectionTimeSensor( + MagicMock(), entry, "1", missing_gen_empty_props + ).native_value + is None + ) + assert ( + BatteryVoltageSensor( + MagicMock(), entry, "1", missing_gen_empty_props + ).native_value + is None + ) + assert ( + OutdoorTemperatureSensor( + MagicMock(), entry, "1", missing_gen_empty_props + ).native_value + is None + ) + + missing_prop = Item( + apparatus=Apparatus(apparatusId=2, type=DEVICE_TYPE_PROPANE_MONITOR), + apparatusDetail=ApparatusDetail(apparatusId=2, tuProperties=None), + ) + assert CapacitySensor(MagicMock(), entry, "2", missing_prop).native_value is None + + # Explicit 0 values from the API must still be preserved as 0.0 + zero_gen = get_mock_item( + DEVICE_TYPE_GENERATOR, + 1, + run_time=0, + protection_time=0, + battery_voltage=0.0, + outdoor_temperature=0.0, + outdoor_temperature_unit="C", + ) + assert RunTimeSensor(MagicMock(), entry, "1", zero_gen).native_value == 0.0 + assert ProtectionTimeSensor(MagicMock(), entry, "1", zero_gen).native_value == 0.0 + assert BatteryVoltageSensor(MagicMock(), entry, "1", zero_gen).native_value == 0.0 + assert ( + OutdoorTemperatureSensor(MagicMock(), entry, "1", zero_gen).native_value == 0.0 + ) + + zero_prop = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1, capacity=0) + assert CapacitySensor(MagicMock(), entry, "2", zero_prop).native_value == 0.0 diff --git a/tests/test_weather.py b/tests/test_weather.py index 22f438b..ba18098 100644 --- a/tests/test_weather.py +++ b/tests/test_weather.py @@ -64,3 +64,16 @@ async def test_weather_sensor(hass): item = get_mock_item(99, 70.0, "F") sensor = WeatherSensor(coordinator, entry, "12345", item) assert sensor.condition == "exceptional" + + # Missing weather or temperature returns None rather than 0 + missing_weather = Item(apparatus=Apparatus(), apparatusDetail=ApparatusDetail()) + assert ( + WeatherSensor(coordinator, entry, "12345", missing_weather).native_temperature + is None + ) + + # Explicit 0.0 temperature is preserved + zero_temp = get_mock_item(1, 0.0, "C") + assert ( + WeatherSensor(coordinator, entry, "12345", zero_temp).native_temperature == 0.0 + ) From d40a6f5b60606cc30692af0f820418a5f9a93edc Mon Sep 17 00:00:00 2001 From: Jose Santiago Date: Fri, 20 Nov 2026 19:15:06 -0500 Subject: [PATCH 2/2] Use FlowManagerIndexView in schema serialization test for HA 2026.9+ compatibility --- tests/test_config_flow.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 48d2b15..a6740d6 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -947,7 +947,6 @@ async def test_options_flow_and_reconfigure_schema_bounds_and_serialization( hass: HomeAssistant, ) -> None: """Options and Reconfigure validate bounds, reject non-finite floats, and serialize cleanly.""" - import voluptuous_serialize from custom_components.generac.const import CONF_EXERCISE_INTERVAL_DAYS from custom_components.generac.const import CONF_FUEL_BURN_RATE from custom_components.generac.const import CONF_LOW_BATTERY_THRESHOLD @@ -957,7 +956,7 @@ async def test_options_flow_and_reconfigure_schema_bounds_and_serialization( from custom_components.generac.const import DEFAULT_SCAN_INTERVAL from custom_components.generac.const import DEFAULT_SERVICE_INTERVAL_HOURS from homeassistant.data_entry_flow import InvalidData - from homeassistant.helpers import config_validation as cv + from homeassistant.helpers.data_entry_flow import FlowManagerIndexView entry = MockConfigEntry( domain=DOMAIN, @@ -984,9 +983,9 @@ async def test_options_flow_and_reconfigure_schema_bounds_and_serialization( # OptionsFlow: schema serializes for HA UI and recovers corrupted defaults cleanly opt_res = await hass.config_entries.options.async_init(entry.entry_id) assert opt_res["type"] == "form" - serialized_opts = voluptuous_serialize.convert( - opt_res["data_schema"], custom_serializer=cv.custom_serializer - ) + serialized_opts = FlowManagerIndexView( + hass.config_entries.options + )._prepare_result_json(opt_res)["data_schema"] assert any(field["name"] == CONF_SCAN_INTERVAL for field in serialized_opts) for bad_input in ( @@ -1020,9 +1019,9 @@ async def test_options_flow_and_reconfigure_schema_bounds_and_serialization( context={"source": "reconfigure", "entry_id": entry.entry_id}, ) assert rec_res["type"] == "form" - serialized_rec = voluptuous_serialize.convert( - rec_res["data_schema"], custom_serializer=cv.custom_serializer - ) + serialized_rec = FlowManagerIndexView( + hass.config_entries.flow + )._prepare_result_json(rec_res)["data_schema"] assert any(field["name"] == CONF_ACTIVE_SCAN_INTERVAL for field in serialized_rec) with pytest.raises(InvalidData):