Add Sofar battery cut-off SOC sensors (#187387)

This commit is contained in:
darkrain-nl
2026-10-20 10:09:49 +03:00
committed by GitHub
parent aa40153892
commit 70c83ea8d7
6 changed files with 425 additions and 5 deletions
+12
View File
@@ -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"
}
+57
View File
@@ -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",
@@ -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"
},
+17
View File
@@ -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%
@@ -2058,7 +2058,7 @@
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '0',
'state': '73',
})
# ---
# name: test_all_entities[sensor.hydxxktl_3p_battery_config_end_of_discharge-entry]
@@ -2109,7 +2109,7 @@
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '0',
'state': '90',
})
# ---
# name: test_all_entities[sensor.hydxxktl_3p_battery_config_eps_buffer-entry]
@@ -2160,7 +2160,7 @@
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'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': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.hydxxktl_3p_charge_cut_off_state_of_charge',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'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({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'HYDxxKTL-3P Charge cut-off state of charge',
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '%',
}),
'context': <ANY>,
'entity_id': 'sensor.hydxxktl_3p_charge_cut_off_state_of_charge',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'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': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'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({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'HYDxxKTL-3P Off-grid discharge cut-off state of charge',
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '%',
}),
'context': <ANY>,
'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_cut_off_state_of_charge',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'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': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'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({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'HYDxxKTL-3P Off-grid discharge recovery state of charge',
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '%',
}),
'context': <ANY>,
'entity_id': 'sensor.hydxxktl_3p_off_grid_discharge_recovery_state_of_charge',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'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': <ANY>,
'config_subentry_id': <ANY>,
'device_class': None,
'device_id': <ANY>,
'disabled_by': None,
'domain': 'sensor',
'entity_category': <EntityCategory.DIAGNOSTIC: 'diagnostic'>,
'entity_id': 'sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'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({
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'HYDxxKTL-3P On-grid discharge cut-off state of charge',
<EntityStateAttribute.UNIT_OF_MEASUREMENT: 'unit_of_measurement'>: '%',
}),
'context': <ANY>,
'entity_id': 'sensor.hydxxktl_3p_on_grid_discharge_cut_off_state_of_charge',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '27',
})
# ---
# name: test_all_entities[sensor.hydxxktl_3p_passive_mode_grid_power-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
+120 -2
View File
@@ -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",
[