-
-
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 2 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,7 @@ def __init__( | |||||||||||||||||||||||||
| if isinstance(description, SigenergySensorEntityDescription) | ||||||||||||||||||||||||||
| else None | ||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||
| 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 +244,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.warning( | ||||||||||||||||||||||||||
| "[%s] Ignoring transient daily energy drop to 0 outside reset window (last=%s)", | ||||||||||||||||||||||||||
| self.entity_id, | ||||||||||||||||||||||||||
| self._last_valid_daily_energy_value, | ||||||||||||||||||||||||||
| ) | ||||||||||||||||||||||||||
| return None | ||||||||||||||||||||||||||
|
||||||||||||||||||||||||||
| _LOGGER.warning( | |
| "[%s] Ignoring transient daily energy drop to 0 outside reset window (last=%s)", | |
| self.entity_id, | |
| self._last_valid_daily_energy_value, | |
| ) | |
| return None | |
| _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 |
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.
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 _last_valid_daily_energy_value = 14.0), and doesn't recover until after the post-midnight window closes (e.g. 00:21), the inverter correctly reports 0 (daily counter has reset) but the guard sees:
value_dec == 0✓_last_valid_daily_energy_value = 14.0 > 0✓_is_near_daily_reset()→False(00:21 is outside the ±20 min window) ✓
The 0 is suppressed and unavailable is published instead.
This does not cause phantom energy (HA's total_increasing will handle the eventual reset correctly once production provides a non-zero reading), but it delays acknowledgment of the midnight reset and leaves daily sensors as unavailable until first real post-sunrise activity — which can look alarming in the Energy Dashboard and may interfere with automations that rely on a clean 0 at start of day.
One approach is to track the wall-clock timestamp of the last non-None reading and, if the gap exceeds a threshold (e.g. 30 min), allow the 0 through unconditionally as a probable legitimate counter reset rather than a transient glitch:
# 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 0 through regardless.
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.
_last_valid_daily_energy_value updates on value_dec == 0 during midnight window
When a midnight-window 0 passes the guard (intentionally allowed), _last_valid_daily_energy_value is set to Decimal(0). This is actually correct — once the daily counter legitimately resets, future 0 polls should not fire the guard (> 0 check prevents it). However, consider adding a short comment here to make the intent explicit, since a reader could easily assume the update should only happen for non-zero values:
| self._last_valid_daily_energy_value = value_dec | |
| return value | |
| # Update reference only for non-suppressed values (includes legitimate midnight 0 resets). | |
| self._last_valid_daily_energy_value = value_dec | |
| return value |
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!
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.