-
-
Notifications
You must be signed in to change notification settings - Fork 25
Fix daily energy zero-bounce spikes during reconnect #314
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -4,6 +4,7 @@ | |||||||||||
| import logging | ||||||||||||
| from typing import Any, Optional, cast | ||||||||||||
| from decimal import Decimal, InvalidOperation | ||||||||||||
| from datetime import timedelta | ||||||||||||
|
|
||||||||||||
| from homeassistant.components.sensor import ( | ||||||||||||
| SensorDeviceClass, | ||||||||||||
|
|
@@ -20,6 +21,7 @@ | |||||||||||
| from homeassistant.core import HomeAssistant | ||||||||||||
| from homeassistant.helpers.entity import DeviceInfo | ||||||||||||
| from homeassistant.helpers.entity_platform import AddEntitiesCallback | ||||||||||||
| from homeassistant.util import dt as dt_util | ||||||||||||
|
|
||||||||||||
| from .modbusregisterdefinitions import ( | ||||||||||||
| RunningState, | ||||||||||||
|
|
@@ -35,7 +37,7 @@ | |||||||||||
| ) | ||||||||||||
| from .static_sensor import StaticSensors as SS | ||||||||||||
| from .static_sensor import COORDINATOR_DIAGNOSTIC_SENSORS # Import the new descriptions | ||||||||||||
| from .common import generate_sigen_entity, generate_device_id, SigenergySensorEntityDescription, SensorEntityDescription | ||||||||||||
| from .common import generate_sigen_entity, generate_device_id, SigenergySensorEntityDescription, SensorEntityDescription, safe_decimal | ||||||||||||
| from .const import ( | ||||||||||||
| DOMAIN, | ||||||||||||
| DEVICE_TYPE_PLANT, | ||||||||||||
|
|
@@ -50,6 +52,18 @@ | |||||||||||
| _LOGGER = logging.getLogger(__name__) | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| PROTECTED_DAILY_ENERGY_KEYS = { | ||||||||||||
| "plant_daily_pv_energy", | ||||||||||||
| "plant_daily_battery_charge_energy", | ||||||||||||
| "plant_daily_battery_discharge_energy", | ||||||||||||
| "inverter_daily_pv_energy", | ||||||||||||
| "inverter_ess_daily_charge_energy", | ||||||||||||
| "inverter_ess_daily_discharge_energy", | ||||||||||||
| } | ||||||||||||
|
|
||||||||||||
| DAILY_RESET_GUARD_WINDOW = timedelta(minutes=20) | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| async def async_setup_entry( | ||||||||||||
| hass: HomeAssistant, | ||||||||||||
| config_entry: ConfigEntry, | ||||||||||||
|
|
@@ -201,6 +215,9 @@ def __init__( | |||||||||||
| if isinstance(description, SigenergySensorEntityDescription) | ||||||||||||
| else None | ||||||||||||
| ) | ||||||||||||
| # In-memory only: this resets on HA restart, so the first post-restart poll | ||||||||||||
| # has no historical reference and is intentionally passed through. | ||||||||||||
| self._last_valid_daily_energy_value: Decimal | None = None | ||||||||||||
|
|
||||||||||||
| def _decode_alarm_bits(self, value: int, alarm_mapping: dict) -> str: | ||||||||||||
| """Decode alarm bits into human-readable text.""" | ||||||||||||
|
|
@@ -229,6 +246,44 @@ def _get_raw_value(self) -> Any: | |||||||||||
| return data.get("dc_chargers", {}).get(self._device_name, {}).get(self.entity_description.key) | ||||||||||||
| return None | ||||||||||||
|
|
||||||||||||
| def _is_near_daily_reset(self) -> bool: | ||||||||||||
| """Return True in a symmetric window around midnight.""" | ||||||||||||
| now = dt_util.now() | ||||||||||||
| seconds_since_midnight = ( | ||||||||||||
| now.hour * 3600 + now.minute * 60 + now.second + now.microsecond / 1_000_000 | ||||||||||||
| ) | ||||||||||||
| distance_to_midnight = min(seconds_since_midnight, 86400 - seconds_since_midnight) | ||||||||||||
| return distance_to_midnight <= DAILY_RESET_GUARD_WINDOW.total_seconds() | ||||||||||||
|
|
||||||||||||
| def _apply_daily_energy_zero_guard(self, value: Any) -> Any: | ||||||||||||
| """Prevent transient zero-bounce for daily total_increasing energy sensors.""" | ||||||||||||
| key = getattr(self.entity_description, "key", None) | ||||||||||||
| if key not in PROTECTED_DAILY_ENERGY_KEYS: | ||||||||||||
| return value | ||||||||||||
|
|
||||||||||||
| if value is None: | ||||||||||||
| return None | ||||||||||||
|
|
||||||||||||
| value_dec = safe_decimal(value) | ||||||||||||
| if value_dec is None: | ||||||||||||
| return value | ||||||||||||
|
|
||||||||||||
| if ( | ||||||||||||
| value_dec == 0 | ||||||||||||
| and self._last_valid_daily_energy_value is not None | ||||||||||||
| and self._last_valid_daily_energy_value > 0 | ||||||||||||
| and not self._is_near_daily_reset() | ||||||||||||
| ): | ||||||||||||
| _LOGGER.debug( | ||||||||||||
| "[%s] Ignoring transient daily energy drop to 0 outside reset window (last=%s)", | ||||||||||||
| self.entity_id, | ||||||||||||
| self._last_valid_daily_energy_value, | ||||||||||||
| ) | ||||||||||||
| return None | ||||||||||||
|
|
||||||||||||
| self._last_valid_daily_energy_value = value_dec | ||||||||||||
| return value | ||||||||||||
|
Comment on lines
+271
to
+285
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Extended outage crossing midnight suppresses legitimate reset If HA stays running but the Modbus/network connection drops before the pre-midnight window opens (e.g. connection goes offline at 23:39, last poll left
The This does not cause phantom energy (HA's One approach is to track the wall-clock timestamp of the last non- # In __init__
self._last_successful_daily_energy_ts: datetime | None = None
# In _apply_daily_energy_zero_guard, replace the suppression block:
STALE_THRESHOLD = timedelta(minutes=30)
now = dt_util.now()
stale = (
self._last_successful_daily_energy_ts is None
or (now - self._last_successful_daily_energy_ts) > STALE_THRESHOLD
)
if (
value_dec == 0
and self._last_valid_daily_energy_value is not None
and self._last_valid_daily_energy_value > 0
and not self._is_near_daily_reset()
and not stale
):
... # suppressThis keeps the glitch protection for short outages while allowing long-gap reconnects to pass a
Comment on lines
+284
to
+285
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
When a midnight-window
Suggested change
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time! |
||||||||||||
|
|
||||||||||||
| @property | ||||||||||||
| def native_value(self) -> Any: | ||||||||||||
| """Return the state of the sensor.""" | ||||||||||||
|
|
@@ -252,8 +307,8 @@ def native_value(self) -> Any: | |||||||||||
|
|
||||||||||||
| # Round if needed | ||||||||||||
| if transformed is not None and self._round_digits is not None: | ||||||||||||
| return round(Decimal(transformed), self._round_digits) | ||||||||||||
| return transformed | ||||||||||||
| transformed = round(Decimal(transformed), self._round_digits) | ||||||||||||
| return self._apply_daily_energy_zero_guard(transformed) | ||||||||||||
| except Exception as ex: | ||||||||||||
| if raw_value is None: | ||||||||||||
| _LOGGER.debug("Value function failed for %s because data is missing: %s", self.entity_id, ex) | ||||||||||||
|
|
@@ -309,15 +364,15 @@ def native_value(self) -> Any: | |||||||||||
| "plant_grid_sensor_status": {0: "Offline", 1: "Online"}, | ||||||||||||
| } | ||||||||||||
| if self.entity_description.key in enum_maps: | ||||||||||||
| return enum_maps[self.entity_description.key].get(raw_value, f"Unknown: {raw_value}") | ||||||||||||
| return self._apply_daily_energy_zero_guard(enum_maps[self.entity_description.key].get(raw_value, f"Unknown: {raw_value}")) | ||||||||||||
|
|
||||||||||||
| if self._round_digits is not None: | ||||||||||||
| try: | ||||||||||||
| return round(Decimal(raw_value), self._round_digits) | ||||||||||||
| return self._apply_daily_energy_zero_guard(round(Decimal(raw_value), self._round_digits)) | ||||||||||||
| except (TypeError, ValueError, InvalidOperation): | ||||||||||||
| _LOGGER.warning("Could not round direct value for %s: %s", self.entity_id, raw_value) | ||||||||||||
|
|
||||||||||||
| return raw_value | ||||||||||||
| return self._apply_daily_energy_zero_guard(raw_value) | ||||||||||||
|
|
||||||||||||
|
|
||||||||||||
| class PVStringSensor(SigenergySensor): | ||||||||||||
|
|
||||||||||||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nonereturn only covers the all-invalid case; partial-offline totals still decreaseThe new
valid_sample_count == 0guard correctly prevents publishing0when every inverter is offline. However, consider a two-inverter setup where Inverter A goes offline (None, skipped) while Inverter B legitimately continues reporting. The function returns Inverter B's value alone — potentially a large drop from the previous combined total (e.g. 10 kWh → 5 kWh). This is less than zero (not caught by thesensor.pyguard which only triggers on a drop to exactly0), and HA'stotal_increasinglogic may record it as a reset.This is a pre-existing issue and this PR's scope is zero-bounce, but it's worth a comment here so the partial-offline decrease case isn't overlooked in a follow-up.