diff --git a/.claude/skills/sync-with-core/SKILL.md b/.claude/skills/sync-with-core/SKILL.md new file mode 100644 index 0000000..92d72f4 --- /dev/null +++ b/.claude/skills/sync-with-core/SKILL.md @@ -0,0 +1,131 @@ +--- +name: sync-with-core +description: Fetch the latest Home Assistant core hive integration (homeassistant/components/hive) from GitHub, compare it with custom_components/hive, and merge core's changes into this repo - new and removed files, and core's edits to the files we keep our own copies of (sensor.py, __init__.py, config_flow.py, const.py, services.yaml, strings.json, icons.json) - while keeping this repo's deliberate differences. Pass `full` for a full scan that compares every file with core's current version, not just what core changed since the last sync. Leaves everything uncommitted for the user to review. Use after a new HA release or beta, when core changes the hive integration, when an import from core fails, or when the user asks to sync with or compare against core. +--- + +# Sync with core + +Principle 1 in `CLAUDE.md` applies: this component re-exports core's hive integration and only keeps its own code where it has to differ from core. Syncing means taking everything core changed, while keeping the differences that are the reason this repo exists. + +**Never commit, stage, push or stash-drop anything.** Leave every change in the working tree for the user to review, and finish with a report of what changed (step 6). Before starting, run `git status --short`. If there are uncommitted changes in files you're about to merge, tell the user and ask before going on, so their work and the merge don't get mixed up. + +## Modes +- **Default** (`/sync-with-core`, or with a target such as `/sync-with-core dev`): merge only what core changed between the last sync (base) and the target. Fast, but it never looks at a file core didn't touch. So drift in our own copies, such as a difference that's no longer needed or a core fix we never took, goes unnoticed. +- **Full scan** (`/sync-with-core full`, optionally with a target, e.g. `/sync-with-core full dev`; also when the user asks for a "full scan", "full compare" or to "check all files"): do everything the default mode does, and also step 4b. That compares **every** file in `custom_components/hive` with core's version at the target, whether core changed it or not. Use it on the first run, after a long gap, or whenever the base in `.github/core_sync.json` might be wrong. + +## 1. Pick the versions +- **Target** (what to merge in): the latest stable core release, unless the user names one (`dev`, a beta tag like `2026.12.0b1`, or another tag). Stable is the default because code from `dev` can use HA APIs our users don't have yet. + ```bash + TARGET=$(gh release view --repo home-assistant/core --json tagName -q .tagName) + ``` +- **Base** (core as it was when we last synced): read it from `.github/core_sync.json`, which looks like `{"ref": "2026.11.2"}`. The merge only applies what core changed between base and target, so our own changes are kept. + If the file doesn't exist yet (first run), use the HA version the tests run against, `.venv/bin/python -c "import homeassistant.const as c; print(c.__version__)"`, and tell the user the first merge is approximate, so they should review every hunk. + +If base and target are the same, there's nothing new from core. In default mode, say so and stop. In full-scan mode, skip the merge (step 4) and go on to step 4b. + +## 2. Fetch both versions of core +```bash +S=/core-sync; rm -rf "$S"; mkdir -p "$S" +for ref in "$BASE" "$TARGET"; do + mkdir -p "$S/$ref" + for f in $(gh api "repos/home-assistant/core/contents/homeassistant/components/hive?ref=$ref" --jq '.[] | select(.type=="file") | .name'); do + gh api "repos/home-assistant/core/contents/homeassistant/components/hive/$f?ref=$ref" --jq .content | base64 -d > "$S/$ref/$f" + done +done +diff -rq "$S/$BASE" "$S/$TARGET" # what core changed +ls custom_components/hive +``` +If a local clone of core exists (see "Related repos" in `CLAUDE.md`), you can `git -C fetch upstream --tags` and use `git -C show :homeassistant/components/hive/` instead. Ignore `__pycache__`. + +## 3. Sort every file +| File | How to sync it | +|---|---| +| Re-exported module (`binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py`, `entity.py`, `services.py`) | Leave it alone. It's one line, `from homeassistant.components.hive. import *`, so core's changes to it reach users automatically. That's expected, and this repo needs no change. Don't diff it, edit it, or list it as a change in the report | +| Our own copy (`sensor.py`, `__init__.py`, `config_flow.py`, `const.py`, `services.yaml`, `strings.json`, `icons.json`) | Three-way merge (step 4) | +| `manifest.json` | Never merge. Our `version`, exact `requirements` pin and codeowners differ on purpose (principle 2). Only add new keys core introduces, such as `quality_scale` or `loggers` | +| `translations/en.json` | Not in core. Regenerate it from `strings.json` with `.venv/bin/python script/gen_translations.py` | +| New in core | Step 5 | +| Gone from core | Step 5 | + +## 4. Merge our copies +For each file in the "our own copy" row that core changed between base and target: +```bash +cp custom_components/hive/ "$S/ours-" # keep a copy to compare against afterwards +git merge-file --diff3 -L ours -L "core $BASE" -L "core $TARGET" \ + custom_components/hive/ "$S/$BASE/" "$S/$TARGET/" +``` +`git merge-file` writes the merged result into our file. It exits with the number of conflicts, so a non-zero exit is normal here. +- **JSON files**: if ours is indented differently from core, the merge is noisy. Reformat ours to core's style first (`jq --indent 2 . `, which keeps key order). That's a whitespace-only change the user will see in the diff, so mention it. +- **Resolving conflicts**: take core's change unless it would undo one of our deliberate differences. The usual differences are the extra attribute sensors in `sensor.py`, our config flow and options flow (scan interval, 2FA debug and device registration) in `config_flow.py` and `strings.json`, and calling core's setup helpers ourselves in `__init__.py`, because core's own `__init__.py` never runs when we replace the `hive` domain. `git log -p -- ` shows why we changed something. +- If you can't tell which side is right, leave the conflict markers in place and list the conflict in the report. Lint and tests will fail until the user decides, which is what you want. +- Check every merged file for code that relies on something newer than the minimum HA version in `hacs.json`. Guard it with `try`/`except ImportError`, or tell the user the minimum needs to go up. + +## 4b. Full scan (full-scan mode only) +Compare every file on both sides with core at the target, two-way (ours against `$S/$TARGET`), whether or not core changed it. This doesn't depend on the base, so it also catches drift the merge can't see. + +**Re-exported modules**: don't diff core's code (it reaches users automatically). Only check that: +- the file is exactly `from homeassistant.components.hive. import *`, with nothing local added. If local code has crept in, report it, because it's a local override (last resort, `CLAUDE.md`); +- core still has `.py` at the target; +- it's listed in the `F403` per-file-ignores in `pyproject.toml`; +- any guarded fallback (`try`/`except ImportError`) is still needed. If the `hacs.json` minimum already has the file, the guard can go. + +**Our own copies** (`sensor.py`, `__init__.py`, `config_flow.py`, `const.py`, `services.yaml`, `strings.json`, `icons.json`), plus `manifest.json` keys: +```bash +diff -u "$S/$TARGET/" custom_components/hive/ +# JSON: compare content, not formatting +diff <(jq -S . "$S/$TARGET/") <(jq -S . custom_components/hive/) +``` +Sort every difference (hunk) into one of: +- **Deliberate**: one of our reasons to differ (the extra attribute sensors, our config and options flow, calling core's setup helpers in `__init__.py`, the `manifest.json` pin and version). Keep it. `git log -p -S '' -- ` usually shows why it was added. +- **Outdated**: core has moved on and our copy still has the old code (a renamed API, a bug fix, a removed or changed key, style core adopted). Take core's version, unless it needs an HA newer than the `hacs.json` minimum. +- **Unclear**: you can't tell. Don't change it. List it for the user. + +Also look for: +- code in our copy that duplicates something core now provides (e.g. a helper or constant core's `const.py` now has). Switch to core's when we can import it rather than copy it; +- local files that core doesn't have, other than `translations/`. Report them, so the user can confirm each one is still needed; +- for `sensor.py`: whether any sensor we add locally is now in core's `sensor.py`. If so, ours is a duplicate and can go. + +Apply only the "outdated" changes. Leave "deliberate" and "unclear" as they are. + +## 5. Add or remove files +- **New module in core** (as `services.py` was in 2026.11): add a re-export. `hacs.json` allows older HA versions that don't have the file, so guard the import: + ```python + """Re-export core's hive (added in Home Assistant ).""" + + try: + from homeassistant.components.hive. import * # noqa: F403 + except ImportError: # Home Assistant < has no hive/.py. + pass + ``` + If core added the file in a version at or below the `hacs.json` minimum, skip the guard and write the plain one line. Either way, add the file to the `F403` per-file-ignores in `pyproject.toml`, next to the other re-exports. + Then read core's `__init__.py`. If it calls something from the new file, our `__init__.py` must call it too. Import it from the local re-export (`from . import …`). Once `hacs.json` reaches that HA version, the guard can go. +- **New platform** (a new `.py` and a new entry in core's `PLATFORMS`): add the re-export and add the platform to `PLATFORMS` / `PLATFORM_LOOKUP` in our `const.py`. Point it out in the report, because it changes the entities users get. +- **New data file**: copy it as it is. +- **Removed or renamed in core**: remove or rename our file to match. Keep a guarded fallback if an older HA version that `hacs.json` still allows has the old name. +- **A re-exported module we'd now need to change**: don't copy it here. Replacing a re-export with a local module is a last resort (`CLAUDE.md`), so raise it with the user. + +Finally, record the new base: write `{"ref": ""}` to `.github/core_sync.json`. It stays uncommitted like everything else. + +## 6. Verify and report +```bash +script/lint --check # without --check it reformats every file, not just the merged ones +script/test +.venv/bin/python -c "import custom_components.hive" +``` +To tell whether a failure is new, run the tests on a clean copy without touching the user's working tree: +```bash +git worktree add "$S/clean" HEAD +(cd "$S/clean" && VENV="$OLDPWD/.venv" script/test -q) +git worktree remove --force "$S/clean" +``` +If the target is newer than the HA version in `.venv`, also run the tests against it (the `triage-compat` skill shows how to set up `.venv-ha-beta`). + +Then report to the user: +- the base and target versions; +- each file added, removed or merged, with a one-line summary of what core changed in it; +- every conflict and how you resolved it, and any you left for them; +- anything that changes behaviour for users (new platforms, entities or services); +- in full-scan mode, a table of every file checked, with each difference marked deliberate (kept), outdated (taken from core) or unclear (left for them). List the re-export checks too, so the user can see nothing was skipped; +- test and lint results, and which failures were already there before the merge. + +Say that nothing has been committed, and that `git diff` shows the full change. diff --git a/.claude/skills/triage-compat/SKILL.md b/.claude/skills/triage-compat/SKILL.md index d1645df..147a20f 100644 --- a/.claude/skills/triage-compat/SKILL.md +++ b/.claude/skills/triage-compat/SKILL.md @@ -15,20 +15,20 @@ gh run list -w compat.yml -L 5 gh run view # which jobs failed gh run view --log-failed | tail -200 ``` -From the log, note the job and the HA version. The "Find Home Assistant … release" step prints `homeassistant=` and `test_plugin=`. +From the log, note the job and the HA version. The "Find Home Assistant … release" step prints `homeassistant=` and `test_package=`. Map it using the table in MAINTAINING.md → "Compatibility is red": - **stable** fails: users are broken now, so treat it as urgent. - **beta** fails: must be fixed before the next monthly HA release. - **dev** smoke import fails: an import was renamed or removed upstream. -- The resolver step fails with "No pytest-homeassistant-custom-component release pins…": the plugin isn't published yet. Rerun later with `gh run rerun --failed`. There's nothing to fix. +- The resolver step fails with "No pytest-homeassistant==… on PyPI yet": the test package isn't published yet. Rerun later with `gh run rerun --failed`. There's nothing to fix. - **HACS/hassfest** fails: follow the validator's message. A `[REQUIREMENTS]` message about `pyhive-integration` differing from core hive is expected, and `.github/scripts/hassfest.py` reports it as a warning (see `CLAUDE.md`). If it's failing on that, hassfest has reworded the message, so update the `ALLOWED` pattern in that script. Don't loosen the pin. ## 2. Reproduce locally Use a separate venv so `.venv` (which matches CI's pinned HA) stays untouched: ```bash VENV=.venv-ha-beta script/setup -VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant-custom-component==" +VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant==" VENV=.venv-ha-beta script/test -x ``` For a dev failure, run the smoke test instead: diff --git a/.github/core_sync.json b/.github/core_sync.json new file mode 100644 index 0000000..1727e4a --- /dev/null +++ b/.github/core_sync.json @@ -0,0 +1 @@ +{"ref": "2026.11.2"} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 970ab31..82a945f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,8 +10,8 @@ updates: patterns: ["*"] labels: [dependencies] - # requirements_test.txt: the HA test plugin (which pins the HA version CI - # tests against) and ruff. pyhive-integration is handled by pyhive_bump.yml. + # requirements_test.txt: pytest-homeassistant (its version is the HA version + # CI tests against) and ruff. pyhive-integration is handled by pyhive_bump.yml. - package-ecosystem: pip directory: / schedule: diff --git a/.github/scripts/resolve_ha_release.py b/.github/scripts/resolve_ha_release.py index ee219dc..c945e25 100644 --- a/.github/scripts/resolve_ha_release.py +++ b/.github/scripts/resolve_ha_release.py @@ -1,8 +1,11 @@ -"""Find the newest Home Assistant release in a channel and its test plugin build. +"""Find the newest Home Assistant release in a channel and check its test package. + +pytest-homeassistant is versioned with Home Assistant (pytest-homeassistant==X +pins homeassistant==X), so the test package to install has the same version. Prints GitHub Actions outputs: homeassistant= - test_plugin= + test_package= skip=true|false python resolve_ha_release.py stable|beta @@ -15,9 +18,7 @@ from packaging.version import Version PYPI = "https://pypi.org/pypi/{}/json" -TEST_PLUGIN = "pytest-homeassistant-custom-component" -# How many recent test plugin releases to search for a matching HA pin. -SEARCH_DEPTH = 40 +TEST_PACKAGE = "pytest-homeassistant" def _get(url: str) -> dict: @@ -25,33 +26,20 @@ def _get(url: str) -> dict: return json.load(response) -def _newest(releases: dict[str, list], *, prerelease: bool) -> Version | None: - versions = [ +def _published(releases: dict[str, list]) -> set[Version]: + return { Version(v) for v, files in releases.items() if files and not all(f.get("yanked") for f in files) - ] - matching = [v for v in versions if v.is_prerelease == prerelease] - return max(matching, default=None) - - -def _test_plugin_for(ha_version: Version) -> str | None: - releases = _get(PYPI.format(TEST_PLUGIN))["releases"] - recent = sorted( - (v for v, files in releases.items() if files), - key=lambda v: max(f["upload_time"] for f in releases[v]), - reverse=True, - )[:SEARCH_DEPTH] - pin = f"homeassistant=={ha_version}" - for version in recent: - info = _get(PYPI.format(f"{TEST_PLUGIN}/{version}"))["info"] - if pin in (info["requires_dist"] or []): - return version - return None + } + + +def _newest(versions: set[Version], *, prerelease: bool) -> Version | None: + return max((v for v in versions if v.is_prerelease == prerelease), default=None) def main(channel: str) -> None: - releases = _get(PYPI.format("homeassistant"))["releases"] + releases = _published(_get(PYPI.format("homeassistant"))["releases"]) stable = _newest(releases, prerelease=False) if channel == "stable": target = stable @@ -69,13 +57,12 @@ def main(channel: str) -> None: print("skip=true") return - plugin = _test_plugin_for(target) - if plugin is None: - # Fail loudly: the plugin normally ships within a day of an HA release. - sys.exit(f"No {TEST_PLUGIN} release pins homeassistant=={target} yet") + if target not in _published(_get(PYPI.format(TEST_PACKAGE))["releases"]): + # Fail loudly: Home Assistant publishes both together, so this is rare. + sys.exit(f"No {TEST_PACKAGE}=={target} on PyPI yet") print(f"homeassistant={target}") - print(f"test_plugin={plugin}") + print(f"test_package={target}") print("skip=false") diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index 2377650..9c9c5b8 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -5,7 +5,7 @@ # users do. # stable/beta: full test suite on the newest release in that channel # (skipped for beta when no beta is newer than stable). -# dev: import smoke test against core's dev branch (the test plugin +# dev: import smoke test against core's dev branch (the test package # isn't published for dev builds). name: Compatibility @@ -50,7 +50,7 @@ jobs: if: steps.ha.outputs.skip != 'true' run: >- uv pip install - "pytest-homeassistant-custom-component==${{ steps.ha.outputs.test_plugin }}" + "pytest-homeassistant==${{ steps.ha.outputs.test_package }}" $(jq -r '.requirements[]' custom_components/hive/manifest.json) - name: Run tests against Home Assistant ${{ steps.ha.outputs.homeassistant }} if: steps.ha.outputs.skip != 'true' diff --git a/CLAUDE.md b/CLAUDE.md index 195765e..d875cc1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,6 +40,32 @@ still, as a testing channel. - Never let the fast channel break people. Stable releases need green CI and a green Compatibility run. +## Related repos + +Every change to this repo has to be weighed against two other repos: + +- **Home Assistant core** (`home-assistant/core`, forked as `Pyhass/core`), and + its `homeassistant/components/hive` integration. +- **`pyhive-integration`** (`Pyhass/Pyhiveapi` on GitHub, imported as + `apyhiveapi`), the library pinned in `manifest.json`. + +**This repo's Hive code mostly just imports core.** The platform modules +(`binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py`, +`entity.py`) re-export core's hive integration as they are. Local code exists only +where we have to differ from core, mainly `sensor.py`, plus the setup glue in +`__init__.py`, `config_flow.py` and `const.py`. So before changing something, check +what core does now, and don't copy core code into this repo to change it. When you +change the local code, compare it with core's version so it doesn't drift further +than it has to, and check that every `apyhiveapi` call matches the library +version we pin. + +Both repos are usually cloned somewhere on the maintainer's computer. Look for the +local clones first, for example by searching nearby directories for a git repo +whose remote matches one of the names above, and don't assume a path. Core's clone +may be a fork, so check its `upstream` remote as well as `origin`. If you can't +find one, ask the user before cloning it, or fall back to GitHub (`gh`). When a +change here should also go upstream (principle 1), say which repo it belongs in. + ## What this means for CI hassfest compares a custom integration's requirements with every core diff --git a/MAINTAINING.md b/MAINTAINING.md index ad16d25..e0acc2b 100644 --- a/MAINTAINING.md +++ b/MAINTAINING.md @@ -83,14 +83,14 @@ break the component with no change here. Open the failing run | **Tests (HA stable)** | Users on the latest HA are probably broken now | Fix first, and release a patch | | **Tests (HA beta)** | The next HA release (first Wednesday of the month) will break it | Fix before that release. Ship a beta if needed | | **Import smoke test (HA dev)** | Something the component imports was renamed or removed in core | Adapt before it reaches beta | -| **Find Home Assistant … release** step | The test plugin for a brand-new HA release isn't on PyPI yet | Usually fixes itself within a day. Rerun it | +| **Find Home Assistant … release** step | `pytest-homeassistant` for a brand-new HA release isn't on PyPI yet | Home Assistant publishes both together, so rerun it | | **HACS and hassfest** | New validation rules | Update the manifest or repo structure as it says. A pyhive `[REQUIREMENTS]` warning is expected; see [Hassfest and the pyhive pin](#hassfest-and-the-pyhive-pin) | To reproduce locally, install the HA version that failed into a separate venv: ```bash VENV=.venv-ha-beta script/setup -VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant-custom-component==" +VIRTUAL_ENV=.venv-ha-beta uv pip install "pytest-homeassistant==" VENV=.venv-ha-beta script/test ``` @@ -128,9 +128,8 @@ would break a user's installation. If hassfest rewords these messages, update th If `pyhive-integration` ever appears in HA's `homeassistant/package_constraints.txt`, HA will refuse to install a different version, and the fast channel needs rethinking. -- **`pytest-homeassistant-custom-component`** (Dependabot): this moves the HA version CI - tests against. Update the comment in `requirements_test.txt` to say which HA - version it pins. If HA has raised its minimum Python version, see below. +- **`pytest-homeassistant`** (Dependabot): Home Assistant's own test package. Its + version is the HA version CI tests against, so bumping it moves that HA version. If HA has raised its minimum Python version, see below. - **`ruff`** (Dependabot): if lint fails, run `script/lint` on the branch and push. - **GitHub Actions** (Dependabot, grouped): merge once CI passes. @@ -147,7 +146,18 @@ Then run `script/setup --recreate`. ### When dropping support for old Home Assistant versions Raise `homeassistant` in `hacs.json`. It stops HACS offering new releases to -users on older HA versions. +users on older HA versions. The minimum is currently **2026.11.0**. + +Then remove whatever only existed for the versions you dropped: + +- `try`/`except ImportError` fallbacks and version checks in `custom_components/hive`. +- Any core change that was skipped only because older versions lacked the API + (the `sync-with-core` skill lists these when it skips them). + +`tests/conftest.py` reads the minimum from `hacs.json` and stops the test run if +Home Assistant is older, so CI can't quietly keep testing a dropped version. If +that fires, bump `pytest-homeassistant` in `requirements_test.txt` to a supported +HA version. ## Repo settings (one-time; check they're still on) @@ -187,3 +197,4 @@ section above. | `/triage-compat` | Find out why Compatibility is red, reproduce it locally and fix it | | `/bump-pyhive` | Move to a new `pyhive-integration` (stable or beta), and check whether its changes affect this component | | `/repo-health` | Check workflows, recent runs, open bot PRs, branch protection and secrets in one report | +| `/sync-with-core` | Fetch the latest core hive integration and merge its changes into this repo, keeping our own differences. `/sync-with-core full` compares every file, not just what core changed. Leaves everything uncommitted for review | diff --git a/README.md b/README.md index c8891ba..7f7e2ec 100644 --- a/README.md +++ b/README.md @@ -101,8 +101,8 @@ and replace the current hive folder with the newly downloaded one. ## Development -Tests use [pytest-homeassistant-custom-component](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component), -which pins the Home Assistant version they run against. Python 3.14 is required. +Tests use Home Assistant's own [pytest-homeassistant](https://github.com/home-assistant/core/tree/dev/packages/pytest-homeassistant) +package. Its version is the Home Assistant version they run against. Python 3.14 is required. ```bash uv venv -p 3.14 && source .venv/bin/activate diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index 83ec9ef..cb3cba1 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -1,18 +1,18 @@ """Support for the Hive devices and services.""" -from __future__ import annotations - from collections.abc import Awaitable, Callable, Coroutine from functools import wraps -import logging from typing import Any, Concatenate from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive -from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +from apyhiveapi.helper.hive_exceptions import ( + HiveInvalidDeviceAuthentication, + HiveReauthRequired, +) from homeassistant.config_entries import ConfigEntry -from homeassistant.const import CONF_SCAN_INTERVAL +from homeassistant.const import CONF_SCAN_INTERVAL, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import ( @@ -23,33 +23,25 @@ from homeassistant.helpers.dispatcher import async_dispatcher_send from homeassistant.helpers.typing import ConfigType -from .const import DOMAIN, PLATFORM_LOOKUP, PLATFORMS +from .const import DOMAIN, PLATFORM_LOOKUP from .entity import HiveEntity - -try: - # Home Assistant 2026.11 moved the boost_* entity services out of the - # climate / water_heater platforms (which this component re-exports) into - # hive/services.py, registered from core's async_setup. This component - # replaces the hive domain, so core's async_setup never runs: call it here. - from homeassistant.components.hive.services import async_setup_services -except ImportError: # Home Assistant < 2026.11: the platforms register them. - async_setup_services = None - -_LOGGER = logging.getLogger(__name__) +from .services import async_setup_services type HiveConfigEntry = ConfigEntry[Hive] + CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Hive integration.""" - if async_setup_services is not None: - async_setup_services(hass) + # This component replaces the hive domain, so core's async_setup never runs. + # Register core's services (the boost_* entity services) here instead. + async_setup_services(hass) return True -async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool: +async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> None: """Set up Hive from a config entry.""" web_session = aiohttp_client.async_get_clientsession(hass) hive_config = dict(entry.data) @@ -64,36 +56,57 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool try: devices = await hive.session.startSession(hive_config) except HTTPException as error: - _LOGGER.error("Could not connect to the internet: %s", error) - raise ConfigEntryNotReady from error - except HiveReauthRequired as err: + raise ConfigEntryNotReady( + f"Could not connect to the internet: {error}" + ) from error + except (HiveReauthRequired, HiveInvalidDeviceAuthentication) as err: + # HiveInvalidDeviceAuthentication: the refresh token expired and this + # device isn't registered for device login, so the user must sign in + # again with 2FA. Without this, the reauth flow is never offered (#224). raise ConfigEntryAuthFailed from err + hub_data = devices["parent"][0] + connections: set[tuple[str, str]] = set() + if mac := hub_data.get("macAddress"): + connections.add((dr.CONNECTION_NETWORK_MAC, mac)) + device_registry = dr.async_get(hass) device_registry.async_get_or_create( config_entry_id=entry.entry_id, - identifiers={(DOMAIN, devices["parent"][0]["device_id"])}, - name=devices["parent"][0]["hiveName"], - model=devices["parent"][0]["deviceData"]["model"], - sw_version=devices["parent"][0]["deviceData"]["version"], - manufacturer=devices["parent"][0]["deviceData"]["manufacturer"], + identifiers={(DOMAIN, hub_data["device_id"])}, + connections=connections, + name=hub_data["hiveName"], + model=hub_data["deviceData"]["model"], + sw_version=hub_data["deviceData"]["version"], + manufacturer=hub_data["deviceData"]["manufacturer"], ) await hass.config_entries.async_forward_entry_setups( - entry, - [ - ha_type - for ha_type, hive_type in PLATFORM_LOOKUP.items() - if devices.get(hive_type) - ], + entry, _platforms_with_devices(devices) ) - return True +def _platforms_with_devices(devices: dict[str, list[Any]]) -> list[Platform]: + """Return the platforms Hive reported devices for. + + Only these are set up, so only these are unloaded (#208): unloading a + platform that was never set up for this entry logs a warning when another + integration has loaded it (and used to raise and abort the reload). A + reload sets the entry up again with a fresh device list, so device types + added since are still picked up. + """ + return [ + ha_type + for ha_type, hive_type in PLATFORM_LOOKUP.items() + if devices.get(hive_type) + ] -async def async_unload_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool: + +async def async_unload_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> None: """Unload a config entry.""" - return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + await hass.config_entries.async_unload_platforms_or_raise( + entry, _platforms_with_devices(entry.runtime_data.session.deviceList) + ) async def async_remove_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> None: @@ -106,19 +119,19 @@ async def async_remove_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> Non async def async_remove_config_entry_device( - hass: HomeAssistant, config_entry: HiveConfigEntry, device_entry: dr.DeviceEntry + hass: HomeAssistant, config_entry: HiveConfigEntry, device_entry: dr.AnyDeviceEntry ) -> bool: """Remove a config entry from a device.""" return True -def refresh_system[_HiveEntityT: HiveEntity, **_P]( - func: Callable[Concatenate[_HiveEntityT, _P], Awaitable[Any]], -) -> Callable[Concatenate[_HiveEntityT, _P], Coroutine[Any, Any, None]]: +def refresh_system[HiveEntityT: HiveEntity, **P]( + func: Callable[Concatenate[HiveEntityT, P], Awaitable[Any]], +) -> Callable[Concatenate[HiveEntityT, P], Coroutine[Any, Any, None]]: """Force update all entities after state change.""" @wraps(func) - async def wrapper(self: _HiveEntityT, *args: _P.args, **kwargs: _P.kwargs) -> None: + async def wrapper(self: HiveEntityT, *args: P.args, **kwargs: P.kwargs) -> None: await func(self, *args, **kwargs) async_dispatcher_send(self.hass, DOMAIN) diff --git a/custom_components/hive/binary_sensor.py b/custom_components/hive/binary_sensor.py index 6fddc41..c89aecb 100755 --- a/custom_components/hive/binary_sensor.py +++ b/custom_components/hive/binary_sensor.py @@ -1 +1 @@ -from homeassistant.components.hive.binary_sensor import * \ No newline at end of file +from homeassistant.components.hive.binary_sensor import * diff --git a/custom_components/hive/climate.py b/custom_components/hive/climate.py index 5db4b4b..5d07024 100755 --- a/custom_components/hive/climate.py +++ b/custom_components/hive/climate.py @@ -1 +1 @@ -from homeassistant.components.hive.climate import * \ No newline at end of file +from homeassistant.components.hive.climate import * diff --git a/custom_components/hive/config_flow.py b/custom_components/hive/config_flow.py index 26174c2..393962a 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -4,7 +4,8 @@ from collections.abc import Mapping import copy -from typing import Any +import logging +from typing import Any, override from apyhiveapi import Auth from apyhiveapi.helper.hive_exceptions import ( @@ -23,7 +24,6 @@ ) from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME from homeassistant.core import callback -import logging from . import HiveConfigEntry from .const import ( @@ -52,7 +52,10 @@ def _walk(node: Any) -> Any: result: dict[str, Any] = {} for key, value in node.items(): key_lower = key.lower() - if any(part in key_lower for part in ("password", "token", "secret", "code", "session")): + if any( + part in key_lower + for part in ("password", "token", "secret", "code", "session") + ): result[key] = _mask(value) else: result[key] = _walk(value) @@ -73,10 +76,11 @@ class HiveFlowHandler(ConfigFlow, domain=DOMAIN): def __init__(self) -> None: """Initialize the config flow.""" self.data: dict[str, Any] = {} - self.tokens: dict[str, str] = {} + self.tokens: dict[str, Any] = {} self.device_registration: bool = False self.device_name = "Home Assistant" + @override async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -128,7 +132,11 @@ async def async_step_user( auth_result = self.tokens.get("AuthenticationResult", {}) new_device = auth_result.get("NewDeviceMetadata") or {} access_token = auth_result.get("AccessToken") - if new_device.get("DeviceGroupKey") and new_device.get("DeviceKey") and access_token: + if ( + new_device.get("DeviceGroupKey") + and new_device.get("DeviceKey") + and access_token + ): # If Hive returned fresh device metadata directly from login, register it now # so fallback device auth works when refresh tokens expire. self.hive_auth.access_token = access_token @@ -136,10 +144,16 @@ async def async_step_user( self.hive_auth.device_key = new_device["DeviceKey"] try: await self.hive_auth.device_registration(self.device_name) - self.data["device_data"] = await self.hive_auth.get_device_data() - _LOGGER.debug("Stored Hive device_data from login NewDeviceMetadata.") + self.data[ + "device_data" + ] = await self.hive_auth.get_device_data() + _LOGGER.debug( + "Stored Hive device_data from login NewDeviceMetadata." + ) except HiveApiError: - _LOGGER.warning("Hive device registration failed after login; continuing without device_data.") + _LOGGER.warning( + "Hive device registration failed after login; continuing without device_data." + ) try: return await self.async_setup_hive_entry() @@ -185,12 +199,23 @@ async def async_step_2fa( if not errors: _LOGGER.debug("2FA successful") if self.source == SOURCE_REAUTH: - device_registered = await self.hive_auth.is_device_registered() - if device_registered: - return await self.async_setup_hive_entry() - - self.device_registration = True - return await self.async_step_configuration() + try: + device_registered = await self.hive_auth.is_device_registered() + except HiveApiError as err: + _LOGGER.debug( + "Failed to check whether the Hive device" + " is registered during reauthentication: %s", + err, + ) + errors["base"] = "no_internet_available" + else: + if device_registered: + return await self.async_setup_hive_entry() + self.device_registration = True + return await self.async_step_configuration() + else: + self.device_registration = True + return await self.async_step_configuration() schema = vol.Schema({vol.Required(CONF_CODE): str}) return self.async_show_form(step_id="2fa", data_schema=schema, errors=errors) @@ -203,10 +228,11 @@ async def async_step_configuration( if user_input: if self.device_registration: + _LOGGER.debug("Attempting to register device") self.device_name = user_input["device_name"] await self.hive_auth.device_registration(user_input["device_name"]) self.data["device_data"] = await self.hive_auth.get_device_data() - + _LOGGER.debug("Device registration successful") try: return await self.async_setup_hive_entry() except UnknownHiveError: @@ -225,6 +251,8 @@ async def async_setup_hive_entry(self) -> ConfigFlowResult: if "AuthenticationResult" not in self.tokens: raise UnknownHiveError + # Setup the config entry + _LOGGER.debug("Setting up Hive entry") self.data["tokens"] = self.tokens if self.source == SOURCE_REAUTH: return self.async_update_reload_and_abort( @@ -239,10 +267,12 @@ async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Re Authenticate a user.""" + self.data = dict(entry_data) data = { CONF_USERNAME: entry_data[CONF_USERNAME], CONF_PASSWORD: entry_data[CONF_PASSWORD], } + _LOGGER.debug("Reauthenticating user") return await self.async_step_user(data) @staticmethod diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 0caf965..0ed498f 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -1,7 +1,7 @@ """Constants for Hive.""" + from homeassistant.const import Platform -ATTR_MODE = "mode" ATTR_TIME_PERIOD = "time_period" ATTR_ONOFF = "on_off" CONF_CODE = "2fa" diff --git a/custom_components/hive/icons.json b/custom_components/hive/icons.json index d955e01..8b8a785 100644 --- a/custom_components/hive/icons.json +++ b/custom_components/hive/icons.json @@ -1,31 +1,31 @@ { - "entity": { - "binary_sensor": { - "heating": { - "default": "mdi:radiator" - }, - "hot_water": { - "default": "mdi:hand-water" - } + "entity": { + "binary_sensor": { + "heating": { + "default": "mdi:radiator" }, - "sensor": { - "heating": { - "default": "mdi:radiator" - }, - "hot_water": { - "default": "mdi:hand-water" - } + "hot_water": { + "default": "mdi:hand-water" } }, - "services": { - "boost_heating_on": { - "service": "mdi:radiator" + "sensor": { + "heating": { + "default": "mdi:radiator" }, - "boost_heating_off": { - "service": "mdi:radiator-off" - }, - "boost_hot_water": { - "service": "mdi:water-boiler" + "hot_water": { + "default": "mdi:hand-water" } } - } \ No newline at end of file + }, + "services": { + "boost_heating_off": { + "service": "mdi:radiator-off" + }, + "boost_heating_on": { + "service": "mdi:radiator" + }, + "boost_hot_water": { + "service": "mdi:water-boiler" + } + } +} diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index c1c317c..aea2177 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -1,8 +1,14 @@ { "domain": "hive", "name": "Hive", + "categories": [ + "climate.thermostats_heating", + "lighting.bulbs_lamps", + "plugs_switches" + ], "codeowners": ["@KJonline"], "config_flow": true, + "connectivity": ["cloud"], "documentation": "https://github.com/Pyhass/Hive-Custom-Component", "homekit": { "models": ["HHKBridge*"] diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index 0c3030c..bf1775b 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -2,9 +2,11 @@ from collections.abc import Callable from dataclasses import dataclass -from datetime import timedelta +from datetime import datetime, timedelta from typing import Any +from apyhiveapi import Hive + from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -20,16 +22,15 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType +from homeassistant.util import dt as dt_util from . import HiveConfigEntry from .entity import HiveEntity -from apyhiveapi import Hive PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) - @dataclass(frozen=True) class HiveSensorEntityDescription(SensorEntityDescription): """Describes Hive sensor entity.""" @@ -41,6 +42,7 @@ class HiveSensorEntityDescription(SensorEntityDescription): HiveSensorEntityDescription( key="Battery", native_unit_of_measurement=PERCENTAGE, + state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.BATTERY, entity_category=EntityCategory.DIAGNOSTIC, ), @@ -92,6 +94,10 @@ class HiveSensorEntityDescription(SensorEntityDescription): HiveSensorEntityDescription(key="Availability", icon="mdi:check-circle"), ) +# Core's binary_sensor already shows whether boost is on for these. We add a +# timestamp sensor for when the boost ends, which automations can trigger on. +BOOST_TYPES = ("Heating_Boost", "Hotwater_Boost") + async def async_setup_entry( hass: HomeAssistant, @@ -103,15 +109,18 @@ async def async_setup_entry( devices = hive.session.deviceList.get("sensor") if not devices: return - async_add_entities( - ( - HiveSensorEntity(hass, entry, hive, dev, description) - for dev in devices - for description in SENSOR_TYPES - if dev["hiveType"] == description.key - ), - True, + entities: list[SensorEntity] = [ + HiveSensorEntity(hass, entry, hive, dev, description) + for dev in devices + for description in SENSOR_TYPES + if dev["hiveType"] == description.key + ] + entities.extend( + HiveBoostEndSensorEntity(hass, entry, hive, dev) + for dev in devices + if dev["hiveType"] in BOOST_TYPES ) + async_add_entities(entities, True) class HiveSensorEntity(HiveEntity, SensorEntity): @@ -131,29 +140,17 @@ def __init__( super().__init__(hass, entry, hive, hive_device) self.entity_description = entity_description - async def async_update(self): + async def async_update(self) -> None: """Update all Node data from Hive.""" await self.hive.session.updateData(self.device) self.device = await self.hive.sensor.getSensor(self.device) - if self.device["hiveType"] == "CurrentTemperature": + if self.device["hiveType"] == "Heating_Current_Temperature": self._attr_extra_state_attributes = await self.get_current_temp_sa() - elif self.device["hiveType"] in ("Heating_State", "Heating_Mode"): + elif self.device["hiveType"] == "Heating_Mode": self._attr_extra_state_attributes = await self.get_heating_state_sa() - elif self.device["hiveType"] == "Heating_Boost": - s_a = {} - if await self.hive.heating.getBoostStatus(self.device) == "ON": - minsend = await self.hive.heating.getBoostTime(self.device) - s_a.update({"Boost ends in": (str(minsend) + " minutes")}) - self._attr_extra_state_attributes = s_a - elif self.device["hiveType"] in ("Hotwater_State", "Hotwater_Mode"): + elif self.device["hiveType"] == "Hotwater_Mode": self._attr_extra_state_attributes = await self.get_hotwater_state_sa() - elif self.device["hiveType"] == "Hotwater_Boost": - s_a = {} - if await self.hive.hotwater.getBoost(self.device) == "ON": - endsin = await self.hive.hotwater.getBoostTime(self.device) - s_a.update({"Boost ends in": (str(endsin) + " minutes")}) - self._attr_extra_state_attributes = s_a if self.device["hiveType"] not in ("sense", "Availability"): self._attr_available = self.device.get("deviceData", {}).get("online", True) @@ -167,9 +164,6 @@ async def async_update(self): async def get_current_temp_sa(self): """Get current heating temperature state attributes.""" s_a = {} - temp_current = 0 - temperature_target = 0 - temperature_difference = 0 minmax_temps = await self.hive.heating.minmaxTemperature(self.device) if minmax_temps is not None: @@ -193,10 +187,15 @@ async def get_current_temp_sa(self): } ) - temp_current = await self.hive.heating.currentTemperature(self.device) - temperature_target = await self.hive.heating.targetTemperature(self.device) + # This sensor's own state is the current temperature (getSensor reads it). + temp_current = self.device.get("status", {}).get("state") + temperature_target = await self.hive.heating.getTargetTemperature(self.device) - if temperature_target > temp_current: + if ( + isinstance(temp_current, (int, float)) + and isinstance(temperature_target, (int, float)) + and temperature_target > temp_current + ): temperature_difference = temperature_target - temp_current temperature_difference = round(temperature_difference, 2) @@ -314,3 +313,60 @@ async def get_hotwater_state_sa(self): s_a.update({"Schedule not active": ""}) return s_a + + +class HiveBoostEndSensorEntity(HiveEntity, SensorEntity): + """When a heating or hot water boost ends (unknown when no boost is on).""" + + _attr_device_class = SensorDeviceClass.TIMESTAMP + _attr_icon = "mdi:timer-outline" + + def __init__( + self, + hass: HomeAssistant, + entry: HiveConfigEntry, + hive: Hive, + hive_device: dict[str, Any], + ) -> None: + """Initialise the boost end sensor.""" + super().__init__(hass, entry, hive, hive_device) + # Core's Boost binary sensor uses "-" already. + self._attr_unique_id = f"{self._attr_unique_id}-end" + self._attr_name = f"{self.device['haName']} ends".strip() + + async def async_update(self) -> None: + """Update the boost end time from Hive.""" + await self.hive.session.updateData(self.device) + self.device = await self.hive.sensor.getSensor(self.device) + self._attr_available = self.device.get("deviceData", {}).get("online", True) + + if self.device["hiveType"] == "Heating_Boost": + boost_on = await self.hive.heating.getBoostStatus(self.device) == "ON" + minutes = await self.hive.heating.getBoostTime(self.device) + else: + boost_on = await self.hive.hotwater.getBoost(self.device) == "ON" + minutes = await self.hive.hotwater.getBoostTime(self.device) + + self._attr_native_value = self._boost_end(boost_on, minutes) + + def _boost_end(self, boost_on: bool, minutes: Any) -> datetime | None: + """Work out when the boost ends, keeping the time steady between polls.""" + try: + remaining = int(minutes) + except TypeError, ValueError: + remaining = None + if not boost_on or remaining is None or remaining < 0: + return None + + end = (dt_util.utcnow() + timedelta(minutes=remaining)).replace( + second=0, microsecond=0 + ) + # Hive reports whole minutes, so each poll's estimate wobbles by up to a + # minute. Keep the previous time unless it moved more than that, so the + # state (and automations using it) only change when the boost does. + previous = self._attr_native_value + if isinstance(previous, datetime) and abs(end - previous) <= timedelta( + minutes=1 + ): + return previous + return end diff --git a/custom_components/hive/services.py b/custom_components/hive/services.py new file mode 100644 index 0000000..0d33f40 --- /dev/null +++ b/custom_components/hive/services.py @@ -0,0 +1 @@ +from homeassistant.components.hive.services import * diff --git a/custom_components/hive/services.yaml b/custom_components/hive/services.yaml index 15c4b7f..e2ad598 100755 --- a/custom_components/hive/services.yaml +++ b/custom_components/hive/services.yaml @@ -44,4 +44,4 @@ boost_hot_water: select: options: - "on" - - "off" \ No newline at end of file + - "off" diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 4ff73ae..90c237a 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -1,62 +1,124 @@ { "config": { - "abort": { - "already_configured": "Account is already configured", - "reauth_successful": "Re-authentication was successful", - "unknown_entry": "Unable to find existing entry." + "step": { + "user": { + "title": "Hive login", + "description": "Enter your Hive login information.", + "data": { + "username": "Username", + "password": "Password", + "disable_2fa_debug": "Disable 2FA (debug)", + "scan_interval": "Scan interval (seconds)" + } }, - "error": { - "invalid_code": "Failed to sign into Hive. Your two-factor authentication code was incorrect.", - "invalid_password": "Failed to sign into Hive. Incorrect password please try again.", - "invalid_username": "Failed to sign into Hive. Your email address is not recognised.", - "twofa_bypassed_debug": "2FA step was intentionally bypassed for debug. Check Home Assistant logs for Hive auth responses.", - "no_internet_available": "An internet connection is required to connect to Hive.", - "unknown": "Unexpected error" + "2fa": { + "title": "Hive two-factor authentication", + "description": "Enter your Hive authentication code.\n\nPlease enter code 0000 to request another code.", + "data": { + "2fa": "Two-factor code" + } }, - "step": { - "2fa": { - "data": { - "2fa": "Two-factor code" - }, - "description": "Enter your Hive authentication code. \n \n Please enter code 0000 to request another code.", - "title": "Hive Two-factor Authentication." - }, - "configuration": { - "data": { - "device_name": "Device Name" - }, - "description": "Enter your Hive configuration ", - "title": "Hive Configuration." - }, - "reauth": { - "data": { - "password": "Password", - "username": "Username" - }, - "description": "Re-enter your Hive login information.", - "title": "Hive Login" - }, - "user": { - "data": { - "password": "Password", - "disable_2fa_debug": "Disable 2FA (debug)", - "scan_interval": "Scan Interval (seconds)", - "username": "Username" - }, - "description": "Enter your Hive login information.", - "title": "Hive Login" - } + "configuration": { + "title": "Hive configuration", + "description": "Enter your Hive configuration.", + "data": { + "device_name": "Device name" + } + }, + "reauth": { + "title": "Hive login", + "description": "Re-enter your Hive login information.", + "data": { + "username": "Username", + "password": "Password" + } } + }, + "error": { + "invalid_username": "Failed to sign in to Hive. Your email address is not recognized.", + "invalid_password": "Failed to sign in to Hive. Incorrect password, please try again.", + "invalid_code": "Failed to sign in to Hive. Your two-factor authentication code was incorrect.", + "twofa_bypassed_debug": "2FA step was intentionally bypassed for debug. Check Home Assistant logs for Hive auth responses.", + "no_internet_available": "An Internet connection is required to connect to Hive.", + "unknown": "Unexpected error" + }, + "abort": { + "already_configured": "Account is already configured", + "unknown_entry": "Unable to find existing entry.", + "reauth_successful": "Re-authentication was successful" + } }, "options": { - "step": { - "user": { - "data": { - "scan_interval": "Scan Interval (seconds)" - }, - "description": "Update the scan interval to poll for data more often.", - "title": "Options for Hive" - } + "step": { + "user": { + "title": "Options for Hive", + "description": "Update the scan interval to poll for data more often.", + "data": { + "scan_interval": "Scan interval (seconds)" + } + } + } + }, + "services": { + "boost_heating_on": { + "name": "Boost heating on", + "description": "Sets the boost mode ON, defining the period of time and the desired target temperature for the boost.", + "fields": { + "time_period": { + "name": "Time period", + "description": "The time period for the boost." + }, + "temperature": { + "name": "Temperature", + "description": "The target temperature for the boost period." + } + } + }, + "boost_heating_off": { + "name": "Boost heating off", + "description": "Sets the boost mode OFF.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "The entity ID to turn boost off." + } + } + }, + "boost_hot_water": { + "name": "Boost hotwater", + "description": "Sets the boost mode ON or OFF, defining the period of time for the boost.", + "fields": { + "entity_id": { + "name": "Entity ID", + "description": "The entity ID to boost." + }, + "time_period": { + "name": "Time period", + "description": "The time period for the boost." + }, + "on_off": { + "name": "Mode", + "description": "Set the boost function on or off." + } + } + } + }, + "entity": { + "sensor": { + "heating": { + "state": { + "manual": "Manual", + "off": "Off", + "schedule": "Schedule" + } + }, + "hot_water": { + "state": { + "on": "On", + "off": "Off", + "schedule": "Schedule" + } } + } } } diff --git a/hacs.json b/hacs.json index 6752d1f..ae2baf6 100644 --- a/hacs.json +++ b/hacs.json @@ -1,6 +1,5 @@ { "name": "Hive Custom Component", - "render_readme": true, - "content_in_root": false, - "homeassistant": "2025.6.0" + "homeassistant": "2026.11.0", + "hide_default_branch": true } diff --git a/pyproject.toml b/pyproject.toml index 16f9fb4..66db6ec 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -19,7 +19,7 @@ ignore = [ [tool.ruff.lint.per-file-ignores] # These platforms re-export Home Assistant core's hive platforms on purpose. -"custom_components/hive/{binary_sensor,climate,entity,light,switch,water_heater}.py" = ["F403"] +"custom_components/hive/{binary_sensor,climate,entity,light,services,switch,water_heater}.py" = ["F403"] [tool.ruff.lint.isort] force-sort-within-sections = true @@ -36,3 +36,7 @@ homeassistant = ["homeassistant"] testpaths = ["tests"] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" +# Let Home Assistant install its httpx alias before respx is imported +# (pytest-homeassistant README). Its HTTP mocks still use respx directly. +addopts = "-p no:respx" +pythonpath = ["."] diff --git a/requirements_test.txt b/requirements_test.txt index c7b64a2..eaa1db6 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,5 +1,9 @@ -# Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). +# pytest-homeassistant is Home Assistant's own test package (it replaced +# pytest-homeassistant-custom-component in 2026.11). Its version is the Home +# Assistant version it pins, so this line sets the HA version the tests run +# against. It must be at or above the hacs.json minimum (2026.11.0), or +# tests/conftest.py stops the run. # Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. ruff==0.17.3 -pytest-homeassistant-custom-component==0.13.370 +pytest-homeassistant==2026.11.2 diff --git a/script/setup b/script/setup index 9eaf514..2ee5a8b 100755 --- a/script/setup +++ b/script/setup @@ -25,7 +25,13 @@ else uv venv --python "$PYTHON_VERSION" "$VENV" fi -# Same install as the CI test job: the HA test plugin (which pins homeassistant), +# pytest-homeassistant replaced pytest-homeassistant-custom-component in HA 2026.11, +# and the two can't be installed together. Remove the old one from older venvs. +if "$VENV/bin/python" -c 'import importlib.util as u, sys; sys.exit(u.find_spec("pytest_homeassistant_custom_component") is None)'; then + VIRTUAL_ENV="$VENV" uv pip uninstall pytest-homeassistant-custom-component +fi + +# Same install as the CI test job: the HA test package (which pins homeassistant), # ruff, and the component's own requirements from manifest.json. VIRTUAL_ENV="$VENV" uv pip install \ -r requirements_test.txt \ diff --git a/tests/conftest.py b/tests/conftest.py index b0b8d9d..f180f38 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,16 +1,32 @@ """Fixtures for Hive custom component tests.""" from collections.abc import Generator +import json +from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, patch +from awesomeversion import AwesomeVersion import pytest -from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry -from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, __version__ as HA_VERSION from homeassistant.core import HomeAssistant -from custom_components.hive.const import DOMAIN +# Only Home Assistant versions at or above the hacs.json minimum are supported. +# Refuse to test anything older, rather than fail with confusing import errors. +MIN_HA_VERSION = json.loads( + (Path(__file__).parents[1] / "hacs.json").read_text(encoding="utf-8") +)["homeassistant"] +if AwesomeVersion(HA_VERSION) < AwesomeVersion(MIN_HA_VERSION): + pytest.exit( + f"Home Assistant {HA_VERSION} is older than the minimum this component " + f"supports ({MIN_HA_VERSION}, from hacs.json). Test against a newer " + "Home Assistant: bump pytest-homeassistant in requirements_test.txt.", + returncode=1, + ) + +from custom_components.hive.const import DOMAIN # noqa: E402 USERNAME = "user@example.com" PASSWORD = "test-password" @@ -24,10 +40,8 @@ } DEVICE_DATA = ["device-group-key", "device-key", "device-password"] - -@pytest.fixture(autouse=True) -def auto_enable_custom_integrations(enable_custom_integrations: None) -> None: - """Load custom_components/hive instead of the core hive integration.""" +# pytest-homeassistant's hass fixture enables custom integrations by default, so +# custom_components/hive loads instead of the core hive integration. def make_device( @@ -123,6 +137,13 @@ def mock_hive( hive.session.updateData = AsyncMock() hive.sensor.getSensor = AsyncMock(side_effect=_echo) hive.heating.getClimate = AsyncMock(side_effect=_echo) + # Extra attributes on the heating sensors (min/max, boost end); no data by default. + hive.heating.minmaxTemperature = AsyncMock(return_value=None) + hive.heating.getTargetTemperature = AsyncMock(return_value=None) + hive.heating.getBoostStatus = AsyncMock(return_value="OFF") + hive.heating.getBoostTime = AsyncMock(return_value=None) + hive.hotwater.getBoost = AsyncMock(return_value="OFF") + hive.hotwater.getBoostTime = AsyncMock(return_value=None) hive.hotwater.getWaterHeater = AsyncMock(side_effect=_echo) hive.light.getLight = AsyncMock(side_effect=_echo) hive.switch.getSwitch = AsyncMock(side_effect=_echo) diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py index 759f76e..7de620d 100644 --- a/tests/test_binary_sensor.py +++ b/tests/test_binary_sensor.py @@ -3,7 +3,7 @@ from typing import Any import pytest -from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant @@ -74,7 +74,8 @@ async def test_heating_and_hot_water_state_sensors( """Heating and hot water state/boost come from the sensor list as binary sensors. They have no description in this component's sensor platform, so they don't - also show up as sensors. + also show up as sensors. The only sensors are the "Boost ends" timestamps + this component adds next to the Boost binary sensors. """ assert hass.states.get("binary_sensor.thermostat_heating_state").state == STATE_ON assert hass.states.get("binary_sensor.thermostat_heating_boost").state == STATE_OFF @@ -82,4 +83,7 @@ async def test_heating_and_hot_water_state_sensors( hass.states.get("binary_sensor.hot_water_hotwater_boost").state == STATE_UNAVAILABLE ) - assert hass.states.async_entity_ids("sensor") == [] + assert sorted(hass.states.async_entity_ids("sensor")) == [ + "sensor.hot_water_hotwater_boost_ends", + "sensor.thermostat_heating_boost_ends", + ] diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index 90cee7f..0ec57ec 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -9,7 +9,7 @@ HiveInvalidUsername, ) import pytest -from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME diff --git a/tests/test_init.py b/tests/test_init.py index 231f9fd..fffc37c 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -4,23 +4,24 @@ from aiohttp.web_exceptions import HTTPServiceUnavailable from apyhiveapi.helper.hive_exceptions import ( - HiveConnectionError, + HiveInvalidDeviceAuthentication, HiveReauthRequired, - HiveUnknownConfiguration, ) import pytest -from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from homeassistant.helpers.dispatcher import async_dispatcher_connect +from homeassistant.setup import async_setup_component from custom_components.hive import async_remove_config_entry_device, refresh_system from custom_components.hive.const import DOMAIN from .conftest import HUB_ID +from .test_light import WARM_WHITE async def test_setup_and_unload( @@ -48,10 +49,11 @@ async def test_setup_and_unload( @pytest.mark.parametrize( ("exception", "state", "reauth"), [ + # pyhive-integration 2.0 adds HiveConnectionError (retry) and + # HiveUnknownConfiguration (reauth). Add them back with that bump. (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY, False), - (HiveConnectionError(), ConfigEntryState.SETUP_RETRY, False), (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR, True), - (HiveUnknownConfiguration(), ConfigEntryState.SETUP_ERROR, True), + (HiveInvalidDeviceAuthentication(), ConfigEntryState.SETUP_ERROR, True), ], ) async def test_setup_failures( @@ -107,6 +109,44 @@ async def test_only_platforms_with_devices_are_set_up(hass: HomeAssistant) -> No assert f"hive.{platform}" not in hass.config.components +async def test_reload_skips_platforms_never_set_up( + hass: HomeAssistant, + setup_integration: MockConfigEntry, + caplog: pytest.LogCaptureFixture, +) -> None: + """Reload only unloads the platforms that were set up (#208). + + Hive has no lights here, but another integration loaded the light component. + Before HA 2026.11, unloading the light platform for this entry raised and + aborted the reload; HA now logs a warning instead. Neither should happen. + """ + assert await async_setup_component(hass, "light", {}) + await hass.async_block_till_done() + + assert await hass.config_entries.async_reload(setup_integration.entry_id) + await hass.async_block_till_done() + + assert setup_integration.state is ConfigEntryState.LOADED + assert "Ignored unload request" not in caplog.text + + +async def test_reload_picks_up_new_device_types( + hass: HomeAssistant, mock_hive: MagicMock, setup_integration: MockConfigEntry +) -> None: + """A device type added since setup (e.g. a new light) appears after a reload.""" + assert "hive.light" not in hass.config.components + devices = {**mock_hive.session.deviceList, "light": [WARM_WHITE]} + mock_hive.session.startSession.return_value = devices + mock_hive.session.deviceList = devices + + assert await hass.config_entries.async_reload(setup_integration.entry_id) + await hass.async_block_till_done() + + assert setup_integration.state is ConfigEntryState.LOADED + assert "hive.light" in hass.config.components + assert hass.states.get("light.kitchen") is not None + + async def test_remove_entry_forgets_device( hass: HomeAssistant, mock_hive: MagicMock, diff --git a/tests/test_sensor.py b/tests/test_sensor.py index db644eb..97b06d1 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -1,11 +1,11 @@ """Tests for the Hive sensors added by this component.""" -from datetime import datetime +from datetime import UTC, datetime from typing import Any from unittest.mock import AsyncMock, MagicMock import pytest -from pytest_homeassistant_custom_component.common import MockConfigEntry +from pytest_homeassistant.common import MockConfigEntry from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant @@ -25,7 +25,7 @@ async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: async def test_battery_sensor( hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry ) -> None: - """Battery level is exposed as a diagnostic percentage sensor.""" + """Battery level is a diagnostic percentage sensor with long-term statistics.""" await _setup(hass, mock_config_entry) state = hass.states.get("sensor.lounge_trv_battery") @@ -33,6 +33,7 @@ async def test_battery_sensor( assert state.state == "87" assert state.attributes["unit_of_measurement"] == PERCENTAGE assert state.attributes["device_class"] == "battery" + assert state.attributes["state_class"] == "measurement" entry = er.async_get(hass).async_get("sensor.lounge_trv_battery") assert entry.unique_id == "trv-1-Battery" @@ -303,3 +304,130 @@ async def test_sensor_platform_without_devices( await sensor.async_setup_entry(hass, mock_config_entry, add_entities) add_entities.assert_not_called() + + +@pytest.mark.parametrize( + "sensor_devices", + [[make_device("Heating_Current_Temperature", 18.5, name="Heating")]], +) +async def test_current_temperature_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The heating current temperature shows min/max and how far it is from target.""" + mock_hive.heating.minmaxTemperature = AsyncMock( + return_value={ + "TodayMin": 17.0, + "TodayMax": 21.5, + "RestartMin": 16.0, + "RestartMax": 22.0, + } + ) + mock_hive.heating.getTargetTemperature = AsyncMock(return_value=21.0) + + await _setup(hass, mock_config_entry) + + attributes = hass.states.get( + "sensor.heating_heating_current_temperature" + ).attributes + assert attributes["Today Min / Max"] == "17.0 °C / 21.5 °C" + assert attributes["Restart Min / Max"] == "16.0 °C / 22.0 °C" + assert attributes["Current Temperature"] == 18.5 + assert attributes["Target Temperature"] == 21.0 + assert attributes["Temperature Difference"] == 2.5 + + +@pytest.mark.parametrize( + "sensor_devices", + [[make_device("Heating_Current_Temperature", 18.5, name="Heating")]], +) +async def test_current_temperature_without_target( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """No target or min/max data leaves the attributes out instead of failing.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.heating_heating_current_temperature") + assert state.state == "18.5" + assert not { + "Today Min / Max", + "Current Temperature", + "Temperature Difference", + } & set(state.attributes) + + +@pytest.mark.parametrize( + ("sensor_devices", "entity_id", "boost_api"), + [ + ( + [make_device("Heating_Boost", "ON", name="Thermostat")], + "sensor.thermostat_heating_boost_ends", + ("heating", "getBoostStatus"), + ), + ( + [make_device("Hotwater_Boost", "ON", name="Hot Water")], + "sensor.hot_water_hotwater_boost_ends", + ("hotwater", "getBoost"), + ), + ], +) +async def test_boost_ends_sensor( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: Any, + entity_id: str, + boost_api: tuple[str, str], +) -> None: + """While boost is on, the sensor holds the time it ends.""" + freezer.move_to("2026-11-21 10:00:30+00:00") + api = getattr(mock_hive, boost_api[0]) + setattr(api, boost_api[1], AsyncMock(return_value="ON")) + api.getBoostTime = AsyncMock(return_value=30) + + await _setup(hass, mock_config_entry) + + state = hass.states.get(entity_id) + assert state.state == "2026-11-21T10:30:00+00:00" + assert state.attributes["device_class"] == "timestamp" + + entry = er.async_get(hass).async_get(entity_id) + assert entry.unique_id.endswith("_Boost-end") + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Boost", "OFF", name="Thermostat")]] +) +async def test_boost_ends_sensor_when_off( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """With no boost running, the end time is unknown.""" + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.thermostat_heating_boost_ends").state == ( + STATE_UNKNOWN + ) + + +@pytest.mark.parametrize( + ("previous", "minutes", "expected"), + [ + # Within a minute of the last estimate: keep it, so the state doesn't wobble. + (datetime(2026, 11, 21, 10, 30, tzinfo=UTC), 29, "10:30"), + # Boost extended: take the new time. + (datetime(2026, 11, 21, 10, 30, tzinfo=UTC), 60, "11:00"), + # Boost stopped or bad data: unknown. + (datetime(2026, 11, 21, 10, 30, tzinfo=UTC), None, None), + (None, "not a number", None), + ], +) +def test_boost_end_is_steady( + freezer: Any, previous: datetime | None, minutes: Any, expected: str | None +) -> None: + """The end time only moves when the boost changes, not on every poll.""" + freezer.move_to("2026-11-21 10:00:40+00:00") + entity = sensor.HiveBoostEndSensorEntity.__new__(sensor.HiveBoostEndSensorEntity) + entity._attr_native_value = previous + + result = entity._boost_end(minutes is not None, minutes) + + assert (result.strftime("%H:%M") if result else None) == expected