5 Commits
Author SHA1 Message Date
rick e03dc44103 Merge agent/optimize-coordinator-tick: v0.1.2 coordinator optimizations 2026-05-09 19:13:27 +02:00
rickandCursor 24e4450bec v0.1.2: coordinator scheduling optimizations
Three focused changes to the coordinator's recompute and publish paths:

1. Drop the redundant 10-minute timer. The DataUpdateCoordinator's
   built-in update_interval and the explicit async_track_time_interval
   tick were both firing every 600 s out of phase, doubling the
   recompute rate on idle. Set update_interval=None and let the
   explicit tick own the cadence (it already owns prune side effects).

2. Per-source-event single-record update. _handle_source_update now
   calls async_set_updated_data with a shallow-copied snapshot dict
   that replaces only the changed record's CoordinatorSnapshot,
   carrying the other records' Prediction instances forward by
   reference. Replaces the previous async_request_refresh which
   triggered a full O(N) walk per source event. First-publish edge
   case (self.data is None) falls back to a complete _compute_snapshots
   so the snapshot dict is never partially populated.

3. Diff-gated heartbeat publish. The 10-minute tick now recomputes
   every record but only calls async_set_updated_data if at least one
   record's externally observable Prediction fields (replace_by,
   confidence, drain_rate_pct_day, threshold_pct) changed, or the set
   of tracked record keys changed. Idle systems where nothing
   time-driven crossed a boundary skip the publish entirely.

   The diff gate applies only to the heartbeat. Per-source events
   (#2) and user-action setters / detector commits / registry events
   keep the unconditional publish path so user-visible toggles always
   reflect immediately, even when they leave the four observable
   Prediction fields unchanged.

The heartbeat is intentionally NOT conditioned on "source value
changed" because three time-driven flips happen with no source
change: stale flip at 7-day source idleness, confidence-ladder
ratchet at 7/30/60-day boundaries, and summary-sensor cutoffs.
All three surface in Prediction, so the Prediction diff gate
preserves them while suppressing genuinely no-op publishes.

Tests: 5 new in tests/test_coordinator.py covering single-timer
contract, per-source O(1) update, idle-heartbeat skip, stale-flip
publish, and unconditional setter refresh. Full suite 112 passed
(was 107 + 5 new), zero regressions.

OpenSpec change: optimize-coordinator-tick.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 19:13:22 +02:00
rickandCursor 537945a20e openspec(optimize-coordinator-tick): propose phase artifacts
Captures the v0.1.2 coordinator optimizations: drop the redundant
10-minute timer, switch per-source-event refreshes to O(1)
async_set_updated_data, and gate the heartbeat publish on a Prediction
diff so idle systems stop fanning out no-op state writes.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-09 19:08:02 +02:00
rickandCursor 3bd221af97 Add HANDOFF.md for next session
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 19:30:45 +02:00
rickandCursor 33708ebb17 v0.1.1: warn about long initial setup; ship icon assets
- Config-flow user step now opens with a bold/all-caps warning that the
  initial setup can take several minutes on installs with many batteries
  (the user reported a multi-minute apparent freeze with 70 devices /
  554 entities). Tells the user not to reload or cancel during setup.
- Adds a teal battery+clock icon at 256x256 and 512x512 under
  custom_components/battery_lifetime/brand/, ready to submit to
  home-assistant/brands as a custom_integrations/battery_lifetime entry
  so HACS can display it instead of "icon not available".
- manifest.json: bump version to 0.1.1; switch documentation and
  issue_tracker URLs to the public GitHub mirror so HACS users land
  somewhere they can actually file bugs.

107 tests still passing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-08 19:24:37 +02:00
13 changed files with 611 additions and 26 deletions
+166
View File
@@ -0,0 +1,166 @@
# Agent Handoff — Battery Lifetime
## Current State (2026-05-08)
The Battery Lifetime custom Home Assistant integration is working and deployed via HACS on the user's live install (70 battery-powered devices → 554 companion entities). Current release is **v0.1.1** on GitHub via HACS.
The OpenSpec change `add-battery-lifetime` is at 56/62 tasks; the remaining six (10.2–10.7) are manual-validation gates against a real HA install. Some are implicitly being validated right now by the live install; see "What Needs Doing Next" below.
## What's Done
- Full implementation of the Battery Lifetime integration:
- Auto-discovery of every numeric percent battery sensor in the HA entity registry; categorical / boolean / voltage-only / no-`unique_id` sensors are skipped (and logged once).
- Eight per-battery companion entities: `sensor.<src>_replace_by` (timestamp), `sensor.<src>_prediction_quality` (enum), `sensor.<src>_drain_rate` (`%/d`), `switch.<src>_profile_lithium`, `switch.<src>_tracking_enabled`, `button.<src>_mark_replaced`, `date.<src>_replaced_on`, `number.<src>_threshold_override`.
- Two integration-level summary sensors: `sensor.battery_lifetime_due_this_month`, `sensor.battery_lifetime_due_next_3_months`.
- Two chemistry profiles (`alkaline` 15%/365d, `lithium` 5%/1825d with 85% plateau gate); default is `lithium`, switchable per battery.
- Auto-replacement detection (jump from `<80%` to `≥100%` with confirmation, 30-day staleness window, 1-hour glitch protection).
- Stale-prior workflow exposed as three HA services (`battery_lifetime.confirm_stale_replacement`, `dismiss_stale_replacement`, `exclude_stale_replacement`); the persistent notification names the entity_id and the three services.
- Cold-start backfill from HA long-term statistics (preferred) and recorder (fallback); backwards-extrapolation fallback after `≥7 days` and `≥1%` drain.
- Confidence ladder (`no_data` → `profile_default` → `low` → `medium` → `high`, plus orthogonal `stale`).
- Forward-prediction service `battery_lifetime.predict_at` with `actionable_only`, `margin_days` (extends evaluation date forward — be conservative), `include_excluded` flags.
- Single-instance config flow + options flow (default profile + bulk overview).
- Persistent state via HA `Store` helper at `.storage/battery_lifetime` with versioned schema and migration scaffold.
- HACS packaging (`hacs.json`, `info.md`, `README.md`, `LICENSE`, `manifest.json`).
- 107 unit tests passing under `pytest-homeassistant-custom-component`.
- v0.1.0 released and installed live on the user's HA install. v0.1.1 follow-up adds a bold/all-caps setup-time warning to the config dialog and ships icon assets in `custom_components/battery_lifetime/brand/` (256×256 + 512×512).
- Both `master` and tags `v0.1.0`/`v0.1.1` pushed to gitea (origin) and GitHub (github).
- README and OpenSpec specs aligned with the implementation; `replacement-detection/spec.md` enumerates the three stale-prior services explicitly.
## What Needs Doing Next (Immediate)
### 1. Brands PR for the HACS icon
HACS sources its integration icons from [home-assistant/brands](https://github.com/home-assistant/brands), not from the integration repo. The local assets at `custom_components/battery_lifetime/brand/icon.png` (256) and `icon@2x.png` (512) are ready to ship. To make HACS display them:
```bash
GH_TOKEN=$(cat /home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token) gh repo fork home-assistant/brands --clone --remote
cd brands
git checkout -b add-battery-lifetime
mkdir -p custom_integrations/battery_lifetime
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon.png custom_integrations/battery_lifetime/icon.png
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon@2x.png custom_integrations/battery_lifetime/icon@2x.png
# logo.png + logo@2x.png are usually required too — same image is fine for an icon-only brand
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon.png custom_integrations/battery_lifetime/logo.png
cp /home/rick/Lab/Dev/Hassio-Battery-Lifetimes/custom_components/battery_lifetime/brand/icon@2x.png custom_integrations/battery_lifetime/logo@2x.png
git add custom_integrations/battery_lifetime
git commit -m "Add battery_lifetime"
git push origin add-battery-lifetime
GH_TOKEN=... gh pr create --repo home-assistant/brands \
--title "Add battery_lifetime" \
--body "Custom integration: https://github.com/Falkvinge/hassio-integration-battery-lifetime"
```
CI in brands runs Pillow checks for image dimensions and format; the assets satisfy them (sized correctly, transparent, RGBA).
### 2. OpenSpec manual-validation gates 10.2 – 10.7
These are the only remaining tasks in `openspec/changes/add-battery-lifetime/tasks.md`. Some are implicitly being validated by the live install right now:
- **10.2** Walk each replacement-detection branch (auto, glitch, stale-prior confirm/dismiss/exclude, cold-start LTS, cold-start recorder, cold-start no-history) end-to-end on real HA. Programmatic coverage is in `tests/test_detection.py` and `tests/test_e2e.py`.
- **10.3** Walk each prediction-quality state transition (`no_data → profile_default → low → medium → high`) by driving simulated drain. Programmatic coverage in `tests/test_prediction.py`.
- **10.4** Validate cold-start backfill against ≥60 d of long-term statistics. Live install with 70 devices triggered this at first boot — it's the apparent cause of the multi-minute initial-setup freeze that v0.1.1 now warns about. Worth observing whether `replaced_on` got populated for batteries that had a `<80% → ≥100%` jump in the recorder.
- **10.5** Validate `predict_at` via Developer Tools → Services with `actionable_only: true`, `include_excluded: true`, and various `margin_days`.
- **10.6** Implicitly validated — HACS install succeeded, integration loaded, 70 devices / 554 entities created.
- **10.7** Tag `v0.1.0` and note the first-30-to-60-day low-confidence behaviour in release notes — **DONE** (v0.1.0 released; release notes do mention the caveat).
Once 10.2 – 10.5 are observed in the live install, mark them in `tasks.md` and run `openspec archive --change "add-battery-lifetime"` (the OpenSpec workflow). The change has `isComplete: true` per `openspec status` (all artifacts are done; the open task checkboxes don't block archive).
### 3. Investigate the multi-minute initial-setup freeze
User reported that pressing **Submit** on the config dialog locked the UI for several minutes on a 70-device / 554-entity install. v0.1.1 warns about this in the dialog, but the underlying cause should be confirmed before considering it acceptable. Likely culprits:
- `_scan_initial_entities` in `custom_components/battery_lifetime/coordinator.py` calls `_ensure_record` for every eligible entity sequentially, and each call awaits the cold-start backfill (`_attempt_cold_start_backfill` → `recorder.async_add_executor_job` → two recorder queries per battery). With 70 batteries that's 140 recorder queries serialized.
- Mitigations to consider: gate cold-start backfill behind a background task instead of blocking setup; batch the recorder queries via `recorder.history.get_significant_states` for all entity_ids at once; or just defer the backfill to the first scheduled coordinator tick (already 10 minutes after setup) and let setup return immediately.
- Lazy-import note: cold-start should not block any of the *other* setup steps — the entity platforms are forwarded after `coordinator.async_setup()` returns. So the freeze is squarely in `_scan_initial_entities`.
### 4. Loose ends from earlier sessions
- **Branch tracking.** `master` currently tracks `github/master` (because of `git push -u github master`). Sibling repos track `origin/master`. To match the sibling pattern:
```bash
git branch --set-upstream-to=origin/master master
```
- **Credential helper.** This local repo doesn't have `credential.helper = store --file=.git/credentials` set in `.git/config` like the siblings do. Every gitea push needs an inline `-c credential.helper="store --file=.git/credentials"` until that's set. To match the sibling pattern:
```bash
git config --local credential.helper "store --file=.git/credentials"
```
- **`.github-token` in this repo.** GitHub operations have been using `/home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token` as the source of truth. To make this project self-contained:
```bash
cp /home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token .github-token
```
Already in `.gitignore`, so it stays local.
These were deliberately not done by the previous agent because of the project's "NEVER update the git config" guardrail; the user can do them in three short commands.
## Architecture Notes
- **Repo layout**: standard HACS custom-integration layout. Source under `custom_components/battery_lifetime/`. Tests under `tests/`. OpenSpec artefacts under `openspec/changes/add-battery-lifetime/`. Brand assets under `custom_components/battery_lifetime/brand/`.
- **Storage**: `.storage/battery_lifetime` (JSON, versioned schema, debounced save). Per-battery entries keyed by source `unique_id`, never `entity_id`.
- **Identity**: `unique_id` is the canonical key everywhere — companion entities, store, replacement events.
- **Profiles**: pure-Python dataclasses in `custom_components/battery_lifetime/models/`.
- **Detection**: pure-logic helpers (`classify_reading`, `classify_followup`, `_scan_for_jump`, `estimate_replaced_on_from_drain`) in `detection.py`, plus an HA-aware `ReplacementDetector` wrapper that holds candidates, arms 1-hour `async_call_later` timers, and emits `battery_lifetime_replacement_detected` events.
- **Coordinator**: `BatteryLifetimeCoordinator(DataUpdateCoordinator)` owns the in-memory `BatteryRecord` map, listens to source state changes + entity-registry updates, and ticks every 10 minutes so `replace_by` and confidence respond to wall-clock time.
- **Companion entities**: derive their `unique_id` deterministically from the source `unique_id` via `companion_unique_id(source_uid, suffix)`. `_attr_has_entity_name = False` and a custom `suggested_object_id` property keep entity IDs in the documented `sensor.<src>_<suffix>` format.
- **Services**: `predict_at` (read-only, response-only), `confirm_stale_replacement`, `dismiss_stale_replacement`, `exclude_stale_replacement`. Defined in `services.py` + `services.yaml`.
- **HACS**: Releases on GitHub are the install source. `manifest.json` `version` field must match the tag.
- **Remotes**: `origin` = Gitea (git.falkvinge.net), `github` = GitHub (`Falkvinge/hassio-integration-battery-lifetime`).
- **Test harness**: `pytest-homeassistant-custom-component` against HA `2024.4+`. Run with `.venv/bin/pytest tests/`. Conftest is minimal (`enable_custom_integrations` fixture).
## Known Gotchas (from `PROJECT_HYGIENE.md` § 11)
These were learned the hard way during initial implementation; future sessions should heed them:
- HA `Entity.suggested_object_id` is a property derived from `self.name`, not the `_attr_suggested_object_id` attribute. Override the property to control companion `entity_id`.
- Single-instance config flow aborts use `_async_current_entries() → async_abort(reason="single_instance_allowed")`, NOT `_abort_if_unique_id_configured` (which aborts with `already_configured`).
- `RegistryEntry.unit_of_measurement` is the only unit field; `original_unit_of_measurement` does not exist on modern HA `RegistryEntry` objects.
- `EntityRegistry.async_get_or_create(unit_of_measurement=...)` accepts `unit_of_measurement`, not `original_unit_of_measurement`.
- `DataUpdateCoordinator.async_shutdown` overrides MUST `await super().async_shutdown()` or the test harness's `verify_cleanup` fixture will trip on a lingering `Debouncer._on_debounce` timer.
- `predict_at`'s `margin_days` *extends* the evaluation date forward (cottage-departure semantic — be conservative, flag MORE batteries).
- When a battery's last reading is already at or below threshold, `replace_by` is the last reading time ("due now"), not `replaced_on + default_lifetime` (which would be years in the future and break the `due_this_month` summary).
- Recorder/LTS calls fail in tests where the recorder isn't bootstrapped. `get_instance(hass)` is wrapped in `try/except (KeyError, RuntimeError)` and `recorder` is in `after_dependencies`, not `dependencies`.
- Two consecutive `hass.states.async_set(entity_id, "100", ...)` with the same string value get deduped by HA's state machine. Use `force_update=True` when a test needs the second one to fire a `state_changed` event.
## Useful Commands
```bash
# Run all tests
.venv/bin/pytest tests/ -q
# Run a single test
.venv/bin/pytest tests/test_prediction.py::test_lithium_plateau_holds_at_default_lifetime
# OpenSpec status
openspec status --change "add-battery-lifetime" --json
# OpenSpec validate
openspec validate "add-battery-lifetime"
# Push to gitea (credential helper not configured locally; inline it)
git -c credential.helper="store --file=.git/credentials" push origin master
# Push to GitHub (PAT is embedded in the remote URL already)
git push github master
# Create release via gh CLI (token from sibling)
GH_TOKEN=$(cat /home/rick/Lab/Dev/Hassio-PerfectDraftPro/.github-token) \
gh release create vX.Y.Z --repo Falkvinge/hassio-integration-battery-lifetime \
--title "..." --notes "..."
```
## Sibling Projects
- **`/home/rick/Lab/Dev/Hassio-PerfectDraftPro`** — the integration this project's `.gitignore` was originally copied from. Source of `.github-token` and the embedded-PAT remote pattern.
- **`/home/rick/Lab/Dev/Hassio-Thermostat-Fork-Darklight`** — source of `scripts/agent-worktree.sh`.
- **`/home/rick/Lab/Dev/Template`** — source of `AGENTS.md` and `PROJECT_HYGIENE.md`.
## OpenSpec Status
Change directory: `openspec/changes/add-battery-lifetime/`
| Artifact | Status |
| -------- | ------ |
| `proposal.md` | Done |
| `design.md` | Done |
| `specs/**/*.md` (5 capabilities) | Done |
| `tasks.md` | 56/62 (10.2 – 10.7 are the manual-validation gates) |
Ready to archive once 10.2 – 10.5 are observed live and the boxes are checked. 10.6 and 10.7 are already effectively done.
Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

@@ -134,7 +134,7 @@ class BatteryLifetimeCoordinator(
hass,
_LOGGER,
name="battery_lifetime",
update_interval=timedelta(seconds=UPDATE_INTERVAL_SECONDS),
update_interval=None,
)
self._store = store
self._records: dict[str, BatteryRecord] = {}
@@ -346,15 +346,17 @@ class BatteryLifetimeCoordinator(
new_at=ts,
tracking_enabled=record.tracking_enabled,
)
if not committed:
if record.tracking_enabled:
record.ewma = update_ewma(record.ewma, pct, ts)
record.last_reading_pct = pct
record.last_reading_at = ts
await self._maybe_backwards_extrapolate(record)
if committed:
return
if record.tracking_enabled:
record.ewma = update_ewma(record.ewma, pct, ts)
record.last_reading_pct = pct
record.last_reading_at = ts
await self._maybe_backwards_extrapolate(record)
self._persist(record)
await self.async_request_refresh()
self._publish_single_record_update(unique_id, record)
async def _maybe_backwards_extrapolate(
self, record: BatteryRecord
@@ -516,22 +518,48 @@ class BatteryLifetimeCoordinator(
@callback
def _handle_tick(self, _now: datetime) -> None:
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
self.hass.async_create_task(self.async_request_refresh())
self.hass.async_create_task(self._async_recompute_and_maybe_publish())
def _persist(self, record: BatteryRecord) -> None:
self._store.upsert_battery(
record.unique_id,
replaced_on=_isoformat_or_none(record.replaced_on),
profile=record.profile_id,
threshold_override=record.threshold_override,
tracking_enabled=record.tracking_enabled,
ewma_state=record.ewma.to_dict(),
last_reading_pct=record.last_reading_pct,
last_reading_at=_isoformat_or_none(record.last_reading_at),
last_replace_by=_isoformat_or_none(record.last_replace_by),
async def _async_recompute_and_maybe_publish(self) -> None:
"""Heartbeat path: recompute every record and publish only if changed.
The unconditional publish path (``async_request_refresh``) is reserved
for explicit user actions and registry/detector callbacks; the periodic
heartbeat exists to surface time-driven flips (stale, confidence
ladder, summary cutoffs) without flooding listeners on idle systems.
"""
new_snapshots = self._compute_snapshots()
if self.data is None or self._snapshots_differ(self.data, new_snapshots):
self.async_set_updated_data(new_snapshots)
def _publish_single_record_update(
self, unique_id: str, record: BatteryRecord
) -> None:
"""Per-source-event path: replace one record's snapshot, publish.
Other records' ``Prediction`` instances are carried forward by
reference so the publish is O(1) in the number of tracked batteries.
On the very first publish (``self.data is None``) we compute every
record so the snapshot dict is complete from the start.
"""
if self.data is None:
self.async_set_updated_data(self._compute_snapshots())
return
snapshots = dict(self.data)
prediction = project_replace_by(
record.to_state(),
now=_utcnow(),
last_replace_by_fallback=record.last_replace_by,
)
if prediction.replace_by is not None:
record.last_replace_by = prediction.replace_by
self._persist(record)
snapshots[unique_id] = CoordinatorSnapshot(
record=record, prediction=prediction
)
self.async_set_updated_data(snapshots)
async def _async_update_data(self) -> dict[str, CoordinatorSnapshot]:
def _compute_snapshots(self) -> dict[str, CoordinatorSnapshot]:
snapshots: dict[str, CoordinatorSnapshot] = {}
now = _utcnow()
for unique_id, record in list(self._records.items()):
@@ -548,6 +576,42 @@ class BatteryLifetimeCoordinator(
)
return snapshots
@staticmethod
def _snapshots_differ(
old: dict[str, CoordinatorSnapshot],
new: dict[str, CoordinatorSnapshot],
) -> bool:
if old.keys() != new.keys():
return True
for unique_id, new_snap in new.items():
old_snap = old[unique_id]
op = old_snap.prediction
np = new_snap.prediction
if (
op.replace_by != np.replace_by
or op.confidence != np.confidence
or op.drain_rate_pct_day != np.drain_rate_pct_day
or op.threshold_pct != np.threshold_pct
):
return True
return False
def _persist(self, record: BatteryRecord) -> None:
self._store.upsert_battery(
record.unique_id,
replaced_on=_isoformat_or_none(record.replaced_on),
profile=record.profile_id,
threshold_override=record.threshold_override,
tracking_enabled=record.tracking_enabled,
ewma_state=record.ewma.to_dict(),
last_reading_pct=record.last_reading_pct,
last_reading_at=_isoformat_or_none(record.last_reading_at),
last_replace_by=_isoformat_or_none(record.last_replace_by),
)
async def _async_update_data(self) -> dict[str, CoordinatorSnapshot]:
return self._compute_snapshots()
def iter_active_records(self) -> Iterable[BatteryRecord]:
for record in self._records.values():
yield record
@@ -1,9 +1,9 @@
{
"domain": "battery_lifetime",
"name": "Battery Lifetime",
"version": "0.1.0",
"documentation": "https://git.falkvinge.net/rick/hassio-battery-lifetime-integration",
"issue_tracker": "https://git.falkvinge.net/rick/hassio-battery-lifetime-integration/issues",
"version": "0.1.2",
"documentation": "https://github.com/Falkvinge/hassio-integration-battery-lifetime",
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-battery-lifetime/issues",
"codeowners": ["@rickfalkvinge"],
"config_flow": true,
"iot_class": "local_polling",
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "Battery Lifetime tracks every numeric percent battery sensor in Home Assistant. After installation, every eligible battery automatically gets a set of companion entities (predicted replacement date, observed drain rate, profile selector, mark-replaced button, etc.). You can opt out individual batteries later. Press Submit to continue."
"description": "**\u26a0 HEADS UP \u2014 INITIAL SETUP CAN TAKE SEVERAL MINUTES.**\n\nBattery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\n**IF YOU HAVE MANY BATTERY-POWERED DEVICES \u2014 SAY 50+ BATTERIES, WHICH MEANS 400+ NEW ENTITIES \u2014 THE UI WILL APPEAR FROZEN FOR SEVERAL MINUTES AFTER YOU PRESS SUBMIT** while the entities are registered and the one-time cold-start backfill from long-term statistics runs. **Don't reload, don't cancel \u2014 just wait. It is working.**\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "Battery Lifetime tracks every numeric percent battery sensor in Home Assistant. After installation, every eligible battery automatically gets a set of companion entities (predicted replacement date, observed drain rate, profile selector, mark-replaced button, etc.). You can opt out individual batteries later. Press Submit to continue."
"description": "**\u26a0 HEADS UP \u2014 INITIAL SETUP CAN TAKE SEVERAL MINUTES.**\n\nBattery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around eight companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\n**IF YOU HAVE MANY BATTERY-POWERED DEVICES \u2014 SAY 50+ BATTERIES, WHICH MEANS 400+ NEW ENTITIES \u2014 THE UI WILL APPEAR FROZEN FOR SEVERAL MINUTES AFTER YOU PRESS SUBMIT** while the entities are registered and the one-time cold-start backfill from long-term statistics runs. **Don't reload, don't cancel \u2014 just wait. It is working.**\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-05-09
@@ -0,0 +1,97 @@
## Context
`BatteryLifetimeCoordinator` extends `DataUpdateCoordinator[dict[str, CoordinatorSnapshot]]`. Today it sets `update_interval=600s`, registers a separate `async_track_time_interval(_handle_tick, 600s)` that calls `async_request_refresh`, and implements `_async_update_data` as a full O(N) walk that recomputes every tracked battery's `Prediction` and replaces the whole snapshot dict.
`async_request_refresh` is also the only refresh path used by source-state-change handlers, the registry handler, and every user-action setter (`set_profile`, `mark_replaced_now`, etc.). It is debounced at the HA framework level (~10 s cooldown), so bursts coalesce, but each refresh that does fire still does the full O(N) walk and unconditionally publishes to all `CoordinatorEntity` listeners (8 companions × N + 2 summaries).
User's current install: 70 batteries / 554 entities. The math cost is sub-millisecond per refresh. The cost that's worth caring about is the entity-state fan-out (writes to the HA state machine, recorder, and any listening automations) on every refresh.
## Goals / Non-Goals
**Goals:**
- Eliminate the duplicate 10-minute timer.
- Avoid recomputing N records when only one source's value actually changed.
- Avoid publishing a fresh snapshot when no record's externally observable `Prediction` changed.
- Preserve the three time-driven flips that are the heartbeat's reason to exist: stale flip at 7-day source idleness, confidence-ladder ratchet at 7/30/60 days, and summary-sensor month/quarter cutoff transitions.
- Preserve all current spec-level behavior. No requirement changes.
**Non-Goals:**
- No change to the prediction math (`project_replace_by`, `evaluate_confidence`, `forward_simulate`).
- No change to the storage schema, persistent state, services, events, or companion-entity layout.
- No introduction of a smarter scheduler (e.g. per-record next-flip timer). The current "tick everything every 10 min" cadence is kept; only the *push* is gated.
- No change to `_async_update_data`'s contract for `coordinator.async_refresh()` callers — it still returns the full snapshot dict so external callers (services, options flow) get the current view.
## Decisions
### Decision 1: Drop `update_interval`, keep the explicit tick
`DataUpdateCoordinator(update_interval=…)` and the explicit `async_track_time_interval(_handle_tick, …)` both call `_async_update_data` every 10 minutes. The explicit tick has a side effect we want to keep — `prune_removed_older_than` — and gives us a callback hook where we can implement the diff gate without overriding `_async_update_data`'s framework contract.
We pass `update_interval=None` to the superclass and let `_handle_tick` drive the cadence via `_async_recompute_and_publish` (a new private method). `_async_update_data` is still implemented (the framework calls it from `async_refresh`/`async_request_refresh`), but it just delegates to a pure recompute that returns the snapshot dict without any "did anything change?" gate, because callers of `async_refresh` explicitly want a fresh snapshot.
**Alternative considered:** keep `update_interval=600s` and drop the explicit tick. Rejected because we'd lose the natural place to put the diff gate (we'd have to override `_async_update_data` to skip publishing, but the superclass calls `async_set_updated_data` itself based on the returned value — there's no clean "compute but don't push" path through the framework).
### Decision 2: O(1) per-source-event update via `async_set_updated_data`
In `_handle_source_update`, after the existing record mutation (detector, EWMA, persistence), build the snapshot dict locally:
```python
snapshots = dict(self.data) if self.data else {}
snapshots[unique_id] = CoordinatorSnapshot(
record=record,
prediction=project_replace_by(
record.to_state(),
now=_utcnow(),
last_replace_by_fallback=record.last_replace_by,
),
)
self.async_set_updated_data(snapshots)
```
This replaces the existing `await self.async_request_refresh()` call. Only the changed record gets a fresh `Prediction`; the rest are carried forward by reference. Companion entities for the unchanged batteries still get a `_handle_coordinator_update` call (HA's `CoordinatorEntity` doesn't diff), but their `native_value` reads return the same value, so HA's state machine dedupes the write (no new `state_changed` event). Net: O(1) math + O(1) recorder writes per source event.
**Alternative considered:** custom listener layer that only notifies the affected entities. Rejected as overkill — the `state_machine` dedupe already gives us the recorder savings, and the entity-level diff is HA's job.
### Decision 3: Diff-gated heartbeat
`_handle_tick` becomes:
```python
@callback
def _handle_tick(self, _now):
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
self.hass.async_create_task(self._async_recompute_and_maybe_publish())
async def _async_recompute_and_maybe_publish(self):
new = self._compute_snapshots()
old = self.data
if old is None or self._snapshots_differ(old, new):
self.async_set_updated_data(new)
```
`_snapshots_differ(old, new)` returns True if:
- `old.keys() != new.keys()` (a record was added or removed), OR
- for any shared key, any of `prediction.replace_by`, `prediction.confidence`, `prediction.drain_rate_pct_day`, `prediction.threshold_pct` differs.
These four fields are the externally observable surface of a `Prediction`. The summary sensors derive from `prediction.replace_by`, so if every record's `replace_by` is unchanged the summary sensors are also unchanged, and skipping the push is safe.
User-action setters (`set_profile`, `set_threshold_override`, etc.) keep using `await self.async_request_refresh()` because they explicitly want an immediate publish (the user just changed something and expects the UI to update). The diff gate would skip cases where, say, toggling the lithium switch on a battery that's currently on plateau happens to leave `replace_by` the same — even though the chemistry change is itself something a user might want reflected. Keeping the unconditional path for explicit user actions is cleaner.
**Alternative considered:** tighter diff (include `record.profile_id`, `record.tracking_enabled`, etc.). Rejected — those fields only change via user-action setters, which already publish unconditionally. Adding them to the diff is dead code on the heartbeat path.
**Alternative considered:** snapshot-equality via `__eq__`. Rejected — `BatteryRecord` is `@dataclass(slots=True)` (mutable, identity-equal by default) and `Prediction` is `frozen=True` (value-equal). Mixing the two equality semantics inside a single comparator is fragile. Explicit field comparison on `Prediction` is clearer.
## Risks / Trade-offs
- **Risk:** A bug in `_snapshots_differ` could swallow a real change. → Mitigation: unit test that asserts a published snapshot for each of the three time-driven flip scenarios (stale at day 7, confidence ratchet from `low` to `medium` at day 30, summary recount on month rollover); plus a test that asserts no publish on a tick where nothing changed.
- **Risk:** `async_set_updated_data` from `_handle_source_update` skips the framework debouncer, so a burst of 70 simultaneous source events publishes 70 snapshots back-to-back. → Acceptance: that's still 1 recompute per event (was: 70 × 70 = 4 900 with `async_request_refresh` even *with* the debouncer eventually settling). Companion-entity dedupe at the HA state-machine level absorbs the rest. If this turns out to be a problem at scale we can wrap the publish in our own asyncio.Lock + small coalescing window, but it's not needed today.
- **Trade-off:** The heartbeat no longer publishes "I ran" — there's no observable signal that the coordinator is alive on idle systems. → Acceptable: the framework's `last_update_success`/`last_update_success_time` already exposes liveness for the framework path; for our explicit tick we accept silence as the success signal. If a diagnostic hook is needed later it can be added without spec change.
- **Trade-off:** Carrying forward unchanged `CoordinatorSnapshot` references means `record` mutations made in place between snapshots are visible in old snapshots too (since both reference the same `BatteryRecord`). → Already true today: `BatteryRecord` is mutable and shared. No regression.
## Migration Plan
In-place upgrade. No storage migration, no service or event signature changes, no entity-id changes.
- Pre-deploy: ensure full test suite passes.
- Deploy via HACS as v0.1.2; HA reloads the integration cleanly on update.
- Rollback: revert to v0.1.1 via HACS; the storage schema is unchanged (still version 1).
@@ -0,0 +1,33 @@
## Why
`BatteryLifetimeCoordinator` currently does redundant and overly broad work on every refresh, costing extra entity-state writes and (at scale) recorder churn:
1. The coordinator runs `_async_update_data` twice every 10 minutes — once via the `DataUpdateCoordinator`'s built-in `update_interval`, once via a separate `async_track_time_interval(_handle_tick, 600s)` that calls `async_request_refresh`. The two timers do the same work out of phase.
2. Every source `state_changed` event triggers a full O(N) recalc of every tracked battery's `Prediction`, even though only the one battery that fired the event has new data.
3. Every 10-minute heartbeat unconditionally pushes a fresh snapshot to all `CoordinatorEntity` listeners (8 companion entities × N batteries + 2 summary sensors), forcing recomputation downstream and recorder writes, even on idle systems where no record's `Prediction` actually changed.
For the user's 70-battery / 554-entity install this is harmless today; at 1 000+ batteries the entity fan-out and recorder pressure become the dominant cost. The math itself is cheap.
## What Changes
- Drop the redundant 10-minute timer: keep the explicit `async_track_time_interval` tick (it owns `prune_removed_older_than` as a side effect) and remove `update_interval` from the `DataUpdateCoordinator` constructor.
- Convert per-source-event refreshes from O(N) full recalc to O(1) single-record update via `async_set_updated_data` on a shallow-copied snapshot dict with only the changed entry replaced.
- Make the heartbeat diff-gated: walk all records, compute a fresh `Prediction` per record, and only call `async_set_updated_data` if at least one record's externally-observable snapshot fields (`Prediction.replace_by`, `Prediction.confidence`, `Prediction.drain_rate_pct_day`, `Prediction.threshold_pct`) changed against the previous snapshot. On idle systems where nothing time-driven crossed a boundary, the heartbeat becomes a no-op.
The heartbeat is intentionally *not* gated on "source value changed". Three time-driven flips happen with no source change: stale flip at 7 days, confidence-ladder ratchet at 7/30/60-day boundaries, and summary-sensor month/quarter cutoff transitions. All three surface in `Prediction`, so a `Prediction`-diff gate preserves them while suppressing no-op pushes.
## Capabilities
### New Capabilities
- `coordinator-scheduling`: Internal contract for when the coordinator recomputes records, when it publishes snapshots to listeners, and which trigger paths are O(1) vs O(N). Captures the diff-gated heartbeat and the per-source-event single-record update introduced in this change as testable requirements.
### Modified Capabilities
- (none — no requirements in the existing `lifetime-prediction`, `replacement-detection`, `forward-prediction`, `battery-discovery`, or `battery-configuration` capabilities change. The new `coordinator-scheduling` spec sits alongside them and documents the scheduling contract that those specs implicitly relied on.)
## Impact
- **Code**: `custom_components/battery_lifetime/coordinator.py` (constructor, `async_setup`, `_handle_state_changed`, `_handle_source_update`, `_handle_tick`, `_async_update_data`).
- **Tests**: `tests/test_coordinator.py` (or equivalent) — add cases for single-record update, diff-gated heartbeat skip, and verify the three time-driven flips still publish.
- **Manifest**: `custom_components/battery_lifetime/manifest.json` version bump to `0.1.2`.
- **Public API / spec**: unchanged. No new entities, services, events, or storage-schema changes.
- **HACS / install**: drop-in replacement; users get the optimization on next HACS update with no configuration steps.
@@ -0,0 +1,41 @@
## ADDED Requirements
### Requirement: Single 10-minute heartbeat
The coordinator SHALL drive its periodic recompute from exactly one timer at the configured `UPDATE_INTERVAL_SECONDS` cadence (default 600 seconds). The `DataUpdateCoordinator.update_interval` framework parameter SHALL NOT be set in addition to the explicit `async_track_time_interval` tick.
#### Scenario: One timer, not two
- **WHEN** the integration is set up against a Home Assistant instance
- **THEN** exactly one periodic recompute fires per `UPDATE_INTERVAL_SECONDS` window — i.e. the coordinator does not call `_async_update_data` twice per interval out of phase
### Requirement: Per-source-event O(1) update
The coordinator SHALL update only the affected record when a single source `state_changed` event arrives, leaving all other records' `Prediction` instances unchanged in the published snapshot dict. The publish path for source-event updates SHALL be `async_set_updated_data`, not `async_request_refresh`.
#### Scenario: One source change updates one record
- **WHEN** a tracked battery's source sensor publishes a new percentage value (e.g. `82.0` → `81.0`) and no other source changes
- **THEN** the coordinator computes a fresh `Prediction` for that battery only, leaves every other record's `Prediction` reference unchanged in the published snapshot, and emits exactly one snapshot to listeners
#### Scenario: Burst of source changes does not multiply work
- **WHEN** N tracked batteries each publish a single new reading inside one debounce window
- **THEN** the coordinator computes exactly N fresh `Prediction` instances total (one per changed record), not N × N
### Requirement: Diff-gated heartbeat publish
On each periodic heartbeat the coordinator SHALL recompute every record's `Prediction`, compare the result against the currently published snapshot, and call `async_set_updated_data` only if at least one record's `Prediction.replace_by`, `Prediction.confidence`, `Prediction.drain_rate_pct_day`, or `Prediction.threshold_pct` differs, or if the set of tracked record keys differs.
#### Scenario: Idle heartbeat publishes nothing
- **WHEN** a heartbeat fires and every record's recomputed `Prediction` matches the four observable fields of its previously published `Prediction`, and the set of tracked records is unchanged
- **THEN** the coordinator does NOT call `async_set_updated_data`, no `CoordinatorEntity` listener is notified, and no entity-state change is written to Home Assistant's state machine
#### Scenario: Stale flip publishes
- **WHEN** a tracked battery's source has produced no update for `STALE_SOURCE_DAYS` (7) days and the next heartbeat fires
- **THEN** that battery's recomputed `Prediction.confidence` becomes `stale`, the coordinator detects the change, and publishes a new snapshot
#### Scenario: Confidence-ladder ratchet publishes
- **WHEN** a tracked battery has crossed the `CONFIDENCE_MEDIUM_DAYS` (30) boundary with sufficient observed drain since the previous heartbeat and no new source reading has arrived
- **THEN** that battery's recomputed `Prediction.confidence` advances from `low` to `medium`, the coordinator detects the change, and publishes a new snapshot
#### Scenario: User-action setters bypass the diff gate
- **WHEN** a user toggles `switch.<src>_profile_lithium`, presses `button.<src>_mark_replaced`, edits `date.<src>_replaced_on`, sets `number.<src>_threshold_override`, or toggles `switch.<src>_tracking_enabled`
- **THEN** the coordinator publishes a fresh snapshot unconditionally, even if the four observable `Prediction` fields happen to be unchanged
@@ -0,0 +1,32 @@
## 1. Coordinator refactor
- [ ] 1.1 Pass `update_interval=None` to the `DataUpdateCoordinator` superclass constructor
- [ ] 1.2 Add a private `_compute_snapshots()` helper that walks `self._records` and returns a fresh `dict[str, CoordinatorSnapshot]` (used by both `_async_update_data` and the heartbeat path)
- [ ] 1.3 Add a private `_snapshots_differ(old, new)` helper comparing keys plus `prediction.replace_by`, `prediction.confidence`, `prediction.drain_rate_pct_day`, `prediction.threshold_pct` per shared key
- [ ] 1.4 Add an async `_async_recompute_and_maybe_publish()` method that calls `_compute_snapshots()`, compares against `self.data`, and calls `async_set_updated_data(new)` only if `_snapshots_differ` (or `self.data is None`)
- [ ] 1.5 Rewrite `_handle_tick` to call `prune_removed_older_than` and schedule `_async_recompute_and_maybe_publish()`
- [ ] 1.6 Reimplement `_async_update_data` to delegate to `_compute_snapshots()` (so external `async_refresh()`/`async_request_refresh()` callers still get a publish)
- [ ] 1.7 In `_handle_source_update`, replace the trailing `await self.async_request_refresh()` with: build `snapshots = dict(self.data) if self.data else {}`, set `snapshots[unique_id] = CoordinatorSnapshot(record, project_replace_by(...))`, then `self.async_set_updated_data(snapshots)`
- [ ] 1.8 Verify all user-action setters (`set_profile`, `set_threshold_override`, `set_tracking_enabled`, `mark_replaced_now`, `set_replaced_on`) and `_async_registry_changed` still call `async_request_refresh` (unconditional publish path)
- [ ] 1.9 Verify `_apply_commit` (replacement-detector callback) still calls `async_request_refresh` (unconditional publish path)
## 2. Tests
- [ ] 2.1 Add a test that asserts only one heartbeat fires per `UPDATE_INTERVAL_SECONDS` window (e.g. by counting `async_set_updated_data` calls or `_compute_snapshots` invocations across a simulated interval)
- [ ] 2.2 Add a test that drives a source state change for one battery and asserts `Prediction` is recomputed for that battery only, while the other batteries' `Prediction` references in the published snapshot are identical (`is`) to the previous snapshot's
- [ ] 2.3 Add a test that fires a heartbeat with no source changes, no time-driven boundary crossings, and asserts no publish (`async_set_updated_data` not called, listener notification count unchanged)
- [ ] 2.4 Add a test that fires a heartbeat after a battery has crossed `STALE_SOURCE_DAYS` (advancing virtual time), asserts the published snapshot's `Prediction.confidence` for that battery is `stale`
- [ ] 2.5 Add a test that fires a heartbeat after a battery has crossed `CONFIDENCE_MEDIUM_DAYS` with sufficient simulated drain, asserts the published snapshot's `Prediction.confidence` advances from `low` to `medium`
- [ ] 2.6 Add a test that calls a user-action setter (e.g. `set_tracking_enabled` toggle) when no `Prediction` field would change and asserts the publish still happens
- [ ] 2.7 Run the full existing suite (`.venv/bin/pytest tests/ -q`) and confirm zero regressions
## 3. Release
- [ ] 3.1 Bump `custom_components/battery_lifetime/manifest.json` `version` to `0.1.2`
- [ ] 3.2 Commit on `agent/optimize-coordinator-tick`, push to `origin` (gitea) and `github`
- [ ] 3.3 Open + merge PR into `master` (or merge directly per project workflow)
- [ ] 3.4 Tag `v0.1.2`, push tag to both remotes
- [ ] 3.5 Create GitHub release `v0.1.2` with notes summarizing the three optimizations
- [ ] 3.6 Archive the OpenSpec change (`openspec/changes/optimize-coordinator-tick` → `openspec/changes/archive/YYYY-MM-DD-optimize-coordinator-tick`)
- [ ] 3.7 Remove the worktree and `agent/optimize-coordinator-tick` branch
- [ ] 3.8 Update HANDOFF.md with the v0.1.2 release and strike the now-obsolete brands-PR task #1 (per HACS brands-proxy discussion earlier this session)
+150
View File
@@ -302,6 +302,156 @@ async def test_removed_source_within_retention_restores_state(
await coord.async_shutdown()
async def test_coordinator_uses_single_periodic_timer(hass: Any) -> None:
"""The framework's update_interval must be off; only the explicit tick fires."""
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
assert coord.update_interval is None
assert coord._unsub_tick is not None
await coord.async_shutdown()
async def test_source_event_does_not_recompute_other_records(
hass: Any,
) -> None:
"""A single source's state change must not recompute peers' Predictions."""
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
_register(registry, entity_id="sensor.bar_battery", unique_id="uid-bar")
hass.states.async_set("sensor.foo_battery", "84", {})
hass.states.async_set("sensor.bar_battery", "60", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
for uid in ("uid-foo", "uid-bar"):
rec = coord.records[uid]
rec.replaced_on = datetime.now(tz=UTC) - timedelta(days=70)
rec.ewma.baseline_pct = 100.0
rec.ewma.baseline_at = rec.replaced_on
rec.ewma.last_pct = rec.last_reading_pct
rec.ewma.last_at = rec.replaced_on
rec.ewma.rate = 0.2
await coord.async_request_refresh()
await hass.async_block_till_done()
assert coord.data is not None
bar_pred_before = coord.data["uid-bar"].prediction
hass.states.async_set("sensor.foo_battery", "82", {})
await hass.async_block_till_done()
bar_pred_after = coord.data["uid-bar"].prediction
assert bar_pred_after is bar_pred_before
assert coord.data["uid-foo"].record.last_reading_pct == 82.0
await coord.async_shutdown()
async def test_idle_heartbeat_does_not_publish(hass: Any) -> None:
"""When nothing observable changed, the heartbeat must not push a snapshot."""
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
rec = coord.records["uid-foo"]
rec.replaced_on = datetime.now(tz=UTC) - timedelta(days=70)
rec.ewma.baseline_pct = 100.0
rec.ewma.baseline_at = rec.replaced_on
rec.ewma.last_pct = 84.0
rec.ewma.last_at = rec.replaced_on
rec.ewma.rate = 0.2
await coord.async_request_refresh()
await hass.async_block_till_done()
data_before = coord.data
await coord._async_recompute_and_maybe_publish()
await hass.async_block_till_done()
assert coord.data is data_before
await coord.async_shutdown()
async def test_heartbeat_publishes_when_source_goes_stale(hass: Any) -> None:
"""A heartbeat that crosses the staleness threshold must publish."""
from custom_components.battery_lifetime.const import (
CONFIDENCE_STALE,
STALE_SOURCE_DAYS,
)
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
rec = coord.records["uid-foo"]
fresh_anchor = datetime.now(tz=UTC) - timedelta(days=70)
rec.replaced_on = fresh_anchor
rec.ewma.baseline_pct = 100.0
rec.ewma.baseline_at = fresh_anchor
rec.ewma.last_pct = 84.0
rec.ewma.last_at = fresh_anchor
rec.ewma.rate = 0.2
rec.last_reading_at = datetime.now(tz=UTC) - timedelta(hours=1)
await coord.async_request_refresh()
await hass.async_block_till_done()
assert coord.data["uid-foo"].prediction.confidence != CONFIDENCE_STALE
rec.last_reading_at = datetime.now(tz=UTC) - timedelta(
days=STALE_SOURCE_DAYS + 1
)
await coord._async_recompute_and_maybe_publish()
await hass.async_block_till_done()
assert coord.data["uid-foo"].prediction.confidence == CONFIDENCE_STALE
await coord.async_shutdown()
async def test_user_action_setter_publishes_unconditionally(hass: Any) -> None:
"""User-action setters route through the unconditional refresh path.
The heartbeat path (``_async_recompute_and_maybe_publish``) is diff-gated;
the setter path (``async_request_refresh`` → ``_async_update_data`` →
framework publish) is not, so the user always sees their toggle reflected
even when it leaves the four observable Prediction fields unchanged.
"""
from unittest.mock import patch
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
rec = coord.records["uid-foo"]
rec.replaced_on = datetime.now(tz=UTC) - timedelta(days=70)
rec.ewma.baseline_pct = 100.0
rec.ewma.baseline_at = rec.replaced_on
rec.ewma.last_pct = 84.0
rec.ewma.last_at = rec.replaced_on
rec.ewma.rate = 0.2
with patch.object(
coord, "async_request_refresh", wraps=coord.async_request_refresh
) as request_refresh:
await coord.set_tracking_enabled("uid-foo", rec.tracking_enabled)
assert request_refresh.call_count == 1
await coord.async_shutdown()
async def test_source_without_unique_id_logged_and_skipped(
hass: Any, caplog: pytest.LogCaptureFixture
) -> None: