From f5d702189e4a710ebef993d5655a39ece03edd57 Mon Sep 17 00:00:00 2001 From: darkrain-nl Date: Tue, 27 Oct 2026 13:55:38 +0100 Subject: [PATCH] Add Sofar fault event entity (#187389) --- homeassistant/components/sofar/__init__.py | 13 +- homeassistant/components/sofar/config_flow.py | 14 +- homeassistant/components/sofar/const.py | 3 + homeassistant/components/sofar/event.py | 150 ++++ homeassistant/components/sofar/icons.json | 5 + homeassistant/components/sofar/strings.json | 392 +++++++++ tests/components/sofar/__init__.py | 14 + .../sofar/snapshots/test_event.ambr | 763 ++++++++++++++++++ tests/components/sofar/test_config_flow.py | 77 +- tests/components/sofar/test_event.py | 345 ++++++++ tests/components/sofar/test_init.py | 70 +- 11 files changed, 1833 insertions(+), 13 deletions(-) create mode 100644 homeassistant/components/sofar/event.py create mode 100644 tests/components/sofar/snapshots/test_event.ambr create mode 100644 tests/components/sofar/test_event.py diff --git a/homeassistant/components/sofar/__init__.py b/homeassistant/components/sofar/__init__.py index ba0f1765b681..a6c25ff45ad3 100644 --- a/homeassistant/components/sofar/__init__.py +++ b/homeassistant/components/sofar/__init__.py @@ -28,6 +28,7 @@ from homeassistant.helpers.update_coordinator import UpdateFailed from .const import ( CONF_UNIT_ID, DOMAIN, + HAS_FAULT_LOG, METER_ENERGY, SCAN_INTERVAL, SETTINGS_SCAN_INTERVAL, @@ -43,6 +44,7 @@ _LOGGER = logging.getLogger(__name__) PLATFORMS: list[Platform] = [ Platform.BINARY_SENSOR, Platform.BUTTON, + Platform.EVENT, Platform.SELECT, Platform.SENSOR, Platform.SWITCH, @@ -125,7 +127,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: SofarConfigEntry) -> Non entry.data[CONF_UNIT_ID], ) - device = SofarInverter(unit, serial_number=serial) + device = SofarInverter( + unit, + serial_number=serial, + has_fault_log=entry.data.get(HAS_FAULT_LOG, False), + ) _async_seed_high_water_marks(hass, serial, device) readings = SofarDataUpdateCoordinator( @@ -169,6 +175,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: SofarConfigEntry) -> Non await settings.async_refresh() # Not tied to a coordinator: identity never changes once read. await device.async_read_identity() + # Stored so a flaky read at a later setup never drops the log. + if device.has_fault_log and not entry.data.get(HAS_FAULT_LOG): + hass.config_entries.async_update_entry( + entry, data={**entry.data, HAS_FAULT_LOG: True} + ) # Up front: a part's device must name an inverter that has an id. inverter = dr.async_get(hass).async_get_or_create_from_info( diff --git a/homeassistant/components/sofar/config_flow.py b/homeassistant/components/sofar/config_flow.py index aea60b90a4ff..6a0fcb54a422 100644 --- a/homeassistant/components/sofar/config_flow.py +++ b/homeassistant/components/sofar/config_flow.py @@ -29,6 +29,8 @@ from .const import ( DEFAULT_PORT, DEFAULT_UNIT_ID, DOMAIN, + HAS_FAULT_LOG, + LAST_HANDLED_FAULT, TYPE_SERIAL, TYPE_TCP, ) @@ -197,7 +199,17 @@ class SofarConfigFlow(ConfigFlow, domain=DOMAIN): if device is not None: await self.async_set_unique_id(probed) self._abort_if_unique_id_mismatch() - return self.async_update_reload_and_abort(entry, data=data) + return self.async_update_reload_and_abort( + entry, + data={ + **data, + **{ + key: entry.data[key] + for key in (HAS_FAULT_LOG, LAST_HANDLED_FAULT) + if key in entry.data + }, + }, + ) suggested = user_input or ( entry.data diff --git a/homeassistant/components/sofar/const.py b/homeassistant/components/sofar/const.py index 5f764ecc645c..f520c063abee 100644 --- a/homeassistant/components/sofar/const.py +++ b/homeassistant/components/sofar/const.py @@ -13,6 +13,9 @@ SETTINGS_SCAN_INTERVAL = 60 CONF_BAUDRATE = "baudrate" CONF_UNIT_ID = "unit_id" +HAS_FAULT_LOG = "has_fault_log" +LAST_HANDLED_FAULT = "last_handled_fault" + METER_ENERGY = "meter_energy" TYPE_SERIAL = "serial" diff --git a/homeassistant/components/sofar/event.py b/homeassistant/components/sofar/event.py new file mode 100644 index 000000000000..47cf29bc0a50 --- /dev/null +++ b/homeassistant/components/sofar/event.py @@ -0,0 +1,150 @@ +"""Support for Sofar event entities.""" + +from collections.abc import Callable +from dataclasses import dataclass +from datetime import datetime +from itertools import takewhile +from typing import override + +from sofar_modbus.modern.device import SofarInverter +from sofar_modbus.modern.fault_log import FaultLog +from sofar_modbus.modern.faults import FAULTS, FaultLogEntry + +from homeassistant.components.event import EventEntity, EventEntityDescription +from homeassistant.const import EntityCategory +from homeassistant.core import CoreState, HomeAssistant, callback +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.typing import UNDEFINED, UndefinedType +from homeassistant.util import dt as dt_util + +from .const import LAST_HANDLED_FAULT +from .coordinator import SofarConfigEntry +from .entity import SofarEntity, SofarEntityDescription + +PARALLEL_UPDATES = 0 + +ATTR_CATEGORY = "category" +ATTR_FAULT_ID = "fault_id" +ATTR_OCCURRED_AT = "occurred_at" + +# A log entry as (fault id, inverter clock), free of any time zone. +type EntryKey = tuple[int, datetime] + + +@dataclass(frozen=True, kw_only=True) +class SofarEventEntityDescription(EventEntityDescription, SofarEntityDescription): + """Describe a Sofar event entity.""" + + fault_log_fn: Callable[[SofarInverter], FaultLog] + + +EVENT_DESCRIPTIONS: tuple[SofarEventEntityDescription, ...] = ( + SofarEventEntityDescription( + key="fault", + component="fault_log", + translation_key="fault", + entity_category=EntityCategory.DIAGNOSTIC, + event_types=[fault.key for fault in FAULTS], + fault_log_fn=lambda device: device.fault_log, + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + entry: SofarConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the Sofar event platform.""" + runtime_data = entry.runtime_data + async_add_entities( + SofarFaultEvent(runtime_data, description) + for description in EVENT_DESCRIPTIONS + if description.component in runtime_data.served_components + ) + + +def _key(entry: FaultLogEntry) -> EntryKey: + """Identify a log entry; simultaneous faults share a timestamp.""" + return entry.fault.id, entry.occurred_at + + +class SofarFaultEvent(SofarEntity, EventEntity): + """Fires an event for each fault the inverter logs.""" + + entity_description: SofarEventEntityDescription + # The newest entry handled; None while the log is empty. + _handled: EntryKey | UndefinedType | None = UNDEFINED + + @override + async def async_added_to_hass(self) -> None: + """Resume after the entry handled before, or from the log as is.""" + if LAST_HANDLED_FAULT in (data := self.coordinator.config_entry.data): + self._handled = ( + None + if (stored := data[LAST_HANDLED_FAULT]) is None + else (stored[0], datetime.fromisoformat(stored[1])) + ) + elif self.available: + self._remember(self._newest()) + await super().async_added_to_hass() + + @callback + @override + def _handle_coordinator_update(self) -> None: + """Fire entries newer than the newest known one, oldest first.""" + # Triggers skip a change from unavailable; recover first. + super()._handle_coordinator_update() + # A failed read says nothing about what the log holds. + if not self.available: + return + # Automations arm their triggers only once Home Assistant runs. + if self.hass.state is not CoreState.running: + return + if (handled := self._handled) is UNDEFINED: + self._remember(self._newest()) + return + for entry in reversed( + list( + takewhile( + lambda logged: _key(logged) != handled, + self._entries(), + ) + ) + ): + self._trigger_event( + entry.fault.key, + { + ATTR_FAULT_ID: entry.fault.id, + ATTR_CATEGORY: entry.fault.category.value, + ATTR_OCCURRED_AT: entry.occurred_at.replace( + tzinfo=dt_util.get_default_time_zone() + ).isoformat(), + }, + ) + # One write per event, so each reaches state triggers. + self.async_write_ha_state() + if (newest := self._newest()) != handled: + self._remember(newest) + + def _entries(self) -> tuple[FaultLogEntry, ...]: + """Return the log entries, newest first.""" + return self.entity_description.fault_log_fn(self.coordinator.device).entries + + def _newest(self) -> EntryKey | None: + """Return the newest entry the log holds now, if any.""" + return next((_key(entry) for entry in self._entries()), None) + + def _remember(self, handled: EntryKey | None) -> None: + """Take the log as handled up to an entry, across restarts too.""" + self._handled = handled + entry = self.coordinator.config_entry + self.hass.config_entries.async_update_entry( + entry, + data={ + **entry.data, + LAST_HANDLED_FAULT: None + if handled is None + else [handled[0], handled[1].isoformat()], + }, + ) diff --git a/homeassistant/components/sofar/icons.json b/homeassistant/components/sofar/icons.json index 8e537b4c8dba..62c52030a523 100644 --- a/homeassistant/components/sofar/icons.json +++ b/homeassistant/components/sofar/icons.json @@ -8,6 +8,11 @@ "default": "mdi:home-clock" } }, + "event": { + "fault": { + "default": "mdi:alert-circle-outline" + } + }, "sensor": { "bat_config_capacity": { "default": "mdi:battery-check-outline" diff --git a/homeassistant/components/sofar/strings.json b/homeassistant/components/sofar/strings.json index f7acde4b448f..8ab830560070 100644 --- a/homeassistant/components/sofar/strings.json +++ b/homeassistant/components/sofar/strings.json @@ -151,6 +151,398 @@ "name": "RTC sync" } }, + "event": { + "fault": { + "name": "Fault", + "state_attributes": { + "category": { + "name": "Category", + "state": { + "ac_output": "AC output", + "arc_fault": "Arc fault", + "battery": "Battery", + "battery_pack": "Battery pack", + "combiner_box": "Combiner box", + "communication": "Communication", + "dc_bus": "DC bus", + "derating": "Derating", + "fan": "Fan", + "grid": "Grid", + "input_fuse": "Input fuse", + "insulation": "Insulation", + "internal": "Internal", + "pv": "PV", + "shutdown": "Shutdown", + "string_fuse": "String fuse", + "thermal": "Thermal" + } + }, + "event_type": { + "state": { + "ac_current_unbalance_fault": "AC current unbalance fault", + "ac_hardware_overcurrent_fault": "AC hardware overcurrent fault", + "ac_output_hardware_overcurrent": "AC output hardware overcurrent", + "afci_0": "Arc fault 0", + "afci_1": "Arc fault 1", + "afci_10": "Arc fault 10", + "afci_11": "Arc fault 11", + "afci_12": "Arc fault 12", + "afci_13": "Arc fault 13", + "afci_14": "Arc fault 14", + "afci_15": "Arc fault 15", + "afci_16": "Arc fault 16", + "afci_17": "Arc fault 17", + "afci_18": "Arc fault 18", + "afci_19": "Arc fault 19", + "afci_2": "Arc fault 2", + "afci_20": "Arc fault 20", + "afci_21": "Arc fault 21", + "afci_22": "Arc fault 22", + "afci_23": "Arc fault 23", + "afci_24": "Arc fault 24", + "afci_25": "Arc fault 25", + "afci_26": "Arc fault 26", + "afci_27": "Arc fault 27", + "afci_28": "Arc fault 28", + "afci_29": "Arc fault 29", + "afci_3": "Arc fault 3", + "afci_30": "Arc fault 30", + "afci_31": "Arc fault 31", + "afci_4": "Arc fault 4", + "afci_5": "Arc fault 5", + "afci_6": "Arc fault 6", + "afci_7": "Arc fault 7", + "afci_8": "Arc fault 8", + "afci_9": "Arc fault 9", + "ambient_temperature_1_protection": "Ambient temperature 1 protection", + "ambient_temperature_2_protection": "Ambient temperature 2 protection", + "anti_backflow_overload": "Feed-in limit exceeded", + "arc_device_communication_failure": "Arc device communication failure", + "arc_shutdown_protection": "Arc shutdown protection", + "auxiliary_power_error": "Auxiliary power error", + "balanced_circuit_overcurrent_protection": "Balancing circuit overcurrent protection", + "battery_charging_low_temperature_protection": "Battery charging low temperature protection", + "battery_charging_over_temperature_protection": "Battery charging overtemperature protection", + "battery_discharge_low_temperature_protection": "Battery discharge low temperature protection", + "battery_discharge_over_temperature_protection": "Battery discharge overtemperature protection", + "battery_hardware_overcurrent": "Battery hardware overcurrent", + "battery_lockout_protection": "Battery lockout protection", + "battery_low_voltage_shutdown": "Battery low voltage shutdown", + "battery_over_voltage": "Battery overvoltage", + "battery_overcurrent_software_protection": "Battery overcurrent software protection", + "battery_partially_disconnected": "Battery partially disconnected", + "battery_temperature_protection": "Battery temperature protection", + "bckbst_hardware_overcurrent": "Buck-boost hardware overcurrent", + "bckbst_software_overcurrent": "Buck-boost software overcurrent", + "bcu_fault": "BCU fault", + "bluetooth_fault": "Bluetooth fault", + "bms_can_version_inconsistency": "BMS CAN version inconsistency", + "bms_can_version_too_low": "BMS CAN version too low", + "bms_high_temperature_protection": "BMS high temperature protection", + "bms_low_temperature_protection": "BMS low temperature protection", + "bms_over_voltage_protection": "BMS overvoltage protection", + "bms_overcurrent_protection": "BMS overcurrent protection", + "bms_short_circuit_protection": "BMS short circuit protection", + "bms_undervoltage_protection": "BMS undervoltage protection", + "bms_version_inconsistency": "BMS version inconsistency", + "bmu_fault": "BMU fault", + "branch_current_sampling_error": "Branch current sampling error", + "bus_hardware_over_voltage_fault": "Bus hardware overvoltage fault", + "bus_overvoltage_fault": "Bus overvoltage fault", + "bus_unbalance_fault": "Bus unbalance fault", + "busbar_instantaneous_value_unbalance": "DC bus instantaneous unbalance", + "busbar_low_voltage": "DC bus low voltage", + "busbar_rms_software_overvoltage": "DC bus RMS software overvoltage", + "busbar_rms_unbalance": "DC bus RMS unbalance", + "busbar_transient_software_overvoltage": "DC bus transient software overvoltage", + "busbar_undervoltage_during_grid_connection": "DC bus undervoltage during grid connection", + "chip_error_ac": "Chip error (AC)", + "chip_error_dc": "Chip error (DC)", + "combiner_oc_1": "Combiner string 1 overcurrent", + "combiner_oc_10": "Combiner string 10 overcurrent", + "combiner_oc_11": "Combiner string 11 overcurrent", + "combiner_oc_12": "Combiner string 12 overcurrent", + "combiner_oc_13": "Combiner string 13 overcurrent", + "combiner_oc_14": "Combiner string 14 overcurrent", + "combiner_oc_15": "Combiner string 15 overcurrent", + "combiner_oc_16": "Combiner string 16 overcurrent", + "combiner_oc_17": "Combiner string 17 overcurrent", + "combiner_oc_18": "Combiner string 18 overcurrent", + "combiner_oc_19": "Combiner string 19 overcurrent", + "combiner_oc_2": "Combiner string 2 overcurrent", + "combiner_oc_20": "Combiner string 20 overcurrent", + "combiner_oc_21": "Combiner string 21 overcurrent", + "combiner_oc_22": "Combiner string 22 overcurrent", + "combiner_oc_23": "Combiner string 23 overcurrent", + "combiner_oc_24": "Combiner string 24 overcurrent", + "combiner_oc_25": "Combiner string 25 overcurrent", + "combiner_oc_26": "Combiner string 26 overcurrent", + "combiner_oc_27": "Combiner string 27 overcurrent", + "combiner_oc_28": "Combiner string 28 overcurrent", + "combiner_oc_29": "Combiner string 29 overcurrent", + "combiner_oc_3": "Combiner string 3 overcurrent", + "combiner_oc_30": "Combiner string 30 overcurrent", + "combiner_oc_31": "Combiner string 31 overcurrent", + "combiner_oc_32": "Combiner string 32 overcurrent", + "combiner_oc_4": "Combiner string 4 overcurrent", + "combiner_oc_5": "Combiner string 5 overcurrent", + "combiner_oc_6": "Combiner string 6 overcurrent", + "combiner_oc_7": "Combiner string 7 overcurrent", + "combiner_oc_8": "Combiner string 8 overcurrent", + "combiner_oc_9": "Combiner string 9 overcurrent", + "combiner_ov_gp_1": "Combiner group 1 overvoltage", + "combiner_ov_gp_10": "Combiner group 10 overvoltage", + "combiner_ov_gp_11": "Combiner group 11 overvoltage", + "combiner_ov_gp_12": "Combiner group 12 overvoltage", + "combiner_ov_gp_13": "Combiner group 13 overvoltage", + "combiner_ov_gp_14": "Combiner group 14 overvoltage", + "combiner_ov_gp_15": "Combiner group 15 overvoltage", + "combiner_ov_gp_16": "Combiner group 16 overvoltage", + "combiner_ov_gp_2": "Combiner group 2 overvoltage", + "combiner_ov_gp_3": "Combiner group 3 overvoltage", + "combiner_ov_gp_4": "Combiner group 4 overvoltage", + "combiner_ov_gp_5": "Combiner group 5 overvoltage", + "combiner_ov_gp_6": "Combiner group 6 overvoltage", + "combiner_ov_gp_7": "Combiner group 7 overvoltage", + "combiner_ov_gp_8": "Combiner group 8 overvoltage", + "combiner_ov_gp_9": "Combiner group 9 overvoltage", + "combiner_reflux_fault_1": "Combiner string 1 reverse current", + "combiner_reflux_fault_10": "Combiner string 10 reverse current", + "combiner_reflux_fault_11": "Combiner string 11 reverse current", + "combiner_reflux_fault_12": "Combiner string 12 reverse current", + "combiner_reflux_fault_13": "Combiner string 13 reverse current", + "combiner_reflux_fault_14": "Combiner string 14 reverse current", + "combiner_reflux_fault_15": "Combiner string 15 reverse current", + "combiner_reflux_fault_16": "Combiner string 16 reverse current", + "combiner_reflux_fault_17": "Combiner string 17 reverse current", + "combiner_reflux_fault_18": "Combiner string 18 reverse current", + "combiner_reflux_fault_19": "Combiner string 19 reverse current", + "combiner_reflux_fault_2": "Combiner string 2 reverse current", + "combiner_reflux_fault_20": "Combiner string 20 reverse current", + "combiner_reflux_fault_21": "Combiner string 21 reverse current", + "combiner_reflux_fault_22": "Combiner string 22 reverse current", + "combiner_reflux_fault_23": "Combiner string 23 reverse current", + "combiner_reflux_fault_24": "Combiner string 24 reverse current", + "combiner_reflux_fault_25": "Combiner string 25 reverse current", + "combiner_reflux_fault_26": "Combiner string 26 reverse current", + "combiner_reflux_fault_27": "Combiner string 27 reverse current", + "combiner_reflux_fault_28": "Combiner string 28 reverse current", + "combiner_reflux_fault_29": "Combiner string 29 reverse current", + "combiner_reflux_fault_3": "Combiner string 3 reverse current", + "combiner_reflux_fault_30": "Combiner string 30 reverse current", + "combiner_reflux_fault_31": "Combiner string 31 reverse current", + "combiner_reflux_fault_32": "Combiner string 32 reverse current", + "combiner_reflux_fault_4": "Combiner string 4 reverse current", + "combiner_reflux_fault_5": "Combiner string 5 reverse current", + "combiner_reflux_fault_6": "Combiner string 6 reverse current", + "combiner_reflux_fault_7": "Combiner string 7 reverse current", + "combiner_reflux_fault_8": "Combiner string 8 reverse current", + "combiner_reflux_fault_9": "Combiner string 9 reverse current", + "combiner_uv_gp_1": "Combiner group 1 undervoltage", + "combiner_uv_gp_10": "Combiner group 10 undervoltage", + "combiner_uv_gp_11": "Combiner group 11 undervoltage", + "combiner_uv_gp_12": "Combiner group 12 undervoltage", + "combiner_uv_gp_13": "Combiner group 13 undervoltage", + "combiner_uv_gp_14": "Combiner group 14 undervoltage", + "combiner_uv_gp_15": "Combiner group 15 undervoltage", + "combiner_uv_gp_16": "Combiner group 16 undervoltage", + "combiner_uv_gp_2": "Combiner group 2 undervoltage", + "combiner_uv_gp_3": "Combiner group 3 undervoltage", + "combiner_uv_gp_4": "Combiner group 4 undervoltage", + "combiner_uv_gp_5": "Combiner group 5 undervoltage", + "combiner_uv_gp_6": "Combiner group 6 undervoltage", + "combiner_uv_gp_7": "Combiner group 7 undervoltage", + "combiner_uv_gp_8": "Combiner group 8 undervoltage", + "combiner_uv_gp_9": "Combiner group 9 undervoltage", + "communication_board_eeprom_error": "Communication board EEPROM error", + "communication_board_flash_error": "Communication board flash error", + "ct_error": "CT error", + "dcdc_fault": "DC/DC fault", + "dci_consistency_error": "DCI consistency error", + "dci_overcurrent_protection": "DCI overcurrent protection", + "dci_sampling_error_ac": "DCI sampling error (AC)", + "dci_sampling_error_dc": "DCI sampling error (DC)", + "dcv_sampling_error": "DCV sampling error", + "drms0_shutdown": "DRM0 shutdown", + "eps_battery_overcurrent_fault": "EPS battery overcurrent fault", + "fan_1_fault": "Fan 1 fault", + "fan_2_fault": "Fan 2 fault", + "fan_3_fault": "Fan 3 fault", + "fan_4_fault": "Fan 4 fault", + "fan_5_fault": "Fan 5 fault", + "fan_6_fault": "Fan 6 fault", + "fan_7_fault": "Fan 7 fault", + "fly_span_capacitor_overvoltage_protection": "Flying capacitor overvoltage protection", + "fly_span_capacitor_under_voltage_protection": "Flying capacitor undervoltage protection", + "forced_shutdown": "Forced shutdown", + "frequency_down_load": "Frequency derating", + "frequency_loading": "Frequency load increase", + "gfci_sampling_error_ac": "GFCI sampling error (AC)", + "gfci_sampling_error_dc": "GFCI sampling error (DC)", + "grid_current_sampling_error": "Grid current sampling error", + "grid_frequency_change_protection": "Grid frequency change protection", + "grid_instantaneous_value_overvoltage_1": "Grid instantaneous overvoltage 1", + "grid_instantaneous_value_overvoltage_2": "Grid instantaneous overvoltage 2", + "grid_line_voltage_error": "Grid line voltage error", + "grid_over_voltage": "Grid overvoltage", + "grid_overfrequency": "Grid overfrequency", + "grid_relay_fault": "Grid relay fault", + "grid_underfrequency": "Grid underfrequency", + "grid_undervoltage": "Grid undervoltage", + "grid_voltage_unbalance": "Grid voltage unbalance", + "ground_zero_voltage_too_high": "Neutral-to-ground voltage too high", + "grounding_error": "Grounding error", + "hardware_differential_overcurrent": "Hardware differential overcurrent", + "hardware_version_mismatch": "Hardware version mismatch", + "heatsink_1_temperature_protection": "Heatsink 1 temperature protection", + "heatsink_2_temperature_protection": "Heatsink 2 temperature protection", + "heatsink_3_temperature_protection": "Heatsink 3 temperature protection", + "heatsink_4_temperature_protection": "Heatsink 4 temperature protection", + "heatsink_5_temperature_protection": "Heatsink 5 temperature protection", + "heatsink_6_temperature_protection": "Heatsink 6 temperature protection", + "high_penetration_error": "High voltage ride-through error", + "input_current_sampling_error": "Input current sampling error", + "input_fuse_open_circuit_0": "Input fuse 0 open circuit", + "input_fuse_open_circuit_1": "Input fuse 1 open circuit", + "input_fuse_open_circuit_10": "Input fuse 10 open circuit", + "input_fuse_open_circuit_11": "Input fuse 11 open circuit", + "input_fuse_open_circuit_12": "Input fuse 12 open circuit", + "input_fuse_open_circuit_13": "Input fuse 13 open circuit", + "input_fuse_open_circuit_14": "Input fuse 14 open circuit", + "input_fuse_open_circuit_15": "Input fuse 15 open circuit", + "input_fuse_open_circuit_2": "Input fuse 2 open circuit", + "input_fuse_open_circuit_3": "Input fuse 3 open circuit", + "input_fuse_open_circuit_4": "Input fuse 4 open circuit", + "input_fuse_open_circuit_5": "Input fuse 5 open circuit", + "input_fuse_open_circuit_6": "Input fuse 6 open circuit", + "input_fuse_open_circuit_7": "Input fuse 7 open circuit", + "input_fuse_open_circuit_8": "Input fuse 8 open circuit", + "input_fuse_open_circuit_9": "Input fuse 9 open circuit", + "input_hardware_overcurrent_fault": "Input hardware overcurrent fault", + "input_mode_setting_fault": "Input mode setting fault", + "input_overcurrent_fault": "Input overcurrent fault", + "input_reversal_error": "Input reversal error", + "inverter_bus_hardware_overvoltage": "Inverter bus hardware overvoltage", + "inverter_rms_current_protection": "Inverter RMS current protection", + "inverter_soft_start_failure": "Inverter soft start failure", + "inverter_soft_start_failure_fault": "Inverter soft start failure fault", + "inverter_transient_overvoltage": "Inverter transient overvoltage", + "inverter_voltage_error": "Inverter voltage error", + "islanding_error": "Islanding error", + "leakage_current_consistency_error": "Leakage current consistency error", + "leakage_current_faults": "Leakage current fault", + "lightning_protection_ac": "Lightning protection (AC)", + "lightning_protection_ac_permanent": "Lightning protection permanent fault (AC)", + "lightning_protection_dc": "Lightning protection (DC)", + "lightning_protection_dc_permanent": "Lightning protection permanent fault (DC)", + "lithium_battery_1_communication_failure": "Lithium battery 1 communication failure", + "lithium_battery_2_communication_failure": "Lithium battery 2 communication failure", + "lithium_battery_3_communication_failure": "Lithium battery 3 communication failure", + "lithium_battery_4_communication_failure": "Lithium battery 4 communication failure", + "llc_busbar_hardware_overvoltage": "LLC bus hardware overvoltage", + "llcbus_overvoltage_protection": "LLC bus overvoltage protection", + "low_insulation_impedance": "Low insulation impedance", + "low_penetration_error": "Low voltage ride-through error", + "low_temperature_load_shedding": "Low temperature derating", + "meter_communication_error": "Meter communication error", + "modify_ovp": "OVP modified", + "module_1_temperature_protection": "Module 1 temperature protection", + "module_2_temperature_protection": "Module 2 temperature protection", + "module_3_temperature_protection": "Module 3 temperature protection", + "module_temperature_difference_too_large": "Module temperature difference too large", + "n_line_open_circuit_fault": "Neutral line open circuit", + "net_voltage_consistency_error": "Grid voltage consistency error", + "network_voltage_sampling_error_ac": "Grid voltage sampling error (AC)", + "network_voltage_sampling_error_dc": "Grid voltage sampling error (DC)", + "neutral_ground_fault": "Neutral ground fault", + "output_current_unbalance": "Output current unbalance", + "output_transient_current_protection": "Output transient current protection", + "output_transient_overcurrent_fault": "Output transient overcurrent fault", + "over_temperature_load_shedding": "Overtemperature derating", + "overload_protection_1": "Overload protection 1", + "overload_protection_2": "Overload protection 2", + "overload_protection_3": "Overload protection 3", + "parallel_error": "Parallel error", + "phase_loss_failure": "Phase loss failure", + "pid_abnormal_output": "PID abnormal output", + "pid_repair_failure": "PID repair failure", + "plc_module_heartbeat_lost": "PLC module heartbeat lost", + "power_station_communication_failure_shutdown": "Power station communication failure shutdown", + "pv_branch_overcurrent_default_off": "PV string overcurrent (default off)", + "pv_branch_overcurrent_default_on": "PV string overcurrent (default on)", + "pv_hardware_overcurrent": "PV hardware overcurrent", + "pv_low_impedance_to_ground": "PV low impedance to ground", + "pv_overvoltage": "PV overvoltage", + "pv_parallel_uneven_current": "PV parallel uneven current", + "pv_software_overcurrent_protection": "PV software overcurrent protection", + "pv_transient_software_overcurrent": "PV transient software overcurrent", + "pv_undervoltage": "PV undervoltage", + "pv_uneven_flow_fault": "PV uneven current fault", + "relay_detection_failure": "Relay detection failure", + "relay_permanent_failure": "Relay permanent failure", + "remote_shutdown": "Remote shutdown", + "resonance_protection": "Resonance protection", + "rtc_clock_fault": "RTC clock fault", + "safety_version_error": "Safety version error", + "sci_error_ac": "SCI error (AC)", + "sci_error_dc": "SCI error (DC)", + "sci_error_fuse": "SCI error (fuse)", + "serial_number_error": "Serial number error", + "serial_number_model_error": "Serial number model error", + "software_version_inconsistency": "Software version inconsistency", + "spi_communication_error_ac": "SPI communication error (AC)", + "spi_communication_error_dc": "SPI communication error (DC)", + "string_fuse_open_circuit_10_1": "String 10 fuse 1 open circuit", + "string_fuse_open_circuit_10_2": "String 10 fuse 2 open circuit", + "string_fuse_open_circuit_11_1": "String 11 fuse 1 open circuit", + "string_fuse_open_circuit_11_2": "String 11 fuse 2 open circuit", + "string_fuse_open_circuit_12_1": "String 12 fuse 1 open circuit", + "string_fuse_open_circuit_12_2": "String 12 fuse 2 open circuit", + "string_fuse_open_circuit_13_1": "String 13 fuse 1 open circuit", + "string_fuse_open_circuit_13_2": "String 13 fuse 2 open circuit", + "string_fuse_open_circuit_14_1": "String 14 fuse 1 open circuit", + "string_fuse_open_circuit_14_2": "String 14 fuse 2 open circuit", + "string_fuse_open_circuit_15_1": "String 15 fuse 1 open circuit", + "string_fuse_open_circuit_15_2": "String 15 fuse 2 open circuit", + "string_fuse_open_circuit_16_1": "String 16 fuse 1 open circuit", + "string_fuse_open_circuit_16_2": "String 16 fuse 2 open circuit", + "string_fuse_open_circuit_1_1": "String 1 fuse 1 open circuit", + "string_fuse_open_circuit_1_2": "String 1 fuse 2 open circuit", + "string_fuse_open_circuit_2_1": "String 2 fuse 1 open circuit", + "string_fuse_open_circuit_2_2": "String 2 fuse 2 open circuit", + "string_fuse_open_circuit_3_1": "String 3 fuse 1 open circuit", + "string_fuse_open_circuit_3_2": "String 3 fuse 2 open circuit", + "string_fuse_open_circuit_4_1": "String 4 fuse 1 open circuit", + "string_fuse_open_circuit_4_2": "String 4 fuse 2 open circuit", + "string_fuse_open_circuit_5_1": "String 5 fuse 1 open circuit", + "string_fuse_open_circuit_5_2": "String 5 fuse 2 open circuit", + "string_fuse_open_circuit_6_1": "String 6 fuse 1 open circuit", + "string_fuse_open_circuit_6_2": "String 6 fuse 2 open circuit", + "string_fuse_open_circuit_7_1": "String 7 fuse 1 open circuit", + "string_fuse_open_circuit_7_2": "String 7 fuse 2 open circuit", + "string_fuse_open_circuit_8_1": "String 8 fuse 1 open circuit", + "string_fuse_open_circuit_8_2": "String 8 fuse 2 open circuit", + "string_fuse_open_circuit_9_1": "String 9 fuse 1 open circuit", + "string_fuse_open_circuit_9_2": "String 9 fuse 2 open circuit", + "sudden_grid_phase_change": "Grid phase jump", + "usb_fault": "USB fault", + "voltage_down_load": "Voltage derating", + "voltage_loading": "Voltage load increase", + "wave_by_wave_current_limit": "Wave-by-wave current limit", + "weak_light_detection_failure": "Low light detection failure", + "wifi_fault": "Wi-Fi fault", + "wrong_input_mode_setting": "Wrong input mode setting" + } + }, + "fault_id": { + "name": "Fault ID" + }, + "occurred_at": { + "name": "Occurred at" + } + } + } + }, "select": { "charger_use_mode": { "name": "Charger use mode", diff --git a/tests/components/sofar/__init__.py b/tests/components/sofar/__init__.py index 4d98879ba015..c26a5984bdba 100644 --- a/tests/components/sofar/__init__.py +++ b/tests/components/sofar/__init__.py @@ -1,5 +1,7 @@ """Tests for the Sofar integration.""" +from datetime import datetime + from modbus_connection import ModbusError from modbus_connection.mock import MockModbusUnit @@ -36,6 +38,8 @@ MOCK_SERIAL_INPUT = { } MOCK_SERIAL_ENTRY_DATA = {CONF_TYPE: TYPE_SERIAL, **MOCK_SERIAL_INPUT} +FAULT_LOG_REGISTER = 0x1480 + def _seed_string(unit: MockModbusUnit, address: int, words: int, text: str) -> None: """Encode ASCII across consecutive registers, two characters each.""" @@ -67,6 +71,16 @@ def seed_pv_inverter(unit: MockModbusUnit, serial: str = MOCK_SERIAL) -> None: unit.holding[0x0685] = 1000 # solar_generation_today low word -> 10.0 kWh +def seed_fault_log(unit: MockModbusUnit, *entries: tuple[int, datetime]) -> None: + """Write the inverter's fault log, newest entry first.""" + for number, (fault_id, when) in enumerate(entries): + address = FAULT_LOG_REGISTER + 4 * number + unit.holding[address] = fault_id + unit.holding[address + 1] = (when.year - 2000) << 8 | when.month + unit.holding[address + 2] = when.day << 8 | when.hour + unit.holding[address + 3] = when.minute << 8 | when.second + + def deny_meter_energy(unit: MockModbusUnit) -> None: """Seed a model that denies the meter block from 0x0688 on.""" # Bits 0-3 must stay set, or the mask is ignored and denies nothing. diff --git a/tests/components/sofar/snapshots/test_event.ambr b/tests/components/sofar/snapshots/test_event.ambr new file mode 100644 index 000000000000..488cd7fb48c0 --- /dev/null +++ b/tests/components/sofar/snapshots/test_event.ambr @@ -0,0 +1,763 @@ +# serializer version: 1 +# name: test_all_entities[event.4_4_ktlx_g3_fault-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'grid_over_voltage', + 'grid_undervoltage', + 'grid_overfrequency', + 'grid_underfrequency', + 'leakage_current_faults', + 'high_penetration_error', + 'low_penetration_error', + 'islanding_error', + 'grid_instantaneous_value_overvoltage_1', + 'grid_instantaneous_value_overvoltage_2', + 'grid_line_voltage_error', + 'inverter_voltage_error', + 'anti_backflow_overload', + 'grid_voltage_unbalance', + 'inverter_transient_overvoltage', + 'sudden_grid_phase_change', + 'grid_current_sampling_error', + 'dci_sampling_error_ac', + 'network_voltage_sampling_error_dc', + 'network_voltage_sampling_error_ac', + 'gfci_sampling_error_dc', + 'gfci_sampling_error_ac', + 'dcv_sampling_error', + 'input_current_sampling_error', + 'dci_sampling_error_dc', + 'branch_current_sampling_error', + 'pv_low_impedance_to_ground', + 'pid_abnormal_output', + 'leakage_current_consistency_error', + 'net_voltage_consistency_error', + 'dci_consistency_error', + 'neutral_ground_fault', + 'spi_communication_error_dc', + 'spi_communication_error_ac', + 'chip_error_dc', + 'chip_error_ac', + 'auxiliary_power_error', + 'inverter_soft_start_failure', + 'arc_shutdown_protection', + 'weak_light_detection_failure', + 'relay_detection_failure', + 'low_insulation_impedance', + 'grounding_error', + 'wrong_input_mode_setting', + 'ct_error', + 'input_reversal_error', + 'parallel_error', + 'serial_number_error', + 'battery_temperature_protection', + 'heatsink_1_temperature_protection', + 'heatsink_2_temperature_protection', + 'heatsink_3_temperature_protection', + 'heatsink_4_temperature_protection', + 'heatsink_5_temperature_protection', + 'heatsink_6_temperature_protection', + 'ambient_temperature_1_protection', + 'ambient_temperature_2_protection', + 'module_1_temperature_protection', + 'module_2_temperature_protection', + 'module_3_temperature_protection', + 'module_temperature_difference_too_large', + 'busbar_rms_unbalance', + 'busbar_instantaneous_value_unbalance', + 'busbar_undervoltage_during_grid_connection', + 'busbar_low_voltage', + 'pv_overvoltage', + 'battery_over_voltage', + 'llcbus_overvoltage_protection', + 'busbar_rms_software_overvoltage', + 'busbar_transient_software_overvoltage', + 'fly_span_capacitor_overvoltage_protection', + 'fly_span_capacitor_under_voltage_protection', + 'pv_undervoltage', + 'battery_overcurrent_software_protection', + 'dci_overcurrent_protection', + 'output_transient_current_protection', + 'bckbst_software_overcurrent', + 'inverter_rms_current_protection', + 'pv_transient_software_overcurrent', + 'pv_parallel_uneven_current', + 'output_current_unbalance', + 'pv_software_overcurrent_protection', + 'balanced_circuit_overcurrent_protection', + 'resonance_protection', + 'wave_by_wave_current_limit', + 'pv_branch_overcurrent_default_on', + 'llc_busbar_hardware_overvoltage', + 'inverter_bus_hardware_overvoltage', + 'bckbst_hardware_overcurrent', + 'battery_hardware_overcurrent', + 'pv_hardware_overcurrent', + 'ac_output_hardware_overcurrent', + 'hardware_differential_overcurrent', + 'meter_communication_error', + 'serial_number_model_error', + 'hardware_version_mismatch', + 'overload_protection_1', + 'overload_protection_2', + 'overload_protection_3', + 'over_temperature_load_shedding', + 'frequency_down_load', + 'frequency_loading', + 'voltage_down_load', + 'voltage_loading', + 'low_temperature_load_shedding', + 'lightning_protection_dc', + 'lightning_protection_ac', + 'battery_lockout_protection', + 'battery_low_voltage_shutdown', + 'ac_hardware_overcurrent_fault', + 'bus_overvoltage_fault', + 'bus_hardware_over_voltage_fault', + 'pv_uneven_flow_fault', + 'eps_battery_overcurrent_fault', + 'output_transient_overcurrent_fault', + 'ac_current_unbalance_fault', + 'inverter_soft_start_failure_fault', + 'input_mode_setting_fault', + 'input_overcurrent_fault', + 'input_hardware_overcurrent_fault', + 'relay_permanent_failure', + 'bus_unbalance_fault', + 'lightning_protection_dc_permanent', + 'lightning_protection_ac_permanent', + 'grid_relay_fault', + 'usb_fault', + 'wifi_fault', + 'bluetooth_fault', + 'rtc_clock_fault', + 'communication_board_eeprom_error', + 'communication_board_flash_error', + 'battery_partially_disconnected', + 'safety_version_error', + 'sci_error_dc', + 'sci_error_ac', + 'sci_error_fuse', + 'software_version_inconsistency', + 'lithium_battery_1_communication_failure', + 'lithium_battery_2_communication_failure', + 'lithium_battery_3_communication_failure', + 'lithium_battery_4_communication_failure', + 'forced_shutdown', + 'remote_shutdown', + 'drms0_shutdown', + 'power_station_communication_failure_shutdown', + 'fan_1_fault', + 'fan_2_fault', + 'fan_3_fault', + 'fan_4_fault', + 'fan_5_fault', + 'fan_6_fault', + 'fan_7_fault', + 'bms_over_voltage_protection', + 'bms_undervoltage_protection', + 'bms_high_temperature_protection', + 'bms_low_temperature_protection', + 'bms_overcurrent_protection', + 'bms_short_circuit_protection', + 'bms_version_inconsistency', + 'bms_can_version_inconsistency', + 'bms_can_version_too_low', + 'battery_discharge_over_temperature_protection', + 'battery_discharge_low_temperature_protection', + 'battery_charging_over_temperature_protection', + 'arc_device_communication_failure', + 'battery_charging_low_temperature_protection', + 'pid_repair_failure', + 'plc_module_heartbeat_lost', + 'string_fuse_open_circuit_1_1', + 'string_fuse_open_circuit_1_2', + 'string_fuse_open_circuit_2_1', + 'string_fuse_open_circuit_2_2', + 'string_fuse_open_circuit_3_1', + 'string_fuse_open_circuit_3_2', + 'string_fuse_open_circuit_4_1', + 'string_fuse_open_circuit_4_2', + 'string_fuse_open_circuit_5_1', + 'string_fuse_open_circuit_5_2', + 'string_fuse_open_circuit_6_1', + 'string_fuse_open_circuit_6_2', + 'string_fuse_open_circuit_7_1', + 'string_fuse_open_circuit_7_2', + 'string_fuse_open_circuit_8_1', + 'string_fuse_open_circuit_8_2', + 'string_fuse_open_circuit_9_1', + 'string_fuse_open_circuit_9_2', + 'string_fuse_open_circuit_10_1', + 'string_fuse_open_circuit_10_2', + 'string_fuse_open_circuit_11_1', + 'string_fuse_open_circuit_11_2', + 'string_fuse_open_circuit_12_1', + 'string_fuse_open_circuit_12_2', + 'string_fuse_open_circuit_13_1', + 'string_fuse_open_circuit_13_2', + 'string_fuse_open_circuit_14_1', + 'string_fuse_open_circuit_14_2', + 'string_fuse_open_circuit_15_1', + 'string_fuse_open_circuit_15_2', + 'string_fuse_open_circuit_16_1', + 'string_fuse_open_circuit_16_2', + 'input_fuse_open_circuit_0', + 'input_fuse_open_circuit_1', + 'input_fuse_open_circuit_2', + 'input_fuse_open_circuit_3', + 'input_fuse_open_circuit_4', + 'input_fuse_open_circuit_5', + 'input_fuse_open_circuit_6', + 'input_fuse_open_circuit_7', + 'input_fuse_open_circuit_8', + 'input_fuse_open_circuit_9', + 'input_fuse_open_circuit_10', + 'input_fuse_open_circuit_11', + 'input_fuse_open_circuit_12', + 'input_fuse_open_circuit_13', + 'input_fuse_open_circuit_14', + 'input_fuse_open_circuit_15', + 'combiner_ov_gp_1', + 'combiner_ov_gp_2', + 'combiner_ov_gp_3', + 'combiner_ov_gp_4', + 'combiner_ov_gp_5', + 'combiner_ov_gp_6', + 'combiner_ov_gp_7', + 'combiner_ov_gp_8', + 'combiner_ov_gp_9', + 'combiner_ov_gp_10', + 'combiner_ov_gp_11', + 'combiner_ov_gp_12', + 'combiner_ov_gp_13', + 'combiner_ov_gp_14', + 'combiner_ov_gp_15', + 'combiner_ov_gp_16', + 'combiner_uv_gp_1', + 'combiner_uv_gp_2', + 'combiner_uv_gp_3', + 'combiner_uv_gp_4', + 'combiner_uv_gp_5', + 'combiner_uv_gp_6', + 'combiner_uv_gp_7', + 'combiner_uv_gp_8', + 'combiner_uv_gp_9', + 'combiner_uv_gp_10', + 'combiner_uv_gp_11', + 'combiner_uv_gp_12', + 'combiner_uv_gp_13', + 'combiner_uv_gp_14', + 'combiner_uv_gp_15', + 'combiner_uv_gp_16', + 'combiner_oc_1', + 'combiner_oc_2', + 'combiner_oc_3', + 'combiner_oc_4', + 'combiner_oc_5', + 'combiner_oc_6', + 'combiner_oc_7', + 'combiner_oc_8', + 'combiner_oc_9', + 'combiner_oc_10', + 'combiner_oc_11', + 'combiner_oc_12', + 'combiner_oc_13', + 'combiner_oc_14', + 'combiner_oc_15', + 'combiner_oc_16', + 'combiner_oc_17', + 'combiner_oc_18', + 'combiner_oc_19', + 'combiner_oc_20', + 'combiner_oc_21', + 'combiner_oc_22', + 'combiner_oc_23', + 'combiner_oc_24', + 'combiner_oc_25', + 'combiner_oc_26', + 'combiner_oc_27', + 'combiner_oc_28', + 'combiner_oc_29', + 'combiner_oc_30', + 'combiner_oc_31', + 'combiner_oc_32', + 'combiner_reflux_fault_1', + 'combiner_reflux_fault_2', + 'combiner_reflux_fault_3', + 'combiner_reflux_fault_4', + 'combiner_reflux_fault_5', + 'combiner_reflux_fault_6', + 'combiner_reflux_fault_7', + 'combiner_reflux_fault_8', + 'combiner_reflux_fault_9', + 'combiner_reflux_fault_10', + 'combiner_reflux_fault_11', + 'combiner_reflux_fault_12', + 'combiner_reflux_fault_13', + 'combiner_reflux_fault_14', + 'combiner_reflux_fault_15', + 'combiner_reflux_fault_16', + 'combiner_reflux_fault_17', + 'combiner_reflux_fault_18', + 'combiner_reflux_fault_19', + 'combiner_reflux_fault_20', + 'combiner_reflux_fault_21', + 'combiner_reflux_fault_22', + 'combiner_reflux_fault_23', + 'combiner_reflux_fault_24', + 'combiner_reflux_fault_25', + 'combiner_reflux_fault_26', + 'combiner_reflux_fault_27', + 'combiner_reflux_fault_28', + 'combiner_reflux_fault_29', + 'combiner_reflux_fault_30', + 'combiner_reflux_fault_31', + 'combiner_reflux_fault_32', + 'afci_0', + 'afci_1', + 'afci_2', + 'afci_3', + 'afci_4', + 'afci_5', + 'afci_6', + 'afci_7', + 'afci_8', + 'afci_9', + 'afci_10', + 'afci_11', + 'afci_12', + 'afci_13', + 'afci_14', + 'afci_15', + 'afci_16', + 'afci_17', + 'afci_18', + 'afci_19', + 'afci_20', + 'afci_21', + 'afci_22', + 'afci_23', + 'afci_24', + 'afci_25', + 'afci_26', + 'afci_27', + 'afci_28', + 'afci_29', + 'afci_30', + 'afci_31', + 'modify_ovp', + 'ground_zero_voltage_too_high', + 'pv_branch_overcurrent_default_off', + 'n_line_open_circuit_fault', + 'grid_frequency_change_protection', + 'phase_loss_failure', + 'dcdc_fault', + 'bcu_fault', + 'bmu_fault', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': , + 'entity_id': 'event.4_4_ktlx_g3_fault', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Fault', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Fault', + 'platform': 'sofar', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'fault', + 'unique_id': 'SS2ES104N5S445_fault', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[event.4_4_ktlx_g3_fault-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : None, + : list([ + 'grid_over_voltage', + 'grid_undervoltage', + 'grid_overfrequency', + 'grid_underfrequency', + 'leakage_current_faults', + 'high_penetration_error', + 'low_penetration_error', + 'islanding_error', + 'grid_instantaneous_value_overvoltage_1', + 'grid_instantaneous_value_overvoltage_2', + 'grid_line_voltage_error', + 'inverter_voltage_error', + 'anti_backflow_overload', + 'grid_voltage_unbalance', + 'inverter_transient_overvoltage', + 'sudden_grid_phase_change', + 'grid_current_sampling_error', + 'dci_sampling_error_ac', + 'network_voltage_sampling_error_dc', + 'network_voltage_sampling_error_ac', + 'gfci_sampling_error_dc', + 'gfci_sampling_error_ac', + 'dcv_sampling_error', + 'input_current_sampling_error', + 'dci_sampling_error_dc', + 'branch_current_sampling_error', + 'pv_low_impedance_to_ground', + 'pid_abnormal_output', + 'leakage_current_consistency_error', + 'net_voltage_consistency_error', + 'dci_consistency_error', + 'neutral_ground_fault', + 'spi_communication_error_dc', + 'spi_communication_error_ac', + 'chip_error_dc', + 'chip_error_ac', + 'auxiliary_power_error', + 'inverter_soft_start_failure', + 'arc_shutdown_protection', + 'weak_light_detection_failure', + 'relay_detection_failure', + 'low_insulation_impedance', + 'grounding_error', + 'wrong_input_mode_setting', + 'ct_error', + 'input_reversal_error', + 'parallel_error', + 'serial_number_error', + 'battery_temperature_protection', + 'heatsink_1_temperature_protection', + 'heatsink_2_temperature_protection', + 'heatsink_3_temperature_protection', + 'heatsink_4_temperature_protection', + 'heatsink_5_temperature_protection', + 'heatsink_6_temperature_protection', + 'ambient_temperature_1_protection', + 'ambient_temperature_2_protection', + 'module_1_temperature_protection', + 'module_2_temperature_protection', + 'module_3_temperature_protection', + 'module_temperature_difference_too_large', + 'busbar_rms_unbalance', + 'busbar_instantaneous_value_unbalance', + 'busbar_undervoltage_during_grid_connection', + 'busbar_low_voltage', + 'pv_overvoltage', + 'battery_over_voltage', + 'llcbus_overvoltage_protection', + 'busbar_rms_software_overvoltage', + 'busbar_transient_software_overvoltage', + 'fly_span_capacitor_overvoltage_protection', + 'fly_span_capacitor_under_voltage_protection', + 'pv_undervoltage', + 'battery_overcurrent_software_protection', + 'dci_overcurrent_protection', + 'output_transient_current_protection', + 'bckbst_software_overcurrent', + 'inverter_rms_current_protection', + 'pv_transient_software_overcurrent', + 'pv_parallel_uneven_current', + 'output_current_unbalance', + 'pv_software_overcurrent_protection', + 'balanced_circuit_overcurrent_protection', + 'resonance_protection', + 'wave_by_wave_current_limit', + 'pv_branch_overcurrent_default_on', + 'llc_busbar_hardware_overvoltage', + 'inverter_bus_hardware_overvoltage', + 'bckbst_hardware_overcurrent', + 'battery_hardware_overcurrent', + 'pv_hardware_overcurrent', + 'ac_output_hardware_overcurrent', + 'hardware_differential_overcurrent', + 'meter_communication_error', + 'serial_number_model_error', + 'hardware_version_mismatch', + 'overload_protection_1', + 'overload_protection_2', + 'overload_protection_3', + 'over_temperature_load_shedding', + 'frequency_down_load', + 'frequency_loading', + 'voltage_down_load', + 'voltage_loading', + 'low_temperature_load_shedding', + 'lightning_protection_dc', + 'lightning_protection_ac', + 'battery_lockout_protection', + 'battery_low_voltage_shutdown', + 'ac_hardware_overcurrent_fault', + 'bus_overvoltage_fault', + 'bus_hardware_over_voltage_fault', + 'pv_uneven_flow_fault', + 'eps_battery_overcurrent_fault', + 'output_transient_overcurrent_fault', + 'ac_current_unbalance_fault', + 'inverter_soft_start_failure_fault', + 'input_mode_setting_fault', + 'input_overcurrent_fault', + 'input_hardware_overcurrent_fault', + 'relay_permanent_failure', + 'bus_unbalance_fault', + 'lightning_protection_dc_permanent', + 'lightning_protection_ac_permanent', + 'grid_relay_fault', + 'usb_fault', + 'wifi_fault', + 'bluetooth_fault', + 'rtc_clock_fault', + 'communication_board_eeprom_error', + 'communication_board_flash_error', + 'battery_partially_disconnected', + 'safety_version_error', + 'sci_error_dc', + 'sci_error_ac', + 'sci_error_fuse', + 'software_version_inconsistency', + 'lithium_battery_1_communication_failure', + 'lithium_battery_2_communication_failure', + 'lithium_battery_3_communication_failure', + 'lithium_battery_4_communication_failure', + 'forced_shutdown', + 'remote_shutdown', + 'drms0_shutdown', + 'power_station_communication_failure_shutdown', + 'fan_1_fault', + 'fan_2_fault', + 'fan_3_fault', + 'fan_4_fault', + 'fan_5_fault', + 'fan_6_fault', + 'fan_7_fault', + 'bms_over_voltage_protection', + 'bms_undervoltage_protection', + 'bms_high_temperature_protection', + 'bms_low_temperature_protection', + 'bms_overcurrent_protection', + 'bms_short_circuit_protection', + 'bms_version_inconsistency', + 'bms_can_version_inconsistency', + 'bms_can_version_too_low', + 'battery_discharge_over_temperature_protection', + 'battery_discharge_low_temperature_protection', + 'battery_charging_over_temperature_protection', + 'arc_device_communication_failure', + 'battery_charging_low_temperature_protection', + 'pid_repair_failure', + 'plc_module_heartbeat_lost', + 'string_fuse_open_circuit_1_1', + 'string_fuse_open_circuit_1_2', + 'string_fuse_open_circuit_2_1', + 'string_fuse_open_circuit_2_2', + 'string_fuse_open_circuit_3_1', + 'string_fuse_open_circuit_3_2', + 'string_fuse_open_circuit_4_1', + 'string_fuse_open_circuit_4_2', + 'string_fuse_open_circuit_5_1', + 'string_fuse_open_circuit_5_2', + 'string_fuse_open_circuit_6_1', + 'string_fuse_open_circuit_6_2', + 'string_fuse_open_circuit_7_1', + 'string_fuse_open_circuit_7_2', + 'string_fuse_open_circuit_8_1', + 'string_fuse_open_circuit_8_2', + 'string_fuse_open_circuit_9_1', + 'string_fuse_open_circuit_9_2', + 'string_fuse_open_circuit_10_1', + 'string_fuse_open_circuit_10_2', + 'string_fuse_open_circuit_11_1', + 'string_fuse_open_circuit_11_2', + 'string_fuse_open_circuit_12_1', + 'string_fuse_open_circuit_12_2', + 'string_fuse_open_circuit_13_1', + 'string_fuse_open_circuit_13_2', + 'string_fuse_open_circuit_14_1', + 'string_fuse_open_circuit_14_2', + 'string_fuse_open_circuit_15_1', + 'string_fuse_open_circuit_15_2', + 'string_fuse_open_circuit_16_1', + 'string_fuse_open_circuit_16_2', + 'input_fuse_open_circuit_0', + 'input_fuse_open_circuit_1', + 'input_fuse_open_circuit_2', + 'input_fuse_open_circuit_3', + 'input_fuse_open_circuit_4', + 'input_fuse_open_circuit_5', + 'input_fuse_open_circuit_6', + 'input_fuse_open_circuit_7', + 'input_fuse_open_circuit_8', + 'input_fuse_open_circuit_9', + 'input_fuse_open_circuit_10', + 'input_fuse_open_circuit_11', + 'input_fuse_open_circuit_12', + 'input_fuse_open_circuit_13', + 'input_fuse_open_circuit_14', + 'input_fuse_open_circuit_15', + 'combiner_ov_gp_1', + 'combiner_ov_gp_2', + 'combiner_ov_gp_3', + 'combiner_ov_gp_4', + 'combiner_ov_gp_5', + 'combiner_ov_gp_6', + 'combiner_ov_gp_7', + 'combiner_ov_gp_8', + 'combiner_ov_gp_9', + 'combiner_ov_gp_10', + 'combiner_ov_gp_11', + 'combiner_ov_gp_12', + 'combiner_ov_gp_13', + 'combiner_ov_gp_14', + 'combiner_ov_gp_15', + 'combiner_ov_gp_16', + 'combiner_uv_gp_1', + 'combiner_uv_gp_2', + 'combiner_uv_gp_3', + 'combiner_uv_gp_4', + 'combiner_uv_gp_5', + 'combiner_uv_gp_6', + 'combiner_uv_gp_7', + 'combiner_uv_gp_8', + 'combiner_uv_gp_9', + 'combiner_uv_gp_10', + 'combiner_uv_gp_11', + 'combiner_uv_gp_12', + 'combiner_uv_gp_13', + 'combiner_uv_gp_14', + 'combiner_uv_gp_15', + 'combiner_uv_gp_16', + 'combiner_oc_1', + 'combiner_oc_2', + 'combiner_oc_3', + 'combiner_oc_4', + 'combiner_oc_5', + 'combiner_oc_6', + 'combiner_oc_7', + 'combiner_oc_8', + 'combiner_oc_9', + 'combiner_oc_10', + 'combiner_oc_11', + 'combiner_oc_12', + 'combiner_oc_13', + 'combiner_oc_14', + 'combiner_oc_15', + 'combiner_oc_16', + 'combiner_oc_17', + 'combiner_oc_18', + 'combiner_oc_19', + 'combiner_oc_20', + 'combiner_oc_21', + 'combiner_oc_22', + 'combiner_oc_23', + 'combiner_oc_24', + 'combiner_oc_25', + 'combiner_oc_26', + 'combiner_oc_27', + 'combiner_oc_28', + 'combiner_oc_29', + 'combiner_oc_30', + 'combiner_oc_31', + 'combiner_oc_32', + 'combiner_reflux_fault_1', + 'combiner_reflux_fault_2', + 'combiner_reflux_fault_3', + 'combiner_reflux_fault_4', + 'combiner_reflux_fault_5', + 'combiner_reflux_fault_6', + 'combiner_reflux_fault_7', + 'combiner_reflux_fault_8', + 'combiner_reflux_fault_9', + 'combiner_reflux_fault_10', + 'combiner_reflux_fault_11', + 'combiner_reflux_fault_12', + 'combiner_reflux_fault_13', + 'combiner_reflux_fault_14', + 'combiner_reflux_fault_15', + 'combiner_reflux_fault_16', + 'combiner_reflux_fault_17', + 'combiner_reflux_fault_18', + 'combiner_reflux_fault_19', + 'combiner_reflux_fault_20', + 'combiner_reflux_fault_21', + 'combiner_reflux_fault_22', + 'combiner_reflux_fault_23', + 'combiner_reflux_fault_24', + 'combiner_reflux_fault_25', + 'combiner_reflux_fault_26', + 'combiner_reflux_fault_27', + 'combiner_reflux_fault_28', + 'combiner_reflux_fault_29', + 'combiner_reflux_fault_30', + 'combiner_reflux_fault_31', + 'combiner_reflux_fault_32', + 'afci_0', + 'afci_1', + 'afci_2', + 'afci_3', + 'afci_4', + 'afci_5', + 'afci_6', + 'afci_7', + 'afci_8', + 'afci_9', + 'afci_10', + 'afci_11', + 'afci_12', + 'afci_13', + 'afci_14', + 'afci_15', + 'afci_16', + 'afci_17', + 'afci_18', + 'afci_19', + 'afci_20', + 'afci_21', + 'afci_22', + 'afci_23', + 'afci_24', + 'afci_25', + 'afci_26', + 'afci_27', + 'afci_28', + 'afci_29', + 'afci_30', + 'afci_31', + 'modify_ovp', + 'ground_zero_voltage_too_high', + 'pv_branch_overcurrent_default_off', + 'n_line_open_circuit_fault', + 'grid_frequency_change_protection', + 'phase_loss_failure', + 'dcdc_fault', + 'bcu_fault', + 'bmu_fault', + ]), + : '4.4 KTLX-G3 Fault', + }), + 'context': , + 'entity_id': 'event.4_4_ktlx_g3_fault', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- diff --git a/tests/components/sofar/test_config_flow.py b/tests/components/sofar/test_config_flow.py index 1b8a38e5a3ea..c9df5a757b7d 100644 --- a/tests/components/sofar/test_config_flow.py +++ b/tests/components/sofar/test_config_flow.py @@ -20,6 +20,8 @@ from homeassistant.components.sofar.const import ( CONF_UNIT_ID, DEFAULT_NAME, DOMAIN, + HAS_FAULT_LOG, + LAST_HANDLED_FAULT, TYPE_SERIAL, TYPE_TCP, ) @@ -315,11 +317,26 @@ async def _start_reconfigure( return result +@pytest.mark.parametrize( + "stored", + [ + pytest.param({}, id="no_fault_log_stored"), + pytest.param( + { + HAS_FAULT_LOG: True, + LAST_HANDLED_FAULT: [3, "2026-10-09T18:30:05"], + }, + id="handled_fault_stored", + ), + ], +) async def test_reconfigure_updates_the_entry( - hass: HomeAssistant, mock_setup_entry: AsyncMock + hass: HomeAssistant, mock_setup_entry: AsyncMock, stored: dict[str, Any] ) -> None: - """Test reconfigure updates the entry and reloads it.""" - entry = MockConfigEntry(domain=DOMAIN, unique_id=MOCK_SERIAL, data=MOCK_ENTRY_DATA) + """Test reconfigure updates the entry, keeping what it detected.""" + entry = MockConfigEntry( + domain=DOMAIN, unique_id=MOCK_SERIAL, data={**MOCK_ENTRY_DATA, **stored} + ) entry.add_to_hass(hass) result = await _start_reconfigure(hass, entry, STEP_RECONFIGURE_TCP) @@ -333,7 +350,47 @@ async def test_reconfigure_updates_the_entry( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" - assert entry.data == {CONF_TYPE: TYPE_TCP, **_NEW_TCP_INPUT} + assert entry.data == {CONF_TYPE: TYPE_TCP, **_NEW_TCP_INPUT, **stored} + + +async def test_reconfigure_keeps_a_fault_handled_while_probing( + hass: HomeAssistant, mock_setup_entry: AsyncMock +) -> None: + """Test a fault the entry handles during the probe stays handled.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_SERIAL, + data={**MOCK_ENTRY_DATA, LAST_HANDLED_FAULT: [3, "2026-10-09T18:30:05"]}, + ) + entry.add_to_hass(hass) + result = await _start_reconfigure(hass, entry, STEP_RECONFIGURE_TCP) + + mock_conn = MockModbusConnection() + seed_pv_inverter(mock_conn.for_unit(1)) + + @asynccontextmanager + async def _get_temporary_unit( + hass: HomeAssistant, + params: ModbusSerialParams | ModbusTcpParams, + unit_id: int, + ) -> AsyncIterator[MockModbusUnit]: + # The loaded entry keeps polling while the new link is probed. + hass.config_entries.async_update_entry( + entry, + data={**entry.data, LAST_HANDLED_FAULT: [1, "2026-10-10T07:45:00"]}, + ) + yield mock_conn.for_unit(unit_id) + + with patch( + "homeassistant.components.sofar.config_flow.async_get_temporary_unit", + side_effect=_get_temporary_unit, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], _NEW_TCP_INPUT + ) + + assert result["reason"] == "reconfigure_successful" + assert entry.data[LAST_HANDLED_FAULT] == [1, "2026-10-10T07:45:00"] async def test_reconfigure_offers_the_current_settings( @@ -553,7 +610,11 @@ async def test_reconfigure_new_line_settings_silent_inverter( assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "inverter_silent"} - assert entry.data == MOCK_SERIAL_ENTRY_DATA + assert entry.data == { + **MOCK_SERIAL_ENTRY_DATA, + HAS_FAULT_LOG: True, + LAST_HANDLED_FAULT: None, + } assert entry.unique_id == MOCK_SERIAL assert entry.state is ConfigEntryState.LOADED @@ -589,7 +650,11 @@ async def test_reconfigure_new_line_settings_wrong_device(hass: HomeAssistant) - assert result["type"] is FlowResultType.ABORT assert result["reason"] == "unique_id_mismatch" - assert entry.data == MOCK_SERIAL_ENTRY_DATA + assert entry.data == { + **MOCK_SERIAL_ENTRY_DATA, + HAS_FAULT_LOG: True, + LAST_HANDLED_FAULT: None, + } assert entry.unique_id == MOCK_SERIAL assert entry.state is ConfigEntryState.LOADED diff --git a/tests/components/sofar/test_event.py b/tests/components/sofar/test_event.py new file mode 100644 index 000000000000..d4cc22b5cd52 --- /dev/null +++ b/tests/components/sofar/test_event.py @@ -0,0 +1,345 @@ +"""Tests for the Sofar event platform.""" + +from collections.abc import Generator +from datetime import datetime, timedelta +from unittest.mock import patch + +from freezegun.api import FrozenDateTimeFactory +from modbus_connection import ModbusError +from modbus_connection.mock import MockModbusConnection +import pytest +from pytest_homeassistant.common import ( + MockConfigEntry, + async_capture_events, + async_fire_time_changed, + snapshot_platform, +) +from pytest_homeassistant.components.common import arm_trigger +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.event import ATTR_EVENT_TYPE +from homeassistant.components.sofar.const import ( + DOMAIN, + HAS_FAULT_LOG, + LAST_HANDLED_FAULT, + SCAN_INTERVAL, +) +from homeassistant.const import ( + EVENT_STATE_CHANGED, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + Platform, +) +from homeassistant.core import CoreState, Event, EventStateChangedData, HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import ( + FAULT_LOG_REGISTER, + MOCK_ENTRY_DATA, + MOCK_MODEL, + MOCK_SERIAL, + seed_fault_log, +) + +ENTITY_ID = "event.4_4_ktlx_g3_fault" + +# Log entries as (fault id, inverter clock). +GRID_OVER_VOLTAGE = (1, datetime(2026, 10, 9, 17, 1, 23)) +FAN_1_FAULT = (169, datetime(2026, 10, 9, 17, 1, 23)) +GRID_OVERFREQUENCY = (3, datetime(2026, 10, 9, 18, 30, 5)) +GRID_OVER_VOLTAGE_AGAIN = (1, datetime(2026, 10, 10, 7, 45, 0)) + + +@pytest.fixture(autouse=True) +def platforms() -> Generator[None]: + """Set up only the event platform.""" + with patch("homeassistant.components.sofar.PLATFORMS", [Platform.EVENT]): + yield + + +def _handled_entry(handled: list[int | str] | None) -> MockConfigEntry: + """Mock a Sofar config entry from a run that handled up to ``handled``.""" + return MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_SERIAL, + data={**MOCK_ENTRY_DATA, LAST_HANDLED_FAULT: handled}, + title=MOCK_MODEL, + ) + + +def _fired(events: list[Event[EventStateChangedData]]) -> list[tuple[str, int, str]]: + """Every event the entity showed, as fault key, id and log time.""" + # Keyed by timestamp, so returning from unavailable is not an event. + return list( + { + state.state: ( + state.attributes[ATTR_EVENT_TYPE], + state.attributes["fault_id"], + state.attributes["occurred_at"], + ) + for event in events + if event.data["entity_id"] == ENTITY_ID + and (state := event.data["new_state"]) is not None + and state.attributes.get(ATTR_EVENT_TYPE) is not None + }.values() + ) + + +async def test_all_entities( + hass: HomeAssistant, + snapshot: SnapshotAssertion, + entity_registry: er.EntityRegistry, + init_integration: MockConfigEntry, +) -> None: + """Test all entities match their snapshot.""" + await snapshot_platform(hass, entity_registry, snapshot, init_integration.entry_id) + + +@pytest.mark.usefixtures("init_integration") +async def test_new_entries_fire_one_event_each_oldest_first( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test entries logged between polls fire in the order they happened.""" + events = async_capture_events(hass, EVENT_STATE_CHANGED) + seed_fault_log( + mock_connection.for_unit(1), + GRID_OVERFREQUENCY, + FAN_1_FAULT, + GRID_OVER_VOLTAGE, + ) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [ + ("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00"), + ("fan_1_fault", 169, "2026-10-09T17:01:23-07:00"), + ("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00"), + ] + state = hass.states.get(ENTITY_ID) + assert state is not None + assert state.attributes["category"] == "grid" + + +@pytest.mark.usefixtures("init_integration") +async def test_entry_fires_once( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test an entry fires once, and the same fault logged again refires.""" + unit = mock_connection.for_unit(1) + events = async_capture_events(hass, EVENT_STATE_CHANGED) + seed_fault_log(unit, GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00")] + + seed_fault_log(unit, GRID_OVER_VOLTAGE_AGAIN, GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [ + ("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00"), + ("grid_over_voltage", 1, "2026-10-10T07:45:00-07:00"), + ] + + +@pytest.mark.parametrize( + ("entry", "expected"), + [ + pytest.param( + MockConfigEntry(domain=DOMAIN, unique_id=MOCK_SERIAL, data=MOCK_ENTRY_DATA), + [], + id="first_run", + ), + pytest.param( + _handled_entry([1, "2026-10-09T17:01:23"]), + [ + ("fan_1_fault", 169, "2026-10-09T17:01:23-07:00"), + ("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00"), + ], + id="stored_entry_in_log", + ), + pytest.param( + _handled_entry([169, "2026-10-01T09:00:00"]), + [ + ("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00"), + ("fan_1_fault", 169, "2026-10-09T17:01:23-07:00"), + ("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00"), + ], + id="stored_entry_rotated_out", + ), + pytest.param( + _handled_entry(None), + [ + ("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00"), + ("fan_1_fault", 169, "2026-10-09T17:01:23-07:00"), + ("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00"), + ], + id="stored_empty_log", + ), + ], +) +@pytest.mark.usefixtures("mock_get_unit") +async def test_setup_fires_only_entries_logged_since_last_run( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, + entry: MockConfigEntry, + expected: list[tuple[str, int, str]], +) -> None: + """Test a restart fires what was logged since the last run, no more.""" + seed_fault_log( + mock_connection.for_unit(1), GRID_OVERFREQUENCY, FAN_1_FAULT, GRID_OVER_VOLTAGE + ) + entry.add_to_hass(hass) + events = async_capture_events(hass, EVENT_STATE_CHANGED) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == expected + + +@pytest.mark.usefixtures("mock_get_unit") +async def test_entries_wait_until_home_assistant_runs( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test entries logged while down fire once triggers can see them.""" + entry = _handled_entry([1, "2026-10-09T17:01:23"]) + seed_fault_log(mock_connection.for_unit(1), GRID_OVERFREQUENCY, GRID_OVER_VOLTAGE) + hass.set_state(CoreState.starting) + entry.add_to_hass(hass) + events = async_capture_events(hass, EVENT_STATE_CHANGED) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [] + + hass.set_state(CoreState.running) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00")] + + +@pytest.mark.usefixtures("mock_get_unit") +async def test_entries_found_by_first_good_read_do_not_fire( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test a log unread at setup fires only what is logged after it answers.""" + unit = mock_connection.for_unit(1) + seed_fault_log(unit, GRID_OVER_VOLTAGE) + unit.fail_read(FAULT_LOG_REGISTER, ModbusError("busy")) + # A stored log keeps its entity even though setup cannot read it. + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_SERIAL, + data={**MOCK_ENTRY_DATA, HAS_FAULT_LOG: True}, + title=MOCK_MODEL, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + unit.fail_read(FAULT_LOG_REGISTER, None) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN + + seed_fault_log(unit, GRID_OVERFREQUENCY, GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + hass.states.get(ENTITY_ID).attributes[ATTR_EVENT_TYPE] == "grid_overfrequency" + ) + + +@pytest.mark.usefixtures("init_integration") +async def test_time_zone_change_does_not_refire( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test a new time zone leaves handled entries handled.""" + events = async_capture_events(hass, EVENT_STATE_CHANGED) + seed_fault_log(mock_connection.for_unit(1), GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + await hass.config.async_update(time_zone="Europe/Amsterdam") + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00")] + + +@pytest.mark.usefixtures("init_integration") +async def test_entry_logged_during_failed_read_fires_after_it( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, +) -> None: + """Test a failed read neither replays old entries nor loses new ones.""" + unit = mock_connection.for_unit(1) + events = async_capture_events(hass, EVENT_STATE_CHANGED) + calls: list[str] = [] + await arm_trigger( + hass, + "event.received", + {"event_type": ["grid_overfrequency"]}, + {"entity_id": ENTITY_ID}, + calls, + ) + seed_fault_log(unit, GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + unit.fail_read(FAULT_LOG_REGISTER, ModbusError("busy")) + seed_fault_log(unit, GRID_OVERFREQUENCY, GRID_OVER_VOLTAGE) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00")] + + unit.fail_read(FAULT_LOG_REGISTER, None) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert _fired(events) == [ + ("grid_over_voltage", 1, "2026-10-09T17:01:23-07:00"), + ("grid_overfrequency", 3, "2026-10-09T18:30:05-07:00"), + ] + # The first fault after recovery still runs its automation. + assert calls == [ENTITY_ID] diff --git a/tests/components/sofar/test_init.py b/tests/components/sofar/test_init.py index ab4848747544..2c5a35d1c416 100644 --- a/tests/components/sofar/test_init.py +++ b/tests/components/sofar/test_init.py @@ -24,10 +24,13 @@ from pytest_homeassistant.common import ( ) from pytest_homeassistant.typing import WebSocketGenerator +from homeassistant.components.event import DOMAIN as EVENT_DOMAIN from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.components.sofar.const import ( CONF_BAUDRATE, DOMAIN, + HAS_FAULT_LOG, + LAST_HANDLED_FAULT, SCAN_INTERVAL, SETTINGS_SCAN_INTERVAL, ) @@ -39,6 +42,7 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.setup import async_setup_component from . import ( + FAULT_LOG_REGISTER, MOCK_ENTRY_DATA, MOCK_HW_VERSION, MOCK_HYBRID_MODEL, @@ -372,7 +376,7 @@ async def test_setup_takes_the_type_from_the_masks( await hass.async_block_till_done(wait_background_tasks=True) assert entry.state is ConfigEntryState.LOADED - assert len(hass.states.async_all()) == 37 + assert len(hass.states.async_all()) == 38 entity_id = entity_registry.async_get_entity_id( SENSOR_DOMAIN, DOMAIN, f"{MOCK_UNRECOGNIZED_SERIAL}_pv_power_1" ) @@ -413,7 +417,7 @@ async def test_setup_while_asleep_reloads_once_the_inverter_answers( assert mock_config_entry.state is ConfigEntryState.LOADED states = hass.states.async_all() - assert len(states) == 37 + assert len(states) == 38 assert {state.state for state in states} == {STATE_UNAVAILABLE} assert "inverter is not answering" in caplog.text @@ -460,7 +464,7 @@ async def test_setup_takes_the_type_once_the_masks_answer( await hass.async_block_till_done(wait_background_tasks=True) assert entry.state is ConfigEntryState.LOADED - assert len(hass.states.async_all()) == 37 + assert len(hass.states.async_all()) == 38 @pytest.mark.usefixtures("mock_get_unit") @@ -1073,10 +1077,14 @@ async def test_a_removed_pack_comes_back_without_a_restart( @pytest.mark.parametrize( ("data", "expected"), [ - pytest.param(MOCK_TCP_INPUT, MOCK_ENTRY_DATA, id="legacy_tcp"), + pytest.param( + MOCK_TCP_INPUT, + {**MOCK_ENTRY_DATA, HAS_FAULT_LOG: True, LAST_HANDLED_FAULT: None}, + id="legacy_tcp", + ), pytest.param( MOCK_SERIAL_ENTRY_DATA, - MOCK_SERIAL_ENTRY_DATA, + {**MOCK_SERIAL_ENTRY_DATA, HAS_FAULT_LOG: True, LAST_HANDLED_FAULT: None}, id="reconfigured_while_disabled", ), ], @@ -1100,3 +1108,55 @@ async def test_migrate_entry_adds_the_connection_type( assert entry.minor_version == 2 assert entry.data == expected + + +@pytest.mark.parametrize( + ("stored", "log_error", "expected_stored", "has_event"), + [ + pytest.param({}, None, True, True, id="first_good_setup_stores_it"), + pytest.param( + {HAS_FAULT_LOG: True}, + ModbusTimeoutError("stuck"), + True, + True, + id="stored_log_survives_a_timeout", + ), + pytest.param( + {}, + ModbusTimeoutError("stuck"), + None, + False, + id="unknown_log_timing_out_is_not_stored", + ), + ], +) +@pytest.mark.usefixtures("mock_get_unit") +async def test_setup_remembers_the_fault_log( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_connection: MockModbusConnection, + stored: dict[str, Any], + log_error: ModbusError | None, + expected_stored: bool | None, + has_event: bool, +) -> None: + """Test a fault log once seen keeps its event through a failed read.""" + mock_connection.for_unit(1).fail_read(FAULT_LOG_REGISTER, log_error) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_SERIAL, + data={**MOCK_ENTRY_DATA, **stored}, + title=MOCK_MODEL, + ) + entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert entry.data.get(HAS_FAULT_LOG) is expected_stored + assert ( + entity_registry.async_get_entity_id( + EVENT_DOMAIN, DOMAIN, f"{MOCK_SERIAL}_fault" + ) + is not None + ) is has_event