Allow negative Fronius battery limits to force the battery (#185435)

This commit is contained in:
Elmar
2026-10-27 08:05:19 +01:00
committed by GitHub
parent d9fdd8435c
commit 82ad053376
5 changed files with 221 additions and 6 deletions
@@ -3,12 +3,13 @@
from abc import ABC, abstractmethod
import asyncio
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, cast, override
from typing import TYPE_CHECKING, Any, Final, cast, override
from fronius_modbus import (
Controls,
FroniusModbusInverter,
Mppt,
Storage,
SunSpecError,
SunSpecMapShiftError,
)
@@ -25,7 +26,7 @@ from fronius_solarapi import (
from modbus_connection import ModbusError
from homeassistant.core import CALLBACK_TYPE, callback
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from homeassistant.helpers.event import async_call_later
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@@ -380,6 +381,17 @@ class FroniusModbusSettingsUpdateCoordinator(FroniusModbusCoordinatorBase):
and component.revert_seconds != self._revert_seconds
):
await component.write("revert_seconds", self._revert_seconds)
if isinstance(component, Storage) and (
refused := _refused_battery_limits(component, field, value)
):
raise ServiceValidationError(
translation_domain=DOMAIN,
translation_key="battery_limits_conflict",
translation_placeholders={
"charge_limit": f"{refused[0]:g}",
"discharge_limit": f"{refused[1]:g}",
},
)
await component.write(field, value)
if enable_field is not None and getattr(component, enable_field):
await component.write(enable_field, True)
@@ -418,6 +430,48 @@ class FroniusModbusSettingsUpdateCoordinator(FroniusModbusCoordinatorBase):
return self._as_device_data(values)
BATTERY_LIMIT_FIELDS: Final = frozenset(
{
"charge_limit",
"discharge_limit",
"charge_limit_enabled",
"discharge_limit_enabled",
}
)
def _refused_battery_limits(
storage: Storage, field: str, value: float | bool
) -> tuple[float, float] | None:
"""Return the charge and discharge limit a write would leave refused.
With both limits enabled, battery power has to fit between the negated
discharge rate and the charge rate. A Gen24 refuses an empty window -
both rates negative, or a charge limit below a forced charging rate -
when the second limit is enabled, and answers with a bare Modbus error.
Other settings of the model stay writable whatever the limits are.
"""
if field not in BATTERY_LIMIT_FIELDS:
return None
limits = {
"charge_limit": storage.charge_limit,
"discharge_limit": storage.discharge_limit,
"charge_limit_enabled": storage.charge_limit_enabled,
"discharge_limit_enabled": storage.discharge_limit_enabled,
field: value,
}
charge, discharge = limits["charge_limit"], limits["discharge_limit"]
if (
limits["charge_limit_enabled"] is True
and limits["discharge_limit_enabled"] is True
and charge is not None
and discharge is not None
and charge + discharge < 0
):
return charge, discharge
return None
class FroniusLoggerUpdateCoordinator(FroniusCoordinatorBase[LoggerInfo]):
"""Query Fronius logger info endpoint."""
+5 -2
View File
@@ -49,6 +49,9 @@ def _modbus_value(key: str) -> Callable[[ModbusValues], float | None]:
return lambda values: values.get(key)
# The battery rates are signed: a negative one turns the direction around, so
# a discharge limit of -100% forces charging at full power - the registers as
# Fronius documents them and other controllers write them.
MODBUS_NUMBER_ENTITY_DESCRIPTIONS: list[FroniusNumberEntityDescription] = [
FroniusNumberEntityDescription(
key="ac_power_limit",
@@ -69,7 +72,7 @@ MODBUS_NUMBER_ENTITY_DESCRIPTIONS: list[FroniusNumberEntityDescription] = [
field="charge_limit",
enable_field="charge_limit_enabled",
native_unit_of_measurement=PERCENTAGE,
native_min_value=0,
native_min_value=-100,
native_max_value=100,
native_step=1,
entity_category=EntityCategory.CONFIG,
@@ -81,7 +84,7 @@ MODBUS_NUMBER_ENTITY_DESCRIPTIONS: list[FroniusNumberEntityDescription] = [
field="discharge_limit",
enable_field="discharge_limit_enabled",
native_unit_of_measurement=PERCENTAGE,
native_min_value=0,
native_min_value=-100,
native_max_value=100,
native_step=1,
entity_category=EntityCategory.CONFIG,
@@ -449,6 +449,9 @@
}
},
"exceptions": {
"battery_limits_conflict": {
"message": "The inverter refuses a charge limit of {charge_limit}% together with a discharge limit of {discharge_limit}% while both limits are enabled. A negative limit forces the opposite direction and must not exceed the other limit, so the two have to add up to at least 0%. Change one of them or turn its limiting off first."
},
"entry_cannot_connect": {
"message": "Failed to connect to Fronius device at {host}: {fronius_error}"
},
+98 -1
View File
@@ -16,13 +16,14 @@ from homeassistant.components.number import (
)
from homeassistant.const import ATTR_ENTITY_ID, Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from . import mock_responses, setup_fronius_integration
from .test_modbus import GEN24_HYBRID_MODULES, assert_state
POWER_LIMIT = "number.gen24_storage_ac_power_limit"
CHARGE_LIMIT = "number.gen24_storage_battery_charge_power_limit"
DISCHARGE_LIMIT = "number.gen24_storage_battery_discharge_power_limit"
async def _setup(
@@ -140,6 +141,102 @@ async def test_battery_setpoint_leaves_the_mode_bits_alone(
assert storage.discharge_limit_enabled is False
@pytest.mark.parametrize(
("entity_id", "field"),
[(CHARGE_LIMIT, "charge_limit"), (DISCHARGE_LIMIT, "discharge_limit")],
)
async def test_battery_rates_are_signed(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_fronius_modbus: MockModbusConnection,
entity_id: str,
field: str,
) -> None:
"""Test a negative battery rate is written - it forces the other way."""
config_entry = await _setup(hass, aioclient_mock, mock_fronius_modbus)
storage = config_entry.runtime_data.modbus_settings_coordinators[
0
].modbus_inverter.storage
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: -50},
blocking=True,
)
await hass.async_block_till_done()
assert_state(hass, entity_id, -50.0)
assert getattr(storage, field) == -50.0
async def _limit_both_ways(config_entry: MockConfigEntry, charge_limit: float) -> None:
"""Enable both battery limits, the charge limit at the given rate."""
coordinator = config_entry.runtime_data.modbus_settings_coordinators[0]
for field, value in (
("charge_limit", charge_limit),
("charge_limit_enabled", True),
("discharge_limit_enabled", True),
):
await coordinator.async_write(lambda inverter: inverter.storage, field, value)
async def test_forcing_within_the_other_limit(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_fronius_modbus: MockModbusConnection,
) -> None:
"""Test forcing up to the other active limit is written."""
config_entry = await _setup(hass, aioclient_mock, mock_fronius_modbus)
storage = config_entry.runtime_data.modbus_settings_coordinators[
0
].modbus_inverter.storage
await _limit_both_ways(config_entry, 100)
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: DISCHARGE_LIMIT, ATTR_VALUE: -100},
blocking=True,
)
assert storage.discharge_limit == -100.0
@pytest.mark.parametrize("charge_limit", [40, 0])
async def test_forcing_beyond_the_other_limit_is_refused(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_fronius_modbus: MockModbusConnection,
charge_limit: float,
) -> None:
"""Test a forcing rate beyond the other active limit is refused up front.
With both limits on, the device refuses a charge limit below the negated
discharge limit - with a bare Modbus error, so it is caught before.
"""
config_entry = await _setup(hass, aioclient_mock, mock_fronius_modbus)
storage = config_entry.runtime_data.modbus_settings_coordinators[
0
].modbus_inverter.storage
await _limit_both_ways(config_entry, charge_limit)
with pytest.raises(ServiceValidationError) as err:
await hass.services.async_call(
NUMBER_DOMAIN,
SERVICE_SET_VALUE,
{ATTR_ENTITY_ID: DISCHARGE_LIMIT, ATTR_VALUE: -100},
blocking=True,
)
assert err.value.translation_key == "battery_limits_conflict"
assert err.value.translation_placeholders == {
"charge_limit": f"{charge_limit:g}",
"discharge_limit": "-100",
}
assert storage.discharge_limit == 0.0
async def test_a_refused_write_raises(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
+59 -1
View File
@@ -19,7 +19,7 @@ from homeassistant.const import (
Platform,
)
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.exceptions import HomeAssistantError, ServiceValidationError
from . import mock_responses, setup_fronius_integration
from .test_modbus import GEN24_HYBRID_MODULES, assert_state
@@ -132,6 +132,64 @@ async def test_turning_a_limit_on_asserts_its_setpoint(
assert controls.power_limit == 100.0
async def test_enabling_a_limit_into_an_empty_window_is_refused(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_fronius_modbus: MockModbusConnection,
) -> None:
"""Test turning on a limit the device would refuse with the other one."""
config_entry = await _setup(hass, aioclient_mock, mock_fronius_modbus)
coordinator = config_entry.runtime_data.modbus_settings_coordinators[0]
storage = coordinator.modbus_inverter.storage
for field, value in (
("charge_limit", -50),
("discharge_limit", -50),
("charge_limit_enabled", True),
):
await coordinator.async_write(lambda inverter: inverter.storage, field, value)
with pytest.raises(ServiceValidationError):
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TURN_ON,
{ATTR_ENTITY_ID: DISCHARGE_LIMITING},
blocking=True,
)
assert storage.discharge_limit_enabled is False
async def test_other_settings_stay_writable_with_refused_limits(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
mock_fronius_modbus: MockModbusConnection,
) -> None:
"""Test the limit guard doesn't block settings that don't touch the limits.
Another controller may leave limits the device would refuse; grid
charging has to stay switchable regardless.
"""
config_entry = await _setup(hass, aioclient_mock, mock_fronius_modbus)
storage = config_entry.runtime_data.modbus_settings_coordinators[
0
].modbus_inverter.storage
# written past the guard, as another controller would
for field, value in (
("charge_limit", -50),
("discharge_limit", -50),
("charge_limit_enabled", True),
("discharge_limit_enabled", True),
):
await storage.write(field, value)
await hass.services.async_call(
SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: GRID_CHARGING}, blocking=True
)
await hass.async_block_till_done()
assert_state(hass, GRID_CHARGING, STATE_ON)
async def test_a_refused_write_raises(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,