From aecf4fb953aa6bee2af14f65a16847cb6764ed60 Mon Sep 17 00:00:00 2001 From: darkrain-nl Date: Sun, 1 Nov 2026 10:39:24 +0100 Subject: [PATCH] Fix Sofar reload loop and phantom sensors after a night setup (#189423) --- homeassistant/components/sofar/__init__.py | 60 ++++-- homeassistant/components/sofar/button.py | 28 ++- homeassistant/components/sofar/config_flow.py | 4 +- homeassistant/components/sofar/const.py | 3 +- homeassistant/components/sofar/coordinator.py | 13 +- homeassistant/components/sofar/event.py | 4 +- .../sofar/snapshots/test_config_flow.ambr | 43 ++++ .../components/sofar/snapshots/test_init.ambr | 70 +++++++ tests/components/sofar/test_config_flow.py | 28 ++- tests/components/sofar/test_event.py | 5 +- tests/components/sofar/test_init.py | 183 +++++++++++++++--- 11 files changed, 362 insertions(+), 79 deletions(-) create mode 100644 tests/components/sofar/snapshots/test_config_flow.ambr create mode 100644 tests/components/sofar/snapshots/test_init.ambr diff --git a/homeassistant/components/sofar/__init__.py b/homeassistant/components/sofar/__init__.py index a6c25ff45ad3..c7755c333221 100644 --- a/homeassistant/components/sofar/__init__.py +++ b/homeassistant/components/sofar/__init__.py @@ -28,9 +28,10 @@ from homeassistant.helpers.update_coordinator import UpdateFailed from .const import ( CONF_UNIT_ID, DOMAIN, - HAS_FAULT_LOG, + FAULT_LOG, METER_ENERGY, SCAN_INTERVAL, + SERVED_COMPONENTS, SETTINGS_SCAN_INTERVAL, TYPE_TCP, ) @@ -108,6 +109,26 @@ def _async_seed_high_water_marks( description.total_fn(device).seed(float(extra.native_value)) +@callback +def _async_store_served( + hass: HomeAssistant, entry: SofarConfigEntry, served: frozenset[str] +) -> None: + """Remember what the inverter serves for a setup it sleeps through.""" + if (stored := sorted(served)) != entry.data.get(SERVED_COMPONENTS): + hass.config_entries.async_update_entry( + entry, data={**entry.data, SERVED_COMPONENTS: stored} + ) + + +async def _async_refresh_versions(hass: HomeAssistant, entry: SofarConfigEntry) -> None: + """Read the firmware versions a setup without the inverter missed.""" + readings = entry.runtime_data.readings + await readings.device.async_read_identity() + dr.async_get(hass).async_get_or_create_from_info( + config_entry_id=entry.entry_id, device_info=readings.device_info + ) + + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Sofar integration.""" async_setup_services(hass) @@ -130,7 +151,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: SofarConfigEntry) -> Non device = SofarInverter( unit, serial_number=serial, - has_fault_log=entry.data.get(HAS_FAULT_LOG, False), + has_fault_log=FAULT_LOG in entry.data.get(SERVED_COMPONENTS, ()), ) _async_seed_high_water_marks(hass, serial, device) @@ -164,33 +185,38 @@ async def async_setup_entry(hass: HomeAssistant, entry: SofarConfigEntry) -> Non err, ) - @callback - def _async_reload_once_answered() -> None: - """Set up again in full once the inverter answers.""" - if readings.last_update_success: - hass.config_entries.async_schedule_reload(entry.entry_id) + served = frozenset( + entry.data.get(SERVED_COMPONENTS, device.expected_components) + ) - entry.async_on_unload(readings.async_add_listener(_async_reload_once_answered)) + @callback + def _async_settle_on_first_answer() -> None: + """Take in what the inverter serves once it answers.""" + remove_listener() + _async_store_served(hass, entry, device.expected_components) + if device.expected_components != served: + hass.config_entries.async_schedule_reload(entry.entry_id) + return + entry.async_create_background_task( + hass, _async_refresh_versions(hass, entry), "sofar_refresh_versions" + ) + + remove_listener = readings.async_add_listener(_async_settle_on_first_answer) else: 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} - ) + served = device.expected_components + _async_store_served(hass, entry, served) # 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( config_entry_id=entry.entry_id, device_info=readings.device_info ) - entry.runtime_data = SofarRuntimeData(readings, settings, inverter.id) + entry.runtime_data = SofarRuntimeData(readings, settings, inverter.id, served) # Until the masks settle the type, nothing is served or denied. if device.inverter_type: - _async_remove_denied_meter_energy( - hass, serial, entry.runtime_data.served_components - ) + _async_remove_denied_meter_energy(hass, serial, served) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) diff --git a/homeassistant/components/sofar/button.py b/homeassistant/components/sofar/button.py index 0c3d5c602494..1460e8033b97 100644 --- a/homeassistant/components/sofar/button.py +++ b/homeassistant/components/sofar/button.py @@ -8,7 +8,7 @@ from sofar_modbus.modern.device import SofarInverter from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.const import EntityCategory -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import SofarConfigEntry @@ -54,11 +54,27 @@ async def async_setup_entry( ) -> None: """Set up the Sofar button platform.""" runtime_data = entry.runtime_data - device = runtime_data.readings.device - async_add_entities( - SofarButton(runtime_data, description) - for description in BUTTON_DESCRIPTIONS - if description.supported_fn(device) + added: set[str] = set() + + @callback + def _async_add_supported() -> None: + """Add a button the first time the inverter's type supports it.""" + new = [ + description + for description in BUTTON_DESCRIPTIONS + if description.key not in added + and description.supported_fn(runtime_data.readings.device) + ] + if not new: + return + added.update(description.key for description in new) + async_add_entities( + SofarButton(runtime_data, description) for description in new + ) + + _async_add_supported() + entry.async_on_unload( + runtime_data.readings.async_add_listener(_async_add_supported) ) diff --git a/homeassistant/components/sofar/config_flow.py b/homeassistant/components/sofar/config_flow.py index 6a0fcb54a422..ebe776e882c6 100644 --- a/homeassistant/components/sofar/config_flow.py +++ b/homeassistant/components/sofar/config_flow.py @@ -29,8 +29,8 @@ from .const import ( DEFAULT_PORT, DEFAULT_UNIT_ID, DOMAIN, - HAS_FAULT_LOG, LAST_HANDLED_FAULT, + SERVED_COMPONENTS, TYPE_SERIAL, TYPE_TCP, ) @@ -205,7 +205,7 @@ class SofarConfigFlow(ConfigFlow, domain=DOMAIN): **data, **{ key: entry.data[key] - for key in (HAS_FAULT_LOG, LAST_HANDLED_FAULT) + for key in (LAST_HANDLED_FAULT, SERVED_COMPONENTS) if key in entry.data }, }, diff --git a/homeassistant/components/sofar/const.py b/homeassistant/components/sofar/const.py index f520c063abee..ef7982ad4789 100644 --- a/homeassistant/components/sofar/const.py +++ b/homeassistant/components/sofar/const.py @@ -13,10 +13,11 @@ SETTINGS_SCAN_INTERVAL = 60 CONF_BAUDRATE = "baudrate" CONF_UNIT_ID = "unit_id" -HAS_FAULT_LOG = "has_fault_log" LAST_HANDLED_FAULT = "last_handled_fault" +FAULT_LOG = "fault_log" METER_ENERGY = "meter_energy" +SERVED_COMPONENTS = "served_components" TYPE_SERIAL = "serial" TYPE_TCP = "tcp" diff --git a/homeassistant/components/sofar/coordinator.py b/homeassistant/components/sofar/coordinator.py index b44af034ff63..44b948def95c 100644 --- a/homeassistant/components/sofar/coordinator.py +++ b/homeassistant/components/sofar/coordinator.py @@ -7,9 +7,8 @@ import logging from typing import override from modbus_connection import ModbusError -from propcache.api import cached_property from sofar_modbus.model import UpdateReport -from sofar_modbus.modern.device import SofarInverter +from sofar_modbus.modern.device import READING_COMPONENTS, SofarInverter from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant @@ -48,7 +47,7 @@ class SofarDataUpdateCoordinator(DataUpdateCoordinator[UpdateReport]): self._poll = poll self._failing: set[str] = set() - @cached_property + @property def device_info(self) -> dr.DeviceInfo: """Return device information.""" serial = self.device.serial_number @@ -112,16 +111,12 @@ class SofarRuntimeData: readings: SofarDataUpdateCoordinator settings: SofarDataUpdateCoordinator inverter_device_id: str + served_components: frozenset[str] wired_packs: set[int] = field(default_factory=set) - @property - def served_components(self) -> frozenset[str]: - """Component names this inverter polls, answered or not.""" - return self.readings.device.expected_components - def coordinator_for(self, component: str) -> SofarDataUpdateCoordinator: """Which coordinator owns a given component's data.""" - if component in self.readings.device.expected_readings_components: + if component in READING_COMPONENTS: return self.readings return self.settings diff --git a/homeassistant/components/sofar/event.py b/homeassistant/components/sofar/event.py index 9b72e960afe7..3d744866ec6f 100644 --- a/homeassistant/components/sofar/event.py +++ b/homeassistant/components/sofar/event.py @@ -17,7 +17,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import Undefined from homeassistant.util import dt as dt_util -from .const import LAST_HANDLED_FAULT +from .const import FAULT_LOG, LAST_HANDLED_FAULT from .coordinator import SofarConfigEntry from .entity import SofarEntity, SofarEntityDescription @@ -41,7 +41,7 @@ class SofarEventEntityDescription(EventEntityDescription, SofarEntityDescription EVENT_DESCRIPTIONS: tuple[SofarEventEntityDescription, ...] = ( SofarEventEntityDescription( key="fault", - component="fault_log", + component=FAULT_LOG, translation_key="fault", entity_category=EntityCategory.DIAGNOSTIC, event_types=[fault.key for fault in FAULTS], diff --git a/tests/components/sofar/snapshots/test_config_flow.ambr b/tests/components/sofar/snapshots/test_config_flow.ambr new file mode 100644 index 000000000000..617d8ce5da2b --- /dev/null +++ b/tests/components/sofar/snapshots/test_config_flow.ambr @@ -0,0 +1,43 @@ +# serializer version: 1 +# name: test_reconfigure_new_line_settings_silent_inverter + dict({ + 'baudrate': 9600, + 'device': '/dev/ttyUSB0', + 'last_handled_fault': None, + 'served_components': list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'meter_energy', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]), + 'type': 'serial', + 'unit_id': 1, + }) +# --- +# name: test_reconfigure_new_line_settings_wrong_device + dict({ + 'baudrate': 9600, + 'device': '/dev/ttyUSB0', + 'last_handled_fault': None, + 'served_components': list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'meter_energy', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]), + 'type': 'serial', + 'unit_id': 1, + }) +# --- diff --git a/tests/components/sofar/snapshots/test_init.ambr b/tests/components/sofar/snapshots/test_init.ambr new file mode 100644 index 000000000000..02eca6eace65 --- /dev/null +++ b/tests/components/sofar/snapshots/test_init.ambr @@ -0,0 +1,70 @@ +# serializer version: 1 +# name: test_migrate_entry_adds_the_connection_type[legacy_tcp] + dict({ + 'host': '192.168.1.100', + 'last_handled_fault': None, + 'port': 502, + 'served_components': list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'meter_energy', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]), + 'type': 'tcp', + 'unit_id': 1, + }) +# --- +# name: test_migrate_entry_adds_the_connection_type[reconfigured_while_disabled] + dict({ + 'baudrate': 9600, + 'device': '/dev/ttyUSB0', + 'last_handled_fault': None, + 'served_components': list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'meter_energy', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]), + 'type': 'serial', + 'unit_id': 1, + }) +# --- +# name: test_setup_while_asleep_fills_in_without_a_reload + list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'meter_energy', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]) +# --- +# name: test_setup_while_asleep_reloads_once_for_what_the_inverter_serves + list([ + 'active_power_control', + 'energy', + 'fault_log', + 'feed_in', + 'grid', + 'pv_1_2', + 'remote', + 'rtc_sync', + 'state', + ]) +# --- diff --git a/tests/components/sofar/test_config_flow.py b/tests/components/sofar/test_config_flow.py index c9df5a757b7d..a7da1775d750 100644 --- a/tests/components/sofar/test_config_flow.py +++ b/tests/components/sofar/test_config_flow.py @@ -9,6 +9,7 @@ from modbus_connection import ModbusSerialParams, ModbusTcpParams, ModbusTimeout from modbus_connection.mock import MockModbusConnection, MockModbusUnit import pytest from pytest_homeassistant.common import MockConfigEntry, get_schema_suggested_value +from syrupy.assertion import SnapshotAssertion from homeassistant import config_entries from homeassistant.components.sofar.config_flow import ( @@ -20,8 +21,9 @@ from homeassistant.components.sofar.const import ( CONF_UNIT_ID, DEFAULT_NAME, DOMAIN, - HAS_FAULT_LOG, + FAULT_LOG, LAST_HANDLED_FAULT, + SERVED_COMPONENTS, TYPE_SERIAL, TYPE_TCP, ) @@ -320,10 +322,10 @@ async def _start_reconfigure( @pytest.mark.parametrize( "stored", [ - pytest.param({}, id="no_fault_log_stored"), + pytest.param({}, id="nothing_stored"), pytest.param( { - HAS_FAULT_LOG: True, + SERVED_COMPONENTS: [FAULT_LOG], LAST_HANDLED_FAULT: [3, "2026-10-09T18:30:05"], }, id="handled_fault_stored", @@ -590,7 +592,9 @@ async def test_reconfigure_new_line_settings( @pytest.mark.usefixtures("mock_get_unit") async def test_reconfigure_new_line_settings_silent_inverter( - hass: HomeAssistant, mock_connection: MockModbusConnection + hass: HomeAssistant, + mock_connection: MockModbusConnection, + snapshot: SnapshotAssertion, ) -> None: """Test a failed probe puts the entry back on the bus it was taken off.""" entry = _serial_entry() @@ -610,11 +614,7 @@ 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, - HAS_FAULT_LOG: True, - LAST_HANDLED_FAULT: None, - } + assert entry.data == snapshot assert entry.unique_id == MOCK_SERIAL assert entry.state is ConfigEntryState.LOADED @@ -630,7 +630,9 @@ async def test_reconfigure_new_line_settings_silent_inverter( @pytest.mark.usefixtures("mock_get_unit") -async def test_reconfigure_new_line_settings_wrong_device(hass: HomeAssistant) -> None: +async def test_reconfigure_new_line_settings_wrong_device( + hass: HomeAssistant, snapshot: SnapshotAssertion +) -> None: """Test a different inverter on the new settings restores the entry.""" entry = _serial_entry() entry.add_to_hass(hass) @@ -650,11 +652,7 @@ 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, - HAS_FAULT_LOG: True, - LAST_HANDLED_FAULT: None, - } + assert entry.data == snapshot 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 index d4cc22b5cd52..8dfdf0f1e7a3 100644 --- a/tests/components/sofar/test_event.py +++ b/tests/components/sofar/test_event.py @@ -20,9 +20,10 @@ from syrupy.assertion import SnapshotAssertion from homeassistant.components.event import ATTR_EVENT_TYPE from homeassistant.components.sofar.const import ( DOMAIN, - HAS_FAULT_LOG, + FAULT_LOG, LAST_HANDLED_FAULT, SCAN_INTERVAL, + SERVED_COMPONENTS, ) from homeassistant.const import ( EVENT_STATE_CHANGED, @@ -257,7 +258,7 @@ async def test_entries_found_by_first_good_read_do_not_fire( entry = MockConfigEntry( domain=DOMAIN, unique_id=MOCK_SERIAL, - data={**MOCK_ENTRY_DATA, HAS_FAULT_LOG: True}, + data={**MOCK_ENTRY_DATA, SERVED_COMPONENTS: [FAULT_LOG]}, title=MOCK_MODEL, ) entry.add_to_hass(hass) diff --git a/tests/components/sofar/test_init.py b/tests/components/sofar/test_init.py index 2c5a35d1c416..e73be04858ff 100644 --- a/tests/components/sofar/test_init.py +++ b/tests/components/sofar/test_init.py @@ -23,15 +23,17 @@ from pytest_homeassistant.common import ( mock_restore_cache_with_extra_data, ) from pytest_homeassistant.typing import WebSocketGenerator +from syrupy.assertion import SnapshotAssertion +from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN 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, + FAULT_LOG, SCAN_INTERVAL, + SERVED_COMPONENTS, SETTINGS_SCAN_INTERVAL, ) from homeassistant.components.sofar.coordinator import SofarRuntimeData @@ -400,7 +402,7 @@ async def test_setup_fails_when_the_masks_decline( @pytest.mark.usefixtures("mock_get_unit") -async def test_setup_while_asleep_reloads_once_the_inverter_answers( +async def test_setup_while_asleep_fills_in_without_a_reload( hass: HomeAssistant, freezer: FrozenDateTimeFactory, caplog: pytest.LogCaptureFixture, @@ -408,8 +410,9 @@ async def test_setup_while_asleep_reloads_once_the_inverter_answers( entity_registry: er.EntityRegistry, mock_connection: MockModbusConnection, mock_config_entry: MockConfigEntry, + snapshot: SnapshotAssertion, ) -> None: - """Test a silent inverter loads unavailable, then sets up in full.""" + """Test a silent inverter loads unavailable and fills in without a reload.""" mock_config_entry.add_to_hass(hass) mock_connection.for_unit(1).fail_requests(ModbusTimeoutError("asleep")) await hass.config_entries.async_setup(mock_config_entry.entry_id) @@ -422,10 +425,13 @@ async def test_setup_while_asleep_reloads_once_the_inverter_answers( assert "inverter is not answering" in caplog.text mock_connection.for_unit(1).fail_requests(None) - freezer.tick(timedelta(seconds=SCAN_INTERVAL)) - async_fire_time_changed(hass) - await hass.async_block_till_done(wait_background_tasks=True) + with patch.object(hass.config_entries, "async_schedule_reload") as mock_reload: + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + mock_reload.assert_not_called() + assert mock_config_entry.data[SERVED_COMPONENTS] == snapshot assert mock_config_entry.state is ConfigEntryState.LOADED entity_id = entity_registry.async_get_entity_id( SENSOR_DOMAIN, DOMAIN, f"{MOCK_SERIAL}_pv_power_1" @@ -439,6 +445,84 @@ async def test_setup_while_asleep_reloads_once_the_inverter_answers( assert device.sw_version == MOCK_SW_VERSION +@pytest.mark.usefixtures("mock_get_unit") +async def test_setup_while_asleep_reloads_once_for_what_the_inverter_serves( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + entity_registry: er.EntityRegistry, + mock_connection: MockModbusConnection, + mock_config_entry: MockConfigEntry, + snapshot: SnapshotAssertion, +) -> None: + """Test a dawn that times out the reload's setup reloads only once.""" + mock_config_entry.add_to_hass(hass) + unit = mock_connection.for_unit(1) + deny_meter_energy(unit) + unit.fail_requests(ModbusTimeoutError("asleep")) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + schedule_reload = hass.config_entries.async_schedule_reload + + def _fall_silent_and_reload(entry_id: str) -> None: + unit.fail_requests(ModbusTimeoutError("waking")) + schedule_reload(entry_id) + + unit.fail_requests(None) + with patch.object( + hass.config_entries, + "async_schedule_reload", + side_effect=_fall_silent_and_reload, + ) as mock_reload: + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert mock_config_entry.state is ConfigEntryState.LOADED + unit.fail_requests(None) + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert mock_reload.call_count == 1 + assert mock_config_entry.data[SERVED_COMPONENTS] == snapshot + assert not any( + entity_registry.async_get_entity_id( + SENSOR_DOMAIN, DOMAIN, f"{MOCK_SERIAL}_{key}" + ) + for key in METER_ENERGY_KEYS + ) + + +@pytest.mark.usefixtures("mock_get_unit") +async def test_setup_while_asleep_builds_from_the_stored_components( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_connection: MockModbusConnection, +) -> None: + """Test a silent restart creates no sensors an earlier setup ruled out.""" + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_SERIAL, + data={**MOCK_ENTRY_DATA, SERVED_COMPONENTS: ["energy"]}, + title=MOCK_MODEL, + ) + entry.add_to_hass(hass) + mock_connection.for_unit(1).fail_requests(ModbusTimeoutError("asleep")) + + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert entry.state is ConfigEntryState.LOADED + assert len(hass.states.async_all()) == 2 + assert not any( + entity_registry.async_get_entity_id( + SENSOR_DOMAIN, DOMAIN, f"{MOCK_SERIAL}_{key}" + ) + for key in METER_ENERGY_KEYS + ) + + @pytest.mark.usefixtures("mock_get_unit") async def test_setup_takes_the_type_once_the_masks_answer( hass: HomeAssistant, @@ -467,6 +551,56 @@ async def test_setup_takes_the_type_once_the_masks_answer( assert len(hass.states.async_all()) == 38 +@pytest.mark.parametrize( + ("platform", "key", "interval", "state"), + [ + pytest.param( + SENSOR_DOMAIN, "grid_frequency", SCAN_INTERVAL, "50.0", id="reading" + ), + pytest.param( + BUTTON_DOMAIN, + "rtc_sync", + SETTINGS_SCAN_INTERVAL, + STATE_UNKNOWN, + id="button", + ), + ], +) +@pytest.mark.usefixtures("mock_get_unit") +async def test_setup_while_asleep_fills_in_a_mask_typed_inverter( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_connection: MockModbusConnection, + entity_registry: er.EntityRegistry, + platform: str, + key: str, + interval: int, + state: str, +) -> None: + """Test a silent restart fills in what only the masks' type allows.""" + entry = _unrecognized_entry(mock_connection) + unit = mock_connection.for_unit(1) + declare_pv_in_masks(unit) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + unit.fail_requests(ModbusTimeoutError("asleep")) + await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + unit.fail_requests(None) + freezer.tick(timedelta(seconds=interval)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + entity_id = entity_registry.async_get_entity_id( + platform, DOMAIN, f"{MOCK_UNRECOGNIZED_SERIAL}_{key}" + ) + assert entity_id is not None + assert hass.states.get(entity_id).state == state + + @pytest.mark.usefixtures("mock_get_unit") async def test_setup_while_asleep_keeps_meter_sensors_of_an_unsettled_type( hass: HomeAssistant, @@ -1075,23 +1209,15 @@ async def test_a_removed_pack_comes_back_without_a_restart( @pytest.mark.parametrize( - ("data", "expected"), + "data", [ - 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, HAS_FAULT_LOG: True, LAST_HANDLED_FAULT: None}, - id="reconfigured_while_disabled", - ), + pytest.param(MOCK_TCP_INPUT, id="legacy_tcp"), + pytest.param(MOCK_SERIAL_ENTRY_DATA, id="reconfigured_while_disabled"), ], ) @pytest.mark.usefixtures("mock_get_unit") async def test_migrate_entry_adds_the_connection_type( - hass: HomeAssistant, data: dict[str, Any], expected: dict[str, Any] + hass: HomeAssistant, snapshot: SnapshotAssertion, data: dict[str, Any] ) -> None: """Test migration marks legacy entries as TCP and keeps a set type.""" entry = MockConfigEntry( @@ -1107,15 +1233,15 @@ async def test_migrate_entry_adds_the_connection_type( await hass.async_block_till_done(wait_background_tasks=True) assert entry.minor_version == 2 - assert entry.data == expected + assert entry.data == snapshot @pytest.mark.parametrize( - ("stored", "log_error", "expected_stored", "has_event"), + ("stored", "log_error", "log_stored", "has_event"), [ pytest.param({}, None, True, True, id="first_good_setup_stores_it"), pytest.param( - {HAS_FAULT_LOG: True}, + {SERVED_COMPONENTS: [FAULT_LOG]}, ModbusTimeoutError("stuck"), True, True, @@ -1124,10 +1250,17 @@ async def test_migrate_entry_adds_the_connection_type( pytest.param( {}, ModbusTimeoutError("stuck"), - None, + False, False, id="unknown_log_timing_out_is_not_stored", ), + pytest.param( + {"has_fault_log": True}, + ModbusTimeoutError("stuck"), + False, + False, + id="beta_flag_alone_probes_again", + ), ], ) @pytest.mark.usefixtures("mock_get_unit") @@ -1137,7 +1270,7 @@ async def test_setup_remembers_the_fault_log( mock_connection: MockModbusConnection, stored: dict[str, Any], log_error: ModbusError | None, - expected_stored: bool | None, + log_stored: bool, has_event: bool, ) -> None: """Test a fault log once seen keeps its event through a failed read.""" @@ -1153,7 +1286,7 @@ async def test_setup_remembers_the_fault_log( 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 (FAULT_LOG in entry.data[SERVED_COMPONENTS]) is log_stored assert ( entity_registry.async_get_entity_id( EVENT_DOMAIN, DOMAIN, f"{MOCK_SERIAL}_fault"