From c1dcce4c7084eee4711bed6f632589f9357d51d0 Mon Sep 17 00:00:00 2001 From: Jose Santiago Date: Wed, 18 Nov 2026 01:16:40 -0500 Subject: [PATCH] Add long-term statistics, fuel autonomy, fault/VPP telemetry, and diagnostic categories --- README.md | 30 ++- custom_components/generac/binary_sensor.py | 56 ++++- custom_components/generac/config_flow.py | 21 +- custom_components/generac/const.py | 3 + custom_components/generac/sensor.py | 131 ++++++++++- .../generac/translations/en.json | 1 + .../generac/translations/fr.json | 1 + .../generac/translations/nb.json | 1 + .../generac/translations/pt.json | 1 + tests/test_binary_sensor.py | 126 ++++++++++- tests/test_config_flow.py | 52 +++++ tests/test_entity_registry.py | 102 ++++++++- tests/test_sensor.py | 206 ++++++++++++++++++ 13 files changed, 715 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 4564ab7..b6fb1c7 100644 --- a/README.md +++ b/README.md @@ -9,16 +9,16 @@ **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`, `missed_exercise` | -| `button` | `reset_service_timer`, `boost_polling` | -| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `hours_until_service` | +| Platform | Entities created for each generator | +| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, `missed_exercise`, plus conditional `enrolled_in_vpp`, `active_vpp_event`, `subscription_dunning` | +| `button` | `reset_service_timer`, `boost_polling` | +| `sensor` | `status`, `run_time`, `protection_time`, `activation_date`, `last_seen`, `connection_time`, `battery_voltage`, `device_type`, `dealer_email`, `dealer_name`, `dealer_phone`, `address`, `status_text`, `status_label`, `error_code`, `serial_number`, `model_number`, `device_ssid`, `panel_id`, `signal_strength`, `hours_until_service`, optional `exercise_minutes`, `outdoor_temperature`, `device_battery_level` | -| Platform | Entities created for each propane tank monitor | -| --------------- | ------------------------------------------------------------------------------------------------------------------------------ | -| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning` | -| `sensor` | `status`, `capacity`, `fuel_level`, `fuel_type`, `orientation`, `last_reading_date`, `battery_level`, `address`, `device_type` | +| Platform | Entities created for each propane tank monitor | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `binary_sensor` | `is_connected`, `is_connecting`, `has_maintenance_alert`, `has_warning`, plus conditional `subscription_dunning` | +| `sensor` | `status`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `fuel_type`, `orientation`, `last_reading_date`, `battery_level`, `address`, `device_type`, optional `signal_strength`, `device_battery_level`, `outdoor_temperature` | ![example][exampleimg] @@ -66,6 +66,12 @@ Click this button to skip steps 1 and 2 below: [![Open your Home Assistant insta ## Configuration is done in the UI +### Options (`Configure`) + +Open **Settings → Devices & services → Generac MobileLink → Configure** to adjust enabled platforms, polling intervals, readiness thresholds, and fuel autonomy calculation: + +- **Estimated fuel burn rate (gal/h)** (`fuel_burn_rate`, default `2.2` gal/h LP at typical 50% load): Used by the propane monitor `Estimated Runtime Remaining` (`estimated_runtime`) sensor to convert `Remaining Fuel` (`remaining_fuel`, in gallons) into hours of generator runtime remaining (`remaining_fuel / fuel_burn_rate`). + ### Adaptive Polling & Outage Boost To stay gentle on Generac's rate-limited cloud API during normal standby while reacting quickly during exercises, outages, and warnings, polling adapts automatically between two configurable intervals (both clamped to at least `10` seconds): @@ -80,6 +86,12 @@ You can also trigger fast polling manually (for example, from an automation trig - **Outage Boost Poll button (`button._outage_boost_poll`)**: Created for each generator; pressing it immediately refreshes data and enables boost polling for `30` minutes. - **`generac.boost_polling` action (service)**: Switches loaded entries into boost polling and triggers an immediate refresh. Accepts optional `duration_minutes` (`1`–`120`, default `30`) and optional `entry_id` (targets all loaded Generac entries if omitted). +### Telemetry, Long-Term Statistics & Diagnostics + +- **Long-Term Statistics (LTS)**: Operational numeric sensors expose Home Assistant `state_class` (`total_increasing` on `run_time` and `protection_time`; `measurement` on `battery_voltage`, `exercise_minutes`, `outdoor_temperature`, `capacity`, `fuel_level`, `remaining_fuel`, `estimated_runtime`, `signal_strength`, `device_battery_level`, and `hours_until_service`) for history graphs and long-term recorder statistics. +- **Fault, VPP & Subscription Telemetry**: Generators expose active fault codes via `Error Code` (`error_code`), and—when present in the MobileLink payload—Virtual Power Plant status (`enrolled_in_vpp`, `active_vpp_event`) and subscription billing alerts (`subscription_dunning`). +- **Diagnostic Categorization**: Static metadata and diagnostic entities (serial/model/panel ID, device SSID/type, address, dealer contact info, activation/last-seen/connection timestamps, fuel type, tank orientation, signal strength, VPP enrollment, and subscription billing alert) are grouped under Home Assistant's **Diagnostic** entity category to keep primary dashboards uncluttered. + ### Readiness Tracking, Maintenance Timer & Repairs Alerts Each generator automatically tracks exercise activity and maintenance runtime baselines using Home Assistant storage (persisting cleanly across restarts without reloading the integration): diff --git a/custom_components/generac/binary_sensor.py b/custom_components/generac/binary_sensor.py index 79e8794..3300bbf 100644 --- a/custom_components/generac/binary_sensor.py +++ b/custom_components/generac/binary_sensor.py @@ -6,6 +6,7 @@ from homeassistant.components.binary_sensor import BinarySensorDeviceClass from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback @@ -38,8 +39,17 @@ def sensors(item: Item | None = None) -> list[Type[GeneracEntity]]: GeneracMaintenanceAlertSensor, GeneracWarningSensor, ] - if item is not None and item.apparatus.type == DEVICE_TYPE_GENERATOR: + if item is None: + return lst + if item.apparatus.type == DEVICE_TYPE_GENERATOR: lst.append(GeneracMissedExerciseSensor) + if ( + item.apparatusDetail.enrolledInVpp is not None + or item.apparatusDetail.hasActiveVppEvent is not None + ): + lst.extend([GeneracVppEnrolledSensor, GeneracActiveVppEventSensor]) + if item.apparatusDetail.subscription is not None: + lst.append(GeneracSubscriptionDunningSensor) return lst @@ -123,3 +133,47 @@ class GeneracMissedExerciseSensor(GeneracEntity, BinarySensorEntity): 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)) + + +class GeneracVppEnrolledSensor(GeneracEntity, BinarySensorEntity): + """Whether the generator is enrolled in a Virtual Power Plant program.""" + + entity_key = "enrolled_in_vpp" + entity_label = "VPP Enrolled" + + _attr_entity_category = EntityCategory.DIAGNOSTIC + + @property + def is_on(self): + """Return true if the generator is enrolled in VPP.""" + return bool(self.aparatus_detail.enrolledInVpp) + + +class GeneracActiveVppEventSensor(GeneracEntity, BinarySensorEntity): + """Whether a Virtual Power Plant dispatch event is currently active.""" + + entity_key = "active_vpp_event" + entity_label = "Active VPP Event" + + @property + def is_on(self): + """Return true if a VPP event is active.""" + return bool(self.aparatus_detail.hasActiveVppEvent) + + +class GeneracSubscriptionDunningSensor(GeneracEntity, BinarySensorEntity): + """Whether the Mobile Link subscription is in billing dunning.""" + + entity_key = "subscription_dunning" + entity_label = "Subscription Billing Alert" + + _attr_device_class = BinarySensorDeviceClass.PROBLEM + _attr_entity_category = EntityCategory.DIAGNOSTIC + + @property + def is_on(self): + """Return true if subscription billing is in dunning.""" + return bool( + self.aparatus_detail.subscription + and self.aparatus_detail.subscription.isDunning + ) diff --git a/custom_components/generac/config_flow.py b/custom_components/generac/config_flow.py index 31d634f..5173d6b 100644 --- a/custom_components/generac/config_flow.py +++ b/custom_components/generac/config_flow.py @@ -22,6 +22,7 @@ """ import asyncio import logging +import math import time import aiohttp @@ -39,6 +40,7 @@ from .const import CONF_ACTIVE_SCAN_INTERVAL from .const import CONF_DPOP_PEM from .const import CONF_EXERCISE_INTERVAL_DAYS +from .const import CONF_FUEL_BURN_RATE from .const import CONF_MFA_CODE from .const import CONF_OPTIONS from .const import CONF_PASSWORD @@ -49,6 +51,7 @@ from .const import CONF_TOKEN_ISSUED_AT from .const import CONF_USERNAME from .const import DEFAULT_ACTIVE_SCAN_INTERVAL +from .const import DEFAULT_FUEL_BURN_RATE from .const import DEFAULT_SCAN_INTERVAL from .const import DOMAIN from .utils import async_client_session @@ -483,6 +486,8 @@ 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 == CONF_FUEL_BURN_RATE: + return vol.All(vol.Coerce(float), vol.Range(min=0.0, min_included=False)) 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): @@ -496,6 +501,20 @@ class GeneracOptionsFlowHandler(config_entries.OptionsFlow): def __init__(self, config_entry): self.options = dict(entry_options(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 == 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 + async def async_step_init(self, user_input=None): # pylint: disable=unused-argument return await self.async_step_user() @@ -509,7 +528,7 @@ async def async_step_user(self, user_input=None): data_schema=vol.Schema( { vol.Required( - k, default=self.options.get(k, v["default"]) + k, default=self._option_default(k, v, self.options) ): _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 ade7ce3..de198c6 100644 --- a/custom_components/generac/const.py +++ b/custom_components/generac/const.py @@ -34,6 +34,7 @@ DEFAULT_ACTIVE_SCAN_INTERVAL = 120 ACTIVE_COOLDOWN_SECONDS = 300 DEFAULT_BOOST_DURATION_MINUTES = 30 +DEFAULT_FUEL_BURN_RATE = 2.2 SERVICE_BOOST_POLLING = "boost_polling" # Platforms @@ -65,6 +66,7 @@ CONF_DPOP_PEM = "dpop_pem" CONF_SCAN_INTERVAL = "scan_interval" CONF_ACTIVE_SCAN_INTERVAL = "active_scan_interval" +CONF_FUEL_BURN_RATE = "fuel_burn_rate" CONF_SERVICE_INTERVAL_HOURS = "service_interval_hours" CONF_EXERCISE_INTERVAL_DAYS = "exercise_interval_days" CONF_LOW_BATTERY_THRESHOLD = "low_battery_threshold" @@ -90,6 +92,7 @@ **bool_opts, CONF_SCAN_INTERVAL: {"type": int, "default": DEFAULT_SCAN_INTERVAL}, CONF_ACTIVE_SCAN_INTERVAL: {"type": int, "default": DEFAULT_ACTIVE_SCAN_INTERVAL}, + CONF_FUEL_BURN_RATE: {"type": float, "default": DEFAULT_FUEL_BURN_RATE}, CONF_SERVICE_INTERVAL_HOURS: { "type": int, "default": DEFAULT_SERVICE_INTERVAL_HOURS, diff --git a/custom_components/generac/sensor.py b/custom_components/generac/sensor.py index 1b222a5..22b5688 100644 --- a/custom_components/generac/sensor.py +++ b/custom_components/generac/sensor.py @@ -6,19 +6,24 @@ from homeassistant.components.sensor import SensorEntity from homeassistant.components.sensor.const import SensorStateClass from homeassistant.config_entries import ConfigEntry +from homeassistant.const import EntityCategory from homeassistant.const import PERCENTAGE from homeassistant.const import UnitOfElectricPotential from homeassistant.const import UnitOfTemperature from homeassistant.const import UnitOfTime +from homeassistant.const import UnitOfVolume from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback +from .const import CONF_FUEL_BURN_RATE +from .const import DEFAULT_FUEL_BURN_RATE from .const import DEVICE_TYPE_GENERATOR from .const import DEVICE_TYPE_PROPANE_MONITOR from .const import DOMAIN from .coordinator import GeneracDataUpdateCoordinator from .entity import GeneracEntity from .models import Item +from .utils import entry_options from .utils import get_detail_property_value from .utils import safe_float as _safe_float @@ -59,6 +64,7 @@ def sensors(item: Item) -> list[Type[GeneracEntity]]: AddressSensor, StatusTextSensor, StatusLabelSensor, + ErrorCodeSensor, SerialNumberSensor, ModelNumberSensor, DeviceSsidSensor, @@ -73,6 +79,8 @@ def sensors(item: Item) -> list[Type[GeneracEntity]]: StatusSensor, CapacitySensor, FuelLevelSensor, + RemainingFuelSensor, + EstimatedRuntimeSensor, FuelTypeSensor, OrientationSensor, LastReadingDateSensor, @@ -134,6 +142,32 @@ def get_apparatus_property_value(item: Item, field: str): return None +def _remaining_gallons(item: Item) -> float | None: + """Compute remaining propane volume in gallons from tank capacity and level.""" + capacity = _safe_float( + get_prop_value(item.apparatusDetail.tuProperties, 1, None), + "capacity", + ) + fuel_level = _safe_float( + get_prop_value(item.apparatusDetail.tuProperties, 9, None), + "fuel_level", + ) + if capacity is None or capacity <= 0 or fuel_level is None or fuel_level < 0: + return None + return round(capacity * (fuel_level / 100.0), 2) + + +def _get_fuel_burn_rate(config_entry: ConfigEntry) -> float: + """Return a positive fuel burn rate (gal/h) from options or default.""" + rate = _safe_float( + entry_options(config_entry).get(CONF_FUEL_BURN_RATE, DEFAULT_FUEL_BURN_RATE), + CONF_FUEL_BURN_RATE, + ) + if rate is None or rate <= 0: + return DEFAULT_FUEL_BURN_RATE + return rate + + class StatusSensor(GeneracEntity, SensorEntity): """generac Sensor class.""" @@ -175,6 +209,7 @@ class DeviceTypeSensor(GeneracEntity, SensorEntity): entity_key = "device_type" + _attr_entity_category = EntityCategory.DIAGNOSTIC options = [ "Wifi", "Ethernet", @@ -207,6 +242,7 @@ class RunTimeSensor(GeneracEntity, SensorEntity): entity_key = "run_time" + _attr_state_class = SensorStateClass.TOTAL_INCREASING device_class = SensorDeviceClass.DURATION native_unit_of_measurement = "h" @@ -222,6 +258,7 @@ class ProtectionTimeSensor(GeneracEntity, SensorEntity): entity_key = "protection_time" + _attr_state_class = SensorStateClass.TOTAL_INCREASING device_class = SensorDeviceClass.DURATION native_unit_of_measurement = "h" @@ -237,6 +274,7 @@ class ActivationDateSensor(GeneracEntity, SensorEntity): entity_key = "activation_date" + _attr_entity_category = EntityCategory.DIAGNOSTIC device_class = SensorDeviceClass.TIMESTAMP @property @@ -253,6 +291,7 @@ class LastSeenSensor(GeneracEntity, SensorEntity): entity_key = "last_seen" + _attr_entity_category = EntityCategory.DIAGNOSTIC device_class = SensorDeviceClass.TIMESTAMP @property @@ -269,6 +308,7 @@ class ConnectionTimeSensor(GeneracEntity, SensorEntity): entity_key = "connection_time" + _attr_entity_category = EntityCategory.DIAGNOSTIC device_class = SensorDeviceClass.TIMESTAMP @property @@ -285,6 +325,7 @@ class BatteryVoltageSensor(GeneracEntity, SensorEntity): entity_key = "battery_voltage" + _attr_state_class = SensorStateClass.MEASUREMENT device_class = SensorDeviceClass.VOLTAGE native_unit_of_measurement = UnitOfElectricPotential.VOLT suggested_display_precision = 1 @@ -302,6 +343,7 @@ class ExerciseMinutesSensor(GeneracEntity, SensorEntity): entity_key = "exercise_minutes" entity_label = "Exercise Duration" + _attr_state_class = SensorStateClass.MEASUREMENT device_class = SensorDeviceClass.DURATION native_unit_of_measurement = "min" @@ -316,6 +358,7 @@ class OutdoorTemperatureSensor(GeneracEntity, SensorEntity): entity_key = "outdoor_temperature" + _attr_state_class = SensorStateClass.MEASUREMENT device_class = SensorDeviceClass.TEMPERATURE @property @@ -345,6 +388,8 @@ def native_value(self): class SerialNumberSensor(GeneracEntity, SensorEntity): entity_key = "serial_number" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -354,6 +399,8 @@ def native_value(self): class ModelNumberSensor(GeneracEntity, SensorEntity): entity_key = "model_number" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -363,6 +410,8 @@ def native_value(self): class DeviceSsidSensor(GeneracEntity, SensorEntity): entity_key = "device_ssid" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -387,9 +436,29 @@ def native_value(self): return self.aparatus_detail.statusText +class ErrorCodeSensor(GeneracEntity, SensorEntity): + """Active generator fault or error code reported by Mobile Link.""" + + entity_key = "error_code" + entity_label = "Error Code" + + _attr_icon = "mdi:alert-octagon-outline" + + @property + def native_value(self): + """Return the stripped error code label if non-empty, else None.""" + code = self.aparatus_detail.eCodeLabel + if not isinstance(code, str): + return None + stripped = code.strip() + return stripped if stripped else None + + class AddressSensor(GeneracEntity, SensorEntity): entity_key = "address" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -399,6 +468,8 @@ def native_value(self): class DealerNameSensor(GeneracEntity, SensorEntity): entity_key = "dealer_name" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -408,6 +479,8 @@ def native_value(self): class DealerEmailSensor(GeneracEntity, SensorEntity): entity_key = "dealer_email" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -417,6 +490,8 @@ def native_value(self): class DealerPhoneSensor(GeneracEntity, SensorEntity): entity_key = "dealer_phone" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -426,6 +501,8 @@ def native_value(self): class PanelIDSensor(GeneracEntity, SensorEntity): entity_key = "panel_id" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -438,10 +515,15 @@ class CapacitySensor(GeneracEntity, SensorEntity): entity_key = "capacity" + _attr_device_class = SensorDeviceClass.VOLUME_STORAGE + _attr_native_unit_of_measurement = UnitOfVolume.GALLONS + _attr_state_class = SensorStateClass.MEASUREMENT + @property def native_value(self): """Return the state of the sensor.""" - return get_prop_value(self.aparatus_detail.tuProperties, 1, 0) + val = get_prop_value(self.aparatus_detail.tuProperties, 1, 0) + return _safe_float(val, "capacity") class FuelTypeSensor(GeneracEntity, SensorEntity): @@ -449,6 +531,8 @@ class FuelTypeSensor(GeneracEntity, SensorEntity): entity_key = "fuel_type" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -460,6 +544,8 @@ class OrientationSensor(GeneracEntity, SensorEntity): entity_key = "orientation" + _attr_entity_category = EntityCategory.DIAGNOSTIC + @property def native_value(self): """Return the state of the sensor.""" @@ -498,6 +584,7 @@ class FuelLevelSensor(GeneracEntity, SensorEntity): entity_key = "fuel_level" + _attr_state_class = SensorStateClass.MEASUREMENT device_class = SensorDeviceClass.BATTERY native_unit_of_measurement = PERCENTAGE @@ -508,11 +595,52 @@ def native_value(self): return _safe_float(val, "fuel_level") +class RemainingFuelSensor(GeneracEntity, SensorEntity): + """Estimated remaining propane fuel volume in gallons.""" + + entity_key = "remaining_fuel" + entity_label = "Remaining Fuel" + + _attr_device_class = SensorDeviceClass.VOLUME_STORAGE + _attr_native_unit_of_measurement = UnitOfVolume.GALLONS + _attr_state_class = SensorStateClass.MEASUREMENT + _attr_suggested_display_precision = 1 + _attr_icon = "mdi:propane-tank-outline" + + @property + def native_value(self): + """Return estimated remaining propane volume in gallons.""" + return _remaining_gallons(self.item) + + +class EstimatedRuntimeSensor(GeneracEntity, SensorEntity): + """Estimated generator runtime remaining from stored propane fuel.""" + + entity_key = "estimated_runtime" + entity_label = "Estimated Runtime Remaining" + + _attr_device_class = SensorDeviceClass.DURATION + _attr_native_unit_of_measurement = UnitOfTime.HOURS + _attr_state_class = SensorStateClass.MEASUREMENT + _attr_suggested_display_precision = 1 + _attr_icon = "mdi:timer-sand" + + @property + def native_value(self): + """Return estimated runtime remaining in hours.""" + remaining_gallons = _remaining_gallons(self.item) + if remaining_gallons is None: + return None + burn_rate = _get_fuel_burn_rate(self.config_entry) + return round(remaining_gallons / burn_rate, 1) + + class SignalStrengthSensor(GeneracEntity, SensorEntity): """generac Sensor class.""" entity_key = "signal_strength" + _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_icon = "mdi:signal-cellular-2" _attr_native_unit_of_measurement = PERCENTAGE _attr_state_class = SensorStateClass.MEASUREMENT @@ -533,6 +661,7 @@ class DeviceBatteryLevelSensor(GeneracEntity, SensorEntity): _attr_device_class = SensorDeviceClass.BATTERY _attr_native_unit_of_measurement = PERCENTAGE + _attr_state_class = SensorStateClass.MEASUREMENT @property def native_value(self): diff --git a/custom_components/generac/translations/en.json b/custom_components/generac/translations/en.json index fe41859..e17e9ca 100644 --- a/custom_components/generac/translations/en.json +++ b/custom_components/generac/translations/en.json @@ -78,6 +78,7 @@ "binary_sensor": "Binary sensors enabled", "button": "Buttons enabled", "exercise_interval_days": "Missed exercise alert interval (days, 0 to disable)", + "fuel_burn_rate": "Estimated fuel burn rate (gal/h)", "image": "Image enabled", "low_battery_threshold": "Low battery voltage alert threshold (V)", "scan_interval": "Cloud polling interval (seconds)", diff --git a/custom_components/generac/translations/fr.json b/custom_components/generac/translations/fr.json index 4f731d8..aee4e02 100644 --- a/custom_components/generac/translations/fr.json +++ b/custom_components/generac/translations/fr.json @@ -64,6 +64,7 @@ "binary_sensor": "Capteur binaire activé", "button": "Boutons activés", "exercise_interval_days": "Intervalle d’alerte d’exercice manqué (jours, 0 pour désactiver)", + "fuel_burn_rate": "Consommation de carburant estimée (gal/h)", "image": "Image activé", "low_battery_threshold": "Seuil d’alerte de tension batterie faible (V)", "scan_interval": "Intervalle d’interrogation en secondes", diff --git a/custom_components/generac/translations/nb.json b/custom_components/generac/translations/nb.json index e230c4a..11abf51 100644 --- a/custom_components/generac/translations/nb.json +++ b/custom_components/generac/translations/nb.json @@ -64,6 +64,7 @@ "binary_sensor": "Binær sensor aktivert", "button": "Knapper aktivert", "exercise_interval_days": "Varselintervall for uteblitt testkjøring (dager, 0 for å deaktivere)", + "fuel_burn_rate": "Estimert drivstofforbruk (gal/t)", "image": "Bilde aktivert", "low_battery_threshold": "Terskel for varsel om lav batterispenning (V)", "scan_interval": "Avstemningsintervall i sekunder", diff --git a/custom_components/generac/translations/pt.json b/custom_components/generac/translations/pt.json index d5c6c9b..36f676e 100644 --- a/custom_components/generac/translations/pt.json +++ b/custom_components/generac/translations/pt.json @@ -64,6 +64,7 @@ "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)", + "fuel_burn_rate": "Taxa estimada de consumo de combustível (gal/h)", "image": "Imagem ativada", "low_battery_threshold": "Limite de alerta de tensão baixa da bateria (V)", "scan_interval": "Intervalo de sondagem (segundos)", diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py index eeb3db2..513c9e8 100644 --- a/tests/test_binary_sensor.py +++ b/tests/test_binary_sensor.py @@ -1,10 +1,13 @@ """Test the Generac binary sensor platform.""" from unittest.mock import MagicMock +from custom_components.generac.binary_sensor import GeneracActiveVppEventSensor 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 GeneracSubscriptionDunningSensor +from custom_components.generac.binary_sensor import GeneracVppEnrolledSensor 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 @@ -12,6 +15,9 @@ 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 homeassistant.components.binary_sensor import BinarySensorDeviceClass +from homeassistant.const import EntityCategory def get_mock_item( @@ -19,15 +25,22 @@ def get_mock_item( is_connecting: bool, has_maintenance_alert: bool, show_warning: bool, + device_type: int = DEVICE_TYPE_GENERATOR, + enrolled_in_vpp: bool | None = None, + has_active_vpp_event: bool | None = None, + subscription: Subscription | None = None, ) -> Item: """Return a mock Item object.""" return Item( - apparatus=Apparatus(), + apparatus=Apparatus(type=device_type), apparatusDetail=ApparatusDetail( isConnected=is_connected, isConnecting=is_connecting, hasMaintenanceAlert=has_maintenance_alert, showWarning=show_warning, + enrolledInVpp=enrolled_in_vpp, + hasActiveVppEvent=has_active_vpp_event, + subscription=subscription, ), ) @@ -132,3 +145,114 @@ async def test_missed_exercise_sensor(hass): coordinator.is_missed_exercise.return_value = False assert sensor.is_on is False + + +async def test_vpp_and_subscription_binary_sensors(hass): + """Test VPP and subscription dunning binary sensors.""" + coordinator = MagicMock() + entry = MagicMock() + entry.entry_id = "e1" + + item = get_mock_item( + True, + False, + False, + False, + enrolled_in_vpp=True, + has_active_vpp_event=False, + subscription=Subscription(type=1, status=1, isLegacy=False, isDunning=True), + ) + enrolled = GeneracVppEnrolledSensor(coordinator, entry, "12345", item) + assert enrolled.entity_key == "enrolled_in_vpp" + assert enrolled.name == "VPP Enrolled" + assert enrolled.entity_category == EntityCategory.DIAGNOSTIC + assert enrolled.is_on is True + + active_event = GeneracActiveVppEventSensor(coordinator, entry, "12345", item) + assert active_event.entity_key == "active_vpp_event" + assert active_event.name == "Active VPP Event" + assert active_event.entity_category is None + assert active_event.is_on is False + + dunning = GeneracSubscriptionDunningSensor(coordinator, entry, "12345", item) + assert dunning.entity_key == "subscription_dunning" + assert dunning.name == "Subscription Billing Alert" + assert dunning.device_class == BinarySensorDeviceClass.PROBLEM + assert dunning.entity_category == EntityCategory.DIAGNOSTIC + assert dunning.is_on is True + + # None / false edge cases + item_off = get_mock_item( + True, + False, + False, + False, + enrolled_in_vpp=None, + has_active_vpp_event=True, + subscription=Subscription(type=1, status=1, isLegacy=False, isDunning=None), + ) + assert ( + GeneracVppEnrolledSensor(coordinator, entry, "12345", item_off).is_on is False + ) + assert ( + GeneracActiveVppEventSensor(coordinator, entry, "12345", item_off).is_on is True + ) + assert ( + GeneracSubscriptionDunningSensor(coordinator, entry, "12345", item_off).is_on + is False + ) + + item_no_sub = get_mock_item(True, False, False, False, subscription=None) + assert ( + GeneracSubscriptionDunningSensor(coordinator, entry, "12345", item_no_sub).is_on + is False + ) + + +def test_binary_sensor_selection(): + """Verify backwards-compatible sensors() and conditional VPP/subscription selection.""" + base = [ + GeneracConnectedSensor, + GeneracConnectingSensor, + GeneracMaintenanceAlertSensor, + GeneracWarningSensor, + ] + assert sensors() == base + + plain_gen = get_mock_item(True, False, False, False) + assert sensors(plain_gen) == [*base, GeneracMissedExerciseSensor] + + # Either VPP field non-None on a generator adds both VPP sensors + vpp_enrolled_only = get_mock_item( + True, False, False, False, enrolled_in_vpp=False, has_active_vpp_event=None + ) + assert sensors(vpp_enrolled_only) == [ + *base, + GeneracMissedExerciseSensor, + GeneracVppEnrolledSensor, + GeneracActiveVppEventSensor, + ] + + vpp_event_only = get_mock_item( + True, False, False, False, enrolled_in_vpp=None, has_active_vpp_event=False + ) + assert sensors(vpp_event_only) == [ + *base, + GeneracMissedExerciseSensor, + GeneracVppEnrolledSensor, + GeneracActiveVppEventSensor, + ] + + # Propane monitors never get VPP sensors even if fields are populated, + # but do get subscription_dunning when subscription is present + propane_with_both = get_mock_item( + True, + False, + False, + False, + device_type=DEVICE_TYPE_PROPANE_MONITOR, + enrolled_in_vpp=True, + has_active_vpp_event=True, + subscription=Subscription(type=1, status=1, isLegacy=False, isDunning=False), + ) + assert sensors(propane_with_both) == [*base, GeneracSubscriptionDunningSensor] diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 17d9a21..0fe17c5 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -177,6 +177,7 @@ async def test_options_flow(hass: HomeAssistant) -> None: "button": True, "scan_interval": 120, "active_scan_interval": 60, + "fuel_burn_rate": 2.2, "service_interval_hours": 100, "exercise_interval_days": 16, "low_battery_threshold": 12.2, @@ -211,6 +212,57 @@ async def test_options_flow_readiness_thresholds(hass: HomeAssistant) -> None: assert isinstance(entry.options[CONF_LOW_BATTERY_THRESHOLD], float) +@pytest.mark.asyncio +async def test_options_flow_fuel_burn_rate(hass: HomeAssistant) -> None: + """Fuel burn rate accepts positive numbers, rejects <= 0, and recovers bad defaults.""" + from custom_components.generac.const import CONF_FUEL_BURN_RATE + from custom_components.generac.const import DEFAULT_FUEL_BURN_RATE + from homeassistant.data_entry_flow import InvalidData + + entry = MockConfigEntry( + domain=DOMAIN, + data={}, + options={CONF_FUEL_BURN_RATE: -5}, + ) + entry.add_to_hass(hass) + + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + result = await hass.config_entries.options.async_init(entry.entry_id) + assert result["type"] == "form" + + # Non-positive burn rate must be rejected by schema validation. + with pytest.raises(InvalidData): + await hass.config_entries.options.async_configure( + result["flow_id"], user_input={CONF_FUEL_BURN_RATE: 0} + ) + with pytest.raises(InvalidData): + await hass.config_entries.options.async_configure( + result["flow_id"], user_input={CONF_FUEL_BURN_RATE: -1.5} + ) + + # Submitting without overriding fuel_burn_rate uses sanitized default (2.2), + # and passing an int coerces to float. + result = await hass.config_entries.options.async_configure( + result["flow_id"], user_input={CONF_FUEL_BURN_RATE: 3} + ) + assert result["type"] == "create_entry" + assert entry.options[CONF_FUEL_BURN_RATE] == 3.0 + + # Non-numeric / bool pre-existing value also recovers to DEFAULT_FUEL_BURN_RATE. + for bad in ("not-a-number", True, float("nan")): + hass.config_entries.async_update_entry( + entry, options={CONF_FUEL_BURN_RATE: bad} + ) + res = await hass.config_entries.options.async_init(entry.entry_id) + done = await hass.config_entries.options.async_configure( + res["flow_id"], user_input={} + ) + assert done["type"] == "create_entry" + assert entry.options[CONF_FUEL_BURN_RATE] == DEFAULT_FUEL_BURN_RATE + + @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 7647872..b27cb8c 100644 --- a/tests/test_entity_registry.py +++ b/tests/test_entity_registry.py @@ -7,6 +7,7 @@ """ from unittest.mock import patch +import pytest from custom_components.generac.auth import DPoPKey from custom_components.generac.const import CONF_DPOP_PEM from custom_components.generac.const import CONF_REFRESH_TOKEN @@ -15,6 +16,7 @@ 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 dacite import from_dict from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -81,11 +83,18 @@ # Entities this change adds for the fixture payloads below. NEW_SUFFIXES = { GENERATOR_ID: { - "sensor": ["exercise_minutes", "hours_until_service"], + "sensor": ["exercise_minutes", "error_code", "hours_until_service"], "binary_sensor": ["missed_exercise"], "button": ["reset_service_timer", "boost_polling"], }, - PROPANE_ID: {"sensor": ["signal_strength", "device_battery_level"]}, + PROPANE_ID: { + "sensor": [ + "signal_strength", + "device_battery_level", + "remaining_fuel", + "estimated_runtime", + ] + }, } @@ -281,12 +290,17 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) _unique_id(GENERATOR_ID, "boost_polling"): ( "button.generator_outage_boost_poll" ), + _unique_id(GENERATOR_ID, "error_code"): "sensor.generator_error_code", _unique_id( PROPANE_ID, "signal_strength" ): "sensor.propane_tank_signal_strength", _unique_id(PROPANE_ID, "device_battery_level"): ( "sensor.propane_tank_device_battery_level" ), + _unique_id(PROPANE_ID, "remaining_fuel"): "sensor.propane_tank_remaining_fuel", + _unique_id( + PROPANE_ID, "estimated_runtime" + ): "sensor.propane_tank_estimated_runtime_remaining", } assert hass.states.get("sensor.generator_exercise_duration").state == "12.0" assert hass.states.get("sensor.generator_hours_until_service").state == "100.0" @@ -295,8 +309,16 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) hass.states.get("button.generator_reset_maintenance_timer").state == "unknown" ) assert hass.states.get("button.generator_outage_boost_poll").state == "unknown" + assert hass.states.get("sensor.generator_error_code").state == "unknown" assert hass.states.get("sensor.propane_tank_signal_strength").state == "60.0" assert hass.states.get("sensor.propane_tank_device_battery_level").state == "80.0" + remaining_state = hass.states.get("sensor.propane_tank_remaining_fuel") + assert remaining_state.attributes["unit_of_measurement"] == "L" + assert float(remaining_state.state) == pytest.approx(225.0 * 3.785411784) + assert ( + hass.states.get("sensor.propane_tank_estimated_runtime_remaining").state + == "102.3" + ) devices = {e.unique_id: e.device_id for e in entries} assert ( @@ -319,10 +341,84 @@ async def test_upgrade_reuses_every_existing_registry_entry(hass: HomeAssistant) devices[_unique_id(GENERATOR_ID, "boost_polling")] == devices[_unique_id(GENERATOR_ID, "status")] ) + assert ( + devices[_unique_id(GENERATOR_ID, "error_code")] + == devices[_unique_id(GENERATOR_ID, "status")] + ) assert ( devices[_unique_id(PROPANE_ID, "device_battery_level")] == devices[_unique_id(PROPANE_ID, "status")] ) + assert ( + devices[_unique_id(PROPANE_ID, "remaining_fuel")] + == devices[_unique_id(PROPANE_ID, "status")] + ) + assert ( + devices[_unique_id(PROPANE_ID, "estimated_runtime")] + == devices[_unique_id(PROPANE_ID, "status")] + ) + + +async def test_conditional_vpp_and_subscription_entities_register(hass: HomeAssistant): + """VPP and subscription binary sensors register cleanly when API provides them.""" + entry = MockConfigEntry( + domain=DOMAIN, + entry_id=ENTRY_ID, + unique_id="user@example.com", + data={ + CONF_USERNAME: "user@example.com", + CONF_REFRESH_TOKEN: "rt", + CONF_DPOP_PEM: DPoPKey.generate().to_pem_str(), + }, + ) + entry.add_to_hass(hass) + + gen = _generator() + gen.apparatusDetail.eCodeLabel = "E1505" + gen.apparatusDetail.enrolledInVpp = True + gen.apparatusDetail.hasActiveVppEvent = True + gen.apparatusDetail.subscription = Subscription( + type=1, status=2, isLegacy=False, isDunning=True + ) + + with patch( + "custom_components.generac.api.GeneracApiClient.async_get_data", + return_value={GENERATOR_ID: gen}, + ): + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + registry = er.async_get(hass) + by_unique_id = { + e.unique_id: e for e in er.async_entries_for_config_entry(registry, ENTRY_ID) + } + assert _unique_id(GENERATOR_ID, "enrolled_in_vpp") in by_unique_id + assert _unique_id(GENERATOR_ID, "active_vpp_event") in by_unique_id + assert _unique_id(GENERATOR_ID, "subscription_dunning") in by_unique_id + assert ( + hass.states.get( + by_unique_id[_unique_id(GENERATOR_ID, "enrolled_in_vpp")].entity_id + ).state + == "on" + ) + assert ( + hass.states.get( + by_unique_id[_unique_id(GENERATOR_ID, "active_vpp_event")].entity_id + ).state + == "on" + ) + assert ( + hass.states.get( + by_unique_id[_unique_id(GENERATOR_ID, "subscription_dunning")].entity_id + ).state + == "on" + ) + assert ( + hass.states.get( + by_unique_id[_unique_id(GENERATOR_ID, "error_code")].entity_id + ).state + == "E1505" + ) def test_every_entity_class_declares_its_own_stable_key(): @@ -342,7 +438,7 @@ def test_every_entity_class_declares_its_own_stable_key(): and issubclass(obj, GeneracEntity) and obj is not GeneracEntity ] - assert len(classes) == 38 + assert len(classes) == 44 keys = {} for cls in classes: assert "entity_key" in vars(cls), cls.__name__ diff --git a/tests/test_sensor.py b/tests/test_sensor.py index 2be257f..646777d 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -1,7 +1,9 @@ """Test the Generac sensor platform.""" +from types import MappingProxyType from unittest.mock import MagicMock import pytest +from custom_components.generac.const import CONF_FUEL_BURN_RATE 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 @@ -20,6 +22,8 @@ from custom_components.generac.sensor import DeviceBatteryLevelSensor from custom_components.generac.sensor import DeviceSsidSensor from custom_components.generac.sensor import DeviceTypeSensor +from custom_components.generac.sensor import ErrorCodeSensor +from custom_components.generac.sensor import EstimatedRuntimeSensor from custom_components.generac.sensor import ExerciseMinutesSensor from custom_components.generac.sensor import FuelLevelSensor from custom_components.generac.sensor import FuelTypeSensor @@ -31,6 +35,7 @@ from custom_components.generac.sensor import OutdoorTemperatureSensor from custom_components.generac.sensor import PanelIDSensor from custom_components.generac.sensor import ProtectionTimeSensor +from custom_components.generac.sensor import RemainingFuelSensor from custom_components.generac.sensor import RunTimeSensor from custom_components.generac.sensor import sensors from custom_components.generac.sensor import SerialNumberSensor @@ -38,6 +43,11 @@ from custom_components.generac.sensor import StatusLabelSensor from custom_components.generac.sensor import StatusSensor from custom_components.generac.sensor import StatusTextSensor +from homeassistant.components.sensor import SensorDeviceClass +from homeassistant.components.sensor.const import SensorStateClass +from homeassistant.const import EntityCategory +from homeassistant.const import UnitOfTime +from homeassistant.const import UnitOfVolume def get_mock_item( @@ -380,6 +390,7 @@ def test_sensor_selection_generator(): item.apparatus.properties = None selected = sensors(item) assert SignalStrengthSensor in selected + assert ErrorCodeSensor in selected assert DeviceBatteryLevelSensor not in selected assert ExerciseMinutesSensor not in selected @@ -387,6 +398,7 @@ def test_sensor_selection_generator(): item.apparatusDetail.properties.append(MagicMock(type=95, value=15)) selected = sensors(item) assert selected.count(SignalStrengthSensor) == 1 + assert ErrorCodeSensor in selected assert DeviceBatteryLevelSensor in selected assert ExerciseMinutesSensor in selected @@ -397,6 +409,9 @@ def test_sensor_selection_propane_monitor(): item.apparatusDetail.properties = None assert SignalStrengthSensor not in sensors(item) assert DeviceBatteryLevelSensor not in sensors(item) + assert RemainingFuelSensor in sensors(item) + assert EstimatedRuntimeSensor in sensors(item) + assert ErrorCodeSensor not in sensors(item) item = _with_apparatus_value(item, signalStrength="60", batteryLevel="80%") selected = sensors(item) @@ -404,6 +419,8 @@ def test_sensor_selection_propane_monitor(): assert DeviceBatteryLevelSensor in selected assert ExerciseMinutesSensor not in selected assert BatteryLevelSensor in selected + assert RemainingFuelSensor in selected + assert EstimatedRuntimeSensor in selected def test_friendly_names_and_stable_unique_ids(): @@ -417,6 +434,12 @@ def test_friendly_names_and_stable_unique_ids(): PanelIDSensor: ("Panel ID", "panel_id"), RunTimeSensor: ("Run Time", "run_time"), DeviceBatteryLevelSensor: ("Device Battery Level", "device_battery_level"), + ErrorCodeSensor: ("Error Code", "error_code"), + RemainingFuelSensor: ("Remaining Fuel", "remaining_fuel"), + EstimatedRuntimeSensor: ( + "Estimated Runtime Remaining", + "estimated_runtime", + ), } for cls, (label, suffix) in cases.items(): sensor = cls(MagicMock(), entry, "9", item) @@ -447,3 +470,186 @@ async def test_hours_until_service_sensor(hass): assert sensor.icon == "mdi:wrench-clock" assert sensor.native_value == 72.5 assert sensor.extra_state_attributes["hours_since_service"] == 27.5 + + +def test_long_term_statistics_state_classes_and_capacity(): + """LTS sensors expose expected state_class, unit, and device_class.""" + entry = MagicMock() + item = get_mock_item( + DEVICE_TYPE_GENERATOR, + 1, + outdoor_temperature=68.5, + outdoor_temperature_unit="F", + ) + item.apparatusDetail.properties.append(MagicMock(type=95, value=10)) + propane = get_mock_item( + DEVICE_TYPE_PROPANE_MONITOR, 1, capacity="500", fuel_level=40 + ) + + assert ( + RunTimeSensor(MagicMock(), entry, "1", item).state_class + == SensorStateClass.TOTAL_INCREASING + ) + assert ( + ProtectionTimeSensor(MagicMock(), entry, "1", item).state_class + == SensorStateClass.TOTAL_INCREASING + ) + + measurement_cases = [ + (BatteryVoltageSensor, item), + (ExerciseMinutesSensor, item), + (OutdoorTemperatureSensor, item), + (SignalStrengthSensor, item), + (DeviceBatteryLevelSensor, item), + (CapacitySensor, propane), + (FuelLevelSensor, propane), + (RemainingFuelSensor, propane), + (EstimatedRuntimeSensor, propane), + ] + for cls, dev_item in measurement_cases: + entity = cls(MagicMock(), entry, "1", dev_item) + assert entity.state_class == SensorStateClass.MEASUREMENT, cls.__name__ + + cap = CapacitySensor(MagicMock(), entry, "1", propane) + assert cap.device_class == SensorDeviceClass.VOLUME_STORAGE + assert cap.native_unit_of_measurement == UnitOfVolume.GALLONS + assert cap.native_value == 500.0 + + propane_bad = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1, capacity="bad") + assert CapacitySensor(MagicMock(), entry, "1", propane_bad).native_value is None + propane_none = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1, capacity=None) + assert CapacitySensor(MagicMock(), entry, "1", propane_none).native_value is None + + +def test_entity_categories_diagnostic_vs_primary(): + """Static metadata sensors are diagnostic; operational sensors remain primary.""" + entry = MagicMock() + item = get_mock_item(DEVICE_TYPE_GENERATOR, 1, outdoor_temperature=70.0) + + diagnostic_classes = [ + DeviceTypeSensor, + ActivationDateSensor, + LastSeenSensor, + ConnectionTimeSensor, + SerialNumberSensor, + ModelNumberSensor, + DeviceSsidSensor, + AddressSensor, + DealerNameSensor, + DealerEmailSensor, + DealerPhoneSensor, + PanelIDSensor, + FuelTypeSensor, + OrientationSensor, + SignalStrengthSensor, + ] + for cls in diagnostic_classes: + entity = cls(MagicMock(), entry, "1", item) + assert entity.entity_category == EntityCategory.DIAGNOSTIC, cls.__name__ + + primary_classes = [ + StatusSensor, + StatusLabelSensor, + StatusTextSensor, + ErrorCodeSensor, + RunTimeSensor, + ProtectionTimeSensor, + BatteryVoltageSensor, + ExerciseMinutesSensor, + OutdoorTemperatureSensor, + CapacitySensor, + FuelLevelSensor, + RemainingFuelSensor, + EstimatedRuntimeSensor, + BatteryLevelSensor, + LastReadingDateSensor, + DeviceBatteryLevelSensor, + HoursUntilServiceSensor, + ] + for cls in primary_classes: + entity = cls(MagicMock(), entry, "1", item) + assert entity.entity_category is None, cls.__name__ + + +def test_remaining_fuel_and_estimated_runtime(): + """Propane remaining gallons and runtime handle options and edge cases.""" + entry = MagicMock() # entry.options is a MagicMock (non-Mapping) -> default 2.2 + item = get_mock_item(DEVICE_TYPE_PROPANE_MONITOR, 1, capacity=500, fuel_level="45%") + + rem = RemainingFuelSensor(MagicMock(), entry, "1", item) + assert rem.device_class == SensorDeviceClass.VOLUME_STORAGE + assert rem.native_unit_of_measurement == UnitOfVolume.GALLONS + assert rem.state_class == SensorStateClass.MEASUREMENT + assert rem.suggested_display_precision == 1 + assert rem.icon == "mdi:propane-tank-outline" + assert rem.native_value == 225.0 + + est = EstimatedRuntimeSensor(MagicMock(), entry, "1", item) + assert est.device_class == SensorDeviceClass.DURATION + assert est.native_unit_of_measurement == UnitOfTime.HOURS + assert est.state_class == SensorStateClass.MEASUREMENT + assert est.suggested_display_precision == 1 + assert est.icon == "mdi:timer-sand" + assert est.native_value == 102.3 + + # MappingProxyType and dict override + entry.options = MappingProxyType({CONF_FUEL_BURN_RATE: 3.0}) + assert est.native_value == 75.0 + + # Zero / negative / malformed / bool options fall back to 2.2 + for invalid_opt in (0, -2.5, "invalid", True, float("nan"), None): + entry.options = {CONF_FUEL_BURN_RATE: invalid_opt} + assert est.native_value == 102.3 + + # Zero fuel level still produces 0.0 gal and 0.0 h when capacity > 0 + empty_tank = get_mock_item( + DEVICE_TYPE_PROPANE_MONITOR, 1, capacity=500, fuel_level=0 + ) + assert RemainingFuelSensor(MagicMock(), entry, "1", empty_tank).native_value == 0.0 + assert ( + EstimatedRuntimeSensor(MagicMock(), entry, "1", empty_tank).native_value == 0.0 + ) + + # Invalid/missing capacity or fuel level returns None + for cap, lvl in [ + (0, 50), + (-100, 50), + (None, 50), + ("N/A", 50), + (500, None), + (500, -1), + (500, "bad"), + (500, True), + (500, float("inf")), + ]: + bad_item = get_mock_item( + DEVICE_TYPE_PROPANE_MONITOR, 1, capacity=cap, fuel_level=lvl + ) + assert ( + RemainingFuelSensor(MagicMock(), entry, "1", bad_item).native_value is None + ) + assert ( + EstimatedRuntimeSensor(MagicMock(), entry, "1", bad_item).native_value + is None + ) + + # Missing tuProperties returns None + item.apparatusDetail.tuProperties = None + assert rem.native_value is None + assert est.native_value is None + + +def test_error_code_sensor(): + """ErrorCodeSensor strips non-empty eCodeLabel and returns None otherwise.""" + entry = MagicMock() + item = get_mock_item(DEVICE_TYPE_GENERATOR, 1) + sensor = ErrorCodeSensor(MagicMock(), entry, "1", item) + assert sensor.icon == "mdi:alert-octagon-outline" + assert sensor.native_value is None + + item.apparatusDetail.eCodeLabel = " E1505 " + assert sensor.native_value == "E1505" + + for empty_val in ("", " ", None, 123): + item.apparatusDetail.eCodeLabel = empty_val + assert sensor.native_value is None