From 70c83ea8d7edb4f8b52dbdd550d58bce2f9e0211 Mon Sep 17 00:00:00 2001 From: darkrain-nl Date: Tue, 20 Oct 2026 09:09:49 +0200 Subject: [PATCH] Add Sofar battery cut-off SOC sensors (#187387) --- homeassistant/components/sofar/icons.json | 12 + homeassistant/components/sofar/sensor.py | 57 +++++ homeassistant/components/sofar/strings.json | 12 + tests/components/sofar/__init__.py | 17 ++ .../sofar/snapshots/test_sensor.ambr | 210 +++++++++++++++++- tests/components/sofar/test_sensor.py | 122 +++++++++- 6 files changed, 425 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/sofar/icons.json b/homeassistant/components/sofar/icons.json index 34798ee1ed38..8e537b4c8dba 100644 --- a/homeassistant/components/sofar/icons.json +++ b/homeassistant/components/sofar/icons.json @@ -12,6 +12,9 @@ "bat_config_capacity": { "default": "mdi:battery-check-outline" }, + "bat_config_charge_cutoff_soc": { + "default": "mdi:battery-arrow-up-outline" + }, "bat_config_depth_of_discharge": { "default": "mdi:battery-check-outline" }, @@ -27,6 +30,15 @@ "battery_state_of_health_total": { "default": "mdi:battery-heart" }, + "off_grid_discharge_cutoff_soc": { + "default": "mdi:battery-arrow-down-outline" + }, + "off_grid_recovery_soc": { + "default": "mdi:battery-sync-outline" + }, + "on_grid_discharge_cutoff_soc": { + "default": "mdi:battery-arrow-down-outline" + }, "state_of_health": { "default": "mdi:battery-heart" } diff --git a/homeassistant/components/sofar/sensor.py b/homeassistant/components/sofar/sensor.py index 0378a92c4cf5..0425a2a45ea9 100644 --- a/homeassistant/components/sofar/sensor.py +++ b/homeassistant/components/sofar/sensor.py @@ -287,6 +287,21 @@ def _part_value_fn( return lambda device: value_fn(device, number) +def _discharge_cutoff_soc(depth: int | None) -> int | None: + """Return the charge left once the battery has discharged by depth.""" + return None if depth is None else 100 - depth + + +def _off_grid_recovery_soc(device: SofarInverter) -> int | None: + """Return the charge at which off-grid discharge resumes.""" + config = device.battery_config + if (cutoff := _discharge_cutoff_soc(config.bat_config_end_of_discharge)) is None: + return None + if (buffer := config.bat_config_eps_buffer) is None: + return None + return cutoff + buffer + + SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( SofarSensorDescription( key="pv_power_total", @@ -1412,6 +1427,48 @@ SENSOR_DESCRIPTIONS: tuple[SofarSensorDescription, ...] = ( entity_registry_enabled_default=False, value_fn=lambda device: device.battery_config.bat_config_voltage_float, ), + SofarSensorDescription( + key="on_grid_discharge_cutoff_soc", + component="battery_config", + translation_key="on_grid_discharge_cutoff_soc", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + value_fn=lambda device: _discharge_cutoff_soc( + device.battery_config.bat_config_depth_of_discharge + ), + ), + SofarSensorDescription( + key="off_grid_discharge_cutoff_soc", + component="battery_config", + translation_key="off_grid_discharge_cutoff_soc", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + value_fn=lambda device: _discharge_cutoff_soc( + device.battery_config.bat_config_end_of_discharge + ), + ), + SofarSensorDescription( + key="off_grid_recovery_soc", + component="battery_config", + translation_key="off_grid_recovery_soc", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + value_fn=_off_grid_recovery_soc, + ), + SofarSensorDescription( + key="bat_config_charge_cutoff_soc", + component="battery_charge_cutoff", + translation_key="bat_config_charge_cutoff_soc", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + value_fn=lambda device: ( + device.battery_charge_cutoff.bat_config_charge_cutoff_soc + ), + ), SofarSensorDescription( key="sync_rtc_result", component="rtc_sync", diff --git a/homeassistant/components/sofar/strings.json b/homeassistant/components/sofar/strings.json index b56222b1b08c..f7acde4b448f 100644 --- a/homeassistant/components/sofar/strings.json +++ b/homeassistant/components/sofar/strings.json @@ -247,6 +247,9 @@ "ternary": "Ternary" } }, + "bat_config_charge_cutoff_soc": { + "name": "Charge cut-off state of charge" + }, "bat_config_charging_voltage": { "name": "Battery config charging voltage" }, @@ -408,6 +411,12 @@ "module_temperature_2": { "name": "Module temperature 2" }, + "off_grid_discharge_cutoff_soc": { + "name": "Off-grid discharge cut-off state of charge" + }, + "off_grid_recovery_soc": { + "name": "Off-grid discharge recovery state of charge" + }, "offgrid_active_power_output": { "name": "Off-grid active power output" }, @@ -501,6 +510,9 @@ "offgrid_voltage_output_l2n": { "name": "Off-grid voltage output L2N" }, + "on_grid_discharge_cutoff_soc": { + "name": "On-grid discharge cut-off state of charge" + }, "passive_eps_wait_time": { "name": "EPS wait time" }, diff --git a/tests/components/sofar/__init__.py b/tests/components/sofar/__init__.py index e8d107e4674b..4d98879ba015 100644 --- a/tests/components/sofar/__init__.py +++ b/tests/components/sofar/__init__.py @@ -1,5 +1,6 @@ """Tests for the Sofar integration.""" +from modbus_connection import ModbusError from modbus_connection.mock import MockModbusUnit from homeassistant.components.sofar.const import ( @@ -79,6 +80,16 @@ def serve_meter_energy(unit: MockModbusUnit) -> None: unit.holding[0x068B] = 10000 # load_consumption_total -> 1000.0 kWh +def deny_charge_cutoff(unit: MockModbusUnit) -> None: + """Seed a battery config mask that leaves out 0x105B.""" + unit.holding[0x1042] = 0x0000 + + +def refuse_battery_config_mask(unit: MockModbusUnit) -> None: + """Seed a model that publishes no battery config mask.""" + unit.fail_read(0x1040, ModbusError("illegal data address")) + + def declare_pv_in_masks(unit: MockModbusUnit) -> None: """Seed masks declaring a three-phase PV model with two strings.""" # Each mask's lowest word sits at base+3; bits 0-3 make it usable. @@ -97,3 +108,9 @@ def seed_hybrid_inverter( unit.holding[0x0608] = 87 # battery_capacity_1 -> 87% unit.holding[0x0612] = 515 # battery_voltage_3 -> 51.5 V unit.holding[0x0616] = 85 # battery_capacity_3 -> 85% + unit.holding[0x104D] = 73 # depth of discharge -> 27% on-grid cut-off + unit.holding[0x104E] = 90 # end of discharge -> 10% off-grid cut-off + unit.holding[0x1052] = 5 # EPS buffer -> 15% off-grid recovery + unit.holding[0x1042] = 0x0800 # 0x105B, the charge cut-off, is served + unit.holding[0x1043] = 0x000F + unit.holding[0x105B] = 95 # charge cut-off -> 95% diff --git a/tests/components/sofar/snapshots/test_sensor.ambr b/tests/components/sofar/snapshots/test_sensor.ambr index 0a8e891fee8f..c99cd92b7dcf 100644 --- a/tests/components/sofar/snapshots/test_sensor.ambr +++ b/tests/components/sofar/snapshots/test_sensor.ambr @@ -2058,7 +2058,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0', + 'state': '73', }) # --- # name: test_all_entities[sensor.hydxxktl_3p_battery_config_end_of_discharge-entry] @@ -2109,7 +2109,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0', + 'state': '90', }) # --- # name: test_all_entities[sensor.hydxxktl_3p_battery_config_eps_buffer-entry] @@ -2160,7 +2160,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0', + 'state': '5', }) # --- # name: test_all_entities[sensor.hydxxktl_3p_battery_config_lead_acid_float_voltage-entry] @@ -3077,6 +3077,57 @@ 'state': '0', }) # --- +# name: test_all_entities[sensor.hydxxktl_3p_charge_cut_off_state_of_charge-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.hydxxktl_3p_charge_cut_off_state_of_charge', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Charge cut-off state of charge', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Charge cut-off state of charge', + 'platform': 'sofar', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'bat_config_charge_cutoff_soc', + 'unique_id': 'SP1XXES100XX_bat_config_charge_cutoff_soc', + 'unit_of_measurement': '%', + }) +# --- +# name: test_all_entities[sensor.hydxxktl_3p_charge_cut_off_state_of_charge-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'HYDxxKTL-3P Charge cut-off state of charge', + : '%', + }), + 'context': , + 'entity_id': 'sensor.hydxxktl_3p_charge_cut_off_state_of_charge', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '95', + }) +# --- # name: test_all_entities[sensor.hydxxktl_3p_current_output_l1-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -5304,6 +5355,108 @@ 'state': '0.0', }) # --- +# name: test_all_entities[sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Off-grid discharge cut-off state of charge', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Off-grid discharge cut-off state of charge', + 'platform': 'sofar', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'off_grid_discharge_cutoff_soc', + 'unique_id': 'SP1XXES100XX_off_grid_discharge_cutoff_soc', + 'unit_of_measurement': '%', + }) +# --- +# name: test_all_entities[sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'HYDxxKTL-3P Off-grid discharge cut-off state of charge', + : '%', + }), + 'context': , + 'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '10', + }) +# --- +# name: test_all_entities[sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Off-grid discharge recovery state of charge', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Off-grid discharge recovery state of charge', + 'platform': 'sofar', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'off_grid_recovery_soc', + 'unique_id': 'SP1XXES100XX_off_grid_recovery_soc', + 'unit_of_measurement': '%', + }) +# --- +# name: test_all_entities[sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'HYDxxKTL-3P Off-grid discharge recovery state of charge', + : '%', + }), + 'context': , + 'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '15', + }) +# --- # name: test_all_entities[sensor.hydxxktl_3p_off_grid_frequency-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ @@ -5991,6 +6144,57 @@ 'state': '0.0', }) # --- +# name: test_all_entities[sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'On-grid discharge cut-off state of charge', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'On-grid discharge cut-off state of charge', + 'platform': 'sofar', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'on_grid_discharge_cutoff_soc', + 'unique_id': 'SP1XXES100XX_on_grid_discharge_cutoff_soc', + 'unit_of_measurement': '%', + }) +# --- +# name: test_all_entities[sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'HYDxxKTL-3P On-grid discharge cut-off state of charge', + : '%', + }), + 'context': , + 'entity_id': 'sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '27', + }) +# --- # name: test_all_entities[sensor.hydxxktl_3p_passive_mode_grid_power-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/sofar/test_sensor.py b/tests/components/sofar/test_sensor.py index 948990ac23dc..65bb2d909725 100644 --- a/tests/components/sofar/test_sensor.py +++ b/tests/components/sofar/test_sensor.py @@ -35,10 +35,19 @@ from . import ( MOCK_HYBRID_SERIAL, MOCK_MODEL, MOCK_SERIAL, + deny_charge_cutoff, + refuse_battery_config_mask, seed_hybrid_inverter, seed_pv_inverter, ) +# Values the app shows, worked out from other battery_config fields. +DERIVED_KEYS = { + "on_grid_discharge_cutoff_soc", + "off_grid_discharge_cutoff_soc", + "off_grid_recovery_soc", +} + @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_all_entities( @@ -78,7 +87,7 @@ def test_sensor_description_components_are_real() -> None: for description in (*SENSOR_DESCRIPTIONS, *TOTAL_SENSOR_DESCRIPTIONS): component = getattr(inverter, description.component, None) assert component is not None, f"unknown component {description.component!r}" - assert hasattr(component, description.key), ( + assert description.key in DERIVED_KEYS or hasattr(component, description.key), ( f"{description.component}.{description.key} does not exist" ) @@ -112,7 +121,7 @@ async def test_sensor_entities_created_and_state( MOCK_HYBRID_SERIAL, MOCK_HYBRID_MODEL, seed_hybrid_inverter, - 145, + 149, 44, id="hybrid", ), @@ -333,6 +342,7 @@ async def test_sensor_availability_on_component_failure( [ pytest.param(description, id=description.key) for description in SENSOR_DESCRIPTIONS + if description.key not in DERIVED_KEYS ], ) async def test_value_fn_reads_the_field_its_key_names( @@ -346,6 +356,114 @@ async def test_value_fn_reads_the_field_its_key_names( assert description.value_fn(device) is sentinel +@pytest.mark.parametrize( + ("key", "values", "expected"), + [ + pytest.param( + "on_grid_discharge_cutoff_soc", + {"bat_config_depth_of_discharge": 73}, + 27, + id="on_grid", + ), + pytest.param( + "on_grid_discharge_cutoff_soc", + {"bat_config_depth_of_discharge": None}, + None, + id="on_grid_unread", + ), + pytest.param( + "off_grid_discharge_cutoff_soc", + {"bat_config_end_of_discharge": 90}, + 10, + id="off_grid", + ), + pytest.param( + "off_grid_discharge_cutoff_soc", + {"bat_config_end_of_discharge": None}, + None, + id="off_grid_unread", + ), + pytest.param( + "off_grid_recovery_soc", + {"bat_config_end_of_discharge": 90, "bat_config_eps_buffer": 5}, + 15, + id="recovery", + ), + pytest.param( + "off_grid_recovery_soc", + {"bat_config_end_of_discharge": None, "bat_config_eps_buffer": 5}, + None, + id="recovery_end_of_discharge_unread", + ), + pytest.param( + "off_grid_recovery_soc", + {"bat_config_end_of_discharge": 90, "bat_config_eps_buffer": None}, + None, + id="recovery_eps_buffer_unread", + ), + ], +) +async def test_derived_cutoff_soc( + init_integration: MockConfigEntry, + key: str, + values: dict[str, int | None], + expected: int | None, +) -> None: + """Test cut-off sensors show what the SofarCloud app shows.""" + device = init_integration.runtime_data.readings.device + with patch.dict(device.battery_config._values, values): + assert ( + next(d for d in SENSOR_DESCRIPTIONS if d.key == key).value_fn(device) + == expected + ) + + +@pytest.mark.parametrize( + "hide_charge_cutoff", + [ + pytest.param(deny_charge_cutoff, id="mask_denies"), + pytest.param(refuse_battery_config_mask, id="no_mask"), + ], +) +async def test_charge_cutoff_needs_a_declaring_mask( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + hide_charge_cutoff: Callable[[MockModbusUnit], None], +) -> None: + """Test a hybrid gets no charge cut-off unless its mask declares it.""" + connection = MockModbusConnection() + unit = connection.for_unit(1) + seed_hybrid_inverter(unit) + hide_charge_cutoff(unit) + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=MOCK_HYBRID_SERIAL, + data=MOCK_ENTRY_DATA, + title=MOCK_HYBRID_MODEL, + ) + entry.add_to_hass(hass) + with patch( + "homeassistant.components.sofar.async_get_unit", + side_effect=lambda hass, entry, params, unit_id: connection.for_unit(unit_id), + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + entity_registry.async_get_entity_id( + SENSOR_DOMAIN, DOMAIN, f"{MOCK_HYBRID_SERIAL}_bat_config_charge_cutoff_soc" + ) + is None + ) + # The rest of the battery config does not need the mask. + assert ( + entity_registry.async_get_entity_id( + SENSOR_DOMAIN, DOMAIN, f"{MOCK_HYBRID_SERIAL}_on_grid_discharge_cutoff_soc" + ) + is not None + ) + + @pytest.mark.parametrize( "description", [