Timestamp relay changes with a read-only state listener
Polling only sees the relay's current state and last change, so two or more changes between polls (e.g. an on/off round trip) made the lag estimate unknown and paused learning for about half an hour. Subscribe to the relay's state changes (read-only) and integrate every recorded change between polls. Because HA delivers these events one loop iteration late, the current state stays authoritative and fills in a change not yet recorded. Unknown periods (non on/off states, missed transitions, event overflow) still restart the estimate with an explicit error bound. Without the listener, behavior is as before. HA skips unload callbacks after unexpected setup errors, so setup now removes the listener itself on any failure and registers it for unload only once setup succeeds. Tested on HA Core 2025.12.0 and 2026.2.3. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
af0a564279
commit
955c679f5e
6 files changed
+185
-22
No files matched your search
@@ -29,6 +29,26 @@ def advance_lag(lag: float, command: bool, seconds: float) -> float:
|
||||
return lag + (1.0 - exp(-seconds / LAG_TAU_SECONDS)) * (float(command) - lag)
|
||||
|
||||
|
||||
def relay_segments(
|
||||
start_on: bool, start: float, changes: list[tuple[float, str]], end: float,
|
||||
) -> list[tuple[bool, float]] | None:
|
||||
"""Split [start, end] into (command, seconds) segments from ordered relay changes.
|
||||
|
||||
`changes` holds (timestamp, new_state) pairs. Return None when the command is
|
||||
unknown for part of the interval: a state other than on/off, a change to the
|
||||
state already in force (so transitions were missed), or out-of-order times.
|
||||
"""
|
||||
segments: list[tuple[bool, float]] = []
|
||||
command, since = start_on, start
|
||||
for when, state in changes:
|
||||
if state not in ("on", "off") or not since <= when <= end or (state == "on") == command:
|
||||
return None
|
||||
segments.append((command, when - since))
|
||||
command, since = state == "on", when
|
||||
segments.append((command, end - since))
|
||||
return segments
|
||||
|
||||
|
||||
def lag_from_time_in_state(command: bool, seconds_in_state: float) -> tuple[float, float]:
|
||||
"""Estimate the lag when only the time since the last relay change is known.
|
||||
|
||||
|
||||
Reference in new issue
Block a user