16 Commits
Author SHA1 Message Date
rickandCursor f0804592c3 Fix backfill-complete notification firing on every HA restart.
Persist a one-shot cold_start_backfill_announced flag in the JSON store so
the initial batch notification is shown only once; backfill still re-runs
silently for batteries without replaced_on. Release v0.1.6.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-25 10:00:34 +02:00
rickandCursor b5c910c425 openspec(quarterly-dashboard-entities): archive and sync lifetime-prediction spec
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:25:36 +02:00
rick 669c9bda5d Merge agent/quarterly-dashboard-entities: quarterly dashboard entities 2026-05-23 11:25:28 +02:00
rickandCursor d048c84eb8 Add quarterly dashboard entities for maintenance cards
Expose due-next-quarter summary and binary companions, days_until_replace
on replace-by sensors, and a simplified example Lovelace card.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:25:23 +02:00
rickandCursor 2d21a34438 openspec(quarterly-dashboard-entities): apply phase complete
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:22:33 +02:00
rickandCursor aeac543356 openspec(quarterly-dashboard-entities): propose phase artifacts
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:21:13 +02:00
rick 8154d29d53 Merge agent/license-rename: replace Swarmops name in LICENSE 2026-05-12 19:55:14 +02:00
rickandCursor 89c0a12e51 license: replace Swarmops name with project name
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 19:54:10 +02:00
rick 986b4f9fa7 Merge agent/license-readme: public-domain license 2026-05-12 19:46:48 +02:00
rickandCursor 8d2c34bf6f docs(license): switch project to public domain
Replace MIT licensing with Swarmops-flavored UNLICENSE/CC0 public-domain
statement and align README's License section to match.

LICENSE content copied verbatim from
github.com/Swarmops/Swarmops:LICENSE-PUBLIC-DOMAIN.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-12 19:46:15 +02:00
rickandCursor 6f577c844f openspec(autoclean-orphan-companion-entities): archive + sync specs; HANDOFF v0.1.4
Sync delta from autoclean-orphan-companion-entities into the canonical
coordinator-scheduling spec (one new requirement: pruned sources have
their companion device removed). Move the change directory under
openspec/changes/archive/.

Update HANDOFF.md: v0.1.4 is current release; the orphan-companion-
entity gap is closed for future prunes; legacy orphans (from before
v0.1.4) remain a manual-cleanup item.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 12:02:52 +02:00
rick 089082a163 Merge agent/autoclean-orphan-companion-entities: v0.1.4 auto-clean
Closes the orphan-companion-entity gap surfaced when discussing the
removal flow: when prune_removed_older_than actually drops a unique_id
from the JSON store, the coordinator now also removes the matching
companion device via device_registry.async_remove_device. HA's
device-registry removal cascades to the entity registry and clears
the eight per-source companion entries automatically. 118 tests
passing.
2026-05-11 12:00:18 +02:00
rickandCursor 34ae5e8d01 openspec(autoclean-orphan-companion-entities): apply phase done; ready to merge
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 12:00:18 +02:00
rickandCursor 13b3dd63ce v0.1.4: auto-clean companion device when source is pruned
When a tracked battery's source disappears, the coordinator's
_async_registry_changed handler soft-deletes the JSON-store entry
(replaced_on/profile/threshold preserved against restore within
30 days) and pops the in-memory BatteryRecord (companion entities
flip to unavailable). After REMOVED_SOURCE_RETENTION_DAYS the soft
deletes are pruned by store.prune_removed_older_than.

Pre-v0.1.4, the eight per-source companion entities and their
device-card entry remained in HA's registry forever as orphan
unavailable rows. Users had to garbage-collect manually.

This release adds a purge step keyed off prune_removed_older_than's
return value (the list of unique_ids actually dropped). For each,
the coordinator looks up the per-source companion device via
device_registry.async_get_device(identifiers={(DOMAIN, source_uid)})
and, if found, calls async_remove_device. HA's device-registry
removal cascades to the entity registry and removes the eight
companion entries automatically.

The purge runs from both prune call sites:
- _async_registry_changed action:remove (immediate prune sweep)
- _handle_tick (every 10-minute heartbeat)

Idempotent: a missing device is a silent no-op (covers manual
prior cleanup races and never-created cases). Soft-deleted entries
within their grace window are NOT touched -- restore via
store.restore_battery still works without UI rebuild.

Out of scope: legacy orphans accumulated before v0.1.4 (their
JSON-store entries are already gone, so there's nothing to drive
the new purge for them). Manual cleanup via UI remains.

Tests: 3 new in tests/test_coordinator.py covering the helper
directly, the no-op-on-missing-device path, and the full
remove-event -> grace-elapsed -> prune -> purge chain.
Full suite 118 passed.

README "When a battery disappears" section added documenting the
soft-delete + restore-window + auto-purge lifecycle.

Modifies the coordinator-scheduling capability with one ADDED
requirement; spec sync at archive time.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:59:56 +02:00
rickandCursor 8fab5a5784 openspec(autoclean-orphan-companion-entities): propose phase artifacts
Proposes that prune_removed_older_than's pruned-unique_ids return value
drives a device-registry purge step in both prune call sites
(_async_registry_changed action:remove and _handle_tick), removing the
per-source companion device whose identifiers={(DOMAIN, source_uid)}.
HA's device-registry removal cascades to the entity registry and
removes the eight orphan companion entries automatically.

Modifies coordinator-scheduling capability with one new requirement
covering the cleanup behavior, including the no-op-on-missing-device
and the keep-during-grace-window scenarios.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:57:15 +02:00
rickandCursor c576310fce openspec(defer-cold-start-backfill): archive + sync specs; HANDOFF v0.1.3
Sync delta from defer-cold-start-backfill into the canonical
coordinator-scheduling spec (two new requirements: non-blocking
cold-start, exactly-once batch-completion notification). Move the
change directory under openspec/changes/archive/.

Update HANDOFF.md: v0.1.3 is current release; the multi-minute
setup freeze is fixed; brand/logo polish shipped; live-install
manual-validation gates 10.2-10.5 still open.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-11 11:43:07 +02:00
35 changed files with 1177 additions and 47 deletions
+24 -16
View File
@@ -1,12 +1,12 @@
# Agent Handoff — Battery Lifetime
## Current State (2026-05-09)
## Current State (2026-05-11, late-morning)
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.2** on GitHub via HACS.
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.6** 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.
The OpenSpec change `optimize-coordinator-tick` (v0.1.2 release) is fully archived under `openspec/changes/archive/2026-05-09-optimize-coordinator-tick/`. Specs synced to `openspec/specs/coordinator-scheduling/spec.md`.
The OpenSpec changes `optimize-coordinator-tick` (v0.1.2), `defer-cold-start-backfill` (v0.1.3), and `autoclean-orphan-companion-entities` (v0.1.4) are fully archived under `openspec/changes/archive/`. All three have their specs synced into `openspec/specs/coordinator-scheduling/spec.md`.
## What's Done
@@ -26,21 +26,22 @@ The OpenSpec change `optimize-coordinator-tick` (v0.1.2 release) is fully archiv
- 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).
- v0.1.2 ships three coordinator scheduling optimizations (drop redundant 10-minute timer, per-source-event O(1) update via `async_set_updated_data`, diff-gated heartbeat publish). 5 new tests in `tests/test_coordinator.py`, full suite 112 passed.
- Both `master` and tags `v0.1.0`/`v0.1.1`/`v0.1.2` 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. `coordinator-scheduling/spec.md` documents the per-event vs heartbeat contracts.
- v0.1.3 defers cold-start backfill out of `async_setup`'s await chain via `hass.async_create_task`, removing the multi-minute config-entry freeze on installs with many batteries (the v0.1.1 dialog warning is no longer applicable and was softened). Adds a one-shot `persistent_notification` (`battery_lifetime_cold_start_complete`) when the initial backfill batch finishes. Ships `brand/logo.png` + `brand/logo@2x.png` (copies of the icon assets) for HA's Brands Proxy logo slot. 3 new tests in `tests/test_coordinator.py`, full suite 115 passed.
- v0.1.4 closes the orphan-companion-entity gap: when `prune_removed_older_than` actually drops a `unique_id` from the JSON store (after the 30-day grace window), the coordinator now removes the per-source companion device via `device_registry.async_remove_device`. HA's device-registry removal cascades to the entity registry and clears the eight per-source companion entries automatically. Cleanup runs from both prune call sites (`_async_registry_changed action: remove` + `_handle_tick`). Idempotent on missing device. Soft-deleted entries within their grace window are NOT touched; restore semantics are unchanged. 3 new tests, full suite 118 passed.
- v0.1.6 fixes the cold-start backfill completion notification firing on every HA restart. The one-shot `persistent_notification` (`battery_lifetime_cold_start_complete`) is now gated by a persisted `cold_start_backfill_announced` flag in the JSON store; backfill still re-runs silently on restart for batteries without `replaced_on` (idempotent, per spec). Upgrades with existing battery entries migrate the flag to `true` so no spurious notification on first restart after update. 1 new test, full suite 127 passed.
- Both `master` and tags `v0.1.0`/`v0.1.1`/`v0.1.2`/`v0.1.3`/`v0.1.4`/`v0.1.5`/`v0.1.6` 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. `coordinator-scheduling/spec.md` documents the per-event vs heartbeat contracts, the non-blocking cold-start contract, AND the prune-driven companion-device purge.
## What Needs Doing Next (Immediate)
### 1. ~~Brands PR for the HACS icon~~ — OBSOLETE as of HA 2026.3
Home Assistant 2026.3 (announcement: <https://developers.home-assistant.io/blog/2026/02/24/brands-proxy-api>) introduced a local Brands Proxy API. Custom integrations now ship `brand/icon.png`, `brand/icon@2x.png` (and optionally `logo.png` / `dark_*.png`) inside their own repository, and HA serves them from `/api/brands/integration/<domain>/icon.png`. The `home-assistant/brands` repo **auto-closes** PRs for `custom_integrations/*` and tells contributors to use the inline mechanism (verified via closed PRs `home-assistant/brands#10149` and `#10230` cited in `hacs/integration#5223`).
Home Assistant 2026.3 (announcement: <https://developers.home-assistant.io/blog/2026/02/24/brands-proxy-api>) introduced a local Brands Proxy API. Custom integrations now ship `brand/icon.png`, `brand/icon@2x.png`, `brand/logo.png`, and `brand/logo@2x.png` inside their own repository, and HA serves them from `/api/brands/integration/<domain>/...`. The `home-assistant/brands` repo **auto-closes** PRs for `custom_integrations/*` and tells contributors to use the inline mechanism.
We already ship `custom_components/battery_lifetime/brand/icon.png` (256×256) and `icon@2x.png` (512×512), so on the user's HA 2026.4.x install the icon is already served by HA core in **Settings → Devices & Services**, the integration card, and the config-flow dialog. **No PR needed.**
We ship all four assets as of v0.1.3 (icons in v0.1.1, logos added in v0.1.3 as copies of the icons). On the user's HA 2026.4.x install the icon and logo are served by HA core in **Settings → Devices & Services**, the integration card, and the config-flow dialog. **No PR needed.**
The one remaining gap is HACS's own dashboard (Downloads / repository list), which still calls the old CDN URL because `hacs/frontend` hasn't been bumped past the brands-proxy rewrite. Tracked in `hacs/integration#5179` and `#5223`; fix PRs `hacs/integration#5228`, `hacs/frontend#937`, `#929`, `#5249` are open but unmerged. Until HACS frontend ships those, the HACS Downloads panel will keep showing "icon not available". This is a HACS issue, not ours.
Optional polish: add `brand/logo.png` and `brand/logo@2x.png` (same image as icon is fine for an icon-only brand) so that places consuming the logo asset get something instead of the placeholder.
### 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:
@@ -54,16 +55,21 @@ These are the only remaining tasks in `openspec/changes/add-battery-lifetime/tas
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
### 3. ~~Investigate the multi-minute initial-setup freeze~~ — FIXED in v0.1.3
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:
v0.1.3 ships the cold-start defer: `_ensure_record` schedules `_attempt_cold_start_backfill` via `hass.async_create_task` instead of awaiting it, so `async_setup` returns within the time bounded by the entity-registry scan (sub-second on the user's install). The coordinator tracks in-flight backfills in `_pending_backfills: set[str]` and fires one persistent notification (`battery_lifetime_cold_start_complete`) when the set drains.
- `_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`.
- v0.1.2 did NOT touch this. The coordinator-tick optimization is downstream of setup; the freeze is upstream. Still open.
The dialog warning was softened from the bold/all-caps freeze warning to a calmer "background backfill may take several minutes; a notification will appear when complete" note in `strings.json` and `translations/en.json`.
### 4. Loose ends from earlier sessions
**Worth observing on the live install after upgrade:** confirm that (a) re-adding the integration completes within seconds rather than minutes; (b) the `battery_lifetime_cold_start_complete` notification appears once the background backfill finishes; (c) the per-battery `replaced_on` values populate over the following minutes; (d) no regressions in the 70 → 554 entity registration.
### 4. ~~Orphan companion entities after permanent removal~~ — FIXED in v0.1.4
v0.1.4 hooks the device-registry purge into the existing prune path. When `prune_removed_older_than` returns a non-empty list (which only happens after the 30-day grace window has expired for a soft-deleted source), the coordinator looks up the matching companion device via `device_registry.async_get_device(identifiers={(DOMAIN, source_uid)})` and calls `async_remove_device`, which cascades to all eight companion entity-registry entries.
**Pre-existing orphans accumulated before v0.1.4 are NOT retroactively cleaned.** Their JSON-store entries are already gone (so the prune-driven purge has nothing to act on for them). User can manually delete via Settings → Devices & Services. If accumulated orphans become a real pain point on the live install, a one-shot legacy-orphan scanner could be added in a future release; deferred until asked.
### 5. 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
@@ -160,3 +166,5 @@ Ready to archive once 10.2 – 10.5 are observed live and the boxes are checked.
### Archived changes
- `openspec/changes/archive/2026-05-09-optimize-coordinator-tick/` — v0.1.2 release. Synced spec `coordinator-scheduling` is at `openspec/specs/coordinator-scheduling/spec.md`.
- `openspec/changes/archive/2026-05-11-defer-cold-start-backfill/` — v0.1.3 release. Same target spec; adds two requirements (Cold-start backfill is non-blocking; Backfill batch completion is announced exactly once).
- `openspec/changes/archive/2026-05-11-autoclean-orphan-companion-entities/` — v0.1.4 release. Same target spec; adds one requirement (Pruned sources have their companion device removed).
+71 -21
View File
@@ -1,21 +1,71 @@
MIT License
Copyright (c) 2026 Rick Falkvinge
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
LICENSE: NO COPYRIGHT MONOPOLY CLAIMED, NO WARRANTY OF ANY KIND GIVEN
All code in this solution and its subprojects are IN THE PUBLIC DOMAIN,
unless specificially marked otherwise (when it comes from a different
package or commercial source).
Where the concept "public domain" does not exist, the copyright monopoly
license Creative Commons Zero (CC0) is used as a declararation of Public
Domain, or as an alternative, the Unlicense (see below).
This means that anybody may use this code for absolutely anything. The
copyright monopoly does not affect it at all. Any question that begins
with a "but can I" or "but what if", concerning permission to use this
software, is answered with a "yes". More than that: it's a "yes, and
why are you so conditioned to ask permission for using knowledge?"
Anybody submitting new code, imagery, or other components to the project
agrees to put their additions in the public domain. If you're adding a
third party component, do flag it as external.
IMPORTANT EXCEPTIONS are all images and the external libraries found
in the Bin folder of the Site projects, and in External Libraries.
The images are flagged with source in their file name. Do not commit
any new restricted code without prior consensus in the project team.
Another way of putting this is the way of the UNLICENSE:
This Project (Home Assistant Battery Lifetime integration) is free
and unencumbered software released irrevocably into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, or do anything else with it; in any form,
specifically including source code form, as a compiled binary, or
as an interpretive dance performance; for any purpose, commercial,
nonprofit, hobby, or otherwise; and by any means, specifically
including any means you can think of. You are also free to eat it,
dance with it, or have sex with it. If you figure out that last
option, the project team appreciates if you share the insight.
In jurisdictions that recognize the immoral exclusive rights of
copyright monopoly laws, the author or authors of this software
dedicate any and all copyright monopoly interest in the software
irrevocably to the public domain. We make this dedication for the
benefit of the public at large and for the benefit of our heirs and
successors (albeit explicitly not a "benefit" in the form of an
immoral and destructive right of exclusivity). We intend this
dedication to be an overt act of relinquishment in perpetuity of
all present and future rights of exclusivity to this software
under copyright monopoly law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
THE AUTHORS DO NOT WARRANT THAT THIS SOFTWARE WILL PERFORM AS
EXPECTED, PERFORM OTHER THAN EXPECTED, OR PERFORM AT ALL.
IN THE EVENT OF DAMAGES EXCEEDING TEN MILLION US DOLLARS OR CASUALTIES
EXCEEDING ONE HUNDRED PEOPLE, THE AFFLICTED USERS AGREE THAT THEY
STOLE THE SOFTWARE WHILE ON VACATION IN A FOREIGN COUNTRY AND THE
AUTHORS HAVE NEVER HEARD OF IT.
For more information, please refer to <http://unlicense.org/>
+16 -2
View File
@@ -72,11 +72,16 @@ For every tracked battery `sensor.foo_battery`, the integration creates:
| `date.foo_battery_replaced_on` | date | Manual override of replaced-on. Future dates rejected. |
| `button.foo_battery_mark_replaced` | button | Sets `replaced_on` to now and resets the model. |
| `number.foo_battery_threshold_override` | number | Optional `%` override. Blank means "use profile default." |
| `binary_sensor.foo_battery_due_next_quarter` | binary | `on` when `replace_by` falls on or before the next quarter end |
And two integration-level summary sensors:
The `replace_by` sensor also exposes a `days_until_replace` attribute (signed
integer days; negative when overdue) when a prediction exists.
And three integration-level summary sensors:
- `sensor.battery_lifetime_due_this_month`
- `sensor.battery_lifetime_due_next_3_months`
- `sensor.battery_lifetime_due_next_quarter` (includes a `next_quarter_end` attribute)
## Replacement detection
@@ -186,6 +191,15 @@ functional throughout, and a one-time persistent notification ("Battery
Lifetime: backfill complete") appears when the initial backfill batch is
done.
## When a battery disappears
When a source battery is removed from Home Assistant (device deleted, Zigbee2MQTT un-paired, integration uninstalled), the integration:
1. Drops the in-memory state immediately. The nine companion entities flip to `unavailable` in the UI.
2. **Soft-deletes** the persistent state in `.storage/battery_lifetime` — `replaced_on`, profile, threshold override, and EWMA state are kept against the chance of restore. The entry is stamped with a `removed_at` timestamp.
3. If the same `unique_id` reappears within 30 days (e.g. you re-pair the device), the prior state is restored and the companion entities resume automatically — no UI rebuild, your `replaced_on` is preserved.
4. After 30 days, the soft-deleted store entry is pruned, and the companion **device card plus all nine companion entities are removed** from Home Assistant's registry. No orphan `unavailable` rows linger.
## The forward-prediction service
```yaml
@@ -233,4 +247,4 @@ The integration **does not** model:
## License
MIT. See `LICENSE`.
This project was AI-generated. Human involvement did not meet the bar for substantial originality required for copyright protection. This work is in the public domain where applicable, or otherwise not subject to copyright protection.
@@ -0,0 +1,83 @@
"""Binary sensor platform: per-battery due-next-quarter flag."""
from __future__ import annotations
from typing import Any
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from .const import CONFIDENCE_NO_DATA, DOMAIN
from .coordinator import BatteryLifetimeCoordinator
from .entity import BatteryCompanionEntity
from .quarters import is_due_by_quarter_end
_DUE_NEXT_QUARTER_SUFFIX = "due_next_quarter"
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
coordinator: BatteryLifetimeCoordinator = hass.data[DOMAIN][entry.entry_id][
"coordinator"
]
@callback
def _build(unique_id: str) -> list[BinarySensorEntity]:
return [DueNextQuarterBinarySensor(coordinator, unique_id)]
initial: list[BinarySensorEntity] = []
for unique_id in coordinator.records:
initial.extend(_build(unique_id))
async_add_entities(initial)
seen: set[str] = set(coordinator.records)
@callback
def _on_update() -> None:
new_entities: list[BinarySensorEntity] = []
for unique_id in coordinator.records:
if unique_id in seen:
continue
seen.add(unique_id)
new_entities.extend(_build(unique_id))
if new_entities:
async_add_entities(new_entities)
entry.async_on_unload(coordinator.async_add_listener(_on_update))
class DueNextQuarterBinarySensor(BatteryCompanionEntity, BinarySensorEntity):
"""Whether the battery is projected to need replacement next quarter."""
_attr_translation_key = "due_next_quarter"
def __init__(
self, coordinator: BatteryLifetimeCoordinator, unique_id: str
) -> None:
super().__init__(coordinator, unique_id, _DUE_NEXT_QUARTER_SUFFIX)
self._attr_name = "Due next quarter"
@property
def is_on(self) -> bool | None:
record = self.record
snapshot = (self.coordinator.data or {}).get(self._source_unique_id)
if record is None or snapshot is None:
return None
if not record.tracking_enabled:
return False
prediction = snapshot.prediction
if prediction.confidence == CONFIDENCE_NO_DATA:
return False
return is_due_by_quarter_end(prediction.replace_by)
@property
def extra_state_attributes(self) -> dict[str, Any]:
record = self.record
if record is None:
return {}
return {"source_entity": record.entity_id}
+1 -1
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
from typing import Final
DOMAIN: Final = "battery_lifetime"
PLATFORMS: Final = ["sensor", "switch", "button", "date", "number"]
PLATFORMS: Final = ["sensor", "binary_sensor", "switch", "button", "date", "number"]
STORAGE_KEY: Final = "battery_lifetime"
STORAGE_VERSION: Final = 1
@@ -28,7 +28,7 @@ from homeassistant.core import (
HomeAssistant,
callback,
)
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
@@ -274,6 +274,8 @@ class BatteryLifetimeCoordinator(
self._announce_backfill_complete()
def _announce_backfill_complete(self) -> None:
if self._store.cold_start_backfill_announced:
return
persistent_notification.async_create(
self.hass,
(
@@ -284,6 +286,31 @@ class BatteryLifetimeCoordinator(
title="Battery Lifetime: backfill complete",
notification_id="battery_lifetime_cold_start_complete",
)
self._store.set_cold_start_backfill_announced()
def _purge_companions_for_pruned(self, unique_ids: list[str]) -> None:
"""Remove the companion device for each pruned source.
HA's device-registry removal cascades to the entity registry and
drops every entry tied to the device, which on the Battery Lifetime
device card is exactly the nine per-source companion entries.
Idempotent: a missing device is a silent no-op.
"""
if not unique_ids:
return
device_registry = dr.async_get(self.hass)
for source_uid in unique_ids:
device = device_registry.async_get_device(
identifiers={(DOMAIN, source_uid)}
)
if device is None:
continue
device_registry.async_remove_device(device.id)
_LOGGER.info(
"battery_lifetime: removed orphan companion device for "
"pruned source %s",
source_uid,
)
async def _attempt_cold_start_backfill(
self, record: BatteryRecord
@@ -333,7 +360,10 @@ class BatteryLifetimeCoordinator(
record = self._records.pop(unique_id, None)
if record is not None:
record.tracking_enabled = False
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
pruned = self._store.prune_removed_older_than(
REMOVED_SOURCE_RETENTION_DAYS
)
self._purge_companions_for_pruned(pruned)
return
registry = er.async_get(self.hass)
entry = registry.async_get(entity_id)
@@ -554,7 +584,10 @@ class BatteryLifetimeCoordinator(
@callback
def _handle_tick(self, _now: datetime) -> None:
self._store.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)
pruned = self._store.prune_removed_older_than(
REMOVED_SOURCE_RETENTION_DAYS
)
self._purge_companions_for_pruned(pruned)
self.hass.async_create_task(self._async_recompute_and_maybe_publish())
async def _async_recompute_and_maybe_publish(self) -> None:
@@ -1,7 +1,7 @@
{
"domain": "battery_lifetime",
"name": "Battery Lifetime",
"version": "0.1.3",
"version": "0.1.6",
"documentation": "https://github.com/Falkvinge/hassio-integration-battery-lifetime",
"issue_tracker": "https://github.com/Falkvinge/hassio-integration-battery-lifetime/issues",
"codeowners": ["@rickfalkvinge"],
@@ -0,0 +1,60 @@
"""Calendar-quarter helpers for dashboard and companion entities."""
from __future__ import annotations
from datetime import datetime, timezone
UTC = timezone.utc
def _to_utc(dt: datetime) -> datetime:
if dt.tzinfo is None:
return dt.replace(tzinfo=UTC)
return dt.astimezone(UTC)
def next_quarter_end(now: datetime | None = None) -> datetime:
"""Return 23:59:59 UTC on the last day of the next calendar quarter."""
now_dt = _to_utc(now) if now is not None else datetime.now(tz=UTC)
year = now_dt.year
month = now_dt.month
if month <= 3:
end_year, end_month, end_day = year, 6, 30
elif month <= 6:
end_year, end_month, end_day = year, 9, 30
elif month <= 9:
end_year, end_month, end_day = year, 12, 31
else:
end_year, end_month, end_day = year + 1, 3, 31
return datetime(
end_year,
end_month,
end_day,
23,
59,
59,
tzinfo=UTC,
)
def is_due_by_quarter_end(
replace_by: datetime | None,
*,
now: datetime | None = None,
) -> bool:
"""True when ``replace_by`` is on or before :func:`next_quarter_end`."""
if replace_by is None:
return False
return _to_utc(replace_by) <= next_quarter_end(now)
def days_until_replace(
replace_by: datetime | None,
*,
now: datetime | None = None,
) -> int | None:
"""Whole UTC days until ``replace_by`` (negative when overdue)."""
if replace_by is None:
return None
now_dt = _to_utc(now) if now is not None else datetime.now(tz=UTC)
return int((_to_utc(replace_by) - now_dt).total_seconds() / 86400.0)
@@ -16,10 +16,12 @@ from .const import (
CONFIDENCE_LOW,
CONFIDENCE_MEDIUM,
CONFIDENCE_HIGH,
CONFIDENCE_NO_DATA,
DOMAIN,
)
from .coordinator import BatteryLifetimeCoordinator
from .entity import BatteryCompanionEntity, companion_unique_id
from .quarters import days_until_replace, is_due_by_quarter_end, next_quarter_end
UTC = timezone.utc
@@ -29,6 +31,7 @@ _DRAIN_RATE_SUFFIX = "drain_rate"
_DUE_THIS_MONTH_UNIQUE = "battery_lifetime:summary:due_this_month"
_DUE_NEXT_3_MONTHS_UNIQUE = "battery_lifetime:summary:due_next_3_months"
_DUE_NEXT_QUARTER_UNIQUE = "battery_lifetime:summary:due_next_quarter"
async def async_setup_entry(
@@ -54,6 +57,7 @@ async def async_setup_entry(
initial.extend(_add_for_record(unique_id))
initial.append(DueThisMonthSensor(coordinator))
initial.append(DueNext3MonthsSensor(coordinator))
initial.append(DueNextQuarterSensor(coordinator))
async_add_entities(initial)
seen: set[str] = set(coordinator.records)
@@ -123,6 +127,21 @@ class ReplaceBySensor(_PerBatterySensor):
return None
return snapshot.prediction.replace_by
@property
def extra_state_attributes(self) -> dict[str, Any]:
attrs = super().extra_state_attributes
snapshot = (self.coordinator.data or {}).get(self._source_unique_id)
if snapshot is None:
return attrs
if snapshot.prediction.confidence == CONFIDENCE_NO_DATA:
return attrs
replace_by = snapshot.prediction.replace_by
remaining = days_until_replace(replace_by)
if remaining is not None:
attrs = dict(attrs)
attrs["days_until_replace"] = remaining
return attrs
class PredictionQualitySensor(_PerBatterySensor):
"""Confidence ladder value as an enum sensor."""
@@ -256,6 +275,37 @@ class DueNext3MonthsSensor(_SummarySensor):
return count
class DueNextQuarterSensor(_SummarySensor):
def __init__(self, coordinator: BatteryLifetimeCoordinator) -> None:
super().__init__(
coordinator,
unique_id=_DUE_NEXT_QUARTER_UNIQUE,
translation_key="due_next_quarter",
name="Due next quarter",
object_id="battery_lifetime_due_next_quarter",
)
@property
def native_value(self) -> int:
snapshots = self.coordinator.data or {}
cutoff = next_quarter_end()
count = 0
for snap in snapshots.values():
if not snap.record.tracking_enabled:
continue
if snap.prediction.confidence == CONFIDENCE_NO_DATA:
continue
replace_by = snap.prediction.replace_by
if replace_by is not None and replace_by <= cutoff:
count += 1
return count
@property
def extra_state_attributes(self) -> dict[str, Any]:
cutoff = next_quarter_end()
return {"next_quarter_end": cutoff.isoformat()}
def _last_day_of_month(now: datetime) -> datetime:
if now.month == 12:
next_month = now.replace(
@@ -46,6 +46,7 @@ def _empty_data(default_profile: str = DEFAULT_PROFILE) -> dict[str, Any]:
return {
"version": STORAGE_VERSION,
"default_profile": default_profile,
"cold_start_backfill_announced": False,
"batteries": {},
}
@@ -110,6 +111,9 @@ class BatteryLifetimeStore:
)
data.setdefault("default_profile", DEFAULT_PROFILE)
data.setdefault("batteries", {})
if "cold_start_backfill_announced" not in data:
# Existing installs already passed the initial backfill phase.
data["cold_start_backfill_announced"] = bool(data["batteries"])
data["version"] = STORAGE_VERSION
for entry in data["batteries"].values():
for field in _PER_BATTERY_FIELDS:
@@ -125,6 +129,18 @@ class BatteryLifetimeStore:
self._ensure_loaded()
return str(self._data.get("default_profile", DEFAULT_PROFILE))
@property
def cold_start_backfill_announced(self) -> bool:
"""Whether the one-time cold-start backfill notification was shown."""
self._ensure_loaded()
return bool(self._data.get("cold_start_backfill_announced"))
def set_cold_start_backfill_announced(self) -> None:
"""Mark the initial cold-start backfill batch as announced."""
self._ensure_loaded()
self._data["cold_start_backfill_announced"] = True
self.async_save_debounced()
def set_default_profile(self, profile: str) -> None:
self._ensure_loaded()
self._data["default_profile"] = profile
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "Battery 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\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
"description": "Battery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around nine companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -79,6 +79,14 @@
},
"due_next_3_months": {
"name": "Due in next 3 months"
},
"due_next_quarter": {
"name": "Due next quarter"
}
},
"binary_sensor": {
"due_next_quarter": {
"name": "Due next quarter"
}
},
"switch": {
@@ -3,7 +3,7 @@
"step": {
"user": {
"title": "Set up Battery Lifetime",
"description": "Battery 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\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
"description": "Battery Lifetime auto-discovers every numeric percent battery sensor in Home Assistant and creates around nine companion entities per battery (replace-by, drain rate, profile, threshold, etc.).\n\nSetup itself completes within seconds. Once setup finishes, a one-time cold-start backfill runs in the background, scanning long-term statistics for each battery's most recent replacement to seed the 'Replaced on' date. On installs with many batteries (50+) this background scan can take several minutes \u2014 the integration is fully functional throughout, and a persistent notification will appear when the backfill finishes.\n\nYou can opt out individual batteries from the integration's options afterwards. Press Submit to continue."
}
},
"abort": {
@@ -79,6 +79,14 @@
},
"due_next_3_months": {
"name": "Due in next 3 months"
},
"due_next_quarter": {
"name": "Due next quarter"
}
},
"binary_sensor": {
"due_next_quarter": {
"name": "Due next quarter"
}
},
"switch": {
@@ -0,0 +1,90 @@
# Quarterly battery maintenance card
#
# Uses Battery Lifetime integration companions:
# - binary_sensor.*_due_next_quarter (inclusion gate)
# - sensor.battery_lifetime_due_next_quarter (header count)
# - sensor.*_replace_by (row display: days_until_replace, last_observed_pct, …)
#
# Requires (HACS): auto-entities, template-entity-row
#
# Visible days 1–10 of March, June, September, December. Remove the outer
# conditional wrapper to preview at any time.
type: conditional
conditions:
- condition: template
value_template: >
{{ now().day <= 10 and now().month in [3, 6, 9, 12] }}
card:
type: vertical-stack
cards:
- type: markdown
content: >-
{% set count = states('sensor.battery_lifetime_due_next_quarter') %}
{% set end = state_attr('sensor.battery_lifetime_due_next_quarter', 'next_quarter_end') %}
## Quarterly battery maintenance
**{{ count }}** {% if count | int == 1 %}battery{% else %}batteries{% endif %}
due before **{{ end | as_datetime | as_local | timestamp_custom('%d %b %Y') if end else 'quarter end' }}**.
Sorted soonest first.
- type: custom:auto-entities
card:
type: entities
show_header_toggle: false
show_empty: false
filter:
template: >-
{% set excluded = [
'sensor.sm_a217f_battery_level',
'sensor.sm_s916b_battery_level',
'sensor.helena_flip_4_battery_level',
'sensor.wolf_leader_battery_level'
] %}
{% set due_flag = entity.entity_id
| replace('_replace_by', '_due_next_quarter') %}
{{ entity.entity_id.endswith('_replace_by')
and is_state(due_flag, 'on')
and state_attr(entity.entity_id, 'source_entity') not in excluded }}
options:
type: custom:template-entity-row
icon: >-
{% set days = state_attr(config.entity, 'days_until_replace') %}
{% if days is not none and days < 0 %}mdi:battery-alert
{% else %}mdi:battery-clock{% endif %}
icon_color: >-
{% set days = state_attr(config.entity, 'days_until_replace') %}
{% if days is none %}disabled
{% elif days < 0 %}red
{% elif days <= 30 %}orange
{% else %}amber{% endif %}
name: >-
{{ state_attr(config.entity, 'source_entity')
| default(config.entity)
| replace('sensor.', '')
| replace('_battery_level', '')
| replace('_battery', '')
| replace('_', ' ')
| regex_replace(find='\\s(temperature|temp)\\s', replace=' temp. ', ignorecase=True)
| title }}
state: >-
{% set days = state_attr(config.entity, 'days_until_replace') %}
{% set due = states(config.entity) %}
{% if days is not none and days < 0 %}Overdue · {{ due | as_datetime | as_local | timestamp_custom('%d %b') }}
{% elif days is not none and days == 0 %}Due today
{% elif days is not none %}{{ days }} day{% if days != 1 %}s{% endif %} · {{ due | as_datetime | as_local | timestamp_custom('%d %b') }}
{% else %}Unknown{% endif %}
secondary: >-
{% set pct = state_attr(config.entity, 'last_observed_pct') %}
{% set conf = state_attr(config.entity, 'confidence') %}
{% set rate = state_attr(config.entity, 'drain_rate_pct_day') %}
{% if pct is not none %}{{ pct | round(0) }}% now{% else %}% unknown{% endif %}
· {{ conf }}
{% if rate is not none %} · {{ rate | round(2) }}%/d{% endif %}
{% if conf == 'profile_default' %} · profile estimate{% endif %}
{% if conf == 'stale' %} · source stale{% endif %}
sort:
method: attribute
attribute: days_until_replace
numeric: true
reverse: false
@@ -0,0 +1,61 @@
## Context
Each tracked battery is represented in HA by a per-source companion device whose identifier tuple is `(DOMAIN, source_unique_id)`. The eight companion entities (replace-by sensor, prediction-quality sensor, drain-rate sensor, two switches, button, date, number) all attach to that device via their `device_info` returned from `BatteryCompanionEntity.device_info`. When the source disappears, `_async_registry_changed`'s `action: remove` branch:
1. Pops `entity_id → unique_id` from `self._source_to_unique`.
2. Soft-deletes the JSON-store entry (`store.remove_battery(unique_id)` stamps `removed_at = time.time()`; the rest of the persisted state — `replaced_on`, profile, threshold override, EWMA state — is retained against possible restore within 30 days).
3. Pops the in-memory `BatteryRecord` from `self._records`. The companion entities' `available` property flips to `False` because `record` becomes `None`, so the eight entities show as `unavailable` in the UI immediately.
4. Calls `prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)` to garbage-collect any *other* soft-deleted entries whose `removed_at` is older than 30 days.
The same `prune_removed_older_than` call also runs on every 10-minute heartbeat tick (`_handle_tick`), so the prune is in fact reasonably continuous — within ten minutes of crossing the 30-day threshold for any soft-deleted entry, the JSON store is cleaned up.
What's missing today: at the moment the JSON store actually drops a `unique_id`, the corresponding companion device + its eight entity-registry entries remain in HA's registry forever. They're orphan rows that the user must manually delete via Settings → Devices & Services → device card → ⋮ → Delete. Over a long-lived install with periodic battery-device churn (Z2M re-pairs, integration churn, sensor renames that change `unique_id`), this accumulates.
## Goals / Non-Goals
**Goals:**
- When `prune_removed_older_than` actually removes a `unique_id` from the JSON store, the matching HA device entry (`identifiers={(DOMAIN, source_unique_id)}`) and all its child entity-registry entries are removed from the HA registry in the same code path.
- The cleanup runs in both the on-remove-event path (`_async_registry_changed`) and the heartbeat path (`_handle_tick`), so cleanup happens as soon as the prune itself fires, regardless of which path triggered it.
- The cleanup is idempotent: if the device is already gone (manually deleted, race with another integration, never created in the first place), the purge step is a no-op rather than an error.
**Non-Goals:**
- Cleaning up legacy orphans accumulated before v0.1.4. Their JSON-store entries are already long pruned, so the new purge — which is keyed by the prune's return value — has nothing to act on for them. A separate one-shot "scan registry for our companion device entries with no matching JSON-store source" pass would be needed; deferred until/unless asked for.
- Changing the 30-day retention window or the prune cadence. Those are governed by `REMOVED_SOURCE_RETENTION_DAYS` and `_handle_tick`'s timer respectively and are unaffected.
- Direct entity-registry walks. HA's device-registry removal cascades the entity removals for us (see Decision 2).
## Decisions
### Decision 1: Purge by device, not by entity prefix
**Choice**: At purge time, look up the per-source companion device via `device_registry.async_get_device(identifiers={(DOMAIN, source_unique_id)})`. If found, call `device_registry.async_remove_device(device.id)`. HA's device-registry removal cascades to the entity registry, which removes all entity entries tied to that device. Since the Battery Lifetime device card is exclusively owned by this integration's eight companion entities (the source battery has its *own* device, separate from ours), the cascade removes exactly what we want.
**Alternatives considered**:
- *Walk entity registry, match by `unique_id` prefix `battery_lifetime:<source_uid>:`*: works but is O(N entities) per purge and duplicates the device-registry's cascade machinery. We'd still need to clean up the device entry separately to avoid an empty-card orphan. Rejected as more code for less cleanup.
- *Iterate the eight known suffixes and look up by exact companion `unique_id`*: brittle to suffix additions/renames. Rejected.
### Decision 2: Trust HA's device-removal cascade rather than walking the entity registry
**Choice**: After `async_remove_device(device_id)`, do not separately walk the entity registry to confirm the entries are gone. HA fires `device_registry_updated` (with `action: remove`) on device removal, and the entity registry has its own listener that removes child entities. This is HA-core behavior and is relied upon by every standard integration.
**Alternative considered**: belt-and-braces walk after the device removal. Rejected — adds code for no real benefit, and would mask if HA ever changed the cascade behavior (which would be a regression we'd want to surface, not paper over).
### Decision 3: Purge only after a successful prune, never speculatively
**Choice**: The purge is keyed off `prune_removed_older_than`'s return value (the list of `unique_id`s it actually dropped). Soft-deleted entries within their grace window are never touched. An entry that's still in the store but has `removed_at != None` is recoverable (via `store.restore_battery`) and its companion device + entities are still intact (they're just `unavailable`); restoring within the window resurrects the user's previous configuration with no UI rebuild needed.
This means: the new behavior is invisible until the 30-day grace window elapses for some real source. For the user's live install, no immediate UI change after the v0.1.4 upgrade.
## Risks / Trade-offs
- **Risk**: A user has manually deleted the device entry already (e.g. cleaned up an orphan via the UI yesterday) but the corresponding store entry hasn't yet been pruned. → Mitigation: `async_get_device` returns `None`, the purge step is a no-op for that source. No error, no warning needed.
- **Risk**: A user has manually re-added entities to our device card (e.g. via customize, or an automation that pinned an entity to our device). On purge, those would also be cascaded out. → Mitigation: practically impossible — HA's customize doesn't let you reparent entities to arbitrary devices, and our device identifiers are a tuple opaque to other integrations. If someone has truly done this, they can re-add post-purge; this risk is theoretical.
- **Risk**: HA removes the device-removal cascade or changes its semantics. → Mitigation: covered by tests; would surface as a regression rather than silent dust accumulation.
- **Trade-off**: Pre-existing orphans (sources removed before v0.1.4) are not cleaned up by this change. Acceptable because: (a) the user's current install only has them if some battery has actually been deleted in the past — observable, finite, and manually fixable; (b) bolting on a one-shot legacy scanner risks racing with the brand-new install's own platform-forward setup; (c) keeping this change small makes it easy to review and easy to ship.
## Migration Plan
No migration required. Persistent state in `.storage/battery_lifetime` is unchanged. After in-place upgrade via HACS, any source whose grace window expires (now or in the future) gets its companion device + entities cleaned up automatically. No user action needed.
## Open Questions
None.
@@ -0,0 +1,30 @@
## Why
When a tracked battery's source entity is removed from Home Assistant (device deleted, integration uninstalled, Z2M un-paired), the coordinator soft-deletes the JSON-store entry and the in-memory `BatteryRecord`, and after `REMOVED_SOURCE_RETENTION_DAYS = 30` the JSON entry is hard-deleted by `BatteryLifetimeStore.prune_removed_older_than`. But the eight HA entity-registry entries for the per-source companion entities (`sensor.<src>_replace_by`, `..._prediction_quality`, `..._drain_rate`, `switch.<src>_profile_lithium`, `..._tracking_enabled`, `button.<src>_mark_replaced`, `date.<src>_replaced_on`, `number.<src>_threshold_override`) plus the per-source companion device entry (`identifiers={(DOMAIN, source_unique_id)}`) are never removed. They stay in HA's registry indefinitely as `unavailable` orphans, and the user has to garbage-collect them manually via Settings → Devices & Services.
This is the moment where "the integration knows the source is gone for good" actually arrives — `prune_removed_older_than` returns the list of `unique_id`s it just dropped from the store. Cleaning up the corresponding companion device at that point is cheap, well-bounded, and matches user expectation.
## What Changes
- The coordinator SHALL purge each pruned source's companion device from Home Assistant's device registry whenever `prune_removed_older_than` returns a non-empty list. Removing the device is sufficient: HA's device-registry removal cascades to all entity-registry entries tied to that device, which on the Battery Lifetime device card means exactly the eight per-source companion entries.
- The two existing call sites that drive prune (`_async_registry_changed` on `action: remove`, and `_handle_tick` on every 10-minute heartbeat) SHALL feed the pruned list into the new purge step. No new call sites; no change to prune timing or the 30-day retention window.
Out of scope: legacy orphans accumulated before v0.1.4 are not retroactively cleaned up. Their JSON-store entries are already gone (so the new purge has no `unique_id` to act on), but their HA registry entries linger. Users can either delete them manually via the UI today, or wait for a future explicit "cleanup pre-existing orphans" pass if this becomes a real pain point. Not adding it now to keep the diff focused on the user's request.
## Capabilities
### New Capabilities
(none)
### Modified Capabilities
- `coordinator-scheduling`: adds a "Pruned sources have their companion device removed" requirement governing the cleanup step that runs after every prune.
## Impact
- `custom_components/battery_lifetime/coordinator.py`: add `_purge_companions_for_pruned(unique_ids)` helper; update both prune call sites to capture the return value and pass it to the purge.
- `custom_components/battery_lifetime/manifest.json`: version bump to `0.1.4`.
- `tests/test_coordinator.py`: two new tests — one direct on the purge helper, one end-to-end driving through a registry-remove + forced-old prune.
- `README.md`: short note in the existing removal/restore narrative (or a "v0.1.4 cleanup" sentence in the cold-start section, depending on what reads cleanest).
- No new runtime dependencies. No schema migration. No public service or event payload changes. No breaking changes for existing installs.
@@ -0,0 +1,25 @@
## ADDED Requirements
### Requirement: Pruned sources have their companion device removed
When `BatteryLifetimeStore.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)` returns a non-empty list of pruned source `unique_id`s, the coordinator SHALL look up the per-source companion device in HA's device registry by `identifiers={(DOMAIN, source_unique_id)}` and, if found, call `device_registry.async_remove_device(device.id)` for each pruned `unique_id`. HA's device-registry removal cascades to the entity registry and removes all entries tied to that device, which on the Battery Lifetime device card is exactly the eight per-source companion entries (`*_replace_by`, `*_prediction_quality`, `*_drain_rate`, `*_profile_lithium`, `*_tracking_enabled`, `*_mark_replaced`, `*_replaced_on`, `*_threshold_override`).
The cleanup SHALL run in both prune call sites:
- `_async_registry_changed` on `action: remove` (after the soft-delete + prune sweep).
- `_handle_tick` on every periodic heartbeat (after the prune sweep).
The cleanup SHALL be idempotent: looking up a device that does not exist (already manually removed, or never created because the source was removed before any platform forward completed) SHALL be a silent no-op.
The cleanup SHALL NOT run for soft-deleted entries that are still within their 30-day grace window. Those remain recoverable via `store.restore_battery`, and their companion devices and entities remain in the HA registry (showing `unavailable`) so that restore re-enables them without rebuilding the UI.
#### Scenario: Source pruned past the grace window has its device removed
- **WHEN** a source battery is removed from the entity registry, then enough time passes that its `removed_at` is older than `REMOVED_SOURCE_RETENTION_DAYS` (30 days), then the coordinator's heartbeat runs and `prune_removed_older_than` returns the source's `unique_id` in its drop list
- **THEN** the corresponding device entry with `identifiers={(DOMAIN, source_unique_id)}` is no longer present in HA's device registry, and the eight per-source companion entries are no longer present in HA's entity registry
#### Scenario: Source removed but still within grace window keeps its device
- **WHEN** a source battery is removed from the entity registry and the next heartbeat fires within the 30-day retention window
- **THEN** the prune returns an empty list for this source, the device entry remains in the registry, the eight companion entries remain in the registry showing `unavailable`, and a subsequent `store.restore_battery(unique_id)` call (e.g. because the source reappeared) re-enables the entities without rebuilding them
#### Scenario: Purge of a source whose device was already manually removed is a no-op
- **WHEN** `prune_removed_older_than` returns a `unique_id` for which the user has already manually deleted the companion device via the HA UI
- **THEN** `device_registry.async_get_device(identifiers={(DOMAIN, source_unique_id)})` returns `None`, the purge step is a silent no-op for that source, and no error is logged
@@ -0,0 +1,28 @@
## 1. Coordinator: purge orphan companion devices on prune
- [x] 1.1 Imported `device_registry as dr` in `coordinator.py`.
- [x] 1.2 Added `_purge_companions_for_pruned(self, unique_ids: list[str]) -> None`. Idempotent on missing device; logs at info level when a device is actually removed.
- [x] 1.3 Captured the return value of `prune_removed_older_than` in `_async_registry_changed` and fed it to the purge.
- [x] 1.4 Same in `_handle_tick`.
## 2. Tests
- [x] 2.1 `test_purge_companions_for_pruned_removes_device` — uses `MockConfigEntry` to satisfy `device_registry.async_get_or_create`'s `config_entry_id` requirement; pre-creates the device, calls the purge, asserts gone.
- [x] 2.2 `test_purge_companions_for_pruned_is_noop_for_missing_device` — calls with a never-existed unique_id and with `[]`. No exception, no notification.
- [x] 2.3 `test_remove_event_chain_purges_after_grace_window` — full chain. Forges `removed_at` directly via `store._data["batteries"]["uid-foo"]["removed_at"] = time.time() - (REMOVED_SOURCE_RETENTION_DAYS + 1) * 86400` to fast-forward the 30-day clock without monkey-patching `time.time`. Drives `_handle_tick` to trigger prune+purge. Asserts both store entry and device entry gone.
## 3. Release plumbing
- [x] 3.1 Bumped `manifest.json` `version` to `0.1.4`.
- [x] 3.2 Added "When a battery disappears" section to `README.md` documenting the soft-delete + 30-day restore window + auto-purge lifecycle.
- [x] 3.3 Full test suite green: 118 passed (115 prior + 3 new).
## 4. Close-out (executed from main checkout, not the worktree)
- [x] 4.1 Committed implementation on `agent/autoclean-orphan-companion-entities` (commit 13b3dd6).
- [ ] 4.2 Merge `agent/autoclean-orphan-companion-entities` into `master` via the main checkout (`git merge --no-ff`).
- [ ] 4.3 Push `master` to both `origin` (gitea) and `github`; push tag `v0.1.4` to both.
- [ ] 4.4 Create GitHub release `v0.1.4` via `gh release create`.
- [ ] 4.5 Sync the delta into `openspec/specs/coordinator-scheduling/spec.md` and archive the change.
- [ ] 4.6 Remove the worktree and branch.
- [ ] 4.7 Update `HANDOFF.md` to reflect v0.1.4 shipped.
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-05-11
@@ -0,0 +1,2 @@
schema: spec-driven
created: 2026-05-23
@@ -0,0 +1,57 @@
## Context
The integration already exposes `sensor.<src>_replace_by` timestamps and two rolling summary counters. A quarterly maintenance card (visible during days 1–10 of March, June, September, and December) needs batteries due before the **end of the next calendar quarter** — e.g. on 15 May (Q2), the cutoff is 30 September (Q3 end). Today that logic lives entirely in Lovelace Jinja duplicated across header and filter blocks.
Existing summary sensors use UTC for cutoff boundaries (`due_this_month`, `due_next_3_months`). This change follows the same convention for consistency.
## Goals / Non-Goals
**Goals:**
- One canonical definition of “next quarter end” reused by summary count, binary companion, and card authors.
- Per-battery `binary_sensor.<src>_due_next_quarter` so `auto-entities` can use a trivial `state: "on"` include.
- `days_until_replace` on replace-by for row coloring and sorting without timestamp parsing in templates.
- Keep companion device purge unchanged — removing the device still cascades all entity-registry entries.
**Non-Goals:**
- Changing `battery_lifetime.predict_at` service schema.
- Local-time quarter boundaries (would diverge from existing summary sensors).
- A custom Lovelace card in this repository.
- Retroactive entity creation for installs until the next coordinator refresh / rediscovery (standard HA platform behaviour).
## Decisions
### Decision: Next quarter end is end of the calendar quarter after the current one
Given a reference datetime, map its month to a cutoff at 23:59:59 UTC on the last day of the next calendar quarter:
| Reference month | Next quarter end (UTC) |
| --------------- | ---------------------- |
| Jan–Mar | 30 June |
| Apr–Jun | 30 September |
| Jul–Sep | 31 December |
| Oct–Dec | 31 March (following year) |
Alternative considered: align only during the Mar/Jun/Sep/Dec maintenance window. Rejected because integration entities should be meaningful year-round for automations and other dashboards.
### Decision: `days_until_replace` is a signed whole-day floor
Compute `floor((replace_by - now) / 86400)` in UTC. Negative values mean overdue. Omit the attribute when `replace_by` is `None` or confidence is `no_data`. Alternative considered: fractional days. Rejected — dashboards want integer labels (“12 days”).
### Decision: Binary companion is `off` for `no_data` and untracked batteries
`binary_sensor.<src>_due_next_quarter` is `on` only when `tracking_enabled`, `replace_by` is set, confidence is not `no_data`, and `replace_by <= next_quarter_end`. Stale batteries with a frozen `replace_by` still evaluate normally. Alternative considered: separate `unknown` state. Rejected — binary sensors are simpler as on/off for Lovelace filters.
### Decision: Shared helper module `quarters.py`
Pure functions `next_quarter_end(now)` and `is_due_by_quarter_end(replace_by, now)` keep sensor and binary_sensor platforms thin and unit-testable without HA imports in the core math.
## Risks / Trade-offs
- **Companion count 8 → 9** → README and stale docs referencing “eight companions” need updating; device purge still removes all entities on the device automatically.
- **UTC vs local quarter** → A battery due “today” in local time may differ by one day from UTC boundary; matches existing summary sensor trade-off.
## Migration Plan
Non-breaking additive change. On upgrade, HA loads the new `binary_sensor` platform and creates new entities on the next setup; existing stores and services unchanged. Users replace Lovelace template filters with `*_due_next_quarter` includes when ready.
@@ -0,0 +1,34 @@
## Why
Quarterly battery-maintenance dashboards need calendar-aligned filters that the existing summary sensors (`due_this_month`, `due_next_3_months`) do not provide. Lovelace cards currently duplicate quarter-boundary math in Jinja templates and cannot filter companion entities with a simple include rule. Exposing `due_next_quarter` summary/count semantics, a `days_until_replace` attribute, and a per-battery `due_next_quarter` binary companion makes dashboard cards simpler, faster to author, and consistent with integration-level prediction data.
## What Changes
- Add integration-level sensor `sensor.battery_lifetime_due_next_quarter` counting tracked batteries whose `replace_by` is on or before the end of the calendar quarter immediately following the current one.
- Add `days_until_replace` attribute on each `sensor.<src>_replace_by` companion (signed integer days from now; negative when overdue; omitted when `replace_by` is unknown).
- Add per-battery binary companion `binary_sensor.<src>_due_next_quarter` that is `on` when the battery is tracked, has a computable `replace_by`, is not `no_data`, and that date falls on or before the next quarter end.
- Add shared quarter-boundary helper used by summary and binary companions (same cutoff semantics everywhere).
- Update the example quarterly maintenance Lovelace card to filter on `*_due_next_quarter` instead of inline timestamp math.
- Per-battery companion count increases from eight to nine; companion-device purge cascades automatically via existing device-registry removal.
## Capabilities
### New Capabilities
(none — behavior extends existing lifetime prediction surface)
### Modified Capabilities
- `lifetime-prediction`: adds next-quarter summary sensor, `days_until_replace` attribute on replace-by, and per-battery `due_next_quarter` binary companion.
## Impact
- `custom_components/battery_lifetime/quarters.py` (new): shared next-quarter-end calculation.
- `custom_components/battery_lifetime/sensor.py`: `days_until_replace` attribute; `DueNextQuarterSensor` summary.
- `custom_components/battery_lifetime/binary_sensor.py` (new platform): `DueNextQuarterBinarySensor` per battery.
- `custom_components/battery_lifetime/const.py`: add `binary_sensor` to `PLATFORMS`.
- `custom_components/battery_lifetime/translations/en.json`, `strings.json`: new entity strings.
- `examples/lovelace/quarterly-battery-maintenance-card.yaml`: simplified card using new entities.
- `README.md`: document new entities.
- Tests in `tests/test_entities.py`, `tests/test_init.py`, and new `tests/test_quarters.py`.
- `manifest.json`: version bump.
@@ -0,0 +1,72 @@
## ADDED Requirements
### Requirement: Next-quarter summary sensor
The integration SHALL provide an integration-level sensor `sensor.battery_lifetime_due_next_quarter` that counts tracked batteries whose `replace_by` timestamp is on or before 23:59:59 UTC on the last day of the calendar quarter immediately following the reference quarter of the current UTC date. Disabled batteries (`switch.<src>_tracking_enabled` off) MUST be excluded. Batteries whose `replace_by` is unknown (`no_data`) MUST NOT be counted.
#### Scenario: Count reflects next-quarter cutoff
- **WHEN** the current UTC date is 15 May 2026 and 4 tracked batteries have `replace_by` on or before 30 September 2026 23:59:59 UTC
- **THEN** `sensor.battery_lifetime_due_next_quarter` reports `4`
#### Scenario: Disabled batteries are excluded
- **WHEN** a tracked battery has `replace_by` within the next-quarter window but `switch.<src>_tracking_enabled` is `off`
- **THEN** that battery is NOT included in the count
#### Scenario: December rolls into March next year
- **WHEN** the current UTC date is 10 December 2026 and a battery has `replace_by` on 15 March 2027
- **THEN** that battery IS counted because the next-quarter end is 31 March 2027 23:59:59 UTC
### Requirement: days_until_replace attribute on replace-by sensor
Each `sensor.<src>_replace_by` companion SHALL expose a `days_until_replace` attribute when `replace_by` is known: the signed integer number of whole UTC days from the current instant to `replace_by`, rounded toward zero (negative when overdue). When `replace_by` is unknown (`no_data`), the attribute MUST be omitted.
#### Scenario: Future replacement
- **WHEN** `replace_by` is 10 UTC days in the future
- **THEN** `days_until_replace` is `10`
#### Scenario: Overdue replacement
- **WHEN** `replace_by` was 3 UTC days ago
- **THEN** `days_until_replace` is `-3`
#### Scenario: Unknown replace-by
- **WHEN** prediction quality is `no_data` and `replace_by` is unknown
- **THEN** the `days_until_replace` attribute is not present
### Requirement: Per-battery due-next-quarter binary companion
For every tracked battery, the integration SHALL create `binary_sensor.<src>_due_next_quarter` on the same companion device as the other per-source entities. It SHALL be `on` when the battery is tracked (`tracking_enabled` true), prediction quality is not `no_data`, `replace_by` is set, and `replace_by` is on or before the next-quarter end (same cutoff as the summary sensor). It SHALL be `off` otherwise.
#### Scenario: Battery due within next quarter
- **WHEN** the current UTC date is 1 March 2026, a battery is tracked with `replace_by` on 15 June 2026, and confidence is `medium`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `on`
#### Scenario: Battery due after next quarter
- **WHEN** the current UTC date is 1 March 2026 and a battery has `replace_by` on 15 August 2026
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off`
#### Scenario: Untracked battery is off
- **WHEN** `switch.<src>_tracking_enabled` is `off`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off` regardless of `replace_by`
#### Scenario: No-data battery is off
- **WHEN** prediction quality is `no_data`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off`
### Requirement: Per-battery companion entity set includes due-next-quarter binary
The per-battery companion entity set SHALL include `binary_sensor.<src>_due_next_quarter` in addition to the existing eight companions. The binary sensor MUST share the same companion device and deterministic unique-id scheme as the other per-source entities.
#### Scenario: New battery discovery creates binary companion
- **WHEN** a new eligible battery source is discovered and companion entities are created
- **THEN** `binary_sensor.<src>_due_next_quarter` exists alongside the other per-source companions within the next coordinator update
@@ -0,0 +1,27 @@
## 1. Quarter boundary helper
- [x] 1.1 Create `custom_components/battery_lifetime/quarters.py` with `next_quarter_end(now)` and `is_due_by_quarter_end(replace_by, now)`
- [x] 1.2 Add unit tests in `tests/test_quarters.py` covering month boundaries and year rollover (December → March)
## 2. Replace-by attribute and summary sensor
- [x] 2.1 Add `days_until_replace` to `ReplaceBySensor.extra_state_attributes` in `sensor.py`
- [x] 2.2 Add `DueNextQuarterSensor` summary entity (`sensor.battery_lifetime_due_next_quarter`) in `sensor.py`
- [x] 2.3 Add translation keys for the new summary sensor
## 3. Binary sensor platform
- [x] 3.1 Create `binary_sensor.py` with `DueNextQuarterBinarySensor` per tracked battery
- [x] 3.2 Register `binary_sensor` in `const.PLATFORMS` and ensure dynamic entity add on discovery matches other platforms
- [x] 3.3 Add translation keys for the binary companion
## 4. Tests and documentation
- [x] 4.1 Extend `tests/test_entities.py` for `days_until_replace`, summary count, and binary sensor on/off cases
- [x] 4.2 Update `tests/test_init.py` for new platform entities
- [x] 4.3 Update `README.md` companion table and summary sensor list (nine companions)
- [x] 4.4 Bump `manifest.json` version
## 5. Lovelace card
- [x] 5.1 Revise `examples/lovelace/quarterly-battery-maintenance-card.yaml` to filter `*_due_next_quarter` and use `days_until_replace` / summary sensor
@@ -45,3 +45,55 @@ On each periodic heartbeat the coordinator SHALL recompute every record's `Predi
#### 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
### Requirement: Cold-start backfill is non-blocking
The coordinator's `async_setup` SHALL NOT await `_attempt_cold_start_backfill` for any record. When `_ensure_record` determines that a record needs cold-start backfill, it SHALL schedule the backfill via `hass.async_create_task` and return without awaiting it. `async_setup` SHALL therefore complete in time bounded by the entity-registry scan, independent of how many tracked batteries need cold-start backfill or how slow the recorder is.
#### Scenario: Setup returns before backfill completes
- **WHEN** the coordinator is set up against an HA instance with one or more eligible source batteries that need cold-start backfill, and `_attempt_cold_start_backfill` is patched to a coroutine that does not return until externally released
- **THEN** `await coordinator.async_setup()` completes (returns control to the caller) before the patched backfill coroutine has been allowed to return
#### Scenario: Setup completes regardless of recorder availability
- **WHEN** the coordinator is set up against an HA instance where the recorder is bootstrapped but slow (or not bootstrapped at all)
- **THEN** `await coordinator.async_setup()` completes within the time bounded by the entity-registry scan; no recorder query is on its await path
### Requirement: Backfill batch completion is announced exactly once
The coordinator SHALL track in-flight cold-start backfill work via an internal `_pending_backfills: set[str]` keyed by source `unique_id`. Each backfill task SHALL add its `unique_id` to the set before it starts and remove it from the set when it finishes (success, no-hit, or exception). When the set transitions from non-empty to empty, the coordinator SHALL fire exactly one `persistent_notification` with `notification_id="battery_lifetime_cold_start_complete"` informing the user that the initial cold-start backfill phase is done.
#### Scenario: First setup with one battery needing backfill fires the notification
- **WHEN** the coordinator is set up with one eligible source battery whose persisted record has no `replaced_on`, `_attempt_cold_start_backfill` runs to completion, and `hass.async_block_till_done()` is awaited
- **THEN** exactly one persistent notification with `notification_id="battery_lifetime_cold_start_complete"` exists in the HA state machine
#### Scenario: First setup with no batteries needing backfill fires no notification
- **WHEN** the coordinator is set up against an HA instance where every eligible source battery already has a `replaced_on` persisted in the store
- **THEN** no persistent notification with `notification_id="battery_lifetime_cold_start_complete"` is created
#### Scenario: Late-discovered battery extends the batch
- **WHEN** the coordinator's initial scan starts a backfill for battery A, and a new eligible source battery B is added via `entity_registry_updated` while A's backfill is still in flight
- **THEN** B's backfill task is added to `_pending_backfills` before A finishes, and the completion notification fires only after BOTH backfills have completed
### Requirement: Pruned sources have their companion device removed
When `BatteryLifetimeStore.prune_removed_older_than(REMOVED_SOURCE_RETENTION_DAYS)` returns a non-empty list of pruned source `unique_id`s, the coordinator SHALL look up the per-source companion device in HA's device registry by `identifiers={(DOMAIN, source_unique_id)}` and, if found, call `device_registry.async_remove_device(device.id)` for each pruned `unique_id`. HA's device-registry removal cascades to the entity registry and removes all entries tied to that device, which on the Battery Lifetime device card is exactly the eight per-source companion entries (`*_replace_by`, `*_prediction_quality`, `*_drain_rate`, `*_profile_lithium`, `*_tracking_enabled`, `*_mark_replaced`, `*_replaced_on`, `*_threshold_override`).
The cleanup SHALL run in both prune call sites:
- `_async_registry_changed` on `action: remove` (after the soft-delete + prune sweep).
- `_handle_tick` on every periodic heartbeat (after the prune sweep).
The cleanup SHALL be idempotent: looking up a device that does not exist (already manually removed, or never created because the source was removed before any platform forward completed) SHALL be a silent no-op.
The cleanup SHALL NOT run for soft-deleted entries that are still within their 30-day grace window. Those remain recoverable via `store.restore_battery`, and their companion devices and entities remain in the HA registry (showing `unavailable`) so that restore re-enables them without rebuilding the UI.
#### Scenario: Source pruned past the grace window has its device removed
- **WHEN** a source battery is removed from the entity registry, then enough time passes that its `removed_at` is older than `REMOVED_SOURCE_RETENTION_DAYS` (30 days), then the coordinator's heartbeat runs and `prune_removed_older_than` returns the source's `unique_id` in its drop list
- **THEN** the corresponding device entry with `identifiers={(DOMAIN, source_unique_id)}` is no longer present in HA's device registry, and the eight per-source companion entries are no longer present in HA's entity registry
#### Scenario: Source removed but still within grace window keeps its device
- **WHEN** a source battery is removed from the entity registry and the next heartbeat fires within the 30-day retention window
- **THEN** the prune returns an empty list for this source, the device entry remains in the registry, the eight companion entries remain in the registry showing `unavailable`, and a subsequent `store.restore_battery(unique_id)` call (e.g. because the source reappeared) re-enables the entities without rebuilding them
#### Scenario: Purge of a source whose device was already manually removed is a no-op
- **WHEN** `prune_removed_older_than` returns a `unique_id` for which the user has already manually deleted the companion device via the HA UI
- **THEN** `device_registry.async_get_device(identifiers={(DOMAIN, source_unique_id)})` returns `None`, the purge step is a silent no-op for that source, and no error is logged
@@ -0,0 +1,70 @@
### Requirement: Next-quarter summary sensor
The integration SHALL provide an integration-level sensor `sensor.battery_lifetime_due_next_quarter` that counts tracked batteries whose `replace_by` timestamp is on or before 23:59:59 UTC on the last day of the calendar quarter immediately following the reference quarter of the current UTC date. Disabled batteries (`switch.<src>_tracking_enabled` off) MUST be excluded. Batteries whose `replace_by` is unknown (`no_data`) MUST NOT be counted.
#### Scenario: Count reflects next-quarter cutoff
- **WHEN** the current UTC date is 15 May 2026 and 4 tracked batteries have `replace_by` on or before 30 September 2026 23:59:59 UTC
- **THEN** `sensor.battery_lifetime_due_next_quarter` reports `4`
#### Scenario: Disabled batteries are excluded
- **WHEN** a tracked battery has `replace_by` within the next-quarter window but `switch.<src>_tracking_enabled` is `off`
- **THEN** that battery is NOT included in the count
#### Scenario: December rolls into March next year
- **WHEN** the current UTC date is 10 December 2026 and a battery has `replace_by` on 15 March 2027
- **THEN** that battery IS counted because the next-quarter end is 31 March 2027 23:59:59 UTC
### Requirement: days_until_replace attribute on replace-by sensor
Each `sensor.<src>_replace_by` companion SHALL expose a `days_until_replace` attribute when `replace_by` is known: the signed integer number of whole UTC days from the current instant to `replace_by`, rounded toward zero (negative when overdue). When `replace_by` is unknown (`no_data`), the attribute MUST be omitted.
#### Scenario: Future replacement
- **WHEN** `replace_by` is 10 UTC days in the future
- **THEN** `days_until_replace` is `10`
#### Scenario: Overdue replacement
- **WHEN** `replace_by` was 3 UTC days ago
- **THEN** `days_until_replace` is `-3`
#### Scenario: Unknown replace-by
- **WHEN** prediction quality is `no_data` and `replace_by` is unknown
- **THEN** the `days_until_replace` attribute is not present
### Requirement: Per-battery due-next-quarter binary companion
For every tracked battery, the integration SHALL create `binary_sensor.<src>_due_next_quarter` on the same companion device as the other per-source entities. It SHALL be `on` when the battery is tracked (`tracking_enabled` true), prediction quality is not `no_data`, `replace_by` is set, and `replace_by` is on or before the next-quarter end (same cutoff as the summary sensor). It SHALL be `off` otherwise.
#### Scenario: Battery due within next quarter
- **WHEN** the current UTC date is 1 March 2026, a battery is tracked with `replace_by` on 15 June 2026, and confidence is `medium`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `on`
#### Scenario: Battery due after next quarter
- **WHEN** the current UTC date is 1 March 2026 and a battery has `replace_by` on 15 August 2026
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off`
#### Scenario: Untracked battery is off
- **WHEN** `switch.<src>_tracking_enabled` is `off`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off` regardless of `replace_by`
#### Scenario: No-data battery is off
- **WHEN** prediction quality is `no_data`
- **THEN** `binary_sensor.<src>_due_next_quarter` is `off`
### Requirement: Per-battery companion entity set includes due-next-quarter binary
The per-battery companion entity set SHALL include `binary_sensor.<src>_due_next_quarter` in addition to the existing eight companions. The binary sensor MUST share the same companion device and deterministic unique-id scheme as the other per-source entities.
#### Scenario: New battery discovery creates binary companion
- **WHEN** a new eligible battery source is discovered and companion entities are created
- **THEN** `binary_sensor.<src>_due_next_quarter` exists alongside the other per-source companions within the next coordinator update
+150 -1
View File
@@ -8,7 +8,7 @@ from typing import Any
import pytest
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.const import PERCENTAGE
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers import device_registry as dr, entity_registry as er
from custom_components.battery_lifetime.const import DOMAIN
from custom_components.battery_lifetime.coordinator import (
@@ -542,6 +542,155 @@ async def test_no_pending_backfill_no_notification(hass: Any) -> None:
await coord.async_shutdown()
async def test_cold_start_completion_not_repeated_on_restart(hass: Any) -> None:
"""The backfill-complete notification fires once, not on every HA restart."""
from unittest.mock import patch
from homeassistant.components.persistent_notification import (
_async_get_or_create_notifications,
)
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()
await hass.async_block_till_done()
notifications = _async_get_or_create_notifications(hass)
assert "battery_lifetime_cold_start_complete" in notifications
assert store.cold_start_backfill_announced is True
await store.async_save()
await coord.async_shutdown()
store_reload = BatteryLifetimeStore(hass)
await store_reload.async_load()
assert store_reload.cold_start_backfill_announced is True
with patch(
"homeassistant.components.persistent_notification.async_create"
) as mock_create:
coord_reload = BatteryLifetimeCoordinator(hass, store=store_reload)
await coord_reload.async_setup()
await hass.async_block_till_done()
mock_create.assert_not_called()
await coord_reload.async_shutdown()
async def test_purge_companions_for_pruned_removes_device(hass: Any) -> None:
"""A pruned source's companion device is removed from the device registry."""
from pytest_homeassistant_custom_component.common import MockConfigEntry
entry = MockConfigEntry(domain=DOMAIN, unique_id=DOMAIN)
entry.add_to_hass(hass)
device_registry = dr.async_get(hass)
device = device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, "uid-foo")},
manufacturer="Battery Lifetime",
name="Battery: sensor.foo_battery",
)
assert (
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
is not None
)
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
coord._purge_companions_for_pruned(["uid-foo"])
await hass.async_block_till_done()
assert (
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
is None
)
await coord.async_shutdown()
async def test_purge_companions_for_pruned_is_noop_for_missing_device(
hass: Any,
) -> None:
"""Purging a unique_id with no device entry is a silent no-op."""
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
coord._purge_companions_for_pruned(["uid-never-existed"])
coord._purge_companions_for_pruned([])
await hass.async_block_till_done()
await coord.async_shutdown()
async def test_remove_event_chain_purges_after_grace_window(hass: Any) -> None:
"""Once the 30-day grace elapses, the next prune drives a device purge.
Exercises the full _async_registry_changed -> store.prune -> purge chain
by forging an old removed_at directly so prune actually removes the
entry (without waiting 30 days of wall clock).
"""
import time as _time
from pytest_homeassistant_custom_component.common import MockConfigEntry
from custom_components.battery_lifetime.const import (
REMOVED_SOURCE_RETENTION_DAYS,
)
entry = MockConfigEntry(domain=DOMAIN, unique_id=DOMAIN)
entry.add_to_hass(hass)
registry = er.async_get(hass)
_register(registry, entity_id="sensor.foo_battery", unique_id="uid-foo")
hass.states.async_set("sensor.foo_battery", "84", {})
device_registry = dr.async_get(hass)
device_registry.async_get_or_create(
config_entry_id=entry.entry_id,
identifiers={(DOMAIN, "uid-foo")},
manufacturer="Battery Lifetime",
name="Battery: sensor.foo_battery",
)
store = BatteryLifetimeStore(hass)
await store.async_load()
coord = BatteryLifetimeCoordinator(hass, store=store)
await coord.async_setup()
await hass.async_block_till_done()
assert "uid-foo" in coord.records
hass.bus.async_fire(
"entity_registry_updated",
{"action": "remove", "entity_id": "sensor.foo_battery"},
)
await hass.async_block_till_done()
assert "uid-foo" not in coord.records
stored = store.get_battery("uid-foo")
assert stored is not None
assert stored.get("removed_at") is not None
assert (
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
is not None
)
store._data["batteries"]["uid-foo"]["removed_at"] = (
_time.time() - (REMOVED_SOURCE_RETENTION_DAYS + 1) * 86400
)
coord._handle_tick(datetime.now(tz=UTC))
await hass.async_block_till_done()
assert store.get_battery("uid-foo") is None
assert (
device_registry.async_get_device(identifiers={(DOMAIN, "uid-foo")})
is None
)
await coord.async_shutdown()
async def test_source_without_unique_id_logged_and_skipped(
hass: Any, caplog: pytest.LogCaptureFixture
) -> None:
+48
View File
@@ -10,6 +10,7 @@ from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.const import PERCENTAGE
from homeassistant.helpers import entity_registry as er
from custom_components.battery_lifetime.binary_sensor import DueNextQuarterBinarySensor
from custom_components.battery_lifetime.button import MarkReplacedButton
from custom_components.battery_lifetime.coordinator import (
BatteryLifetimeCoordinator,
@@ -20,6 +21,7 @@ from custom_components.battery_lifetime.number import ThresholdOverrideNumber
from custom_components.battery_lifetime.sensor import (
DrainRateSensor,
DueNext3MonthsSensor,
DueNextQuarterSensor,
PredictionQualitySensor,
ReplaceBySensor,
)
@@ -79,6 +81,8 @@ async def test_replace_by_sensor_returns_prediction(
attrs = sensor.extra_state_attributes
assert attrs["source_entity"] == "sensor.foo_battery"
assert attrs["confidence"] in ("low", "medium", "high")
assert "days_until_replace" in attrs
assert isinstance(attrs["days_until_replace"], int)
async def test_prediction_quality_sensor_returns_string(
@@ -138,6 +142,50 @@ async def test_summary_sensors_exclude_disabled_batteries(
assert due_next.native_value == 0
async def test_summary_sensor_counts_due_next_quarter(
coord_with_battery: BatteryLifetimeCoordinator,
) -> None:
record = coord_with_battery.records["uid-foo"]
record.last_reading_pct = 18.0
record.ewma.last_pct = 18.0
record.ewma.last_at = datetime.now(tz=UTC)
record.last_reading_at = record.ewma.last_at
record.ewma.rate = 1.0
coord_with_battery.data = await coord_with_battery._async_update_data()
sensor = DueNextQuarterSensor(coord_with_battery)
assert sensor.native_value == 1
assert "next_quarter_end" in sensor.extra_state_attributes
async def test_due_next_quarter_binary_sensor(
coord_with_battery: BatteryLifetimeCoordinator,
) -> None:
record = coord_with_battery.records["uid-foo"]
record.last_reading_pct = 18.0
record.ewma.last_pct = 18.0
record.ewma.last_at = datetime.now(tz=UTC)
record.last_reading_at = record.ewma.last_at
record.ewma.rate = 1.0
coord_with_battery.data = await coord_with_battery._async_update_data()
binary = DueNextQuarterBinarySensor(coord_with_battery, "uid-foo")
assert binary.is_on is True
record.tracking_enabled = False
coord_with_battery.data = await coord_with_battery._async_update_data()
assert binary.is_on is False
async def test_replace_by_omits_days_until_for_no_data(
coord_with_battery: BatteryLifetimeCoordinator,
) -> None:
record = coord_with_battery.records["uid-foo"]
record.replaced_on = None
record.ewma.rate = None
coord_with_battery.data = await coord_with_battery._async_update_data()
sensor = ReplaceBySensor(coord_with_battery, "uid-foo")
assert "days_until_replace" not in sensor.extra_state_attributes
async def test_profile_switch_toggles_profile(
coord_with_battery: BatteryLifetimeCoordinator,
) -> None:
+2
View File
@@ -53,8 +53,10 @@ async def test_async_setup_entry_creates_companion_entities(hass: Any) -> None:
assert "button.foo_battery_mark_replaced" in states
assert "date.foo_battery_replaced_on" in states
assert "number.foo_battery_threshold_override" in states
assert "binary_sensor.foo_battery_due_next_quarter" in states
assert "sensor.battery_lifetime_due_this_month" in states
assert "sensor.battery_lifetime_due_next_3_months" in states
assert "sensor.battery_lifetime_due_next_quarter" in states
assert hass.services.has_service(DOMAIN, SERVICE_PREDICT_AT)
assert await hass.config_entries.async_unload(entry.entry_id)
+49
View File
@@ -0,0 +1,49 @@
"""Unit tests for calendar-quarter boundary helpers."""
from __future__ import annotations
from datetime import datetime, timezone
from custom_components.battery_lifetime.quarters import (
days_until_replace,
is_due_by_quarter_end,
next_quarter_end,
)
UTC = timezone.utc
def test_next_quarter_end_from_q1() -> None:
now = datetime(2026, 2, 10, 12, 0, 0, tzinfo=UTC)
end = next_quarter_end(now)
assert end == datetime(2026, 6, 30, 23, 59, 59, tzinfo=UTC)
def test_next_quarter_end_from_q2() -> None:
now = datetime(2026, 5, 15, tzinfo=UTC)
end = next_quarter_end(now)
assert end == datetime(2026, 9, 30, 23, 59, 59, tzinfo=UTC)
def test_next_quarter_end_from_q4_rolls_to_march() -> None:
now = datetime(2026, 12, 10, tzinfo=UTC)
end = next_quarter_end(now)
assert end == datetime(2027, 3, 31, 23, 59, 59, tzinfo=UTC)
def test_is_due_by_quarter_end() -> None:
now = datetime(2026, 3, 1, tzinfo=UTC)
due = datetime(2026, 6, 15, tzinfo=UTC)
late = datetime(2026, 8, 1, tzinfo=UTC)
assert is_due_by_quarter_end(due, now=now) is True
assert is_due_by_quarter_end(late, now=now) is False
assert is_due_by_quarter_end(None, now=now) is False
def test_days_until_replace_future_and_overdue() -> None:
now = datetime(2026, 5, 1, 12, 0, 0, tzinfo=UTC)
future = datetime(2026, 5, 11, 12, 0, 0, tzinfo=UTC)
past = datetime(2026, 4, 28, 12, 0, 0, tzinfo=UTC)
assert days_until_replace(future, now=now) == 10
assert days_until_replace(past, now=now) == -3
assert days_until_replace(None, now=now) is None
+2
View File
@@ -27,6 +27,7 @@ async def store(hass: Any) -> BatteryLifetimeStore:
async def test_fresh_store_loads_defaults(store: BatteryLifetimeStore) -> None:
assert store.default_profile == DEFAULT_PROFILE
assert store.cold_start_backfill_announced is False
assert list(store.iter_batteries()) == []
@@ -104,6 +105,7 @@ async def test_migration_fills_missing_fields(
assert entry["profile"] == DEFAULT_PROFILE
assert entry["tracking_enabled"] is True
assert entry["threshold_override"] is None
assert store.cold_start_backfill_announced is True
async def test_remove_then_prune(store: BatteryLifetimeStore) -> None: