From d87982702d2b47540607b5d08fa60ed2a0825498 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 9 Nov 2025 13:02:27 +0000 Subject: [PATCH 01/31] Create stale.yml --- .github/workflows/stale.yml | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .github/workflows/stale.yml diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml new file mode 100644 index 0000000..26d957d --- /dev/null +++ b/.github/workflows/stale.yml @@ -0,0 +1,27 @@ +# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. +# +# You can adjust the behavior by modifying this file. +# For more information, see: +# https://github.com/actions/stale +name: Mark stale issues and pull requests + +on: + schedule: + - cron: '29 5 * * *' + +jobs: + stale: + + runs-on: ubuntu-latest + permissions: + issues: write + pull-requests: write + + steps: + - uses: actions/stale@v5 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + stale-issue-message: 'Stale issue message' + stale-pr-message: 'Stale pull request message' + stale-issue-label: 'no-issue-activity' + stale-pr-label: 'no-pr-activity' From 73bb288ce31e27c9edf9a1bea85fe29cb5ec3296 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 9 Nov 2025 16:57:32 +0000 Subject: [PATCH 02/31] feat: ignore brands validation in HACS hassfest workflow --- .github/workflows/hassfest.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/hassfest.yaml b/.github/workflows/hassfest.yaml index c422ec3..59b401c 100644 --- a/.github/workflows/hassfest.yaml +++ b/.github/workflows/hassfest.yaml @@ -16,3 +16,4 @@ jobs: uses: "hacs/action@main" with: category: "integration" + ignore: "brands" From e9ab17b1a2fe849d10cb05fa14826efc7ac7b4de Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 10 Nov 2025 07:23:36 +0000 Subject: [PATCH 03/31] Update stale.yml --- .github/workflows/stale.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 26d957d..619b886 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -21,7 +21,7 @@ jobs: - uses: actions/stale@v5 with: repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-issue-message: 'Stale issue message' - stale-pr-message: 'Stale pull request message' + stale-issue-message: 'There has been no activity on this Issue' + stale-pr-message: 'There has been no activity on this PR.' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity' From dd04218f0911b2f529370f86658366c558a7dd0f Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 10 Nov 2025 22:36:07 +0000 Subject: [PATCH 04/31] chore: bump pyhive-integration dependency to 1.0.7 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 72f7d31..7979bb9 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -8,7 +8,7 @@ "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.6"], + "requirements": ["pyhive-integration==1.0.7"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 699ad4e08bc9d3f825d9445823ddf582d582cb25 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 10 Nov 2025 22:36:23 +0000 Subject: [PATCH 05/31] chore: bump version to 2025.11.2 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 7979bb9..fe5c5a7 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,7 +4,7 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2025.11.0", + "version": "2025.11.2", "homekit": { "models": ["HHKBridge*"] }, From 6c2d99d6ce06b33df0145ff985335105dd07041b Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 10 Nov 2025 22:45:41 +0000 Subject: [PATCH 06/31] feat: improve stale issue/PR workflow with configurable timeouts - Added automatic closure timelines (30 days for issues, 14 days for PRs) - Updated stale messages to inform users of closure deadlines - Exempted enhancement and question issues from auto-closure --- .github/workflows/stale.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 619b886..8ab7fa6 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -21,7 +21,10 @@ jobs: - uses: actions/stale@v5 with: repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-issue-message: 'There has been no activity on this Issue' - stale-pr-message: 'There has been no activity on this PR.' + stale-issue-message: 'There has been no activity on this Issue. Issue will be closed in 30 Days' + stale-pr-message: 'There has been no activity on this PR. PR will be closed in 14 Days' stale-issue-label: 'no-issue-activity' stale-pr-label: 'no-pr-activity' + days-before-close: 30 + days-before-pr-close: 14 + exempt-issue-labels: 'enhancement, question' From cfe38d8e7576aad10560c56f98b11d64e0dc28a5 Mon Sep 17 00:00:00 2001 From: tamunro93 Date: Mon, 23 Feb 2026 16:40:13 +0000 Subject: [PATCH 07/31] Fix Hive reauth loop by persisting device metadata; add debug 2FA toggle --- custom_components/hive/config_flow.py | 293 +++++++++++++++++++- custom_components/hive/const.py | 1 + custom_components/hive/manifest.json | 2 +- custom_components/hive/strings.json | 4 +- custom_components/hive/translations/en.json | 4 +- 5 files changed, 300 insertions(+), 4 deletions(-) diff --git a/custom_components/hive/config_flow.py b/custom_components/hive/config_flow.py index 7a89548..6e4e070 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -1 +1,292 @@ -from homeassistant.components.hive.config_flow import * \ No newline at end of file +"""Config Flow for Hive.""" + +from __future__ import annotations + +from collections.abc import Mapping +import copy +from typing import Any + +from apyhiveapi import Auth +from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, + HiveInvalid2FACode, + HiveInvalidPassword, + HiveInvalidUsername, +) +import voluptuous as vol + +from homeassistant.config_entries import ( + SOURCE_REAUTH, + ConfigFlow, + ConfigFlowResult, + OptionsFlow, +) +from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME +from homeassistant.core import callback +import logging + +from . import HiveConfigEntry +from .const import ( + CONF_CODE, + CONF_DEVICE_NAME, + CONF_DISABLE_2FA_DEBUG, + CONFIG_ENTRY_VERSION, + DOMAIN, +) + +_LOGGER = logging.getLogger(__name__) + + +def _sanitize_payload(payload: dict[str, Any]) -> dict[str, Any]: + """Return a copy of payload with sensitive values masked for logs.""" + + def _mask(value: Any) -> Any: + if not isinstance(value, str): + return value + if len(value) <= 8: + return "***" + return f"{value[:4]}...{value[-4:]}" + + def _walk(node: Any) -> Any: + if isinstance(node, dict): + 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")): + result[key] = _mask(value) + else: + result[key] = _walk(value) + return result + if isinstance(node, list): + return [_walk(item) for item in node] + return node + + return _walk(copy.deepcopy(payload)) + + +class HiveFlowHandler(ConfigFlow, domain=DOMAIN): + """Handle a Hive config flow.""" + + VERSION = CONFIG_ENTRY_VERSION + hive_auth: Auth + + def __init__(self) -> None: + """Initialize the config flow.""" + self.data: dict[str, Any] = {} + self.tokens: dict[str, str] = {} + self.device_registration: bool = False + self.device_name = "Home Assistant" + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Prompt user input. Create or edit entry.""" + errors: dict[str, str] = {} + if user_input is not None: + self.data.update( + { + CONF_USERNAME: user_input[CONF_USERNAME], + CONF_PASSWORD: user_input[CONF_PASSWORD], + CONF_DISABLE_2FA_DEBUG: bool( + user_input.get(CONF_DISABLE_2FA_DEBUG, False) + ), + } + ) + self.hive_auth = Auth( + username=self.data[CONF_USERNAME], password=self.data[CONF_PASSWORD] + ) + + await self.async_set_unique_id(self.data[CONF_USERNAME]) + if self.context["source"] != SOURCE_REAUTH: + self._abort_if_unique_id_configured() + + try: + self.tokens = await self.hive_auth.login() + _LOGGER.debug( + "Hive login response (sanitized): %s", + _sanitize_payload(self.tokens), + ) + except HiveInvalidUsername: + errors["base"] = "invalid_username" + except HiveInvalidPassword: + errors["base"] = "invalid_password" + except HiveApiError: + errors["base"] = "no_internet_available" + + if self.tokens.get("ChallengeName") == "SMS_MFA": + if self.data.get(CONF_DISABLE_2FA_DEBUG): + _LOGGER.warning( + "Hive returned SMS_MFA and disable_2fa_debug is enabled. " + "Skipping 2FA submission for debug. Challenge payload: %s", + _sanitize_payload(self.tokens), + ) + errors["base"] = "twofa_bypassed_debug" + else: + return await self.async_step_2fa() + + if not errors and "AuthenticationResult" in self.tokens: + 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 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 + self.hive_auth.device_group_key = new_device["DeviceGroupKey"] + 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.") + except HiveApiError: + _LOGGER.warning("Hive device registration failed after login; continuing without device_data.") + + try: + return await self.async_setup_hive_entry() + except UnknownHiveError: + errors["base"] = "unknown" + + schema = vol.Schema( + { + vol.Required(CONF_USERNAME): str, + vol.Required(CONF_PASSWORD): str, + vol.Optional(CONF_DISABLE_2FA_DEBUG, default=False): bool, + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + async def async_step_2fa( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle 2fa step.""" + errors = {} + + if user_input and user_input["2fa"] == "0000": + _LOGGER.debug("2FA resend requested (code 0000).") + self.tokens = await self.hive_auth.login() + _LOGGER.debug( + "Hive login response after 2FA resend request (sanitized): %s", + _sanitize_payload(self.tokens), + ) + elif user_input: + try: + self.tokens = await self.hive_auth.sms_2fa( + user_input["2fa"], self.tokens + ) + _LOGGER.debug( + "Hive 2FA response (sanitized): %s", + _sanitize_payload(self.tokens), + ) + except HiveInvalid2FACode: + errors["base"] = "invalid_code" + except HiveApiError: + errors["base"] = "no_internet_available" + + if not errors: + if self.source == SOURCE_REAUTH: + return await self.async_setup_hive_entry() + 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) + + async def async_step_configuration( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle hive configuration step.""" + errors = {} + + if user_input: + if self.device_registration: + 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() + + try: + return await self.async_setup_hive_entry() + except UnknownHiveError: + errors["base"] = "unknown" + + schema = vol.Schema( + {vol.Optional(CONF_DEVICE_NAME, default=self.device_name): str} + ) + return self.async_show_form( + step_id="configuration", data_schema=schema, errors=errors + ) + + async def async_setup_hive_entry(self) -> ConfigFlowResult: + """Finish setup and create the config entry.""" + + if "AuthenticationResult" not in self.tokens: + raise UnknownHiveError + + self.data["tokens"] = self.tokens + if self.source == SOURCE_REAUTH: + return self.async_update_reload_and_abort( + self._get_reauth_entry(), + title=self.data["username"], + data=self.data, + reason="reauth_successful", + ) + return self.async_create_entry(title=self.data["username"], data=self.data) + + async def async_step_reauth( + self, entry_data: Mapping[str, Any] + ) -> ConfigFlowResult: + """Re Authenticate a user.""" + data = { + CONF_USERNAME: entry_data[CONF_USERNAME], + CONF_PASSWORD: entry_data[CONF_PASSWORD], + } + return await self.async_step_user(data) + + @staticmethod + @callback + def async_get_options_flow( + config_entry: HiveConfigEntry, + ) -> HiveOptionsFlowHandler: + """Hive options callback.""" + return HiveOptionsFlowHandler(config_entry) + + +class HiveOptionsFlowHandler(OptionsFlow): + """Config flow options for Hive.""" + + config_entry: HiveConfigEntry + + def __init__(self, config_entry: HiveConfigEntry) -> None: + """Initialize Hive options flow.""" + self.hive = None + self.interval = config_entry.options.get(CONF_SCAN_INTERVAL, 120) + + async def async_step_init( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Manage the options.""" + return await self.async_step_user() + + async def async_step_user( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle a flow initialized by the user.""" + self.hive = self.config_entry.runtime_data + errors: dict[str, str] = {} + if user_input is not None: + new_interval = user_input.get(CONF_SCAN_INTERVAL) + assert self.hive + await self.hive.updateInterval(new_interval) + return self.async_create_entry(title="", data=user_input) + + schema = vol.Schema( + { + vol.Optional(CONF_SCAN_INTERVAL, default=self.interval): vol.All( + vol.Coerce(int), vol.Range(min=30) + ) + } + ) + return self.async_show_form(step_id="user", data_schema=schema, errors=errors) + + +class UnknownHiveError(Exception): + """Catch unknown hive error.""" diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 8271495..0caf965 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -6,6 +6,7 @@ ATTR_ONOFF = "on_off" CONF_CODE = "2fa" CONF_DEVICE_NAME = "device_name" +CONF_DISABLE_2FA_DEBUG = "disable_2fa_debug" CONFIG_ENTRY_VERSION = 1 DEFAULT_NAME = "Hive" DOMAIN = "hive" diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index fe5c5a7..2b7f39e 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -8,7 +8,7 @@ "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.7"], + "requirements": ["pyhive-integration==1.0.8.dev10"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] diff --git a/custom_components/hive/strings.json b/custom_components/hive/strings.json index 874b86a..2bca947 100755 --- a/custom_components/hive/strings.json +++ b/custom_components/hive/strings.json @@ -7,6 +7,7 @@ "data": { "username": "[%key:common::config_flow::data::username%]", "password": "[%key:common::config_flow::data::password%]", + "disable_2fa_debug": "Disable 2FA (debug)", "scan_interval": "Scan interval (seconds)" } }, @@ -37,6 +38,7 @@ "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": "[%key:common::config_flow::error::unknown%]" }, @@ -119,4 +121,4 @@ } } } -} \ No newline at end of file +} diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 5f3ae19..4ff73ae 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -9,6 +9,7 @@ "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" }, @@ -38,6 +39,7 @@ "user": { "data": { "password": "Password", + "disable_2fa_debug": "Disable 2FA (debug)", "scan_interval": "Scan Interval (seconds)", "username": "Username" }, @@ -57,4 +59,4 @@ } } } -} \ No newline at end of file +} From 8c8ffe4ab6089d64b48a2c1080e37c79256a9316 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Fri, 27 Feb 2026 20:11:05 +0000 Subject: [PATCH 08/31] chore: update pyhive-integration dependency to stable 1.0.8 release --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 2b7f39e..99c116f 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -8,7 +8,7 @@ "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.8.dev10"], + "requirements": ["pyhive-integration==1.0.8"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 27991d60b5f211aad538191df1c3a2228fe21569 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sat, 7 Mar 2026 15:40:08 +0000 Subject: [PATCH 09/31] chore: update pyhive-integration dependency to 1.0.9.dev1 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 99c116f..14ab744 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -8,7 +8,7 @@ "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.8"], + "requirements": ["pyhive-integration==1.0.9.dev1"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 6764a1f1d2a09d0d936ad0f0bec7fc99212a8c11 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Wed, 11 Mar 2026 20:15:42 +0000 Subject: [PATCH 10/31] Update version in manifest.json to 2026.3.1b2 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 99c116f..c5b399a 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,7 +4,7 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2025.11.2", + "version": "2026.3.1b2", "homekit": { "models": ["HHKBridge*"] }, From 81fbe68157e8c8f3219be54ba5387aeaa8576f64 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 15 Mar 2026 20:40:04 +0000 Subject: [PATCH 11/31] chore: bump version to 2026.3.1b3 and update pyhive-integration to 1.0.9.dev2 --- custom_components/hive/manifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 14ab744..7173405 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,11 +4,11 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2025.11.2", + "version": "2026.3.1b3", "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.9.dev1"], + "requirements": ["pyhive-integration==1.0.9.dev2"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 5f03c35cbb9d4067d038b5d51a748a1a19426e8d Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 22 Mar 2026 22:48:09 +0000 Subject: [PATCH 12/31] chore: bump version to 2026.3.1b4 and update pyhive-integration to 1.0.9.dev3 --- custom_components/hive/manifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 7173405..333a6d1 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,11 +4,11 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2026.3.1b3", + "version": "2026.3.1b4", "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.9.dev2"], + "requirements": ["pyhive-integration==1.0.9.dev3"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 6463566712455620b4a9fa1580da92a77fa915c8 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 22 Mar 2026 22:52:49 +0000 Subject: [PATCH 13/31] chore: add device registration check during 2FA reauth flow --- custom_components/hive/config_flow.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/custom_components/hive/config_flow.py b/custom_components/hive/config_flow.py index 6e4e070..26174c2 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -183,8 +183,12 @@ async def async_step_2fa( errors["base"] = "no_internet_available" if not errors: + _LOGGER.debug("2FA successful") if self.source == SOURCE_REAUTH: - return await self.async_setup_hive_entry() + 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() From b9655aa28781129cb1a684084ffc287307c0992f Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sun, 12 Apr 2026 10:17:52 +0100 Subject: [PATCH 14/31] chore: bump version to 2026.4.1 and update pyhive-integration to stable 1.0.9 release --- custom_components/hive/manifest.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 333a6d1..b8754c1 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,11 +4,11 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2026.3.1b4", + "version": "2026.4.1", "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.9.dev3"], + "requirements": ["pyhive-integration==1.0.9"], "codeowners": ["@KJonline"], "iot_class": "cloud_polling", "loggers": ["apyhiveapi"] From 99e34fddaf992a24dee3528ab85ce87507bba076 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Sat, 8 Aug 2026 09:25:14 +0100 Subject: [PATCH 15/31] chore: bump version to 2026.8.0 and refactor sensor entity with improved type hints and enum support --- .vscode/settings.json | 3 +- custom_components/hive/manifest.json | 2 +- custom_components/hive/sensor.py | 94 ++++++++++++++++------------ 3 files changed, 58 insertions(+), 41 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index de288e1..5bf97ab 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,4 @@ { - "python.formatting.provider": "black" + "python.formatting.provider": "black", + "python.defaultInterpreterPath": "/Users/kholejones/Git/Home-Automation/Hive-Custom-Component/.venv/bin/python" } \ No newline at end of file diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index b8754c1..111c468 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -4,7 +4,7 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2026.4.1", + "version": "2026.8.0", "homekit": { "models": ["HHKBridge*"] }, diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index be34455..0c3030c 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -1,6 +1,9 @@ """Support for the Hive sensors.""" +from collections.abc import Callable +from dataclasses import dataclass from datetime import timedelta +from typing import Any from homeassistant.components.sensor import ( SensorDeviceClass, @@ -16,70 +19,77 @@ ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.helpers.typing import StateType from . import HiveConfigEntry from .entity import HiveEntity +from apyhiveapi import Hive PARALLEL_UPDATES = 0 SCAN_INTERVAL = timedelta(seconds=15) -SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( - SensorEntityDescription( + + +@dataclass(frozen=True) +class HiveSensorEntityDescription(SensorEntityDescription): + """Describes Hive sensor entity.""" + + fn: Callable[[StateType], StateType] = lambda x: x + + +SENSOR_TYPES: tuple[HiveSensorEntityDescription, ...] = ( + HiveSensorEntityDescription( key="Battery", native_unit_of_measurement=PERCENTAGE, device_class=SensorDeviceClass.BATTERY, entity_category=EntityCategory.DIAGNOSTIC, ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Power", native_unit_of_measurement=UnitOfPower.WATT, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, ), - SensorEntityDescription( + HiveSensorEntityDescription( + key="Current_Temperature", + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + state_class=SensorStateClass.MEASUREMENT, + device_class=SensorDeviceClass.TEMPERATURE, + entity_category=EntityCategory.DIAGNOSTIC, + ), + HiveSensorEntityDescription( key="Heating_Current_Temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, - icon="mdi:thermometer", ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Heating_Target_Temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, icon="mdi:thermometer", ), - SensorEntityDescription( - key="Heating_State", - icon="mdi:radiator", - ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Heating_Mode", - icon="mdi:radiator", - ), - SensorEntityDescription( - key="Heating_Boost", - icon="mdi:radiator", - ), - SensorEntityDescription( - key="Hotwater_State", - icon="mdi:water-pump", + device_class=SensorDeviceClass.ENUM, + options=["schedule", "manual", "off"], + translation_key="heating", + fn=lambda x: x.lower() if isinstance(x, str) else None, ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Hotwater_Mode", - icon="mdi:water-pump", + device_class=SensorDeviceClass.ENUM, + options=["schedule", "on", "off"], + translation_key="hot_water", + fn=lambda x: x.lower() if isinstance(x, str) else None, ), - SensorEntityDescription( - key="Hotwater_Boost", - icon="mdi:water-pump", - ), - SensorEntityDescription( + HiveSensorEntityDescription( key="Mode", icon="mdi:eye", ), - SensorEntityDescription(key="Availability", icon="mdi:check-circle"), + HiveSensorEntityDescription(key="Availability", icon="mdi:check-circle"), ) @@ -95,7 +105,7 @@ async def async_setup_entry( return async_add_entities( ( - HiveSensorEntity(hive, dev, description) + HiveSensorEntity(hass, entry, hive, dev, description) for dev in devices for description in SENSOR_TYPES if dev["hiveType"] == description.key @@ -107,9 +117,18 @@ async def async_setup_entry( class HiveSensorEntity(HiveEntity, SensorEntity): """Hive Sensor Entity.""" - def __init__(self, hive, hive_device, entity_description): + entity_description: HiveSensorEntityDescription + + def __init__( + self, + hass: HomeAssistant, + entry: HiveConfigEntry, + hive: Hive, + hive_device: dict[str, Any], + entity_description: HiveSensorEntityDescription, + ) -> None: """Initialise hive sensor.""" - super().__init__(hive, hive_device) + super().__init__(hass, entry, hive, hive_device) self.entity_description = entity_description async def async_update(self): @@ -119,9 +138,7 @@ async def async_update(self): if self.device["hiveType"] == "CurrentTemperature": self._attr_extra_state_attributes = await self.get_current_temp_sa() - elif self.device["hiveType"] == "Heating_State": - self._attr_extra_state_attributes = await self.get_heating_state_sa() - elif self.device["hiveType"] == "Heating_Mode": + elif self.device["hiveType"] in ("Heating_State", "Heating_Mode"): self._attr_extra_state_attributes = await self.get_heating_state_sa() elif self.device["hiveType"] == "Heating_Boost": s_a = {} @@ -129,9 +146,7 @@ async def async_update(self): 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"] == "Hotwater_State": - self._attr_extra_state_attributes = await self.get_hotwater_state_sa() - elif self.device["hiveType"] == "Hotwater_Mode": + elif self.device["hiveType"] in ("Hotwater_State", "Hotwater_Mode"): self._attr_extra_state_attributes = await self.get_hotwater_state_sa() elif self.device["hiveType"] == "Hotwater_Boost": s_a = {} @@ -145,8 +160,9 @@ async def async_update(self): else: self._attr_available = True - if self._attr_available: - self._attr_native_value = self.device["status"]["state"] + self._attr_native_value = self.entity_description.fn( + self.device.get("status", {}).get("state") + ) async def get_current_temp_sa(self): """Get current heating temperature state attributes.""" From c407de58c7a0a7ad7e8b0292620bb67e14591aef Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:44:08 +0100 Subject: [PATCH 16/31] chore: update GitHub workflows, documentation, and code formatting - Remove legacy issue/PR templates in favor of GitHub forms - Update delete_beta.yml workflow with improved permissions and action version - Remove hassfest.yaml workflow (redundant with CI) - Enhance stale.yml workflow with better configuration and exempt labels - Expand .gitignore with Python and cache patterns - Update README.md with new repository URLs, CI badges, and development guide - Improve SECURITY.md with private vulnerability --- .github/ISSUE_TEMPLATE/bug_report.md | 34 --- .github/ISSUE_TEMPLATE/bug_report.yml | 110 ++++++++ .github/ISSUE_TEMPLATE/config.yml | 8 + .github/ISSUE_TEMPLATE/feature_request.md | 20 -- .github/ISSUE_TEMPLATE/feature_request.yml | 35 +++ .../pull_request_template.md | 16 -- .github/dependabot.yml | 19 ++ .github/pull_request_template.md | 14 + .github/scripts/check_release.py | 54 ++++ .github/scripts/resolve_ha_release.py | 83 ++++++ .github/scripts/smoke_import.py | 30 ++ .github/workflows/ci.yml | 89 ++++++ .github/workflows/compat.yml | 73 +++++ .github/workflows/delete_beta.yml | 19 +- .github/workflows/hassfest.yaml | 19 -- .github/workflows/pyhive_bump.yml | 91 +++++++ .github/workflows/release.yml | 42 +++ .github/workflows/stale.yml | 38 +-- .gitignore | 9 +- README.md | 38 ++- SECURITY.md | 16 +- custom_components/hive/__init__.py | 8 +- custom_components/hive/binary_sensor.py | 2 +- custom_components/hive/climate.py | 2 +- custom_components/hive/config_flow.py | 25 +- custom_components/hive/const.py | 1 + custom_components/hive/manifest.json | 11 +- custom_components/hive/sensor.py | 4 +- custom_components/hive/translations/en.json | 166 +++++++---- hacs.json | 3 +- pyproject.toml | 38 +++ requirements_test.txt | 4 + script/gen_translations.py | 89 ++++++ setup.cfg | 2 - tests/__init__.py | 1 + tests/conftest.py | 122 +++++++++ tests/test_config_flow.py | 257 ++++++++++++++++++ tests/test_init.py | 67 +++++ tests/test_sensor.py | 112 ++++++++ tests/test_translations.py | 43 +++ 40 files changed, 1611 insertions(+), 203 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml delete mode 100644 .github/PULL_REQUEST_TEMPLATE/pull_request_template.md create mode 100644 .github/dependabot.yml create mode 100644 .github/pull_request_template.md create mode 100644 .github/scripts/check_release.py create mode 100644 .github/scripts/resolve_ha_release.py create mode 100644 .github/scripts/smoke_import.py create mode 100644 .github/workflows/ci.yml create mode 100644 .github/workflows/compat.yml delete mode 100644 .github/workflows/hassfest.yaml create mode 100644 .github/workflows/pyhive_bump.yml create mode 100644 .github/workflows/release.yml create mode 100644 pyproject.toml create mode 100644 requirements_test.txt create mode 100644 script/gen_translations.py delete mode 100644 setup.cfg create mode 100644 tests/__init__.py create mode 100644 tests/conftest.py create mode 100644 tests/test_config_flow.py create mode 100644 tests/test_init.py create mode 100644 tests/test_sensor.py create mode 100644 tests/test_translations.py diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 7f6c579..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: "[BUG]" -labels: bug -assignees: KJonline - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behaviour: - -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behaviour** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Desktop (please complete the following information):** - -- OS: [e.g. iOS] -- Browser [e.g. chrome, safari] -- Version [e.g. 22] - -**Additional context** -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000..75cb477 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,110 @@ +name: Bug report +description: Something isn't working with the Hive custom component +title: "[BUG] " +labels: [bug] +assignees: [KJonline] +body: + - type: markdown + attributes: + value: | + Thanks for reporting a problem. Please check the [open issues](https://github.com/Pyhass/Hive-Custom-Component/issues) first in case it's already reported. + + **Security issues:** don't report them here. Use [private vulnerability reporting](https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new) instead. + + - type: textarea + id: description + attributes: + label: What happened? + description: What went wrong, and what did you expect to happen instead? + validations: + required: true + + - type: textarea + id: reproduce + attributes: + label: Steps to reproduce + placeholder: | + 1. Go to Settings > Devices & services > Hive + 2. ... + validations: + required: false + + - type: input + id: component-version + attributes: + label: Hive custom component version + description: Shown in HACS, or `version` in `custom_components/hive/manifest.json`. + placeholder: "2026.8.0" + validations: + required: true + + - type: input + id: ha-version + attributes: + label: Home Assistant version + description: Settings > About. + placeholder: "2026.9.4" + validations: + required: true + + - type: dropdown + id: install-method + attributes: + label: How did you install the component? + options: + - HACS + - Manually + validations: + required: true + + - type: dropdown + id: devices + attributes: + label: Which Hive devices are affected? + multiple: true + options: + - Heating / thermostat + - Hot water + - Radiator valves (TRVs) + - Lights + - Smart plugs + - Sensors (motion, contact) + - Hub + - Login / 2FA / setup + - Other + validations: + required: true + + - type: textarea + id: logs + attributes: + label: Debug logs + description: | + Add this to `configuration.yaml`, restart, reproduce the problem, then paste the relevant lines from **Settings > System > Logs** (select *Show raw logs*): + ```yaml + logger: + default: warning + logs: + custom_components.hive: debug + apyhiveapi: debug + ``` + **Remove your email address, tokens and any other personal details before posting.** + render: text + validations: + required: false + + - type: textarea + id: context + attributes: + label: Anything else? + description: Screenshots, when it started, whether it worked on an earlier version, etc. + validations: + required: false + + - type: checkboxes + id: checks + attributes: + label: Checks + options: + - label: I've removed personal information (email, tokens, device IDs) from the logs above. + required: true diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000..2647a16 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,8 @@ +blank_issues_enabled: false +contact_links: + - name: Report a security vulnerability + url: https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new + about: Report privately so it can be fixed before it's public. + - name: Home Assistant Hive integration docs + url: https://www.home-assistant.io/integrations/hive/ + about: Setup and usage of the Hive integration this component extends. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 76d928d..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: "[FEATURE]" -labels: enhancement -assignees: KJonline - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000..2bb783c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,35 @@ +name: Feature request +description: Suggest an improvement or new feature +title: "[FEATURE] " +labels: [enhancement] +assignees: [KJonline] +body: + - type: textarea + id: problem + attributes: + label: What problem would this solve? + description: For example, "I can't see when my hot water boost ends." + validations: + required: true + + - type: textarea + id: solution + attributes: + label: What would you like to happen? + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: Alternatives you've considered + validations: + required: false + + - type: input + id: devices + attributes: + label: Hive devices involved + placeholder: "e.g. Hive Thermostat mini, radiator valves" + validations: + required: false diff --git a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md b/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md deleted file mode 100644 index dea4213..0000000 --- a/.github/PULL_REQUEST_TEMPLATE/pull_request_template.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: Pull Request -about: Create PR to update HA Custom Component -title: "[PR]" -labels: PR -assignees: KJonline - ---- -**Related Issues** -PLease tag any related issues this PR fixes - -**Describe the change proposed** -A clear and concise description of what the PR is. - -**Additional context** -Add any other context about the problem here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..970ab31 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,19 @@ +version: 2 +updates: + # Keeps action versions in .github/workflows current. + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + github-actions: + 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. + - package-ecosystem: pip + directory: / + schedule: + interval: weekly + labels: [dependencies] diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..d13e47b --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,14 @@ +## What does this change? + + + +## Related issues + + + +## Checklist + +- [ ] Tests added or updated (`python -m pytest`) +- [ ] `ruff check .` and `ruff format --check .` pass +- [ ] If `strings.json` changed: ran `python script/gen_translations.py` +- [ ] If this is going into a release: bumped `version` in `manifest.json` diff --git a/.github/scripts/check_release.py b/.github/scripts/check_release.py new file mode 100644 index 0000000..c7f1c4b --- /dev/null +++ b/.github/scripts/check_release.py @@ -0,0 +1,54 @@ +"""Check a release tag agrees with manifest.json before it reaches HACS users. + + python check_release.py + +HACS installs by tag, so the tag must match the manifest version (compared as +versions, so tag 2026.3.1.b1 matches manifest 2026.3.1b1). A beta version must be +a GitHub pre-release, otherwise HACS offers it to every user. +""" + +import json +from pathlib import Path +import sys + +from packaging.version import InvalidVersion, Version + +MANIFEST = ( + Path(__file__).resolve().parents[2] / "custom_components" / "hive" / "manifest.json" +) + + +def main(tag: str, prerelease: bool) -> int: + manifest_version = json.loads(MANIFEST.read_text(encoding="utf-8"))["version"] + errors = [] + try: + tag_version = Version(tag) + except InvalidVersion: + print(f"::error::Tag {tag!r} is not a valid version") + return 1 + + if tag_version != Version(manifest_version): + errors.append( + f"Tag {tag} doesn't match manifest.json version {manifest_version}. " + "Bump the manifest version before tagging." + ) + if tag_version.is_prerelease and not prerelease: + errors.append( + f"{tag} is a beta version but the release isn't marked as a pre-release, " + "so HACS will offer it to every user." + ) + if prerelease and not tag_version.is_prerelease: + errors.append( + f"{tag} is marked as a pre-release but isn't a beta version " + "(expected something like 2026.9.0b1)." + ) + + for error in errors: + print(f"::error::{error}") + if not errors: + print(f"Tag {tag} matches manifest.json version {manifest_version}") + return 1 if errors else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1], sys.argv[2].lower() == "true")) diff --git a/.github/scripts/resolve_ha_release.py b/.github/scripts/resolve_ha_release.py new file mode 100644 index 0000000..ee219dc --- /dev/null +++ b/.github/scripts/resolve_ha_release.py @@ -0,0 +1,83 @@ +"""Find the newest Home Assistant release in a channel and its test plugin build. + +Prints GitHub Actions outputs: + homeassistant= + test_plugin= + skip=true|false + + python resolve_ha_release.py stable|beta +""" + +import json +import sys +from urllib.request import urlopen + +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 + + +def _get(url: str) -> dict: + with urlopen(url, timeout=30) as response: + return json.load(response) + + +def _newest(releases: dict[str, list], *, prerelease: bool) -> Version | None: + versions = [ + 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 main(channel: str) -> None: + releases = _get(PYPI.format("homeassistant"))["releases"] + stable = _newest(releases, prerelease=False) + if channel == "stable": + target = stable + elif channel == "beta": + beta = _newest(releases, prerelease=True) + target = beta if beta and stable and beta > stable else None + else: + sys.exit(f"unknown channel {channel!r}, expected stable or beta") + + if target is None: + print( + f"::notice::No Home Assistant {channel} release newer than stable", + file=sys.stderr, + ) + 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") + + print(f"homeassistant={target}") + print(f"test_plugin={plugin}") + print("skip=false") + + +if __name__ == "__main__": + main(sys.argv[1] if len(sys.argv) > 1 else "stable") diff --git a/.github/scripts/smoke_import.py b/.github/scripts/smoke_import.py new file mode 100644 index 0000000..9ef323e --- /dev/null +++ b/.github/scripts/smoke_import.py @@ -0,0 +1,30 @@ +"""Import every module of the component, including the core platforms it re-exports. + +Catches Home Assistant removing or renaming something the component depends on. +""" + +import importlib +from pathlib import Path +import sys +import traceback + +ROOT = Path(__file__).resolve().parents[2] +COMPONENT = ROOT / "custom_components" / "hive" +sys.path.insert(0, str(ROOT)) + +failures = 0 +for path in sorted(COMPONENT.glob("*.py")): + module = f"custom_components.hive.{path.stem}".removesuffix(".__init__") + try: + importlib.import_module(module) + except Exception: # report every failure, not just the first + failures += 1 + print(f"::error file={path.relative_to(ROOT)}::Failed to import {module}") + traceback.print_exc() + else: + print(f"ok {module}") + +from homeassistant.const import __version__ # noqa: E402 + +print(f"Home Assistant {__version__}") +sys.exit(1 if failures else 0) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1652435 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,89 @@ +# Checks every PR and push to master. Make the jobs below required checks on master. +# +# This workflow deliberately has no schedule: GitHub auto-disables scheduled +# workflows after 60 days without repo activity, which also stops their +# push/pull_request triggers. Nightly jobs live in compat.yml instead. +name: CI + +on: + pull_request: + push: + branches: [master] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + hacs: + name: HACS validation + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: hacs/action@22.5.0 + with: + category: integration + ignore: brands + + hassfest: + name: Hassfest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + # home-assistant/actions has no maintained releases; master tracks the + # current hassfest rules, which is what we want to validate against. + - uses: home-assistant/actions/hassfest@master + + lint: + name: Lint + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10 + - name: Ruff version from requirements_test.txt + id: ruff + run: echo "spec=$(grep '^ruff==' requirements_test.txt)" >> "$GITHUB_OUTPUT" + - run: uvx "${{ steps.ruff.outputs.spec }}" check --output-format=github . + - run: uvx "${{ steps.ruff.outputs.spec }}" format --check . + + test: + name: Tests + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10 + with: + python-version: "3.14" + activate-environment: true + enable-cache: true + cache-dependency-glob: | + requirements_test.txt + custom_components/hive/manifest.json + - name: Install dependencies + run: uv pip install -r requirements_test.txt $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - run: python -m pytest + + enable-scheduled-workflows: + # Self-heal: switch nightly/weekly workflows back on if GitHub disabled them + # for inactivity, so they don't stay off unnoticed like they did in 2026. + name: Re-enable scheduled workflows + if: github.event_name == 'push' + runs-on: ubuntu-latest + permissions: + actions: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + steps: + - run: | + for workflow in compat.yml stale.yml pyhive_bump.yml; do + state=$(gh workflow view "$workflow" --json state --jq .state) + if [ "$state" = "disabled_inactivity" ]; then + gh workflow enable "$workflow" + echo "::notice::Re-enabled $workflow (was disabled for inactivity)" + fi + done diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml new file mode 100644 index 0000000..7f7eccf --- /dev/null +++ b/.github/workflows/compat.yml @@ -0,0 +1,73 @@ +# Nightly check against Home Assistant releases this repo doesn't pin. +# +# Most platforms here re-export core's hive platforms, so a new HA release can +# break the component without any change in this repo. This catches that before +# 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 +# isn't published for dev builds). +name: Compatibility + +on: + schedule: + - cron: "17 4 * * *" + workflow_dispatch: + +permissions: + contents: read + +jobs: + validate: + name: HACS and hassfest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: hacs/action@22.5.0 + with: + category: integration + ignore: brands + - uses: home-assistant/actions/hassfest@master + + tests: + name: Tests (HA ${{ matrix.channel }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + channel: [stable, beta] + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10 + with: + python-version: "3.14" + activate-environment: true + - run: uv pip install packaging + - name: Find Home Assistant ${{ matrix.channel }} release + id: ha + run: python .github/scripts/resolve_ha_release.py ${{ matrix.channel }} >> "$GITHUB_OUTPUT" + - name: Install dependencies + if: steps.ha.outputs.skip != 'true' + run: >- + uv pip install + "pytest-homeassistant-custom-component==${{ steps.ha.outputs.test_plugin }}" + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - name: Run tests against Home Assistant ${{ steps.ha.outputs.homeassistant }} + if: steps.ha.outputs.skip != 'true' + run: python -m pytest + + dev: + name: Import smoke test (HA dev) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10 + with: + python-version: "3.14" + activate-environment: true + - name: Install Home Assistant dev + run: >- + uv pip install + "homeassistant @ git+https://github.com/home-assistant/core@dev" + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + - run: python .github/scripts/smoke_import.py diff --git a/.github/workflows/delete_beta.yml b/.github/workflows/delete_beta.yml index 3375064..f388a00 100644 --- a/.github/workflows/delete_beta.yml +++ b/.github/workflows/delete_beta.yml @@ -1,16 +1,21 @@ +# Manually clean up old beta releases (and their tags), keeping the newest one. +# Stable releases are never touched. name: Delete Beta Releases -on: +on: workflow_dispatch: - + +permissions: + contents: write + jobs: - close: + delete: runs-on: ubuntu-latest steps: - - uses: dev-drprasad/delete-older-releases@v0.2.0 + - uses: dev-drprasad/delete-older-releases@v0.3.4 with: keep_latest: 1 - delete_tags: true - delete_tag_pattern: _b + delete_prerelease_only: true + delete_tags: true env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + GITHUB_TOKEN: ${{ github.token }} diff --git a/.github/workflows/hassfest.yaml b/.github/workflows/hassfest.yaml deleted file mode 100644 index 59b401c..0000000 --- a/.github/workflows/hassfest.yaml +++ /dev/null @@ -1,19 +0,0 @@ -name: Validate - -on: - push: - pull_request: - schedule: - - cron: "0 0 * * *" - workflow_dispatch: - -jobs: - validate-hacs: - runs-on: "ubuntu-latest" - steps: - - uses: "actions/checkout@v3" - - name: HACS validation - uses: "hacs/action@main" - with: - category: "integration" - ignore: "brands" diff --git a/.github/workflows/pyhive_bump.yml b/.github/workflows/pyhive_bump.yml new file mode 100644 index 0000000..7301dc1 --- /dev/null +++ b/.github/workflows/pyhive_bump.yml @@ -0,0 +1,91 @@ +# Opens a PR bumping pyhive-integration in manifest.json. Dependabot can't do +# this because the requirement lives in manifest.json, not a requirements file. +# +# Triggers: +# - weekly check of PyPI for a new stable release +# - manually, optionally with a specific version (e.g. a beta) +# - from the Pyhive repo after it publishes, with a step like: +# - run: >- +# gh api repos/Pyhass/Hive-Custom-Component/dispatches +# -f event_type=pyhive-release +# -F "client_payload[version]=${{ github.ref_name }}" +# env: +# GH_TOKEN: ${{ secrets.HIVE_COMPONENT_DISPATCH_TOKEN }} +# +# PRs opened with the default GITHUB_TOKEN don't trigger CI. Add a BOT_TOKEN +# secret (fine-grained PAT with contents + pull-requests write on this repo) so +# CI runs on them; without it, close and reopen the PR to start CI. +name: Bump pyhive-integration + +on: + schedule: + - cron: "23 6 * * 1" + workflow_dispatch: + inputs: + version: + description: Version to bump to (blank = latest stable on PyPI) + required: false + repository_dispatch: + types: [pyhive-release] + +permissions: + contents: read + +jobs: + bump: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@v7 + + - name: Work out versions + id: versions + env: + REQUESTED: ${{ inputs.version || github.event.client_payload.version }} + run: | + current=$(jq -r '.requirements[] | select(startswith("pyhive-integration==")) | ltrimstr("pyhive-integration==")' custom_components/hive/manifest.json) + target="${REQUESTED#v}" + if [ -z "$target" ]; then + target=$(curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r .info.version) + fi + # Make sure the version exists on PyPI before opening a PR for it. + curl -fsS "https://pypi.org/pypi/pyhive-integration/$target/json" > /dev/null + echo "current=$current" >> "$GITHUB_OUTPUT" + echo "target=$target" >> "$GITHUB_OUTPUT" + echo "pyhive-integration: current $current, target $target" + + - name: Update manifest.json + if: steps.versions.outputs.current != steps.versions.outputs.target + env: + TARGET: ${{ steps.versions.outputs.target }} + run: | + python3 - <<'EOF' + import os, pathlib, re + path = pathlib.Path("custom_components/hive/manifest.json") + text = path.read_text() + text, count = re.subn( + r'"pyhive-integration==[^"]+"', + f'"pyhive-integration=={os.environ["TARGET"]}"', + text, + ) + assert count == 1, "pyhive-integration requirement not found" + path.write_text(text) + EOF + + - name: Open pull request + if: steps.versions.outputs.current != steps.versions.outputs.target + uses: peter-evans/create-pull-request@v8 + with: + token: ${{ secrets.BOT_TOKEN || github.token }} + branch: deps/pyhive-integration-${{ steps.versions.outputs.target }} + commit-message: "chore: bump pyhive-integration to ${{ steps.versions.outputs.target }}" + title: "chore: bump pyhive-integration to ${{ steps.versions.outputs.target }}" + body: | + Bumps `pyhive-integration` from `${{ steps.versions.outputs.current }}` to `${{ steps.versions.outputs.target }}`. + + - Release notes: https://pypi.org/project/pyhive-integration/${{ steps.versions.outputs.target }}/ + - The component `version` in manifest.json is **not** changed; bump it when releasing. + labels: dependencies + delete-branch: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..ac79ca3 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +# Runs when a GitHub release is published (including pre-releases). +# Fails the run if the tag doesn't match manifest.json, then attaches hive.zip +# for manual installs. +name: Release + +on: + release: + types: [published] + +permissions: + contents: read + +jobs: + check: + name: Check tag matches manifest + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: astral-sh/setup-uv@v10 + - env: + TAG: ${{ github.event.release.tag_name }} + PRERELEASE: ${{ github.event.release.prerelease }} + run: >- + uv run --no-project --with packaging + python .github/scripts/check_release.py "$TAG" "$PRERELEASE" + + attach-zip: + name: Attach hive.zip + needs: check + runs-on: ubuntu-latest + permissions: + contents: write + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + TAG: ${{ github.event.release.tag_name }} + steps: + - uses: actions/checkout@v7 + - name: Build zip + working-directory: custom_components/hive + run: zip -r "$GITHUB_WORKSPACE/hive.zip" . -x '__pycache__/*' + - run: gh release upload "$TAG" hive.zip --clobber diff --git a/.github/workflows/stale.yml b/.github/workflows/stale.yml index 8ab7fa6..f331445 100644 --- a/.github/workflows/stale.yml +++ b/.github/workflows/stale.yml @@ -1,30 +1,34 @@ -# This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. -# -# You can adjust the behavior by modifying this file. -# For more information, see: +# Warns and then closes issues and PRs with no activity. # https://github.com/actions/stale name: Mark stale issues and pull requests on: schedule: - - cron: '29 5 * * *' + - cron: "29 5 * * *" + workflow_dispatch: + +permissions: + contents: read jobs: stale: - runs-on: ubuntu-latest permissions: issues: write pull-requests: write - steps: - - uses: actions/stale@v5 - with: - repo-token: ${{ secrets.GITHUB_TOKEN }} - stale-issue-message: 'There has been no activity on this Issue. Issue will be closed in 30 Days' - stale-pr-message: 'There has been no activity on this PR. PR will be closed in 14 Days' - stale-issue-label: 'no-issue-activity' - stale-pr-label: 'no-pr-activity' - days-before-close: 30 - days-before-pr-close: 14 - exempt-issue-labels: 'enhancement, question' + - uses: actions/stale@v11 + with: + days-before-stale: 60 + days-before-close: 30 + days-before-pr-close: 14 + stale-issue-message: >- + There has been no activity on this issue for 60 days. It will be + closed in 30 days unless there is new activity. + stale-pr-message: >- + There has been no activity on this PR for 60 days. It will be closed + in 14 days unless there is new activity. + stale-issue-label: no-issue-activity + stale-pr-label: no-pr-activity + exempt-issue-labels: enhancement,question,vulnerability,pinned + exempt-pr-labels: dependencies,pinned diff --git a/.gitignore b/.gitignore index b0f2192..2ee111a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,7 @@ -__pycache__ -.venv \ No newline at end of file +__pycache__/ +*.py[cod] +.venv/ +.pytest_cache/ +.ruff_cache/ +.coverage +hive.zip diff --git a/README.md b/README.md index 572d4f2..cb4b5d0 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # Hive Custom Component -![Pylint](https://github.com/Pyhive/HA-Hive-Custom-Component/workflows/Pylint/badge.svg) -![GitHub Release](https://img.shields.io/github/v/release/Pyhive/HA-Hive-Custom-Component?display_name=tag&logo=Github) +[![CI](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/ci.yml/badge.svg)](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/ci.yml) +[![Compatibility](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/compat.yml/badge.svg)](https://github.com/Pyhass/Hive-Custom-Component/actions/workflows/compat.yml) +![GitHub Release](https://img.shields.io/github/v/release/Pyhass/Hive-Custom-Component?display_name=tag&logo=Github) @@ -27,7 +28,7 @@ For details on what the Home Assistant Hive component supports, please see below Issues and trouble reports should be reported in the issues tab: -[**>> Report issues here <<**](https://github.com/Pyhive/HA-Hive-Custom-Component/issues) +[**>> Report issues here <<**](https://github.com/Pyhass/Hive-Custom-Component/issues) ## Install @@ -41,9 +42,9 @@ This will show and option to add an integration click it and search for Hive in Once installation is complete please follow the [setup section](#setup) to set the Hive integration up. -### Manally +### Manually -To install the Hive integration manually you need to download the [latest version](https://github.com/Pyhive/HA-Hive-Custom-Component/releases/latest). +To install the Hive integration manually you need to download the [latest version](https://github.com/Pyhass/Hive-Custom-Component/releases/latest). Once downloaded you will need to copy the Hive folder into the custom_components folder within your home assistant configuration, if this does not exist then the folder will need creating. Once installation is complete please follow the [setup section](#setup) to set the Hive integration up. @@ -79,8 +80,33 @@ Hacs will auto notify you within the HACS panel that there is a pending update. ### Manual Update -To update to the next version download the [latest version](https://github.com/Pyhive/HA-Hive-Custom-Component/releases/latest) again +To update to the next version download the [latest version](https://github.com/Pyhass/Hive-Custom-Component/releases/latest) again and replace the current hive folder with the newly downloaded one. :warning: **Setting up this custom version will overwrite the default integration.** + +## 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. + +```bash +uv venv -p 3.14 && source .venv/bin/activate +uv pip install -r requirements_test.txt $(jq -r '.requirements[]' custom_components/hive/manifest.json) + +python -m pytest # tests +ruff check . && ruff format --check # lint +python script/gen_translations.py # regenerate translations/en.json after editing strings.json +``` + +### CI + +| Workflow | When | What | +| --- | --- | --- | +| `ci.yml` | PRs and pushes to master | HACS validation, hassfest, ruff, tests | +| `compat.yml` | Nightly | Tests against the latest HA stable and beta, import check against HA dev | +| `release.yml` | Release published | Checks the tag matches `manifest.json`, attaches `hive.zip` | +| `pyhive_bump.yml` | Weekly, manual, or dispatched from Pyhive | Opens a PR bumping `pyhive-integration` | +| `stale.yml` | Daily | Marks and closes inactive issues and PRs | +| `delete_beta.yml` | Manual | Deletes old beta releases | diff --git a/SECURITY.md b/SECURITY.md index 902fb00..bd06b0a 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,15 +2,15 @@ ## Supported Versions -We support the below versions of the Hive Custom Component. - -| Version | Supported | -| ------- | ------------------ | -| > 2025.1.x | :white_check_mark: | | -| < 2025 | :x: | +Only the latest release of the Hive Custom Component receives security fixes. +Update through HACS or download the [latest release](https://github.com/Pyhass/Hive-Custom-Component/releases/latest). ## Reporting a Vulnerability -To report a vulnerability, please raise a bug with a label of vulnerability. +Please **don't** open a public issue for security problems. + +Report it privately through GitHub instead: +[**>> Report a vulnerability <<**](https://github.com/Pyhass/Hive-Custom-Component/security/advisories/new) -[**>> Report vulnerability here <<**](https://github.com/Pyhive/HA-Hive-Custom-Component/issues) +Include what you found, how to reproduce it, and which version you tested. Please +remove any Hive account details, tokens or logs containing personal information. diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index 5c2527a..62986f6 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -89,13 +89,13 @@ async def async_remove_config_entry_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..2922fa2 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -4,6 +4,7 @@ from collections.abc import Mapping import copy +import logging from typing import Any from apyhiveapi import Auth @@ -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) @@ -128,7 +131,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 +143,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() diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 0caf965..99df0f5 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -1,4 +1,5 @@ """Constants for Hive.""" + from homeassistant.const import Platform ATTR_MODE = "mode" diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 111c468..90900b9 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -1,15 +1,16 @@ { "domain": "hive", "name": "Hive", + "codeowners": ["@KJonline"], "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/hive", - "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", - "version": "2026.8.0", "homekit": { "models": ["HHKBridge*"] }, - "requirements": ["pyhive-integration==1.0.9"], - "codeowners": ["@KJonline"], + "integration_type": "hub", "iot_class": "cloud_polling", - "loggers": ["apyhiveapi"] + "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", + "loggers": ["apyhiveapi"], + "requirements": ["pyhive-integration==1.0.9"], + "version": "2026.8.0" } diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index 0c3030c..378b98a 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -5,6 +5,8 @@ from datetime import timedelta from typing import Any +from apyhiveapi import Hive + from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -23,13 +25,11 @@ 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.""" 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 b5fe413..6752d1f 100644 --- a/hacs.json +++ b/hacs.json @@ -1,5 +1,6 @@ { "name": "Hive Custom Component", "render_readme": true, - "content_in_root": false + "content_in_root": false, + "homeassistant": "2025.6.0" } diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..16f9fb4 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,38 @@ +# Tooling config only - this repo is a Home Assistant custom component, not a package. + +[tool.ruff] +target-version = "py314" +extend-exclude = [".vscode"] + +[tool.ruff.lint] +select = [ + "B", # flake8-bugbear + "E", # pycodestyle errors + "F", # pyflakes + "I", # isort + "UP", # pyupgrade + "W", # pycodestyle warnings +] +ignore = [ + "E501", # line length is handled by the formatter +] + +[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"] + +[tool.ruff.lint.isort] +force-sort-within-sections = true +combine-as-imports = true +known-first-party = ["custom_components.hive"] +known-third-party = ["apyhiveapi"] +section-order = ["future", "standard-library", "third-party", "homeassistant", "first-party", "local-folder"] +split-on-trailing-comma = false + +[tool.ruff.lint.isort.sections] +homeassistant = ["homeassistant"] + +[tool.pytest.ini_options] +testpaths = ["tests"] +asyncio_mode = "auto" +asyncio_default_fixture_loop_scope = "function" diff --git a/requirements_test.txt b/requirements_test.txt new file mode 100644 index 0000000..67c5f6c --- /dev/null +++ b/requirements_test.txt @@ -0,0 +1,4 @@ +# Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). +# Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. +pytest-homeassistant-custom-component==0.13.367 +ruff==0.16.9 diff --git a/script/gen_translations.py b/script/gen_translations.py new file mode 100644 index 0000000..6b4a5d3 --- /dev/null +++ b/script/gen_translations.py @@ -0,0 +1,89 @@ +"""Generate translations/en.json from strings.json. + +strings.json uses Home Assistant's [%key:...%] references, which only core resolves. +Custom components load translations/en.json as-is, so the references have to be +expanded here. Needs homeassistant installed (it provides the common:: strings). + + python script/gen_translations.py # rewrite translations/en.json + python script/gen_translations.py --check # exit 1 if en.json is out of date +""" + +import argparse +import json +from pathlib import Path +import re +import sys +from typing import Any + +import homeassistant + +COMPONENT = Path(__file__).resolve().parent.parent / "custom_components" / "hive" +STRINGS = COMPONENT / "strings.json" +EN_JSON = COMPONENT / "translations" / "en.json" +REFERENCE = re.compile(r"\[%key:([a-z0-9_:]+)%\]") + + +def _lookup(tree: dict[str, Any], path: list[str]) -> str: + node: Any = tree + for part in path: + node = node[part] + if not isinstance(node, str): + raise TypeError(f"{'::'.join(path)} is not a string") + return node + + +def generate() -> dict[str, Any]: + """Return strings.json with every [%key:...%] reference expanded.""" + strings = json.loads(STRINGS.read_text(encoding="utf-8")) + core = json.loads( + (Path(homeassistant.__file__).parent / "strings.json").read_text( + encoding="utf-8" + ) + ) + trees = {"common": core["common"], "component::hive": strings} + + def resolve(value: str) -> str: + def replace(match: re.Match[str]) -> str: + key = match.group(1) + if key.startswith("component::hive::"): + path = key.removeprefix("component::hive::").split("::") + return resolve(_lookup(strings, path)) + if key.startswith("common::"): + return _lookup(trees["common"], key.split("::")[1:]) + raise KeyError(f"can't resolve reference {key}") + + return REFERENCE.sub(replace, value) + + def walk(node: Any) -> Any: + if isinstance(node, dict): + return {key: walk(value) for key, value in node.items()} + return resolve(node) + + return walk(strings) + + +def render() -> str: + """Return en.json content as it should be on disk.""" + return json.dumps(generate(), indent=2, ensure_ascii=False) + "\n" + + +def main() -> int: + """Write or check translations/en.json.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--check", action="store_true", help="only check, don't write") + args = parser.parse_args() + + expected = render() + if args.check: + if EN_JSON.read_text(encoding="utf-8") != expected: + print(f"{EN_JSON} is out of date, run: python script/gen_translations.py") + return 1 + return 0 + + EN_JSON.write_text(expected, encoding="utf-8") + print(f"Wrote {EN_JSON}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 3009b91..0000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[settings] -known_third_party = aiohttp,homeassistant,pyhiveapi,voluptuous diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..fefaa1d --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Tests for the Hive custom component.""" diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..3be1ca9 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,122 @@ +"""Fixtures for Hive custom component tests.""" + +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME + +from custom_components.hive.const import DOMAIN + +USERNAME = "user@example.com" +PASSWORD = "test-password" +HUB_ID = "hub-1" +TOKENS = { + "AuthenticationResult": { + "AccessToken": "access-token", + "RefreshToken": "refresh-token", + "IdToken": "id-token", + } +} +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.""" + + +def make_device( + hive_type: str, + state: Any, + *, + hive_id: str = "trv-1", + name: str = "Lounge TRV", + online: bool = True, +) -> dict[str, Any]: + """Build a device dict shaped like the ones pyhive returns.""" + return { + "hiveID": hive_id, + "hiveName": name, + "hiveType": hive_type, + "haType": "sensor", + "haName": f"{name} {hive_type.replace('_', ' ')}", + "device_id": hive_id, + "device_name": name, + "parentDevice": HUB_ID, + "deviceData": { + "model": "TRV001", + "manufacturer": "Hive", + "version": "1.0.0", + "online": online, + }, + "status": {"state": state}, + } + + +HUB_DEVICE = { + "device_id": HUB_ID, + "hiveName": "Hive Hub", + "deviceData": {"model": "NANO2", "manufacturer": "Hive", "version": "4.0.0"}, +} + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return a config entry for an account that finished setup.""" + return MockConfigEntry( + domain=DOMAIN, + title=USERNAME, + unique_id=USERNAME, + data={ + CONF_USERNAME: USERNAME, + CONF_PASSWORD: PASSWORD, + "tokens": TOKENS, + "device_data": DEVICE_DATA, + }, + ) + + +@pytest.fixture +def sensor_devices() -> list[dict[str, Any]]: + """Sensor devices returned by the mocked Hive session.""" + return [make_device("Battery", 87)] + + +@pytest.fixture +def mock_hive(sensor_devices: list[dict[str, Any]]) -> Generator[MagicMock]: + """Patch the Hive API client used by async_setup_entry.""" + devices = {"parent": [HUB_DEVICE], "sensor": sensor_devices} + hive = MagicMock() + hive.session.startSession = AsyncMock(return_value=devices) + hive.session.deviceList = devices + hive.session.updateData = AsyncMock() + hive.sensor.getSensor = AsyncMock(side_effect=lambda device: device) + hive.updateInterval = AsyncMock() + with patch("custom_components.hive.Hive", return_value=hive): + yield hive + + +@pytest.fixture +def mock_auth() -> Generator[MagicMock]: + """Patch the Hive Auth client used by the config flow.""" + auth = MagicMock() + auth.login = AsyncMock(return_value=TOKENS) + auth.sms_2fa = AsyncMock(return_value=TOKENS) + auth.device_registration = AsyncMock() + auth.get_device_data = AsyncMock(return_value=DEVICE_DATA) + auth.is_device_registered = AsyncMock(return_value=True) + with patch("custom_components.hive.config_flow.Auth", return_value=auth): + yield auth + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Stop config flow tests from setting up the integration.""" + with patch( + "custom_components.hive.async_setup_entry", return_value=True + ) as setup_entry: + yield setup_entry diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py new file mode 100644 index 0000000..af88aea --- /dev/null +++ b/tests/test_config_flow.py @@ -0,0 +1,257 @@ +"""Tests for the Hive config and options flows.""" + +from unittest.mock import AsyncMock, MagicMock + +from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, + HiveInvalid2FACode, + HiveInvalidPassword, + HiveInvalidUsername, +) +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from custom_components.hive.const import CONF_CODE, CONF_DEVICE_NAME, DOMAIN + +from .conftest import DEVICE_DATA, PASSWORD, TOKENS, USERNAME + +SMS_CHALLENGE = {"ChallengeName": "SMS_MFA", "Session": "session-token"} + +pytestmark = pytest.mark.usefixtures("mock_setup_entry") + + +async def _start_user_flow(hass: HomeAssistant) -> dict: + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + return await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + + +async def test_user_flow_without_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Login that returns tokens straight away creates the entry.""" + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == USERNAME + assert result["data"][CONF_USERNAME] == USERNAME + assert result["data"]["tokens"] == TOKENS + assert result["result"].unique_id == USERNAME + mock_auth.device_registration.assert_not_awaited() + + +async def test_user_flow_registers_device_from_login_metadata( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """NewDeviceMetadata in the login response is registered and stored.""" + mock_auth.login.return_value = { + "AuthenticationResult": { + **TOKENS["AuthenticationResult"], + "NewDeviceMetadata": {"DeviceGroupKey": "group", "DeviceKey": "key"}, + } + } + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("Home Assistant") + + +async def test_user_flow_with_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """SMS 2FA goes through the code and device name steps.""" + mock_auth.login.return_value = SMS_CHALLENGE + + result = await _start_user_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "configuration" + mock_auth.sms_2fa.assert_awaited_once_with("123456", SMS_CHALLENGE) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("My HA") + + +async def test_2fa_resend_code(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Entering 0000 requests a new SMS code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "0000"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert mock_auth.login.await_count == 2 + mock_auth.sms_2fa.assert_not_awaited() + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalid2FACode, "invalid_code"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_2fa_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """2FA failures keep the user on the code step.""" + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.sms_2fa.side_effect = exception + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert result["errors"] == {"base": error} + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalidUsername, "invalid_username"), + (HiveInvalidPassword, "invalid_password"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_user_flow_login_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """Login failures are shown on the user step and can be retried.""" + mock_auth.login.side_effect = exception + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": error} + + mock_auth.login.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_flow_unexpected_login_response( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """A login response without tokens or a challenge doesn't create an entry. + + The form is shown again without an error message; this pins current behaviour. + """ + mock_auth.login.return_value = {} + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {} + + +async def test_2fa_debug_bypass(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """The debug toggle stops at the SMS challenge instead of asking for a code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD, "disable_2fa_debug": True}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": "twofa_bypassed_debug"} + + +async def test_user_flow_already_configured( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The same account can't be added twice.""" + mock_config_entry.add_to_hass(hass) + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + mock_auth.login.assert_not_awaited() + + +async def test_reauth( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth logs in again and updates the existing entry.""" + mock_config_entry.add_to_hass(hass) + new_tokens = {"AuthenticationResult": {"AccessToken": "new-access-token"}} + mock_auth.login.return_value = new_tokens + + result = await mock_config_entry.start_reauth_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data["tokens"] == new_tokens + + +async def test_reauth_with_2fa_on_registered_device( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth with 2FA skips device registration when the device is known.""" + mock_config_entry.add_to_hass(hass) + mock_auth.login.return_value = SMS_CHALLENGE + + result = await mock_config_entry.start_reauth_flow(hass) + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + mock_auth.device_registration.assert_not_awaited() + + +async def test_options_flow( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """The scan interval option is saved and pushed to the Hive client.""" + mock_config_entry.add_to_hass(hass) + hive = MagicMock() + hive.updateInterval = AsyncMock() + mock_config_entry.runtime_data = hive + + result = await hass.config_entries.options.async_init(mock_config_entry.entry_id) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_SCAN_INTERVAL: 60} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert mock_config_entry.options == {CONF_SCAN_INTERVAL: 60} + hive.updateInterval.assert_awaited_once_with(60) diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..0d5a9e8 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,67 @@ +"""Tests for setting up and unloading the Hive integration.""" + +from unittest.mock import MagicMock + +from aiohttp.web_exceptions import HTTPServiceUnavailable +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr + +from custom_components.hive.const import DOMAIN + +from .conftest import HUB_ID + + +async def test_setup_and_unload( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The entry loads, registers the hub and unloads cleanly.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_config_entry.runtime_data is mock_hive + hub = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, HUB_ID), mock_config_entry.entry_id + ) + assert hub is not None + assert hub.name == "Hive Hub" + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + + +@pytest.mark.parametrize( + ("exception", "state"), + [ + (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY), + (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR), + ], +) +async def test_setup_failures( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_auth: MagicMock, + mock_config_entry: MockConfigEntry, + exception: Exception, + state: ConfigEntryState, +) -> None: + """Network errors retry setup, auth errors start reauth.""" + mock_hive.session.startSession.side_effect = exception + # Keep the reauth flow waiting on the 2FA step so it can be observed. + mock_auth.login.return_value = {"ChallengeName": "SMS_MFA"} + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is state + reauth_flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) + assert bool(list(reauth_flows)) is isinstance(exception, HiveReauthRequired) diff --git a/tests/test_sensor.py b/tests/test_sensor.py new file mode 100644 index 0000000..aa0f697 --- /dev/null +++ b/tests/test_sensor.py @@ -0,0 +1,112 @@ +"""Tests for the Hive sensors added by this component.""" + +from datetime import datetime +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import make_device + + +async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +async def test_battery_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Battery level is exposed as a diagnostic percentage sensor.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.lounge_trv_battery") + assert state is not None + assert state.state == "87" + assert state.attributes["unit_of_measurement"] == PERCENTAGE + assert state.attributes["device_class"] == "battery" + + entry = er.async_get(hass).async_get("sensor.lounge_trv_battery") + assert entry.unique_id == "trv-1-Battery" + assert entry.entity_category == "diagnostic" + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Battery", 50, online=False), + make_device("Availability", "Offline"), + ] + ], +) +async def test_offline_device( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Offline devices are unavailable, but their Availability sensor still reports.""" + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.lounge_trv_battery").state == STATE_UNAVAILABLE + assert hass.states.get("sensor.lounge_trv_availability").state == "Offline" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", "SCHEDULE", name="Thermostat")]] +) +async def test_heating_mode_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Heating mode is an enum sensor with lower-cased state.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.thermostat_heating_mode") + assert state.state == "schedule" + assert state.attributes["options"] == ["schedule", "manual", "off"] + assert state.attributes["Schedule not active"] == "" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "ON", name="Hot Water")]] +) +async def test_hotwater_mode_schedule_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Hot water mode shows the now/next schedule slots as attributes.""" + + def slot(status: str, start: int, end: int) -> dict[str, Any]: + return { + "value": {"status": status}, + "start": start * 60, + "Start_DateTime": datetime(2026, 1, 1, start, 0), + "End_DateTime": datetime(2026, 1, 1, end, 0), + } + + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock( + return_value={"now": slot("ON", 6, 8), "next": slot("OFF", 8, 17)} + ) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.hot_water_hotwater_mode") + assert state.state == "on" + assert state.attributes["Now"] == "ON : 06:00 - 08:00" + assert state.attributes["Next"] == "OFF : 08:00 - 17:00" + assert "Later" not in state.attributes + + +@pytest.mark.parametrize("sensor_devices", [[make_device("Unknown_Type", 1)]]) +async def test_unknown_sensor_type_is_ignored( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Device types without a description don't create entities.""" + await _setup(hass, mock_config_entry) + + assert hass.states.async_entity_ids("sensor") == [] diff --git a/tests/test_translations.py b/tests/test_translations.py new file mode 100644 index 0000000..f427174 --- /dev/null +++ b/tests/test_translations.py @@ -0,0 +1,43 @@ +"""Check the translation files stay in step with the code.""" + +import json +from pathlib import Path +import re +import sys + +import yaml + +ROOT = Path(__file__).parent.parent +COMPONENT = ROOT / "custom_components" / "hive" +EN_JSON = COMPONENT / "translations" / "en.json" + +sys.path.insert(0, str(ROOT / "script")) +import gen_translations # noqa: E402 + + +def _en() -> dict: + return json.loads(EN_JSON.read_text(encoding="utf-8")) + + +def test_en_json_is_generated_from_strings_json() -> None: + """translations/en.json matches strings.json with references expanded. + + Fix with: python script/gen_translations.py + """ + assert EN_JSON.read_text(encoding="utf-8") == gen_translations.render() + + +def test_config_flow_errors_are_translated() -> None: + """Every error the config flow can set has English text.""" + source = (COMPONENT / "config_flow.py").read_text(encoding="utf-8") + used = set(re.findall(r'errors\["base"\] = "([a-z0-9_]+)"', source)) + + assert used + assert used - set(_en()["config"]["error"]) == set() + + +def test_services_are_translated() -> None: + """Every service in services.yaml has a name in en.json.""" + services = yaml.safe_load((COMPONENT / "services.yaml").read_text(encoding="utf-8")) + + assert set(services) - set(_en().get("services", {})) == set() From 9cbde95e148cd1dec6828618533c41b5719d73c1 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:49:59 +0100 Subject: [PATCH 17/31] chore: pin astral-sh/setup-uv to v10.2.0 and update documentation URL in manifest --- .github/workflows/ci.yml | 4 ++-- .github/workflows/compat.yml | 4 ++-- .github/workflows/release.yml | 2 +- custom_components/hive/manifest.json | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1652435..cce84ae 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -43,7 +43,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.2.0 - name: Ruff version from requirements_test.txt id: ruff run: echo "spec=$(grep '^ruff==' requirements_test.txt)" >> "$GITHUB_OUTPUT" @@ -55,7 +55,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.2.0 with: python-version: "3.14" activate-environment: true diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index 7f7eccf..f0c0f59 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -38,7 +38,7 @@ jobs: channel: [stable, beta] steps: - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.2.0 with: python-version: "3.14" activate-environment: true @@ -61,7 +61,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.2.0 with: python-version: "3.14" activate-environment: true diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ac79ca3..289616e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -16,7 +16,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - - uses: astral-sh/setup-uv@v10 + - uses: astral-sh/setup-uv@v10.2.0 - env: TAG: ${{ github.event.release.tag_name }} PRERELEASE: ${{ github.event.release.prerelease }} diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 90900b9..5bedf9f 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -3,7 +3,7 @@ "name": "Hive", "codeowners": ["@KJonline"], "config_flow": true, - "documentation": "https://www.home-assistant.io/integrations/hive", + "documentation": "https://github.com/Pyhass/Hive-Custom-Component", "homekit": { "models": ["HHKBridge*"] }, From 40e54870d4a67085f18a16a67a35b61781dcab9a Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Mon, 28 Sep 2026 18:53:40 +0100 Subject: [PATCH 18/31] chore: add CODEOWNERS file with automatic review assignment for @KJonline --- .github/CODEOWNERS | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .github/CODEOWNERS diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..7b022a9 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,5 @@ +# Code owners are requested for review automatically on every PR. +# With "Require review from Code Owners" on master, their approval is needed to merge. +# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners + +* @KJonline From 77857a6b180eefee75f42b7e7bf492355b168421 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Tue, 29 Sep 2026 18:09:20 +0100 Subject: [PATCH 19/31] chore: add test infrastructure with fixtures, config flow tests, and PR template --- .github/pull_request_template.md | 13 ++ .gitignore | 14 +- tests/conftest.py | 168 +++++++++++++++ tests/test_config_flow.py | 337 +++++++++++++++++++++++++++++++ tests/test_init.py | 145 +++++++++++++ tests/test_sensor.py | 305 ++++++++++++++++++++++++++++ 6 files changed, 980 insertions(+), 2 deletions(-) create mode 100644 .github/pull_request_template.md create mode 100644 tests/conftest.py create mode 100644 tests/test_config_flow.py create mode 100644 tests/test_init.py create mode 100644 tests/test_sensor.py diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..0a52d37 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,13 @@ +## What does this change? + + + +## Related issues + + + +## Checklist + +- [ ] Tests added or updated, and `script/test` passes +- [ ] `script/lint --check` passes (after `script/lint`, which also regenerates translations) +- [ ] If this is going into a release: bumped `version` in `manifest.json` diff --git a/.gitignore b/.gitignore index b0f2192..722b5d5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,12 @@ -__pycache__ -.venv \ No newline at end of file +__pycache__/ +*.py[cod] +.venv/ +.venv-*/ +.pytest_cache/ +.ruff_cache/ +.coverage +hive.zip + +# script/develop's Home Assistant instance +config/* +!config/configuration.yaml diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..b0b8d9d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,168 @@ +"""Fixtures for Hive custom component tests.""" + +from collections.abc import Generator +from typing import Any +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import DOMAIN + +USERNAME = "user@example.com" +PASSWORD = "test-password" +HUB_ID = "hub-1" +TOKENS = { + "AuthenticationResult": { + "AccessToken": "access-token", + "RefreshToken": "refresh-token", + "IdToken": "id-token", + } +} +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.""" + + +def make_device( + hive_type: str, + state: Any = None, + *, + ha_type: str = "sensor", + hive_id: str = "trv-1", + name: str = "Lounge TRV", + ha_name: str | None = None, + online: bool = True, + status: dict[str, Any] | None = None, + **extra: Any, +) -> dict[str, Any]: + """Build a device dict shaped like the ones pyhive returns. + + status defaults to {"state": state}; extra keys (e.g. temperatureunit, min_temp) + are added at the top level, the way pyhive's addList adds them. + """ + return { + "hiveID": hive_id, + "hiveName": name, + "hiveType": hive_type, + "haType": ha_type, + "haName": ha_name or f"{name} {hive_type.replace('_', ' ')}", + "device_id": hive_id, + "device_name": name, + "parentDevice": HUB_ID, + "deviceData": { + "model": "TRV001", + "manufacturer": "Hive", + "version": "1.0.0", + "online": online, + }, + "status": {"state": state} if status is None else status, + **extra, + } + + +HUB_DEVICE = { + "device_id": HUB_ID, + "hiveName": "Hive Hub", + "deviceData": {"model": "NANO2", "manufacturer": "Hive", "version": "4.0.0"}, +} + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return a config entry for an account that finished setup.""" + return MockConfigEntry( + domain=DOMAIN, + title=USERNAME, + unique_id=USERNAME, + data={ + CONF_USERNAME: USERNAME, + CONF_PASSWORD: PASSWORD, + "tokens": TOKENS, + "device_data": DEVICE_DATA, + }, + ) + + +@pytest.fixture +def sensor_devices() -> list[dict[str, Any]]: + """Sensor devices returned by the mocked Hive session.""" + return [make_device("Battery", 87)] + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Devices for the other platforms, keyed like pyhive's deviceList.""" + return {} + + +def _echo(device: dict[str, Any]) -> dict[str, Any]: + return device + + +@pytest.fixture +def mock_hive( + sensor_devices: list[dict[str, Any]], + platform_devices: dict[str, list[dict[str, Any]]], +) -> Generator[MagicMock]: + """Patch the Hive API client used by async_setup_entry. + + Every getter hands the device back unchanged, so a test controls entity + state through the device dicts it passes in. + """ + devices = {"parent": [HUB_DEVICE], "sensor": sensor_devices, **platform_devices} + hive = MagicMock() + hive.session.startSession = AsyncMock(return_value=devices) + hive.session.deviceList = devices + hive.session.updateData = AsyncMock() + hive.sensor.getSensor = AsyncMock(side_effect=_echo) + hive.heating.getClimate = AsyncMock(side_effect=_echo) + hive.hotwater.getWaterHeater = AsyncMock(side_effect=_echo) + hive.light.getLight = AsyncMock(side_effect=_echo) + hive.switch.getSwitch = AsyncMock(side_effect=_echo) + hive.updateInterval = AsyncMock() + with patch("custom_components.hive.Hive", return_value=hive): + yield hive + + +@pytest.fixture +def mock_auth() -> Generator[MagicMock]: + """Patch the Hive Auth client used by the config flow.""" + auth = MagicMock() + auth.login = AsyncMock(return_value=TOKENS) + auth.sms_2fa = AsyncMock(return_value=TOKENS) + auth.device_registration = AsyncMock() + auth.get_device_data = AsyncMock(return_value=DEVICE_DATA) + auth.is_device_registered = AsyncMock(return_value=True) + auth.forget_device = AsyncMock() + with ( + patch("custom_components.hive.config_flow.Auth", return_value=auth), + patch("custom_components.hive.Auth", return_value=auth), + ): + yield auth + + +@pytest.fixture +def mock_setup_entry() -> Generator[AsyncMock]: + """Stop config flow tests from setting up the integration.""" + with patch( + "custom_components.hive.async_setup_entry", return_value=True + ) as setup_entry: + yield setup_entry + + +@pytest.fixture +async def setup_integration( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> MockConfigEntry: + """Set up the integration with the mocked Hive client.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + return mock_config_entry diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py new file mode 100644 index 0000000..90cee7f --- /dev/null +++ b/tests/test_config_flow.py @@ -0,0 +1,337 @@ +"""Tests for the Hive config and options flows.""" + +from unittest.mock import AsyncMock, MagicMock + +from apyhiveapi.helper.hive_exceptions import ( + HiveApiError, + HiveInvalid2FACode, + HiveInvalidPassword, + HiveInvalidUsername, +) +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.config_entries import SOURCE_USER +from homeassistant.const import CONF_PASSWORD, CONF_SCAN_INTERVAL, CONF_USERNAME +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType + +from custom_components.hive.config_flow import _sanitize_payload +from custom_components.hive.const import CONF_CODE, CONF_DEVICE_NAME, DOMAIN + +from .conftest import DEVICE_DATA, PASSWORD, TOKENS, USERNAME + +SMS_CHALLENGE = {"ChallengeName": "SMS_MFA", "Session": "session-token"} + +pytestmark = pytest.mark.usefixtures("mock_setup_entry") + + +async def _start_user_flow(hass: HomeAssistant) -> dict: + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + return await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + + +async def test_user_flow_without_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Login that returns tokens straight away creates the entry.""" + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == USERNAME + assert result["data"][CONF_USERNAME] == USERNAME + assert result["data"]["tokens"] == TOKENS + assert result["result"].unique_id == USERNAME + mock_auth.device_registration.assert_not_awaited() + + +async def test_user_flow_registers_device_from_login_metadata( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """NewDeviceMetadata in the login response is registered and stored.""" + mock_auth.login.return_value = { + "AuthenticationResult": { + **TOKENS["AuthenticationResult"], + "NewDeviceMetadata": {"DeviceGroupKey": "group", "DeviceKey": "key"}, + } + } + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("Home Assistant") + + +async def test_user_flow_with_2fa(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """SMS 2FA goes through the code and device name steps.""" + mock_auth.login.return_value = SMS_CHALLENGE + + result = await _start_user_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "configuration" + mock_auth.sms_2fa.assert_awaited_once_with("123456", SMS_CHALLENGE) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"]["device_data"] == DEVICE_DATA + mock_auth.device_registration.assert_awaited_once_with("My HA") + + +async def test_2fa_resend_code(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """Entering 0000 requests a new SMS code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "0000"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert mock_auth.login.await_count == 2 + mock_auth.sms_2fa.assert_not_awaited() + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalid2FACode, "invalid_code"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_2fa_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """2FA failures keep the user on the code step.""" + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.sms_2fa.side_effect = exception + result = await _start_user_flow(hass) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "2fa" + assert result["errors"] == {"base": error} + + +@pytest.mark.parametrize( + ("exception", "error"), + [ + (HiveInvalidUsername, "invalid_username"), + (HiveInvalidPassword, "invalid_password"), + (HiveApiError, "no_internet_available"), + ], +) +async def test_user_flow_login_errors( + hass: HomeAssistant, mock_auth: MagicMock, exception: type[Exception], error: str +) -> None: + """Login failures are shown on the user step and can be retried.""" + mock_auth.login.side_effect = exception + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": error} + + mock_auth.login.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_user_flow_unexpected_login_response( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """A login response without tokens or a challenge doesn't create an entry. + + The form is shown again without an error message; this pins current behaviour. + """ + mock_auth.login.return_value = {} + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {} + + +async def test_2fa_debug_bypass(hass: HomeAssistant, mock_auth: MagicMock) -> None: + """The debug toggle stops at the SMS challenge instead of asking for a code.""" + mock_auth.login.return_value = SMS_CHALLENGE + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD, "disable_2fa_debug": True}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": "twofa_bypassed_debug"} + + +async def test_user_flow_already_configured( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The same account can't be added twice.""" + mock_config_entry.add_to_hass(hass) + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + mock_auth.login.assert_not_awaited() + + +async def test_reauth( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth logs in again and updates the existing entry.""" + mock_config_entry.add_to_hass(hass) + new_tokens = {"AuthenticationResult": {"AccessToken": "new-access-token"}} + mock_auth.login.return_value = new_tokens + + result = await mock_config_entry.start_reauth_flow(hass) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert mock_config_entry.data["tokens"] == new_tokens + + +async def test_reauth_with_2fa_on_registered_device( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth with 2FA skips device registration when the device is known.""" + mock_config_entry.add_to_hass(hass) + mock_auth.login.return_value = SMS_CHALLENGE + + result = await mock_config_entry.start_reauth_flow(hass) + assert result["step_id"] == "2fa" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + mock_auth.device_registration.assert_not_awaited() + + +async def test_options_flow( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """The scan interval option is saved and pushed to the Hive client.""" + mock_config_entry.add_to_hass(hass) + hive = MagicMock() + hive.updateInterval = AsyncMock() + mock_config_entry.runtime_data = hive + + result = await hass.config_entries.options.async_init(mock_config_entry.entry_id) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.options.async_configure( + result["flow_id"], {CONF_SCAN_INTERVAL: 60} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert mock_config_entry.options == {CONF_SCAN_INTERVAL: 60} + hive.updateInterval.assert_awaited_once_with(60) + + +async def test_device_registration_failure_still_creates_entry( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """If registering the device fails, setup carries on without device_data.""" + mock_auth.login.return_value = { + "AuthenticationResult": { + **TOKENS["AuthenticationResult"], + "NewDeviceMetadata": {"DeviceGroupKey": "group", "DeviceKey": "key"}, + } + } + mock_auth.device_registration.side_effect = HiveApiError + + result = await _start_user_flow(hass) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert "device_data" not in result["data"] + + +async def test_reauth_with_2fa_on_unregistered_device( + hass: HomeAssistant, mock_auth: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Reauth with 2FA registers the device again if Hive has forgotten it.""" + mock_config_entry.add_to_hass(hass) + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.is_device_registered.return_value = False + + result = await mock_config_entry.start_reauth_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + assert result["step_id"] == "configuration" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + mock_auth.device_registration.assert_awaited_once_with("My HA") + + +async def test_2fa_response_without_tokens( + hass: HomeAssistant, mock_auth: MagicMock +) -> None: + """A 2FA response without tokens shows an unknown error on the last step.""" + mock_auth.login.return_value = SMS_CHALLENGE + mock_auth.sms_2fa.return_value = {"ChallengeName": "SOMETHING_ELSE"} + result = await _start_user_flow(hass) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_CODE: "123456"} + ) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_DEVICE_NAME: "My HA"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "configuration" + assert result["errors"] == {"base": "unknown"} + + +def test_sanitize_payload() -> None: + """Secrets are masked in logged payloads; other values are left alone.""" + payload = { + "ChallengeName": "SMS_MFA", + "Session": "abcdefghijklmnop", + "AuthenticationResult": {"AccessToken": "short", "ExpiresIn": 3600}, + "Devices": [{"DeviceKey": "key", "RefreshToken": 12345}], + } + + assert _sanitize_payload(payload) == { + "ChallengeName": "SMS_MFA", + "Session": "abcd...mnop", + "AuthenticationResult": {"AccessToken": "***", "ExpiresIn": 3600}, + "Devices": [{"DeviceKey": "key", "RefreshToken": 12345}], + } + assert payload["Session"] == "abcdefghijklmnop" diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..547490b --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,145 @@ +"""Tests for setting up and unloading the Hive integration.""" + +from unittest.mock import MagicMock + +from aiohttp.web_exceptions import HTTPServiceUnavailable +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +import pytest +from pytest_homeassistant_custom_component.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 custom_components.hive import async_remove_config_entry_device, refresh_system +from custom_components.hive.const import DOMAIN + +from .conftest import HUB_ID + + +async def test_setup_and_unload( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """The entry loads, registers the hub and unloads cleanly.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_config_entry.runtime_data is mock_hive + hub = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, HUB_ID), mock_config_entry.entry_id + ) + assert hub is not None + assert hub.name == "Hive Hub" + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + + +@pytest.mark.parametrize( + ("exception", "state"), + [ + (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY), + (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR), + ], +) +async def test_setup_failures( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_auth: MagicMock, + mock_config_entry: MockConfigEntry, + exception: Exception, + state: ConfigEntryState, +) -> None: + """Network errors retry setup, auth errors start reauth.""" + mock_hive.session.startSession.side_effect = exception + # Keep the reauth flow waiting on the 2FA step so it can be observed. + mock_auth.login.return_value = {"ChallengeName": "SMS_MFA"} + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is state + reauth_flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) + assert bool(list(reauth_flows)) is isinstance(exception, HiveReauthRequired) + + +@pytest.mark.parametrize( + ("options", "interval"), [({}, 120), ({CONF_SCAN_INTERVAL: 60}, 60)] +) +async def test_scan_interval_passed_to_session( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + options: dict, + interval: int, +) -> None: + """The scan interval option (default 120s) is handed to the Hive session.""" + mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry(mock_config_entry, options=options) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + session_config = mock_hive.session.startSession.await_args.args[0] + assert session_config["options"] == {CONF_SCAN_INTERVAL: interval} + assert session_config["tokens"] == mock_config_entry.data["tokens"] + + +@pytest.mark.usefixtures("setup_integration") +async def test_only_platforms_with_devices_are_set_up(hass: HomeAssistant) -> None: + """Platforms Hive reports no devices for aren't loaded.""" + assert "hive.sensor" in hass.config.components + for platform in ("binary_sensor", "climate", "light", "switch", "water_heater"): + assert f"hive.{platform}" not in hass.config.components + + +async def test_remove_entry_forgets_device( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_auth: MagicMock, + setup_integration: MockConfigEntry, +) -> None: + """Deleting the entry deregisters this Home Assistant device from Hive.""" + await hass.config_entries.async_remove(setup_integration.entry_id) + await hass.async_block_till_done() + + mock_auth.forget_device.assert_awaited_once_with("access-token", "device-key") + + +async def test_remove_device( + hass: HomeAssistant, setup_integration: MockConfigEntry +) -> None: + """Any Hive device can be removed from the device page.""" + hub = dr.async_get(hass).async_get_device_by_identifier( + (DOMAIN, HUB_ID), setup_integration.entry_id + ) + + assert await async_remove_config_entry_device(hass, setup_integration, hub) + + +async def test_refresh_system(hass: HomeAssistant) -> None: + """refresh_system runs the method, then signals every entity to update.""" + calls = [] + signals = [] + async_dispatcher_connect(hass, DOMAIN, lambda: signals.append(True)) + + class FakeEntity: + def __init__(self) -> None: + self.hass = hass + + @refresh_system + async def turn_on(self, value: int) -> None: + calls.append(value) + + await FakeEntity().turn_on(5) + await hass.async_block_till_done() + + assert calls == [5] + assert signals == [True] diff --git a/tests/test_sensor.py b/tests/test_sensor.py new file mode 100644 index 0000000..db644eb --- /dev/null +++ b/tests/test_sensor.py @@ -0,0 +1,305 @@ +"""Tests for the Hive sensors added by this component.""" + +from datetime import datetime +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from custom_components.hive import sensor + +from .conftest import make_device + + +async def _setup(hass: HomeAssistant, entry: MockConfigEntry) -> None: + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + +async def test_battery_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Battery level is exposed as a diagnostic percentage sensor.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.lounge_trv_battery") + assert state is not None + assert state.state == "87" + assert state.attributes["unit_of_measurement"] == PERCENTAGE + assert state.attributes["device_class"] == "battery" + + entry = er.async_get(hass).async_get("sensor.lounge_trv_battery") + assert entry.unique_id == "trv-1-Battery" + assert entry.entity_category == "diagnostic" + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Battery", 50, online=False), + make_device("Availability", "Offline"), + ] + ], +) +async def test_offline_device( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Offline devices are unavailable, but their Availability sensor still reports.""" + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.lounge_trv_battery").state == STATE_UNAVAILABLE + assert hass.states.get("sensor.lounge_trv_availability").state == "Offline" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", "SCHEDULE", name="Thermostat")]] +) +async def test_heating_mode_sensor( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Heating mode is an enum sensor with lower-cased state.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.thermostat_heating_mode") + assert state.state == "schedule" + assert state.attributes["options"] == ["schedule", "manual", "off"] + assert state.attributes["Schedule not active"] == "" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "ON", name="Hot Water")]] +) +async def test_hotwater_mode_schedule_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Hot water mode shows the now/next schedule slots as attributes.""" + + def slot(status: str, start: int, end: int) -> dict[str, Any]: + return { + "value": {"status": status}, + "start": start * 60, + "Start_DateTime": datetime(2026, 1, 1, start, 0), + "End_DateTime": datetime(2026, 1, 1, end, 0), + } + + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock( + return_value={"now": slot("ON", 6, 8), "next": slot("OFF", 8, 17)} + ) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.hot_water_hotwater_mode") + assert state.state == "on" + assert state.attributes["Now"] == "ON : 06:00 - 08:00" + assert state.attributes["Next"] == "OFF : 08:00 - 17:00" + assert "Later" not in state.attributes + + +@pytest.mark.parametrize("sensor_devices", [[make_device("Unknown_Type", 1)]]) +async def test_unknown_sensor_type_is_ignored( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Device types without a description don't create entities.""" + await _setup(hass, mock_config_entry) + + assert hass.states.async_entity_ids("sensor") == [] + + +@pytest.mark.parametrize( + ("sensor_devices", "entity_id", "expected"), + [ + ( + [make_device("Power", 42.5, name="Fan Plug")], + "sensor.fan_plug_power", + {"state": "42.5", "unit_of_measurement": "W", "device_class": "power"}, + ), + ( + [make_device("Current_Temperature", 19.5, name="Hallway")], + "sensor.hallway_current_temperature", + { + "state": "19.5", + "unit_of_measurement": "°C", + "device_class": "temperature", + }, + ), + ( + [make_device("Heating_Current_Temperature", 20.1, name="Heating")], + "sensor.heating_heating_current_temperature", + { + "state": "20.1", + "unit_of_measurement": "°C", + "state_class": "measurement", + }, + ), + ( + [make_device("Heating_Target_Temperature", 21, name="Heating")], + "sensor.heating_heating_target_temperature", + {"state": "21", "icon": "mdi:thermometer"}, + ), + ( + [make_device("Mode", "SCHEDULE", name="Fan Plug")], + "sensor.fan_plug_mode", + {"state": "SCHEDULE", "icon": "mdi:eye"}, + ), + ], +) +async def test_value_sensors( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + entity_id: str, + expected: dict[str, str], +) -> None: + """Each simple sensor type reports its value with the right unit and class.""" + await _setup(hass, mock_config_entry) + + state = hass.states.get(entity_id) + assert state.state == expected.pop("state") + for attribute, value in expected.items(): + assert state.attributes[attribute] == value + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", "MANUAL", name="Thermostat")]] +) +async def test_heating_mode_schedule_attributes( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Heating mode shows now/next/later target temperatures; incomplete slots are skipped.""" + + def slot(target: float, start: int, end: int) -> dict[str, Any]: + return { + "value": {"target": target}, + "start": start * 60, + "Start_DateTime": datetime(2026, 1, 1, start, 0), + "End_DateTime": datetime(2026, 1, 1, end, 0), + } + + mock_hive.heating.getScheduleNowNextLater = AsyncMock( + return_value={ + "now": slot(20, 6, 9), + "next": slot(16, 9, 17), + "later": slot(21, 17, 22), + } + ) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.thermostat_heating_mode") + assert state.state == "manual" + assert state.attributes["Now"] == "20 °C : 06:00 - 09:00" + assert state.attributes["Next"] == "16 °C : 09:00 - 17:00" + assert state.attributes["Later"] == "21 °C : 17:00 - 22:00" + + +INCOMPLETE_SCHEDULES = [ + {}, + {"now": {"value": {}, "start": 0}, "next": {"value": {}}, "later": {}}, +] + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Heating_Mode", "SCHEDULE", name="Thermostat"), + make_device("Hotwater_Mode", "SCHEDULE", name="Hot Water"), + ] + ], +) +@pytest.mark.parametrize("schedule", INCOMPLETE_SCHEDULES) +async def test_incomplete_schedule( + hass: HomeAssistant, + mock_hive: MagicMock, + mock_config_entry: MockConfigEntry, + schedule: dict[str, Any], +) -> None: + """Schedule slots missing a target, status or time are left out.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=schedule) + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock(return_value=schedule) + + await _setup(hass, mock_config_entry) + + for entity_id in ( + "sensor.thermostat_heating_mode", + "sensor.hot_water_hotwater_mode", + ): + attributes = hass.states.get(entity_id).attributes + assert not {"Now", "Next", "Later", "Schedule not active"} & set(attributes) + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "SCHEDULE", name="Hot Water")]] +) +async def test_hotwater_mode_later_slot( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Hot water shows the later slot when Hive sends one.""" + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock( + return_value={ + "later": { + "value": {"status": "ON"}, + "start": 1020, + "Start_DateTime": datetime(2026, 1, 1, 17, 0), + "End_DateTime": datetime(2026, 1, 1, 18, 0), + }, + } + ) + + await _setup(hass, mock_config_entry) + + attributes = hass.states.get("sensor.hot_water_hotwater_mode").attributes + assert attributes["Later"] == "ON : 17:00 - 18:00" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Hotwater_Mode", "OFF", name="Hot Water")]] +) +async def test_hotwater_mode_no_schedule( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """Without a schedule the hot water sensor says so.""" + mock_hive.hotwater.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + state = hass.states.get("sensor.hot_water_hotwater_mode") + assert state.state == "off" + assert state.attributes["Schedule not active"] == "" + + +@pytest.mark.parametrize( + "sensor_devices", [[make_device("Heating_Mode", None, name="Thermostat")]] +) +async def test_mode_sensor_without_state( + hass: HomeAssistant, mock_hive: MagicMock, mock_config_entry: MockConfigEntry +) -> None: + """A mode sensor with no state reads unknown instead of failing.""" + mock_hive.heating.getScheduleNowNextLater = AsyncMock(return_value=None) + + await _setup(hass, mock_config_entry) + + assert hass.states.get("sensor.thermostat_heating_mode").state == STATE_UNKNOWN + + +async def test_sensor_platform_without_devices( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """The sensor platform adds nothing when Hive reports no sensors.""" + hive = MagicMock() + hive.session.deviceList = {"sensor": []} + mock_config_entry.runtime_data = hive + add_entities = MagicMock() + + await sensor.async_setup_entry(hass, mock_config_entry, add_entities) + + add_entities.assert_not_called() From 7f4af8d9b6af0d9a2a04b8aad9e5115743c70eaf Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Tue, 29 Sep 2026 18:11:24 +0100 Subject: [PATCH 20/31] chore: add Claude Code skills, maintenance documentation, and development tooling - Add four Claude Code skills for automated maintenance tasks: - `/bump-pyhive`: update pyhive-integration dependency and verify compatibility - `/release`: cut beta or stable releases with automated checks - `/triage-compat`: diagnose and fix failing Compatibility workflow runs - `/repo-health`: one-shot health report for workflows, PRs, and settings - Add CONTRIBUTING.md with setup instructions, everyday --- .claude/skills/bump-pyhive/SKILL.md | 54 ++++++++ .claude/skills/release/SKILL.md | 48 +++++++ .claude/skills/repo-health/SKILL.md | 34 +++++ .claude/skills/triage-compat/SKILL.md | 57 ++++++++ CONTRIBUTING.md | 67 ++++++++++ MAINTAINING.md | 133 +++++++++++++++++++ config/configuration.yaml | 8 ++ script/_common.sh | 14 ++ script/develop | 15 +++ script/lint | 17 +++ script/setup | 36 ++++++ script/test | 6 + tests/test_binary_sensor.py | 85 ++++++++++++ tests/test_climate.py | 180 ++++++++++++++++++++++++++ tests/test_light.py | 151 +++++++++++++++++++++ tests/test_switch.py | 90 +++++++++++++ tests/test_water_heater.py | 128 ++++++++++++++++++ 17 files changed, 1123 insertions(+) create mode 100644 .claude/skills/bump-pyhive/SKILL.md create mode 100644 .claude/skills/release/SKILL.md create mode 100644 .claude/skills/repo-health/SKILL.md create mode 100644 .claude/skills/triage-compat/SKILL.md create mode 100644 CONTRIBUTING.md create mode 100644 MAINTAINING.md create mode 100644 config/configuration.yaml create mode 100644 script/_common.sh create mode 100755 script/develop create mode 100755 script/lint create mode 100755 script/setup create mode 100755 script/test create mode 100644 tests/test_binary_sensor.py create mode 100644 tests/test_climate.py create mode 100644 tests/test_light.py create mode 100644 tests/test_switch.py create mode 100644 tests/test_water_heater.py diff --git a/.claude/skills/bump-pyhive/SKILL.md b/.claude/skills/bump-pyhive/SKILL.md new file mode 100644 index 0000000..234640b --- /dev/null +++ b/.claude/skills/bump-pyhive/SKILL.md @@ -0,0 +1,54 @@ +--- +name: bump-pyhive +description: Update the pyhive-integration (apyhiveapi) requirement in the Hive custom component's manifest.json, review what changed in the library, and verify the component against it. Use when a pyhive bump PR is open, a new pyhive release is out, or the user wants to test a pyhive beta/dev build. +--- + +# Bump pyhive-integration + +`pyhive-integration` (imported as `apyhiveapi`) is pinned in `custom_components/hive/manifest.json` `requirements`. Dependabot can't bump it, so `.github/workflows/pyhive_bump.yml` opens `deps/pyhive-integration-` PRs instead. + +## 1. Pick the target +```bash +jq -r '.requirements[]' custom_components/hive/manifest.json # current +curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.info.version' # latest stable +curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' | tail -10 +gh pr list --label dependencies --search "pyhive-integration in:title" # existing bot PR? +``` +If there's already a bot PR for the target, work on that branch (`gh pr checkout `) instead of making a new change. + +## 2. Review what changed +Diff the two versions' sources and look closely at anything this component calls: +```bash +S=$(mktemp -d) +for v in ; do + uv pip download --no-deps "pyhive-integration==$v" -d "$S/$v" 2>/dev/null || pip download --no-deps "pyhive-integration==$v" -d "$S/$v" +done +``` +Unpack both and diff `apyhiveapi/`. Things to check: +- `Auth` methods used in `config_flow.py` and `__init__.py`: `login`, `sms_2fa`, `device_registration`, `get_device_data`, `is_device_registered`, `forget_device`. +- `Hive`, `session.startSession`, `session.deviceList`, `updateInterval`. +- `helper/const.py`: `PRODUCTS`, `DEVICES` and `sensor_commands`. A new or renamed `hiveType` needs a matching `SENSOR_TYPES` entry in `sensor.py`, or core's platform descriptions, before it shows up in HA. +- Exceptions in `helper/hive_exceptions.py`. +- The getters that tests mock: `getSensor`, `getClimate`, `getWaterHeater`, `getLight`, `getSwitch` and `getScheduleNowNextLater`. + +Also check whether the version HA core pins (`homeassistant/components/hive/manifest.json` in `.venv`) differs a lot. Core's re-exported platforms are written against that version. + +## 3. Apply and verify +- Change only the `pyhive-integration==` pin in `manifest.json`. Don't change the component `version`; that happens at release. +- Install and test: + ```bash + VIRTUAL_ENV=.venv uv pip install "pyhive-integration==" + script/test + script/lint --check + ``` +- Where the diff showed behaviour changes, add tests for them. +- For a beta or dev build, suggest also releasing a component beta (see `/release`) so users can try it. + +## 4. Report +Report: +- the version change +- a short summary of the library changes that matter to this component, with any risks +- the test results +- whether it's ready to merge + +If a bot PR has no CI runs, remind the user to close and reopen it, or to set up the `BOT_TOKEN` secret. Don't commit, push, or merge unless asked. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md new file mode 100644 index 0000000..bbb03a4 --- /dev/null +++ b/.claude/skills/release/SKILL.md @@ -0,0 +1,48 @@ +--- +name: release +description: Cut a beta or stable release of the Hive custom component - bump manifest.json, publish the GitHub release with a matching tag, and verify the Release workflow. Use when the user asks to release, ship, tag, or publish a version or beta. +--- + +# Release + +Follow MAINTAINING.md → "Releasing". The rules that matter: +- The tag must equal `version` in `custom_components/hive/manifest.json`, for example `2026.10.0` or `2026.10.0b1`. +- Beta tags (`bN`) are always published as pre-releases. Stable tags never are. +- Publishing a release is visible to every HACS user, and so is deleting one. **Confirm the exact tag and whether it is a pre-release with the user before running `gh release create`.** Never commit, push, or open PRs unless the user asks. + +## Steps + +1. **Pick the version.** + - Read the current `version` from the manifest and list recent tags: `gh release list -L 10`. + - Propose the next version and let the user confirm or change it: + - New month: `YEAR.MONTH.0`. + - Same month: bump the patch number. + - Beta: add `b1`, or the next free `bN`. + +2. **Check it's safe to ship.** + - `gh run list -w ci.yml -b master -L 1` and `gh run list -w compat.yml -L 1` must both be green. If either is red, stop and report. For a red Compatibility run, suggest `/triage-compat`. + - `script/test` and `script/lint --check` must pass locally. + - Check `git log ..origin/master --oneline`. If there's nothing to release, say so. + +3. **Bump the manifest.** Change only the `version` value in `manifest.json`. Don't touch `requirements`; that's `/bump-pyhive`. The change must reach `master` before tagging: + - If the user asks, make a branch `release/`, commit it, and open a PR. + - Otherwise hand the change over for them to commit. + - Wait until it's merged, and check with `git fetch && git show origin/master:custom_components/hive/manifest.json | jq -r .version`. + +4. **Publish** (only after the user confirms the tag): + ```bash + gh release create --target master --generate-notes --prerelease # beta + gh release create --target master --generate-notes --latest # stable + ``` + +5. **Verify.** + - Watch the Release workflow: + ```bash + gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId') --exit-status + ``` + - Then confirm `hive.zip` is attached: `gh release view --json assets -q '.assets[].name'`. + - If the check job fails, the release is already visible to HACS users. Tell the user, and offer `gh release delete --cleanup-tag` (it needs their OK), then a corrected release. + +6. **Clean up** after a stable release that replaces betas. Offer `gh workflow run delete_beta.yml`. It keeps the newest pre-release and never touches stable releases. + +Report the release URL, the Release run result and anything left for the user to do. diff --git a/.claude/skills/repo-health/SKILL.md b/.claude/skills/repo-health/SKILL.md new file mode 100644 index 0000000..553c4b3 --- /dev/null +++ b/.claude/skills/repo-health/SKILL.md @@ -0,0 +1,34 @@ +--- +name: repo-health +description: One-shot health report for the Hive custom component repo - workflow states and latest results, open bot/dependency PRs, stale-labelled items, pending release, branch protection and required secrets. Use when the user asks for status, "is everything OK", a maintenance check, or what needs attention. +--- + +# Repo health + +This is read-only. Gather everything first, then report. Don't change settings, rerun workflows, or merge anything unless the user asks. + +```bash +R=Pyhass/Hive-Custom-Component +gh workflow list --all -R $R # any "disabled_inactivity"? +for w in ci.yml compat.yml pyhive_bump.yml stale.yml release.yml; do + echo "== $w"; gh run list -R $R -w $w -L 3 --json conclusion,createdAt,headBranch,event -q '.[] | "\(.createdAt) \(.event) \(.headBranch) \(.conclusion)"' +done +gh pr list -R $R --state open --json number,title,author,labels,statusCheckRollup,createdAt +gh issue list -R $R --label no-issue-activity +gh pr list -R $R --label no-pr-activity +gh release list -R $R -L 5 +git fetch -q origin && git log $(gh release list -R $R -L1 --exclude-pre-releases --json tagName -q '.[0].tagName')..origin/master --oneline +gh api repos/$R/branches/master/protection 2>&1 | jq '{checks: .required_status_checks.contexts, code_owners: .required_pull_request_reviews.require_code_owner_reviews}' +gh secret list -R $R # expect BOT_TOKEN +``` +(The protection and secrets calls need admin access. If they fail, say so rather than guessing.) + +Compare what you find with MAINTAINING.md: +- **Workflows:** all active, with no `disabled_inactivity`. The latest CI run on master and the latest Compatibility run should both be green. The last Compatibility run should be under ~26 hours old. +- **Bot PRs:** Dependabot and pyhive bump PRs with no checks at all mean `BOT_TOKEN` is missing (for pyhive ones). PRs failing checks need attention. Anything older than about 2 weeks is going stale. +- **Unreleased commits on master:** suggest a release if there are user-facing changes. +- **Branch protection:** the required checks should be `HACS validation`, `Hassfest`, `Lint` and `Tests`, with code owner review on. +- **Secrets:** `BOT_TOKEN` should be present. +- **Pinned HA:** compare the HA version in the `requirements_test.txt` comment with the latest stable on PyPI (`curl -fsS https://pypi.org/pypi/homeassistant/json | jq -r .info.version`). A gap of more than one minor release means the Dependabot PR is stuck. + +Report as a short table with ✅ / ⚠️ / ❌ and one line each. Then list the actions in priority order, each with the skill to use (`/triage-compat`, `/bump-pyhive`, `/release`) or the settings page to change. diff --git a/.claude/skills/triage-compat/SKILL.md b/.claude/skills/triage-compat/SKILL.md new file mode 100644 index 0000000..3448d35 --- /dev/null +++ b/.claude/skills/triage-compat/SKILL.md @@ -0,0 +1,57 @@ +--- +name: triage-compat +description: Diagnose and fix a failing nightly Compatibility workflow (compat.yml) for the Hive custom component - identifies which Home Assistant channel broke, reproduces it locally against that HA version, and fixes it. Use when Compatibility is red, a new HA release/beta broke the component, or the user asks whether the component works with a given HA version. +--- + +# Triage Compatibility + +Background: most platform files (`binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py`, `entity.py`) re-export `homeassistant.components.hive.*`. `__init__.py`, `sensor.py` and `config_flow.py` are this repo's own code, but they rely on HA helpers and on core's `HiveEntity`. HA changes break things here without any commit in this repo. + +## 1. Find what failed +```bash +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=`. + +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. +- **HACS/hassfest** fails: follow the validator's message. + +## 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==" +VENV=.venv-ha-beta script/test -x +``` +For a dev failure, run the smoke test instead: +```bash +VIRTUAL_ENV=.venv-ha-dev uv pip install "homeassistant @ git+https://github.com/home-assistant/core@dev" +.venv-ha-dev/bin/python .github/scripts/smoke_import.py +``` +(Create `.venv-ha-dev` with `VENV=.venv-ha-dev script/setup` first.) + +## 3. Find the upstream change +- Compare core's hive integration between the two HA versions: + `https://github.com/home-assistant/core/commits/dev/homeassistant/components/hive`. +- Search https://developers.home-assistant.io/blog for deprecations of the symbol that failed. +- Check the installed source: `.venv-ha-beta/lib/python3.*/site-packages/homeassistant/components/hive/`. + +## 4. Fix +- Keep the fix working on **both** the pinned HA (`.venv`) and the failing version. Run `script/test` in both venvs. +- If core changed a re-exported platform in a way that conflicts with this component (for example it now expects something `__init__.py` doesn't provide), adapt `__init__.py`. Only replace the re-export with a local module as a last resort, and tell the user. +- Add or adjust a test that would have caught it. +- Run `script/lint`. + +## 5. Report +Tell the user: +- which HA version and channel broke, and the root cause (with the upstream link) +- the fix, and the test results in both venvs +- whether a release is needed: stable breakage needs a patch release now (suggest `/release`); beta breakage needs one before HA's release date + +Don't commit, push, or open PRs unless asked. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a8bd5e9 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,67 @@ +# Contributing + +Thanks for helping out. This is a Home Assistant custom component for Hive. It is +installed through HACS and builds on the Hive integration in Home Assistant core. + +## Set up + +You need [uv](https://docs.astral.sh/uv/getting-started/installation/) and `jq`. + +```bash +script/setup # .venv with Python 3.14, Home Assistant and the test tools, same as CI +``` + +## Everyday commands + +| Command | What it does | +|---|---| +| `script/test` | Run the tests. Extra arguments go to pytest: `script/test tests/test_climate.py -x` | +| `script/lint` | Fix lint and formatting, and regenerate `translations/en.json` | +| `script/lint --check` | The checks CI runs, without changing anything | +| `script/develop` | Run Home Assistant at http://localhost:8123 with this component loaded | + +`script/develop` keeps its Home Assistant instance in `config/`. The first time, +go through onboarding, then add the Hive integration with a real Hive account. +Restart it after changing code. + +## How the component is put together + +- `sensor.py` and `config_flow.py` are this repo's own code. `__init__.py` is too. +- `binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py` and + `entity.py` are one-line re-exports of Home Assistant core's hive platforms. To + change their behaviour, either replace the re-export with a real module here, or + change it in core. +- Talking to Hive is done by [`pyhive-integration`](https://pypi.org/project/pyhive-integration/) + (imported as `apyhiveapi`). Its version is pinned in `manifest.json`. +- Text shown in the UI lives in `strings.json`. Run `script/lint` after editing it; + `translations/en.json` is generated from it and a test checks they match. + +## Tests + +The tests start a real Home Assistant in memory and mock the Hive API, so they +need no network or account. There is one file per platform. The fixtures in +`tests/conftest.py` do most of the work: + +- `make_device(...)` builds a device the way pyhive returns it. +- Parametrize `sensor_devices` or `platform_devices` to choose what Hive reports. +- `setup_integration` loads the integration with those devices. + +```python +@pytest.mark.parametrize( + "platform_devices", + [{"switch": [make_device("activeplug", True, ha_type="switch", ha_name="Fan")]}], +) +@pytest.mark.usefixtures("setup_integration") +async def test_plug(hass: HomeAssistant) -> None: + assert hass.states.get("switch.fan").state == "on" +``` + +Add or update a test with every behaviour change. + +## Pull requests + +- Branch from `master` and open the PR against `master`. +- CI must pass: HACS validation, hassfest, lint and tests. +- @KJonline is asked to review automatically. +- Don't bump `version` in `manifest.json` unless the PR is meant to be released + (see [MAINTAINING.md](MAINTAINING.md)). diff --git a/MAINTAINING.md b/MAINTAINING.md new file mode 100644 index 0000000..7cc963d --- /dev/null +++ b/MAINTAINING.md @@ -0,0 +1,133 @@ +# Maintaining + +This is the runbook for keeping the component released, compatible and healthy. +For development setup, see [CONTRIBUTING.md](CONTRIBUTING.md). Each procedure also +has a Claude Code skill in `.claude/skills/`, listed at the end. + +## What runs automatically + +| When | Workflow | What it does | If it fails | +|---|---|---|---| +| Every PR and every push to `master` | `ci.yml` | HACS validation, hassfest, lint and tests. A push to master also re-enables scheduled workflows that GitHub turned off. | Fix it in the PR before merging | +| Daily, 04:17 UTC | `compat.yml` | Tests against the newest HA stable and beta, plus an import check against HA `dev` | [Compatibility is red](#compatibility-is-red) | +| Daily, 05:29 UTC | `stale.yml` | Labels issues and PRs inactive for 60 days, then closes issues after 30 more days and PRs after 14 | Add the `pinned` label to keep something open | +| Monday, 06:23 UTC | `pyhive_bump.yml` | Opens a PR if a newer `pyhive-integration` is on PyPI | [Dependency PRs](#dependency-prs) | +| Weekly | Dependabot | PRs for GitHub Actions versions and for `requirements_test.txt` | [Dependency PRs](#dependency-prs) | +| A GitHub release is published | `release.yml` | Checks the tag matches `manifest.json`, then attaches `hive.zip` | [Releasing](#releasing) | +| Manual | `delete_beta.yml` | Deletes old pre-releases and their tags, keeping the newest | Not applicable | + +## Releasing + +Versions are `YEAR.MONTH.PATCH`, for example `2026.10.0`. Betas add `bN`, for example `2026.10.0b1`. +HACS installs by tag, so **the tag must equal `version` in `manifest.json`**. + +1. Open a PR that sets `version` in `custom_components/hive/manifest.json`. Merge it + once CI passes. +2. Check that the last Compatibility run on `master` passed, so you aren't shipping + something current HA versions break. +3. Publish the release from the same version: + + ```bash + # beta: HACS offers it only to users who opt into betas + gh release create 2026.10.0b1 --target master --prerelease --generate-notes + # stable + gh release create 2026.10.0 --target master --latest --generate-notes + ``` + +4. Watch the **Release** run: `gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId')`. + - It checks the tag *after* publishing. If it fails, the release is already + visible to HACS users. Delete it straight away with + `gh release delete --cleanup-tag`, fix the cause, and release again. + - A beta tag must be a pre-release, and a pre-release must have a beta tag. +5. After a stable release that replaces a run of betas, run **Delete Beta Releases**: + `gh workflow run delete_beta.yml`. + +## Compatibility is red + +Most platforms re-export Home Assistant core's hive code, so a new HA release can +break the component with no change here. Open the failing run +(`gh run list -w compat.yml`) and check which job failed: + +| Failing job | Usually means | Do this | +|---|---|---| +| **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 | +| **HACS and hassfest** | New validation rules | Update the manifest or repo structure as it says | + +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==" +VENV=.venv-ha-beta script/test +``` + +Common causes are renamed imports, changed entity base classes, and new +required manifest keys. The Home Assistant developer blog +(https://developers.home-assistant.io/blog) announces these ahead of time. + +## Dependency PRs + +- **`pyhive-integration`** (from `pyhive_bump.yml`): read the release notes linked in the + PR. If CI hasn't run, close and reopen the PR (see the `BOT_TOKEN` note below). Merge + it once green. Release it on its own, or together with the next change. +- **`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. +- **`ruff`** (Dependabot): if lint fails, run `script/lint` on the branch and push. +- **GitHub Actions** (Dependabot, grouped): merge once CI passes. + +### When Home Assistant needs a newer Python + +Update every one of these together: + +- `python-version` in `.github/workflows/ci.yml` and `compat.yml` (3 places) +- `PYTHON_VERSION` in `script/_common.sh` +- `target-version` in `pyproject.toml` + +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. + +## Repo settings (one-time; check they're still on) + +- **Branch protection on `master`:** + - Require the checks *HACS validation*, *Hassfest*, *Lint* and *Tests*. + - Turn on *Require review from Code Owners*. +- **Secret `BOT_TOKEN`:** a fine-grained PAT with Contents and Pull requests write + access on this repo. Without it, PRs from `pyhive_bump.yml` don't trigger CI. +- **Pyhive repo:** add a `HIVE_COMPONENT_DISPATCH_TOKEN` secret and a publish step + that sends `repository_dispatch`. The snippet is in the header of `pyhive_bump.yml`. + It triggers a bump PR as soon as Pyhive releases. +- **Scheduled workflows enabled:** + - Check with `gh workflow list --all`. + - CI switches them back on after the next push to master, but if the repo goes + quiet for 60 days they stop again. + +## Known issues in the code + +- `sensor.py` has update branches for `CurrentTemperature`, `Heating_Boost` and + `Hotwater_Boost` that never run, because no sensor description matches those + types. `get_current_temp_sa()` also calls `heating.minmaxTemperature`, + `currentTemperature` and `targetTemperature`, but only the first of those exists + in pyhive. Pointing it at `Current_Temperature` would therefore crash. Either + delete this code or fix it along with the pyhive method names. +- `async_setup_hive_entry` raises `UnknownHiveError` from the user step. That path + is unreachable, because the step checks for `AuthenticationResult` first. + +## Claude Code skills + +Run these in Claude Code from the repo root. Each one follows the matching +section above. + +| Skill | Use it to | +|---|---| +| `/release` | Cut a beta or stable release, from the version bump through to checking the Release run | +| `/triage-compat` | Find out why Compatibility is red, reproduce it locally and fix it | +| `/bump-pyhive` | Move to a new `pyhive-integration`, and check whether its changes affect this component | +| `/repo-health` | Check workflows, recent runs, open bot PRs, branch protection and secrets in one report | diff --git a/config/configuration.yaml b/config/configuration.yaml new file mode 100644 index 0000000..5256bf2 --- /dev/null +++ b/config/configuration.yaml @@ -0,0 +1,8 @@ +# Local Home Assistant for script/develop. Everything else in config/ is ignored by git. +default_config: + +logger: + default: info + logs: + custom_components.hive: debug + apyhiveapi: debug diff --git a/script/_common.sh b/script/_common.sh new file mode 100644 index 0000000..9d86975 --- /dev/null +++ b/script/_common.sh @@ -0,0 +1,14 @@ +# Shared by the scripts in this folder. Source it, don't run it. +set -euo pipefail + +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +VENV="${VENV:-$ROOT/.venv}" +PYTHON_VERSION="3.14" +cd "$ROOT" + +need_venv() { + if [ ! -x "$VENV/bin/python" ]; then + echo "No virtualenv at $VENV. Run script/setup first." >&2 + exit 1 + fi +} diff --git a/script/develop b/script/develop new file mode 100755 index 0000000..a894c44 --- /dev/null +++ b/script/develop @@ -0,0 +1,15 @@ +#!/usr/bin/env bash +# Run a local Home Assistant with this component loaded, at http://localhost:8123. +# +# config/ holds the HA instance (onboarding, your Hive login, the database). Only +# config/configuration.yaml is committed. Stop with Ctrl+C; code changes need a restart. +source "$(dirname "$0")/_common.sh" +need_venv + +mkdir -p config +# HA loads custom components from /custom_components. +if [ ! -e config/custom_components ]; then + ln -s ../custom_components config/custom_components +fi + +exec "$VENV/bin/hass" --config config --debug "$@" diff --git a/script/lint b/script/lint new file mode 100755 index 0000000..01300ab --- /dev/null +++ b/script/lint @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Fix what can be fixed, then run the same checks as CI's Lint job. +# script/lint # fix and check +# script/lint --check # check only (what CI does) +source "$(dirname "$0")/_common.sh" +need_venv + +ruff="$VENV/bin/ruff" +if [ "${1:-}" = "--check" ]; then + "$ruff" check . + "$ruff" format --check . + "$VENV/bin/python" script/gen_translations.py --check +else + "$ruff" check --fix . + "$ruff" format . + "$VENV/bin/python" script/gen_translations.py +fi diff --git a/script/setup b/script/setup new file mode 100755 index 0000000..9eaf514 --- /dev/null +++ b/script/setup @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +# Create .venv with the same Python and dependencies CI uses. +# +# script/setup # create or update .venv +# script/setup --recreate # delete .venv first (e.g. it was built with the wrong Python) +source "$(dirname "$0")/_common.sh" + +if ! command -v uv >/dev/null; then + echo "uv is required: https://docs.astral.sh/uv/getting-started/installation/" >&2 + exit 1 +fi + +if [ "${1:-}" = "--recreate" ]; then + rm -rf "$VENV" +fi + +if [ -x "$VENV/bin/python" ]; then + current=$("$VENV/bin/python" -c 'import sys; print(f"{sys.version_info[0]}.{sys.version_info[1]}")') + if [ "$current" != "$PYTHON_VERSION" ]; then + echo "$VENV uses Python $current but Home Assistant needs $PYTHON_VERSION." >&2 + echo "Run: script/setup --recreate" >&2 + exit 1 + fi +else + uv venv --python "$PYTHON_VERSION" "$VENV" +fi + +# Same install as the CI test job: the HA test plugin (which pins homeassistant), +# ruff, and the component's own requirements from manifest.json. +VIRTUAL_ENV="$VENV" uv pip install \ + -r requirements_test.txt \ + $(jq -r '.requirements[]' custom_components/hive/manifest.json) + +echo +"$VENV/bin/python" -c 'from homeassistant.const import __version__; print(f"Ready: Home Assistant {__version__}")' +echo "Next: script/test, script/lint, script/develop" diff --git a/script/test b/script/test new file mode 100755 index 0000000..de928e1 --- /dev/null +++ b/script/test @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +# Run the test suite. Extra arguments go to pytest, e.g. +# script/test tests/test_climate.py -k boost -x +source "$(dirname "$0")/_common.sh" +need_venv +exec "$VENV/bin/python" -m pytest "$@" diff --git a/tests/test_binary_sensor.py b/tests/test_binary_sensor.py new file mode 100644 index 0000000..759f76e --- /dev/null +++ b/tests/test_binary_sensor.py @@ -0,0 +1,85 @@ +"""Tests for the binary sensors re-exported from Home Assistant core.""" + +from typing import Any + +import pytest +from pytest_homeassistant_custom_component.common import MockConfigEntry + +from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant + +from .conftest import make_device + +CONTACT = make_device( + "contactsensor", + True, + ha_type="binary_sensor", + hive_id="contact-1", + name="Front Door", + ha_name="Front Door", +) +MOTION_OFFLINE = make_device( + "motionsensor", + False, + ha_type="binary_sensor", + hive_id="motion-1", + name="Hallway", + ha_name="Hallway", + online=False, +) +HUB_STATUS_OFFLINE = make_device( + "Connectivity", + False, + ha_type="binary_sensor", + hive_id="hub-1", + name="Hive Hub", + ha_name="Hive Hub Status", + online=False, +) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Binary sensor devices returned by the mocked Hive session.""" + return {"binary_sensor": [CONTACT, MOTION_OFFLINE, HUB_STATUS_OFFLINE]} + + +@pytest.mark.usefixtures("setup_integration") +async def test_binary_sensors(hass: HomeAssistant) -> None: + """Device class and state come from the Hive device.""" + state = hass.states.get("binary_sensor.front_door") + assert state.state == STATE_ON + assert state.attributes["device_class"] == "opening" + + # Offline devices go unavailable, except the hub's own connectivity sensor. + assert hass.states.get("binary_sensor.hallway").state == STATE_UNAVAILABLE + state = hass.states.get("binary_sensor.hive_hub_status") + assert state.state == STATE_OFF + assert state.attributes["device_class"] == "connectivity" + + +@pytest.mark.parametrize( + "sensor_devices", + [ + [ + make_device("Heating_State", "ON", name="Thermostat"), + make_device("Heating_Boost", "OFF", name="Thermostat"), + make_device("Hotwater_Boost", "ON", name="Hot Water", online=False), + ] + ], +) +async def test_heating_and_hot_water_state_sensors( + hass: HomeAssistant, setup_integration: MockConfigEntry +) -> None: + """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. + """ + assert hass.states.get("binary_sensor.thermostat_heating_state").state == STATE_ON + assert hass.states.get("binary_sensor.thermostat_heating_boost").state == STATE_OFF + assert ( + hass.states.get("binary_sensor.hot_water_hotwater_boost").state + == STATE_UNAVAILABLE + ) + assert hass.states.async_entity_ids("sensor") == [] diff --git a/tests/test_climate.py b/tests/test_climate.py new file mode 100644 index 0000000..37fecc3 --- /dev/null +++ b/tests/test_climate.py @@ -0,0 +1,180 @@ +"""Tests for the climate entity re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.climate import ( + ATTR_HVAC_ACTION, + ATTR_HVAC_MODE, + ATTR_PRESET_MODE, + DOMAIN as CLIMATE_DOMAIN, + PRESET_BOOST, + PRESET_NONE, + SERVICE_SET_HVAC_MODE, + SERVICE_SET_PRESET_MODE, + SERVICE_SET_TEMPERATURE, + HVACAction, + HVACMode, +) +from homeassistant.const import ATTR_ENTITY_ID, ATTR_TEMPERATURE, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import ( + DOMAIN, + SERVICE_BOOST_HEATING_OFF, + SERVICE_BOOST_HEATING_ON, +) + +from .conftest import make_device + +ENTITY_ID = "climate.heating" + + +def heating( + *, mode: str = "SCHEDULE", boost: str = "OFF", online: bool = True +) -> dict[str, Any]: + """A heating product as pyhive's getClimate returns it.""" + return make_device( + "heating", + ha_type="climate", + hive_id="heating-1", + name="Heating", + ha_name="Heating", + online=online, + temperatureunit="C", + min_temp=5, + max_temp=32, + status={ + "mode": mode, + "action": True, + "current_temperature": 19.2, + "target_temperature": 21, + "boost": boost, + }, + ) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Climate devices returned by the mocked Hive session.""" + return {"climate": [heating()]} + + +@pytest.fixture +def mock_heating(mock_hive: MagicMock) -> MagicMock: + """Make the heating setters awaitable.""" + for method in ("setMode", "setTargetTemperature", "setBoostOn", "setBoostOff"): + setattr(mock_hive.heating, method, AsyncMock()) + return mock_hive.heating + + +@pytest.mark.usefixtures("setup_integration") +async def test_climate_state(hass: HomeAssistant) -> None: + """Hive heating status maps to HA climate state.""" + state = hass.states.get(ENTITY_ID) + assert state.state == HVACMode.AUTO + assert state.attributes[ATTR_HVAC_ACTION] == HVACAction.HEATING + assert state.attributes["current_temperature"] == 19.2 + assert state.attributes[ATTR_TEMPERATURE] == 21 + assert state.attributes["min_temp"] == 5 + assert state.attributes["max_temp"] == 32 + assert state.attributes[ATTR_PRESET_MODE] == PRESET_NONE + + +@pytest.mark.parametrize( + "platform_devices", [{"climate": [heating(mode="OFF", boost="ON")]}] +) +@pytest.mark.usefixtures("setup_integration") +async def test_climate_boost_shows_as_heat(hass: HomeAssistant) -> None: + """While boosting, the mode reads heat and the preset reads boost.""" + state = hass.states.get(ENTITY_ID) + assert state.state == HVACMode.HEAT + assert state.attributes[ATTR_PRESET_MODE] == PRESET_BOOST + + +@pytest.mark.parametrize("platform_devices", [{"climate": [heating(online=False)]}]) +@pytest.mark.usefixtures("setup_integration") +async def test_climate_offline(hass: HomeAssistant) -> None: + """An offline thermostat is unavailable.""" + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("hvac_mode", "hive_mode"), + [(HVACMode.AUTO, "SCHEDULE"), (HVACMode.HEAT, "MANUAL"), (HVACMode.OFF, "OFF")], +) +@pytest.mark.usefixtures("setup_integration") +async def test_set_hvac_mode( + hass: HomeAssistant, mock_heating: MagicMock, hvac_mode: HVACMode, hive_mode: str +) -> None: + """HVAC modes are sent to Hive as its own mode names.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_HVAC_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_HVAC_MODE: hvac_mode}, + blocking=True, + ) + + mock_heating.setMode.assert_awaited_once() + assert mock_heating.setMode.await_args.args[1] == hive_mode + + +@pytest.mark.usefixtures("setup_integration") +async def test_set_temperature(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """The target temperature is sent to Hive.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_TEMPERATURE: 22.5}, + blocking=True, + ) + + assert mock_heating.setTargetTemperature.await_args.args[1] == 22.5 + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_preset_on(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """The boost preset boosts for 30 minutes to half a degree above current.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_PRESET_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_BOOST}, + blocking=True, + ) + + assert mock_heating.setBoostOn.await_args.args[1:] == (30, 19.5) + + +@pytest.mark.parametrize("platform_devices", [{"climate": [heating(boost="ON")]}]) +@pytest.mark.usefixtures("setup_integration") +async def test_boost_preset_off(hass: HomeAssistant, mock_heating: MagicMock) -> None: + """Choosing no preset while boosting turns boost off.""" + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_PRESET_MODE, + {ATTR_ENTITY_ID: ENTITY_ID, ATTR_PRESET_MODE: PRESET_NONE}, + blocking=True, + ) + + mock_heating.setBoostOff.assert_awaited_once() + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_heating_services( + hass: HomeAssistant, mock_heating: MagicMock +) -> None: + """hive.boost_heating_on/off call Hive with minutes and temperature.""" + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HEATING_ON, + {ATTR_ENTITY_ID: ENTITY_ID, "time_period": "01:30:00", ATTR_TEMPERATURE: 23}, + blocking=True, + ) + assert mock_heating.setBoostOn.await_args.args[1:] == (90, 23.0) + + await hass.services.async_call( + DOMAIN, SERVICE_BOOST_HEATING_OFF, {ATTR_ENTITY_ID: ENTITY_ID}, blocking=True + ) + mock_heating.setBoostOff.assert_awaited_once() diff --git a/tests/test_light.py b/tests/test_light.py new file mode 100644 index 0000000..b01db5e --- /dev/null +++ b/tests/test_light.py @@ -0,0 +1,151 @@ +"""Tests for the lights re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.light import ( + ATTR_BRIGHTNESS, + ATTR_COLOR_MODE, + ATTR_COLOR_TEMP_KELVIN, + ATTR_HS_COLOR, + ATTR_SUPPORTED_COLOR_MODES, + DOMAIN as LIGHT_DOMAIN, + ColorMode, +) +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant + +from .conftest import make_device + + +def light( + hive_type: str, name: str, *, online: bool = True, **status: Any +) -> dict[str, Any]: + """A light product as pyhive's getLight returns it.""" + return make_device( + hive_type, + ha_type="light", + hive_id=f"{hive_type}-1", + name=name, + ha_name=name, + online=online, + status={"state": True, "brightness": 128, **status}, + attributes={"mode": "SCHEDULE"}, + ) + + +WARM_WHITE = light("warmwhitelight", "Kitchen") +TUNEABLE = light("tuneablelight", "Bedroom", color_temp=370) +COLOUR = light( + "colourtuneablelight", "Lounge Lamp", mode="COLOUR", hs_color=(255, 0, 0) +) +COLOUR_WHITE = light( + "colourtuneablelight", "Desk Lamp", mode="WHITE", color_temp=153 +) | {"hiveID": "colour-white-1", "device_id": "colour-white-1"} + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Light devices returned by the mocked Hive session.""" + return {"light": [WARM_WHITE, TUNEABLE, COLOUR, COLOUR_WHITE]} + + +@pytest.fixture +def mock_light(mock_hive: MagicMock) -> MagicMock: + """Make the light setters awaitable.""" + mock_hive.light.turnOn = AsyncMock() + mock_hive.light.turnOff = AsyncMock() + return mock_hive.light + + +@pytest.mark.usefixtures("setup_integration") +async def test_light_states(hass: HomeAssistant) -> None: + """Each Hive light type exposes the matching colour modes.""" + state = hass.states.get("light.kitchen") + assert state.state == STATE_ON + assert state.attributes[ATTR_BRIGHTNESS] == 128 + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.BRIGHTNESS] + assert state.attributes["mode"] == "SCHEDULE" + + state = hass.states.get("light.bedroom") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 2702 # 370 mireds + + state = hass.states.get("light.lounge_lamp") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.HS + assert state.attributes[ATTR_HS_COLOR] == (0.0, 100.0) + + state = hass.states.get("light.desk_lamp") + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert state.attributes[ATTR_COLOR_TEMP_KELVIN] == 6535 # 153 mireds + + +@pytest.mark.parametrize( + "platform_devices", + [ + { + "light": [ + light("warmwhitelight", "Kitchen", state=False), + light("warmwhitelight", "Porch", online=False) + | {"hiveID": "porch-1", "device_id": "porch-1"}, + ] + } + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_light_off_and_offline(hass: HomeAssistant) -> None: + """A light that is off reads off; an offline light is unavailable.""" + assert hass.states.get("light.kitchen").state == STATE_OFF + assert hass.states.get("light.porch").state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("entity_id", "data", "expected"), + [ + ("light.kitchen", {}, (None, None, None)), + # Brightness is sent as a percentage rounded to 5, never below 5. + ("light.kitchen", {ATTR_BRIGHTNESS: 255}, (100, None, None)), + ("light.kitchen", {ATTR_BRIGHTNESS: 1}, (5, None, None)), + ("light.bedroom", {ATTR_COLOR_TEMP_KELVIN: 4000}, (None, 4000, None)), + ("light.lounge_lamp", {ATTR_HS_COLOR: (120, 50)}, (None, None, (120, 50, 100))), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_turn_on( + hass: HomeAssistant, + mock_light: MagicMock, + entity_id: str, + data: dict[str, Any], + expected: tuple, +) -> None: + """turn_on converts HA values to what Hive expects.""" + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: entity_id, **data}, + blocking=True, + ) + + assert mock_light.turnOn.await_args.args[1:] == expected + + +@pytest.mark.usefixtures("setup_integration") +async def test_turn_off(hass: HomeAssistant, mock_light: MagicMock) -> None: + """turn_off is passed straight to Hive.""" + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "light.kitchen"}, + blocking=True, + ) + + mock_light.turnOff.assert_awaited_once() diff --git a/tests/test_switch.py b/tests/test_switch.py new file mode 100644 index 0000000..01636eb --- /dev/null +++ b/tests/test_switch.py @@ -0,0 +1,90 @@ +"""Tests for the switches re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import make_device + +PLUG = make_device( + "activeplug", + True, + ha_type="switch", + hive_id="plug-1", + name="Fan Plug", + ha_name="Fan Plug", + attributes={"mode": "MANUAL"}, +) +HEAT_ON_DEMAND = make_device( + "Heating_Heat_On_Demand", + False, + ha_type="switch", + hive_id="heating-1", + name="Heating", + ha_name="Heating Heat on Demand", +) +OFFLINE_PLUG = make_device( + "activeplug", + True, + ha_type="switch", + hive_id="plug-2", + name="Lamp Plug", + ha_name="Lamp Plug", + online=False, +) +# pyhive lists Hive actions as switches, but there is no description for them. +ACTION = make_device( + "action", True, ha_type="switch", hive_id="action-1", ha_name="Leaving Home" +) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Switch devices returned by the mocked Hive session.""" + return {"switch": [PLUG, HEAT_ON_DEMAND, OFFLINE_PLUG, ACTION]} + + +@pytest.mark.usefixtures("setup_integration") +async def test_switch_states(hass: HomeAssistant) -> None: + """Plugs and heat on demand are switches; actions are not.""" + state = hass.states.get("switch.fan_plug") + assert state.state == STATE_ON + assert state.attributes["mode"] == "MANUAL" + + assert hass.states.get("switch.heating_heat_on_demand").state == STATE_OFF + entry = er.async_get(hass).async_get("switch.heating_heat_on_demand") + assert entry.entity_category == "config" + + assert hass.states.get("switch.lamp_plug").state == STATE_UNAVAILABLE + assert hass.states.get("switch.leaving_home") is None + + +@pytest.mark.parametrize( + ("service", "method"), + [(SERVICE_TURN_ON, "turnOn"), (SERVICE_TURN_OFF, "turnOff")], +) +@pytest.mark.usefixtures("setup_integration") +async def test_turn_on_off( + hass: HomeAssistant, mock_hive: MagicMock, service: str, method: str +) -> None: + """Turning a switch on or off calls Hive.""" + setattr(mock_hive.switch, method, AsyncMock()) + + await hass.services.async_call( + SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.fan_plug"}, blocking=True + ) + + getattr(mock_hive.switch, method).assert_awaited_once() diff --git a/tests/test_water_heater.py b/tests/test_water_heater.py new file mode 100644 index 0000000..c13cee0 --- /dev/null +++ b/tests/test_water_heater.py @@ -0,0 +1,128 @@ +"""Tests for the water heater re-exported from Home Assistant core.""" + +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from homeassistant.components.water_heater import ( + ATTR_OPERATION_MODE, + DOMAIN as WATER_HEATER_DOMAIN, + SERVICE_SET_OPERATION_MODE, + STATE_ECO, +) +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, + STATE_OFF, + STATE_ON, + STATE_UNAVAILABLE, +) +from homeassistant.core import HomeAssistant + +from custom_components.hive.const import DOMAIN, SERVICE_BOOST_HOT_WATER + +from .conftest import make_device + +ENTITY_ID = "water_heater.hot_water" + + +def hot_water(operation: str = "SCHEDULE", *, online: bool = True) -> dict[str, Any]: + """A hot water product as pyhive's getWaterHeater returns it.""" + return make_device( + "hotwater", + ha_type="water_heater", + hive_id="hotwater-1", + name="Hot Water", + ha_name="Hot Water", + online=online, + status={"current_operation": operation}, + ) + + +@pytest.fixture +def platform_devices() -> dict[str, list[dict[str, Any]]]: + """Water heater devices returned by the mocked Hive session.""" + return {"water_heater": [hot_water()]} + + +@pytest.fixture +def mock_hotwater(mock_hive: MagicMock) -> MagicMock: + """Make the hot water setters awaitable.""" + for method in ("setMode", "setBoostOn", "setBoostOff"): + setattr(mock_hive.hotwater, method, AsyncMock()) + return mock_hive.hotwater + + +@pytest.mark.parametrize( + ("platform_devices", "expected"), + [ + ({"water_heater": [hot_water("SCHEDULE")]}, STATE_ECO), + ({"water_heater": [hot_water("ON")]}, STATE_ON), + ({"water_heater": [hot_water("OFF")]}, STATE_OFF), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_water_heater_state(hass: HomeAssistant, expected: str) -> None: + """Hive operation names map to HA water heater states.""" + assert hass.states.get(ENTITY_ID).state == expected + + +@pytest.mark.parametrize( + "platform_devices", [{"water_heater": [hot_water(online=False)]}] +) +@pytest.mark.usefixtures("setup_integration") +async def test_water_heater_offline(hass: HomeAssistant) -> None: + """An offline hot water controller is unavailable.""" + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + ("service", "data", "hive_mode"), + [ + (SERVICE_TURN_ON, {}, "MANUAL"), + (SERVICE_TURN_OFF, {}, "OFF"), + (SERVICE_SET_OPERATION_MODE, {ATTR_OPERATION_MODE: STATE_ECO}, "SCHEDULE"), + (SERVICE_SET_OPERATION_MODE, {ATTR_OPERATION_MODE: STATE_ON}, "MANUAL"), + ], +) +@pytest.mark.usefixtures("setup_integration") +async def test_set_mode( + hass: HomeAssistant, + mock_hotwater: MagicMock, + service: str, + data: dict[str, Any], + hive_mode: str, +) -> None: + """Turning on/off and changing operation set the Hive mode.""" + await hass.services.async_call( + WATER_HEATER_DOMAIN, + service, + {ATTR_ENTITY_ID: ENTITY_ID, **data}, + blocking=True, + ) + + assert mock_hotwater.setMode.await_args.args[1] == hive_mode + + +@pytest.mark.usefixtures("setup_integration") +async def test_boost_hot_water_service( + hass: HomeAssistant, mock_hotwater: MagicMock +) -> None: + """hive.boost_hot_water boosts for the given minutes, or turns boost off.""" + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HOT_WATER, + {ATTR_ENTITY_ID: ENTITY_ID, "time_period": "01:00:00", "on_off": "on"}, + blocking=True, + ) + assert mock_hotwater.setBoostOn.await_args.args[1] == 60 + + await hass.services.async_call( + DOMAIN, + SERVICE_BOOST_HOT_WATER, + {ATTR_ENTITY_ID: ENTITY_ID, "on_off": "off"}, + blocking=True, + ) + mock_hotwater.setBoostOff.assert_awaited_once() From c099716b1d0750f15fbb540fde8080afeda2cadc Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Tue, 29 Sep 2026 19:26:35 +0100 Subject: [PATCH 21/31] chore: resolve merge conflicts in test files, PR template, and gitignore --- .github/pull_request_template.md | 6 ----- .gitignore | 6 ----- tests/conftest.py | 39 -------------------------------- tests/test_config_flow.py | 6 ----- tests/test_init.py | 9 -------- tests/test_sensor.py | 10 -------- 6 files changed, 76 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 2c87b08..0a52d37 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -8,12 +8,6 @@ ## Checklist -<<<<<<< HEAD - [ ] Tests added or updated, and `script/test` passes - [ ] `script/lint --check` passes (after `script/lint`, which also regenerates translations) -======= -- [ ] Tests added or updated (`python -m pytest`) -- [ ] `ruff check .` and `ruff format --check .` pass -- [ ] If `strings.json` changed: ran `python script/gen_translations.py` ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf - [ ] If this is going into a release: bumped `version` in `manifest.json` diff --git a/.gitignore b/.gitignore index b48a9da..722b5d5 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,12 @@ __pycache__/ *.py[cod] .venv/ -<<<<<<< HEAD .venv-*/ -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf .pytest_cache/ .ruff_cache/ .coverage hive.zip -<<<<<<< HEAD # script/develop's Home Assistant instance config/* !config/configuration.yaml -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf diff --git a/tests/conftest.py b/tests/conftest.py index b239a98..b0b8d9d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,10 +8,7 @@ from pytest_homeassistant_custom_component.common import MockConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME -<<<<<<< HEAD from homeassistant.core import HomeAssistant -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf from custom_components.hive.const import DOMAIN @@ -35,7 +32,6 @@ def auto_enable_custom_integrations(enable_custom_integrations: None) -> None: def make_device( hive_type: str, -<<<<<<< HEAD state: Any = None, *, ha_type: str = "sensor", @@ -51,26 +47,12 @@ def make_device( status defaults to {"state": state}; extra keys (e.g. temperatureunit, min_temp) are added at the top level, the way pyhive's addList adds them. """ -======= - state: Any, - *, - hive_id: str = "trv-1", - name: str = "Lounge TRV", - online: bool = True, -) -> dict[str, Any]: - """Build a device dict shaped like the ones pyhive returns.""" ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf return { "hiveID": hive_id, "hiveName": name, "hiveType": hive_type, -<<<<<<< HEAD "haType": ha_type, "haName": ha_name or f"{name} {hive_type.replace('_', ' ')}", -======= - "haType": "sensor", - "haName": f"{name} {hive_type.replace('_', ' ')}", ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf "device_id": hive_id, "device_name": name, "parentDevice": HUB_ID, @@ -80,12 +62,8 @@ def make_device( "version": "1.0.0", "online": online, }, -<<<<<<< HEAD "status": {"state": state} if status is None else status, **extra, -======= - "status": {"state": state}, ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf } @@ -119,7 +97,6 @@ def sensor_devices() -> list[dict[str, Any]]: @pytest.fixture -<<<<<<< HEAD def platform_devices() -> dict[str, list[dict[str, Any]]]: """Devices for the other platforms, keyed like pyhive's deviceList.""" return {} @@ -140,24 +117,15 @@ def mock_hive( state through the device dicts it passes in. """ devices = {"parent": [HUB_DEVICE], "sensor": sensor_devices, **platform_devices} -======= -def mock_hive(sensor_devices: list[dict[str, Any]]) -> Generator[MagicMock]: - """Patch the Hive API client used by async_setup_entry.""" - devices = {"parent": [HUB_DEVICE], "sensor": sensor_devices} ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf hive = MagicMock() hive.session.startSession = AsyncMock(return_value=devices) hive.session.deviceList = devices hive.session.updateData = AsyncMock() -<<<<<<< HEAD hive.sensor.getSensor = AsyncMock(side_effect=_echo) hive.heating.getClimate = AsyncMock(side_effect=_echo) hive.hotwater.getWaterHeater = AsyncMock(side_effect=_echo) hive.light.getLight = AsyncMock(side_effect=_echo) hive.switch.getSwitch = AsyncMock(side_effect=_echo) -======= - hive.sensor.getSensor = AsyncMock(side_effect=lambda device: device) ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf hive.updateInterval = AsyncMock() with patch("custom_components.hive.Hive", return_value=hive): yield hive @@ -172,15 +140,11 @@ def mock_auth() -> Generator[MagicMock]: auth.device_registration = AsyncMock() auth.get_device_data = AsyncMock(return_value=DEVICE_DATA) auth.is_device_registered = AsyncMock(return_value=True) -<<<<<<< HEAD auth.forget_device = AsyncMock() with ( patch("custom_components.hive.config_flow.Auth", return_value=auth), patch("custom_components.hive.Auth", return_value=auth), ): -======= - with patch("custom_components.hive.config_flow.Auth", return_value=auth): ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf yield auth @@ -191,7 +155,6 @@ def mock_setup_entry() -> Generator[AsyncMock]: "custom_components.hive.async_setup_entry", return_value=True ) as setup_entry: yield setup_entry -<<<<<<< HEAD @pytest.fixture @@ -203,5 +166,3 @@ async def setup_integration( assert await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() return mock_config_entry -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf diff --git a/tests/test_config_flow.py b/tests/test_config_flow.py index b73b7f3..90cee7f 100644 --- a/tests/test_config_flow.py +++ b/tests/test_config_flow.py @@ -16,10 +16,7 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType -<<<<<<< HEAD from custom_components.hive.config_flow import _sanitize_payload -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf from custom_components.hive.const import CONF_CODE, CONF_DEVICE_NAME, DOMAIN from .conftest import DEVICE_DATA, PASSWORD, TOKENS, USERNAME @@ -259,7 +256,6 @@ async def test_options_flow( assert result["type"] is FlowResultType.CREATE_ENTRY assert mock_config_entry.options == {CONF_SCAN_INTERVAL: 60} hive.updateInterval.assert_awaited_once_with(60) -<<<<<<< HEAD async def test_device_registration_failure_still_creates_entry( @@ -339,5 +335,3 @@ def test_sanitize_payload() -> None: "Devices": [{"DeviceKey": "key", "RefreshToken": 12345}], } assert payload["Session"] == "abcdefghijklmnop" -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf diff --git a/tests/test_init.py b/tests/test_init.py index 08cc726..547490b 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -8,18 +8,12 @@ from pytest_homeassistant_custom_component.common import MockConfigEntry from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState -<<<<<<< HEAD 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 custom_components.hive import async_remove_config_entry_device, refresh_system -======= -from homeassistant.core import HomeAssistant -from homeassistant.helpers import device_registry as dr - ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf from custom_components.hive.const import DOMAIN from .conftest import HUB_ID @@ -74,7 +68,6 @@ async def test_setup_failures( assert mock_config_entry.state is state reauth_flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) assert bool(list(reauth_flows)) is isinstance(exception, HiveReauthRequired) -<<<<<<< HEAD @pytest.mark.parametrize( @@ -150,5 +143,3 @@ async def turn_on(self, value: int) -> None: assert calls == [5] assert signals == [True] -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf diff --git a/tests/test_sensor.py b/tests/test_sensor.py index d2ab9fe..db644eb 100644 --- a/tests/test_sensor.py +++ b/tests/test_sensor.py @@ -7,19 +7,12 @@ import pytest from pytest_homeassistant_custom_component.common import MockConfigEntry -<<<<<<< HEAD from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from custom_components.hive import sensor -======= -from homeassistant.const import PERCENTAGE, STATE_UNAVAILABLE -from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry as er - ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf from .conftest import make_device @@ -119,7 +112,6 @@ async def test_unknown_sensor_type_is_ignored( await _setup(hass, mock_config_entry) assert hass.states.async_entity_ids("sensor") == [] -<<<<<<< HEAD @pytest.mark.parametrize( @@ -311,5 +303,3 @@ async def test_sensor_platform_without_devices( await sensor.async_setup_entry(hass, mock_config_entry, add_entities) add_entities.assert_not_called() -======= ->>>>>>> 1a55d87294f3c1fd059bd190faec008e020cc2cf From 3d7a5f8d374124f333d66929bdaf45d1de852aad Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:14:46 +0000 Subject: [PATCH 22/31] Bump pytest-homeassistant-custom-component from 0.13.367 to 0.13.370 Bumps [pytest-homeassistant-custom-component](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component) from 0.13.367 to 0.13.370. - [Release notes](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/releases) - [Changelog](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/blob/master/CHANGELOG.md) - [Commits](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/compare/0.13.367...0.13.370) --- updated-dependencies: - dependency-name: pytest-homeassistant-custom-component dependency-version: 0.13.370 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements_test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_test.txt b/requirements_test.txt index 67c5f6c..f76e180 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,4 +1,4 @@ # Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). # Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. -pytest-homeassistant-custom-component==0.13.367 +pytest-homeassistant-custom-component==0.13.370 ruff==0.16.9 From 3f3e358475bc635e8f0677299eec0efdc482c031 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 11 Oct 2026 10:14:57 +0000 Subject: [PATCH 23/31] Bump ruff from 0.16.9 to 0.16.10 Bumps [ruff](https://github.com/astral-sh/ruff) from 0.16.9 to 0.16.10. - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/0.16.10/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.16.9...0.16.10) --- updated-dependencies: - dependency-name: ruff dependency-version: 0.16.10 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements_test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_test.txt b/requirements_test.txt index 67c5f6c..4ce1810 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,4 +1,4 @@ # Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). # Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. pytest-homeassistant-custom-component==0.13.367 -ruff==0.16.9 +ruff==0.16.10 From 95279ba650ca2d5f9b9ac70031e58e4863025f1d Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Thu, 15 Oct 2026 23:03:57 +0100 Subject: [PATCH 24/31] deps: bump pyhive-integration to 2.0.0b4 Pin the 2.0.0 beta and handle the exceptions its start_session can now raise. A failed device fetch raises HiveConnectionError, which now retries setup instead of failing it. HiveUnknownConfiguration starts reauth, matching what 1.0.9 did for an empty device fetch. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/__init__.py | 11 +++++++++-- custom_components/hive/manifest.json | 2 +- tests/test_init.py | 17 ++++++++++++----- 3 files changed, 22 insertions(+), 8 deletions(-) diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index 62986f6..071b7c7 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -9,7 +9,11 @@ from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive -from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +from apyhiveapi.helper.hive_exceptions import ( + HiveConnectionError, + HiveReauthRequired, + HiveUnknownConfiguration, +) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL @@ -43,7 +47,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool except HTTPException as error: _LOGGER.error("Could not connect to the internet: %s", error) raise ConfigEntryNotReady from error - except HiveReauthRequired as err: + except HiveConnectionError as error: + _LOGGER.error("Could not fetch devices from Hive: %s", error) + raise ConfigEntryNotReady from error + except (HiveReauthRequired, HiveUnknownConfiguration) as err: raise ConfigEntryAuthFailed from err device_registry = dr.async_get(hass) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 5bedf9f..2379960 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -11,6 +11,6 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", "loggers": ["apyhiveapi"], - "requirements": ["pyhive-integration==1.0.9"], + "requirements": ["pyhive-integration==2.0.0b4"], "version": "2026.8.0" } diff --git a/tests/test_init.py b/tests/test_init.py index 547490b..231f9fd 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -3,7 +3,11 @@ from unittest.mock import MagicMock from aiohttp.web_exceptions import HTTPServiceUnavailable -from apyhiveapi.helper.hive_exceptions import HiveReauthRequired +from apyhiveapi.helper.hive_exceptions import ( + HiveConnectionError, + HiveReauthRequired, + HiveUnknownConfiguration, +) import pytest from pytest_homeassistant_custom_component.common import MockConfigEntry @@ -42,10 +46,12 @@ async def test_setup_and_unload( @pytest.mark.parametrize( - ("exception", "state"), + ("exception", "state", "reauth"), [ - (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY), - (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR), + (HTTPServiceUnavailable(), ConfigEntryState.SETUP_RETRY, False), + (HiveConnectionError(), ConfigEntryState.SETUP_RETRY, False), + (HiveReauthRequired(), ConfigEntryState.SETUP_ERROR, True), + (HiveUnknownConfiguration(), ConfigEntryState.SETUP_ERROR, True), ], ) async def test_setup_failures( @@ -55,6 +61,7 @@ async def test_setup_failures( mock_config_entry: MockConfigEntry, exception: Exception, state: ConfigEntryState, + reauth: bool, ) -> None: """Network errors retry setup, auth errors start reauth.""" mock_hive.session.startSession.side_effect = exception @@ -67,7 +74,7 @@ async def test_setup_failures( assert mock_config_entry.state is state reauth_flows = mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}) - assert bool(list(reauth_flows)) is isinstance(exception, HiveReauthRequired) + assert bool(list(reauth_flows)) is reauth @pytest.mark.parametrize( From bfc9f843a1d339a40fe6f0c067ee494d4a49ee35 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:34:31 +0100 Subject: [PATCH 25/31] chore: adopt override principles in CI, skills and docs This component replaces core's hive integration as an opt-in fast channel, and may pin a newer pyhive-integration than core, including pre-releases in betas. Write that down and make CI, the release check and the skills follow it. - CLAUDE.md: the two principles (extend and reuse core; opt-in fast channel). - hassfest.py: run the official hassfest image, and report only the pyhive-integration differences from core hive's pin as warnings. Every other error still fails. ci.yml and compat.yml use it. - check_release.py: a stable release must not pin a pre-release pyhive. - ci.yml: fix the re-enable job (gh workflow view has no --json here). - Skills: /release checks PyPI for the newest pyhive, betas included, before a beta; /bump-pyhive gets a working download step and the principles; /triage-compat and /repo-health expect the hassfest warning. - MAINTAINING.md and README.md document the process and the beta channel. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/bump-pyhive/SKILL.md | 57 +++++++++++------ .claude/skills/release/SKILL.md | 34 +++++++--- .claude/skills/repo-health/SKILL.md | 3 + .claude/skills/triage-compat/SKILL.md | 4 +- .github/scripts/check_release.py | 18 +++++- .github/scripts/hassfest.py | 69 ++++++++++++++++++++ .github/workflows/ci.yml | 8 +-- .github/workflows/compat.yml | 2 +- CLAUDE.md | 65 +++++++++++++++++++ MAINTAINING.md | 92 +++++++++++++++++++++------ README.md | 11 ++++ 11 files changed, 307 insertions(+), 56 deletions(-) create mode 100644 .github/scripts/hassfest.py create mode 100644 CLAUDE.md diff --git a/.claude/skills/bump-pyhive/SKILL.md b/.claude/skills/bump-pyhive/SKILL.md index 234640b..f4c5da0 100644 --- a/.claude/skills/bump-pyhive/SKILL.md +++ b/.claude/skills/bump-pyhive/SKILL.md @@ -1,54 +1,71 @@ --- name: bump-pyhive -description: Update the pyhive-integration (apyhiveapi) requirement in the Hive custom component's manifest.json, review what changed in the library, and verify the component against it. Use when a pyhive bump PR is open, a new pyhive release is out, or the user wants to test a pyhive beta/dev build. +description: Update the pyhive-integration (apyhiveapi) requirement in the Hive custom component's manifest.json, review what changed in the library, and verify the component against it. Use when a pyhive bump PR is open, a new pyhive release or beta is out, before cutting a component beta, or the user wants to test a pyhive beta/dev build. --- # Bump pyhive-integration `pyhive-integration` (imported as `apyhiveapi`) is pinned in `custom_components/hive/manifest.json` `requirements`. Dependabot can't bump it, so `.github/workflows/pyhive_bump.yml` opens `deps/pyhive-integration-` PRs instead. +Read the principles in `CLAUDE.md` first. In short: +- This repo may pin a **newer** `pyhive-integration` than core hive does, including pre-releases. That's intended. +- Keep the pin exact (`==`). Don't switch to `>=` to quiet hassfest; `.github/scripts/hassfest.py` already treats that difference as a warning. +- A pre-release pin can only ship in a component **beta**. A stable component release needs a stable pin. + ## 1. Pick the target ```bash -jq -r '.requirements[]' custom_components/hive/manifest.json # current +jq -r '.requirements[]' custom_components/hive/manifest.json # current pin curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.info.version' # latest stable -curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' | tail -10 -gh pr list --label dependencies --search "pyhive-integration in:title" # existing bot PR? +# newest version overall, pre-releases included (sorted as versions, not by upload date) +curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' +gh pr list --search "pyhive-integration in:title" --state open # existing PR? ``` -If there's already a bot PR for the target, work on that branch (`gh pr checkout `) instead of making a new change. +- For a beta (or when the user asks for "latest"), the target is the newest version overall. +- For a stable release, the target is the latest stable. +- Also note core's pin, from `.venv/lib/python*/site-packages/homeassistant/components/hive/manifest.json`. Core's re-exported platforms are written against it, so a big gap needs a closer look. + +If there's already an open PR for the target, work on that branch (`gh pr checkout `) instead of making a new change. ## 2. Review what changed -Diff the two versions' sources and look closely at anything this component calls: +`uv pip download` doesn't exist, so fetch the wheels from PyPI's JSON API into the scratchpad and unpack them there: ```bash -S=$(mktemp -d) +S=/pyhive for v in ; do - uv pip download --no-deps "pyhive-integration==$v" -d "$S/$v" 2>/dev/null || pip download --no-deps "pyhive-integration==$v" -d "$S/$v" + url=$(curl -fsS "https://pypi.org/pypi/pyhive-integration/$v/json" | jq -r '[.urls[]|select(.packagetype=="bdist_wheel")][0].url') + mkdir -p "$S/dl-$v" "$S/src-$v" && curl -fsSL -o "$S/dl-$v/pkg.whl" "$url" && unzip -qo "$S/dl-$v/pkg.whl" -d "$S/src-$v" done +diff -rq "$S/src-/apyhiveapi" "$S/src-/apyhiveapi" ``` -Unpack both and diff `apyhiveapi/`. Things to check: -- `Auth` methods used in `config_flow.py` and `__init__.py`: `login`, `sms_2fa`, `device_registration`, `get_device_data`, `is_device_registered`, `forget_device`. -- `Hive`, `session.startSession`, `session.deviceList`, `updateInterval`. -- `helper/const.py`: `PRODUCTS`, `DEVICES` and `sensor_commands`. A new or renamed `hiveType` needs a matching `SENSOR_TYPES` entry in `sensor.py`, or core's platform descriptions, before it shows up in HA. -- Exceptions in `helper/hive_exceptions.py`. -- The getters that tests mock: `getSensor`, `getClimate`, `getWaterHeater`, `getLight`, `getSwitch` and `getScheduleNowNextLater`. +Check anything this component, or core's re-exported platforms, calls: +- `Auth` methods used in `config_flow.py` and `__init__.py`: `login`, `sms_2fa`, `device_registration`, `get_device_data`, `is_device_registered`, `forget_device`. Also the attributes the flow sets: `access_token`, `device_group_key`, `device_key`. +- `Hive`, `session.startSession`, `session.deviceList`, `session.updateData`, `updateInterval`. +- Every `hive..(` call in the component and in core's hive platforms (`grep -hoE "hive\.[a-z_]+\.[A-Za-z_]+\(" ...`). Confirm each exists on the target with a compatible signature, at runtime rather than by reading code. +- How devices are accessed (`device["hiveType"]`, `.get("deviceData")`). 2.x devices are dataclasses with a legacy-key mapping. +- `PRODUCTS`, `DEVICES` and the sensor dispatch. A new or renamed `hiveType` needs a matching `SENSOR_TYPES` entry in `sensor.py`, or core's platform descriptions, before it shows up in HA. +- Exceptions in `helper/hive_exceptions.py`, especially anything `startSession` can now raise. `async_setup_entry` must map it: connection problems to `ConfigEntryNotReady`, credential or config problems to `ConfigEntryAuthFailed`. -Also check whether the version HA core pins (`homeassistant/components/hive/manifest.json` in `.venv`) differs a lot. Core's re-exported platforms are written against that version. +Also check that `pyhive-integration` isn't in HA's `homeassistant/package_constraints.txt`. If it ever is, HA won't install a different version, and principle 2 needs rethinking. ## 3. Apply and verify - Change only the `pyhive-integration==` pin in `manifest.json`. Don't change the component `version`; that happens at release. - Install and test: ```bash - VIRTUAL_ENV=.venv uv pip install "pyhive-integration==" + VIRTUAL_ENV=.venv uv pip install --refresh-package pyhive-integration "pyhive-integration==" script/test script/lint --check + python3 .github/scripts/hassfest.py # needs Docker; the pyhive line should be a warning ``` + (`--refresh-package` matters for a release published in the last few hours.) +- The tests mock the library. On 2.x, also run an offline session from the bundled `data/data.json` (username `use@file.com`) and call the real getters for every platform. - Where the diff showed behaviour changes, add tests for them. -- For a beta or dev build, suggest also releasing a component beta (see `/release`) so users can try it. +- For a pre-release target, the next step is a component beta (`/release`). For a stable target, it can go in the next stable release. ## 4. Report Report: -- the version change +- the version change, and how it compares with core's pin - a short summary of the library changes that matter to this component, with any risks -- the test results -- whether it's ready to merge +- the test, lint and hassfest results +- whether it's ready to merge, and whether it can ship stable or only as a beta If a bot PR has no CI runs, remind the user to close and reopen it, or to set up the `BOT_TOKEN` secret. Don't commit, push, or merge unless asked. diff --git a/.claude/skills/release/SKILL.md b/.claude/skills/release/SKILL.md index bbb03a4..4b8c4b9 100644 --- a/.claude/skills/release/SKILL.md +++ b/.claude/skills/release/SKILL.md @@ -1,13 +1,15 @@ --- name: release -description: Cut a beta or stable release of the Hive custom component - bump manifest.json, publish the GitHub release with a matching tag, and verify the Release workflow. Use when the user asks to release, ship, tag, or publish a version or beta. +description: Cut a beta or stable release of the Hive custom component - check for the newest pyhive-integration (betas included) when releasing a beta, bump manifest.json, publish the GitHub release with a matching tag, and verify the Release workflow. Use when the user asks to release, ship, tag, or publish a version or beta. --- # Release -Follow MAINTAINING.md → "Releasing". The rules that matter: -- The tag must equal `version` in `custom_components/hive/manifest.json`, for example `2026.10.0` or `2026.10.0b1`. +Follow MAINTAINING.md → "Releasing", and the principles in `CLAUDE.md`. The rules that matter: +- **Betas are the fast, opt-in channel.** They're how new `pyhive-integration` builds and fixes reach users before core HA ships them. Stable releases go to every HACS user. +- The tag must equal `version` in `custom_components/hive/manifest.json`, for example `2026.10.0` or `2026.10.0b1`. Use a lowercase `b`, with no dot before it. - Beta tags (`bN`) are always published as pre-releases. Stable tags never are. +- A stable release must pin a stable `pyhive-integration`. A pre-release pin only ships in a beta. `check_release.py` fails the Release run otherwise, but by then the release is already public, so check before publishing. - Publishing a release is visible to every HACS user, and so is deleting one. **Confirm the exact tag and whether it is a pre-release with the user before running `gh release create`.** Never commit, push, or open PRs unless the user asks. ## Steps @@ -19,23 +21,35 @@ Follow MAINTAINING.md → "Releasing". The rules that matter: - Same month: bump the patch number. - Beta: add `b1`, or the next free `bN`. -2. **Check it's safe to ship.** +2. **Check pyhive-integration.** + - **Beta:** always look up the newest version on PyPI, pre-releases included: + ```bash + curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' + jq -r '.requirements[]' custom_components/hive/manifest.json + ``` + If it's newer than the pin, run `/bump-pyhive` for it first, and get that merged to `master`, unless the user decides to skip it. Check for an open `deps/pyhive-integration-*` PR before starting a new one. + - **Stable:** the pin must not be a pre-release. If `master` pins a pyhive beta, stop: either wait for a stable pyhive, or move the pin to the latest stable with `/bump-pyhive` first. + +3. **Check it's safe to ship.** - `gh run list -w ci.yml -b master -L 1` and `gh run list -w compat.yml -L 1` must both be green. If either is red, stop and report. For a red Compatibility run, suggest `/triage-compat`. + - A hassfest **warning** about `pyhive-integration` differing from core hive is expected (see `CLAUDE.md`). Only errors count. - `script/test` and `script/lint --check` must pass locally. - Check `git log ..origin/master --oneline`. If there's nothing to release, say so. -3. **Bump the manifest.** Change only the `version` value in `manifest.json`. Don't touch `requirements`; that's `/bump-pyhive`. The change must reach `master` before tagging: +4. **Bump the manifest.** Change only the `version` value in `manifest.json`. Don't touch `requirements`; that's `/bump-pyhive`. The change must reach `master` before tagging: - If the user asks, make a branch `release/`, commit it, and open a PR. - Otherwise hand the change over for them to commit. - - Wait until it's merged, and check with `git fetch && git show origin/master:custom_components/hive/manifest.json | jq -r .version`. + - Wait until it's merged, then check with `git fetch && git show origin/master:custom_components/hive/manifest.json | jq -r '.version, .requirements[]'`. -4. **Publish** (only after the user confirms the tag): +5. **Publish** (only after the user confirms the tag): ```bash gh release create --target master --generate-notes --prerelease # beta gh release create --target master --generate-notes --latest # stable ``` + For a beta, add the `pyhive-integration` version to the notes, and say whether it's ahead of core's. -5. **Verify.** +6. **Verify.** - Watch the Release workflow: ```bash gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId') --exit-status @@ -43,6 +57,6 @@ Follow MAINTAINING.md → "Releasing". The rules that matter: - Then confirm `hive.zip` is attached: `gh release view --json assets -q '.assets[].name'`. - If the check job fails, the release is already visible to HACS users. Tell the user, and offer `gh release delete --cleanup-tag` (it needs their OK), then a corrected release. -6. **Clean up** after a stable release that replaces betas. Offer `gh workflow run delete_beta.yml`. It keeps the newest pre-release and never touches stable releases. +7. **Clean up** after a stable release that replaces betas. Offer `gh workflow run delete_beta.yml`. It keeps the newest pre-release and never touches stable releases. -Report the release URL, the Release run result and anything left for the user to do. +Report the release URL, the `pyhive-integration` version it ships, the Release run result and anything left for the user to do. diff --git a/.claude/skills/repo-health/SKILL.md b/.claude/skills/repo-health/SKILL.md index 553c4b3..c303011 100644 --- a/.claude/skills/repo-health/SKILL.md +++ b/.claude/skills/repo-health/SKILL.md @@ -29,6 +29,9 @@ Compare what you find with MAINTAINING.md: - **Unreleased commits on master:** suggest a release if there are user-facing changes. - **Branch protection:** the required checks should be `HACS validation`, `Hassfest`, `Lint` and `Tests`, with code owner review on. - **Secrets:** `BOT_TOKEN` should be present. +- **Hassfest:** a warning that `pyhive-integration` differs from core hive is expected (see `CLAUDE.md`), so don't report it as a problem. +- **pyhive-integration:** compare the manifest pin with core hive's pin and with the newest version on PyPI, pre-releases included. A newer pyhive beta than the pin is a candidate for the next component beta (`/bump-pyhive`, then `/release`). A pre-release pin on `master` blocks stable releases until it's moved to a stable version. +- **Latest beta release:** the tag should match the `version` in its manifest (`git show :custom_components/hive/manifest.json | jq -r .version`). - **Pinned HA:** compare the HA version in the `requirements_test.txt` comment with the latest stable on PyPI (`curl -fsS https://pypi.org/pypi/homeassistant/json | jq -r .info.version`). A gap of more than one minor release means the Dependabot PR is stuck. Report as a short table with ✅ / ⚠️ / ❌ and one line each. Then list the actions in priority order, each with the skill to use (`/triage-compat`, `/bump-pyhive`, `/release`) or the settings page to change. diff --git a/.claude/skills/triage-compat/SKILL.md b/.claude/skills/triage-compat/SKILL.md index 3448d35..d1645df 100644 --- a/.claude/skills/triage-compat/SKILL.md +++ b/.claude/skills/triage-compat/SKILL.md @@ -5,6 +5,8 @@ description: Diagnose and fix a failing nightly Compatibility workflow (compat.y # Triage Compatibility +Principle 1 in `CLAUDE.md` applies: this component extends core's hive integration and reuses it wherever possible, so fixes adapt to core rather than fork it. + Background: most platform files (`binary_sensor.py`, `climate.py`, `light.py`, `switch.py`, `water_heater.py`, `entity.py`) re-export `homeassistant.components.hive.*`. `__init__.py`, `sensor.py` and `config_flow.py` are this repo's own code, but they rely on HA helpers and on core's `HiveEntity`. HA changes break things here without any commit in this repo. ## 1. Find what failed @@ -20,7 +22,7 @@ Map it using the table in MAINTAINING.md → "Compatibility is red": - **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. -- **HACS/hassfest** fails: follow the validator's message. +- **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: diff --git a/.github/scripts/check_release.py b/.github/scripts/check_release.py index c7f1c4b..cc901b6 100644 --- a/.github/scripts/check_release.py +++ b/.github/scripts/check_release.py @@ -4,13 +4,17 @@ HACS installs by tag, so the tag must match the manifest version (compared as versions, so tag 2026.3.1.b1 matches manifest 2026.3.1b1). A beta version must be -a GitHub pre-release, otherwise HACS offers it to every user. +a GitHub pre-release, otherwise HACS offers it to every user. A stable release +must also pin a stable pyhive-integration: pre-release libraries only ship in the +opt-in beta channel (see CLAUDE.md). """ import json from pathlib import Path import sys +from packaging.requirements import Requirement +from packaging.utils import canonicalize_name from packaging.version import InvalidVersion, Version MANIFEST = ( @@ -19,7 +23,8 @@ def main(tag: str, prerelease: bool) -> int: - manifest_version = json.loads(MANIFEST.read_text(encoding="utf-8"))["version"] + manifest = json.loads(MANIFEST.read_text(encoding="utf-8")) + manifest_version = manifest["version"] errors = [] try: tag_version = Version(tag) @@ -42,6 +47,15 @@ def main(tag: str, prerelease: bool) -> int: f"{tag} is marked as a pre-release but isn't a beta version " "(expected something like 2026.9.0b1)." ) + if not tag_version.is_prerelease: + for req in map(Requirement, manifest.get("requirements", [])): + if canonicalize_name(req.name) == "pyhive-integration" and any( + Version(spec.version).is_prerelease for spec in req.specifier + ): + errors.append( + f"{tag} is a stable release but pins {req}. Stable releases go " + "to every HACS user, so ship pre-release pyhive in a beta instead." + ) for error in errors: print(f"::error::{error}") diff --git a/.github/scripts/hassfest.py b/.github/scripts/hassfest.py new file mode 100644 index 0000000..09fc159 --- /dev/null +++ b/.github/scripts/hassfest.py @@ -0,0 +1,69 @@ +"""Run hassfest, allowing only the errors this repo causes on purpose. + + python .github/scripts/hassfest.py + +This component replaces Home Assistant core's hive integration and may pin a +different pyhive-integration than core does (see CLAUDE.md). hassfest checks a +custom integration's requirements against every core integration's pins, including +core hive's own, so it reports that difference as an error. Those errors are shown +as warnings here. Any other error, or a failure with no error lines, still fails. +""" + +from pathlib import Path +import re +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[2] +IMAGE = "ghcr.io/home-assistant/hassfest" + +# Packages whose core pin belongs to the core integration this repo replaces. +OVERRIDDEN_PACKAGES = {"pyhive-integration"} + +# The two hassfest errors about differing from a core integration's pin. Errors +# about Home Assistant's own dependencies or package constraints are not here: +# those can break the whole installation, so they must fail. +ALLOWED = re.compile( + r"\[REQUIREMENTS\] Requirement (?P[A-Za-z0-9][A-Za-z0-9._-]*)\S* " + r"(pins a package Home Assistant depends on" + r"|is incompatible with \S+, which Home Assistant depends on\.)" +) + + +def is_allowed(line: str) -> bool: + """Return True if a hassfest error line is an expected override difference.""" + match = ALLOWED.search(line) + return bool(match) and match["package"].lower() in OVERRIDDEN_PACKAGES + + +def main() -> int: + result = subprocess.run( + ["docker", "run", "--rm", "-v", f"{ROOT}:/github/workspace", IMAGE], + capture_output=True, + text=True, + check=False, + ) + output = result.stdout + result.stderr + print(output) + if result.returncode == 0: + return 0 + + errors = [line for line in output.splitlines() if "[ERROR]" in line] + if not errors: + print( + f"::error::hassfest exited with {result.returncode} without an error line" + ) + return result.returncode + + blocking = [line for line in errors if not is_allowed(line)] + for line in errors: + level = "error" if line in blocking else "warning" + print(f"::{level}::{line.lstrip('* ').strip()}") + if blocking: + return 1 + print("Only expected differences from core hive's requirements; passing.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cce84ae..45d3efe 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,9 +34,9 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - # home-assistant/actions has no maintained releases; master tracks the - # current hassfest rules, which is what we want to validate against. - - uses: home-assistant/actions/hassfest@master + # Runs the same image as home-assistant/actions/hassfest (latest rules), + # but lets our pyhive-integration pin differ from core hive's. See CLAUDE.md. + - run: python3 .github/scripts/hassfest.py lint: name: Lint @@ -81,7 +81,7 @@ jobs: steps: - run: | for workflow in compat.yml stale.yml pyhive_bump.yml; do - state=$(gh workflow view "$workflow" --json state --jq .state) + state=$(gh api "repos/$GH_REPO/actions/workflows/$workflow" --jq .state) if [ "$state" = "disabled_inactivity" ]; then gh workflow enable "$workflow" echo "::notice::Re-enabled $workflow (was disabled for inactivity)" diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml index f0c0f59..2377650 100644 --- a/.github/workflows/compat.yml +++ b/.github/workflows/compat.yml @@ -27,7 +27,7 @@ jobs: with: category: integration ignore: brands - - uses: home-assistant/actions/hassfest@master + - run: python3 .github/scripts/hassfest.py tests: name: Tests (HA ${{ matrix.channel }}) diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..195765e --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,65 @@ +# Hive Custom Component + +A HACS custom component that replaces Home Assistant core's `hive` integration +(same `domain`). Procedures live in [MAINTAINING.md](MAINTAINING.md), setup in +[CONTRIBUTING.md](CONTRIBUTING.md), and step-by-step skills in `.claude/skills/`. + +## Why this repo exists + +Two principles decide most questions here. Apply them to code, CI, releases and +the skills. + +### 1. Extend core, reuse it wherever possible + +The component adds capability on top of core's hive integration, such as the extra +attribute sensors in `sensor.py`. It is not a fork. + +- Re-export core's platforms (`binary_sensor.py`, `climate.py`, `light.py`, + `switch.py`, `water_heater.py`, `entity.py`) instead of copying them. Only write + local code for something core doesn't do, and keep it as small as possible. +- When core changes, adapt to it. Replacing a re-export with a local module is a + last resort, and the user should know. +- A fix or feature that would help everyone belongs upstream in core or + `pyhive-integration` as well. This repo can ship it first. + +### 2. The opt-in fast channel + +Everyone on core's integration gets the official, slower release train. Installing +this component is an opt-in to get changes sooner, and its HACS betas go further +still, as a testing channel. + +- `manifest.json` may pin a **newer `pyhive-integration` than core does**, including + pre-releases. That divergence is the point of the repo, not a mistake. +- The pin stays exact (`==`). Users get the version we tested. +- **Pre-release `pyhive-integration` only ships in component betas** (pre-releases, + which HACS offers only to users who opt in). A stable component release must pin a + stable `pyhive-integration`. `.github/scripts/check_release.py` enforces this. +- When cutting a component beta, always check PyPI for the newest + `pyhive-integration`, pre-releases included, and bump to it first if it's newer + than the pin (`/bump-pyhive`, then `/release`). +- Never let the fast channel break people. Stable releases need green CI and a + green Compatibility run. + +## What this means for CI + +hassfest compares a custom integration's requirements with every core +integration's pins, including core hive's own. With principle 2 that always gives a +`[REQUIREMENTS]` error for `pyhive-integration`: "pins a package Home Assistant +depends on" when we match core, or "is incompatible with …" when we're ahead. +`.github/scripts/hassfest.py` runs the official hassfest image and turns only those +`pyhive-integration` errors into warnings. Every other error still fails, including +conflicts with Home Assistant's own dependencies or package constraints, because +those can break a user's whole installation. Don't loosen the pin to `>=` to +silence it. + +## Working here + +- `script/setup`, `script/test`, `script/lint` (`--check` in CI). `.venv` must be + Python 3.14 (`script/setup --recreate`). +- Tests mock `apyhiveapi`. When the library changes, also exercise the real code: + from 2.0 the library ships `apyhiveapi/data/data.json`, and + `startSession({"username": "use@file.com"})` runs a session from it offline. +- The tag of a release must equal `version` in `manifest.json`. Beta tags (`bN`) + are always pre-releases, and stable tags never are. +- Don't commit, push, release or merge unless asked. Releases are visible to every + HACS user. diff --git a/MAINTAINING.md b/MAINTAINING.md index 7cc963d..ad16d25 100644 --- a/MAINTAINING.md +++ b/MAINTAINING.md @@ -4,28 +4,56 @@ This is the runbook for keeping the component released, compatible and healthy. For development setup, see [CONTRIBUTING.md](CONTRIBUTING.md). Each procedure also has a Claude Code skill in `.claude/skills/`, listed at the end. +## Principles + +The full version is in [CLAUDE.md](CLAUDE.md). Everything below follows from these two: + +1. **Extend core, reuse it wherever possible.** This component replaces core's + `hive` integration to add capability, but re-exports core's platforms instead of + copying them. Local code only covers what core doesn't do. +2. **An opt-in fast channel.** Users on core get the official release train. + Installing this component opts in to changes sooner, and its betas are the + testing channel. It may pin a newer `pyhive-integration` than core, including + pre-releases, but **pre-release pyhive only ships in component betas**. Stable + releases pin stable pyhive. + ## What runs automatically | When | Workflow | What it does | If it fails | |---|---|---|---| -| Every PR and every push to `master` | `ci.yml` | HACS validation, hassfest, lint and tests. A push to master also re-enables scheduled workflows that GitHub turned off. | Fix it in the PR before merging | +| Every PR and every push to `master` | `ci.yml` | HACS validation, hassfest (through `.github/scripts/hassfest.py`, see [Hassfest and the pyhive pin](#hassfest-and-the-pyhive-pin)), lint and tests. A push to master also re-enables scheduled workflows that GitHub turned off. | Fix it in the PR before merging | | Daily, 04:17 UTC | `compat.yml` | Tests against the newest HA stable and beta, plus an import check against HA `dev` | [Compatibility is red](#compatibility-is-red) | | Daily, 05:29 UTC | `stale.yml` | Labels issues and PRs inactive for 60 days, then closes issues after 30 more days and PRs after 14 | Add the `pinned` label to keep something open | | Monday, 06:23 UTC | `pyhive_bump.yml` | Opens a PR if a newer `pyhive-integration` is on PyPI | [Dependency PRs](#dependency-prs) | | Weekly | Dependabot | PRs for GitHub Actions versions and for `requirements_test.txt` | [Dependency PRs](#dependency-prs) | -| A GitHub release is published | `release.yml` | Checks the tag matches `manifest.json`, then attaches `hive.zip` | [Releasing](#releasing) | +| A GitHub release is published | `release.yml` | Checks the tag matches `manifest.json`, and that a stable release doesn't pin pre-release pyhive, then attaches `hive.zip` | [Releasing](#releasing) | | Manual | `delete_beta.yml` | Deletes old pre-releases and their tags, keeping the newest | Not applicable | ## Releasing -Versions are `YEAR.MONTH.PATCH`, for example `2026.10.0`. Betas add `bN`, for example `2026.10.0b1`. -HACS installs by tag, so **the tag must equal `version` in `manifest.json`**. +Versions are `YEAR.MONTH.PATCH`, for example `2026.10.0`. Betas add `bN`, for example +`2026.10.0b1` (lowercase `b`, no dot before it). HACS installs by tag, so **the tag must +equal `version` in `manifest.json`**. + +Betas are the normal way to get something out quickly: HACS only offers them to users +who opt in. Stable releases go to everyone. + +1. **Check `pyhive-integration`:** + - **Beta:** look up the newest version on PyPI, pre-releases included, and if it's + newer than the pin, bump to it first ([Dependency PRs](#dependency-prs)): + + ```bash + curl -fsS https://pypi.org/pypi/pyhive-integration/json | jq -r '.releases | keys[]' \ + | .venv/bin/python -c 'import sys; from packaging.version import Version; print(max(sys.stdin.read().split(), key=Version))' + ``` -1. Open a PR that sets `version` in `custom_components/hive/manifest.json`. Merge it + - **Stable:** the pin must be a stable version. If `master` pins a pyhive beta, wait + for a stable pyhive, or move the pin back to the latest stable first. +2. Open a PR that sets `version` in `custom_components/hive/manifest.json`. Merge it once CI passes. -2. Check that the last Compatibility run on `master` passed, so you aren't shipping +3. Check that the last Compatibility run on `master` passed, so you aren't shipping something current HA versions break. -3. Publish the release from the same version: +4. Publish the release from the same version: ```bash # beta: HACS offers it only to users who opt into betas @@ -34,12 +62,14 @@ HACS installs by tag, so **the tag must equal `version` in `manifest.json`**. gh release create 2026.10.0 --target master --latest --generate-notes ``` -4. Watch the **Release** run: `gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId')`. + For a beta, mention the `pyhive-integration` version in the release notes. +5. Watch the **Release** run: `gh run watch $(gh run list -w release.yml -L1 --json databaseId -q '.[0].databaseId')`. - It checks the tag *after* publishing. If it fails, the release is already visible to HACS users. Delete it straight away with `gh release delete --cleanup-tag`, fix the cause, and release again. - A beta tag must be a pre-release, and a pre-release must have a beta tag. -5. After a stable release that replaces a run of betas, run **Delete Beta Releases**: + - A stable release must not pin a pre-release `pyhive-integration`. +6. After a stable release that replaces a run of betas, run **Delete Beta Releases**: `gh workflow run delete_beta.yml`. ## Compatibility is red @@ -54,7 +84,7 @@ break the component with no change here. Open the failing run | **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 | -| **HACS and hassfest** | New validation rules | Update the manifest or repo structure as it says | +| **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: @@ -70,9 +100,34 @@ required manifest keys. The Home Assistant developer blog ## Dependency PRs -- **`pyhive-integration`** (from `pyhive_bump.yml`): read the release notes linked in the - PR. If CI hasn't run, close and reopen the PR (see the `BOT_TOKEN` note below). Merge - it once green. Release it on its own, or together with the next change. +- **`pyhive-integration`** (from `pyhive_bump.yml`, or `/bump-pyhive`): read the release + notes linked in the PR. If CI hasn't run, close and reopen the PR (see the `BOT_TOKEN` + note below). Merge it once green. + - Keep the pin exact (`==`), even when it's ahead of core's. + - The weekly run only proposes stable versions. For a pyhive beta, run the workflow + with its version (`gh workflow run pyhive_bump.yml -f version=`) or use + `/bump-pyhive`. + - A stable pyhive can go out in the next release. A pyhive beta can only go out in a + component beta. + - The tests mock the library. For anything beyond a patch release, also run an + offline session against the library's bundled data (see `/bump-pyhive`). + +### Hassfest and the pyhive pin + +hassfest checks a custom integration's requirements against the pins of every core +integration, including core hive's own `pyhive-integration`. Because this component +replaces core hive, and may pin a different version on purpose, that check always +reports an error, worded either as "pins a package Home Assistant depends on" or as +"is incompatible with …, which Home Assistant depends on". + +`.github/scripts/hassfest.py` runs the official hassfest image and shows only those +`pyhive-integration` errors as warnings. Any other error still fails, including a +conflict with Home Assistant's own dependencies or package constraints, because those +would break a user's installation. If hassfest rewords these messages, update the +`ALLOWED` pattern in the script. Don't switch the pin to `>=` to silence it. + +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. @@ -114,9 +169,10 @@ users on older HA versions. - `sensor.py` has update branches for `CurrentTemperature`, `Heating_Boost` and `Hotwater_Boost` that never run, because no sensor description matches those types. `get_current_temp_sa()` also calls `heating.minmaxTemperature`, - `currentTemperature` and `targetTemperature`, but only the first of those exists - in pyhive. Pointing it at `Current_Temperature` would therefore crash. Either - delete this code or fix it along with the pyhive method names. + `currentTemperature` and `targetTemperature`. In pyhive 1.x only the first of + those exists, so pointing it at `Current_Temperature` would crash there. 2.x adds + the other two as aliases. Either delete this code or fix it along with the pyhive + method names. - `async_setup_hive_entry` raises `UnknownHiveError` from the user step. That path is unreachable, because the step checks for `AuthenticationResult` first. @@ -127,7 +183,7 @@ section above. | Skill | Use it to | |---|---| -| `/release` | Cut a beta or stable release, from the version bump through to checking the Release run | +| `/release` | Cut a beta or stable release, from the pyhive check and version bump through to checking the Release run | | `/triage-compat` | Find out why Compatibility is red, reproduce it locally and fix it | -| `/bump-pyhive` | Move to a new `pyhive-integration`, and check whether its changes affect this component | +| `/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 | diff --git a/README.md b/README.md index cb4b5d0..7cc4cb1 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,17 @@ sensors e.g `Living Room Lamp Battery Level` * Current State - Heating/Hotwater only * Boost State - Heating/Hotwater only +## How this relates to the built-in Hive integration + +This component replaces Home Assistant's built-in Hive integration. It reuses the +built-in code wherever it can and adds the extras above on top. + +Think of it as an opt-in fast channel. Fixes and new versions of the Hive library +([`pyhive-integration`](https://pypi.org/project/pyhive-integration/)) usually reach +this component before they reach Home Assistant itself. If you want to help test the +newest changes, turn on beta releases for this repository in HACS. Betas may use +pre-release versions of the library. Stable releases only use stable ones. + For details on what the Home Assistant Hive component supports, please see below: [**>> Hive Component Documentation <<**](https://www.home-assistant.io/integrations/hive/) From 969d4c71c7a7b2e4a89816fc13bca4e64cfd67d1 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Fri, 16 Oct 2026 08:41:26 +0100 Subject: [PATCH 26/31] release: 2026.10.1b2 Beta release shipping pyhive-integration 2.0.0b4, ahead of core's 1.0.9. Co-Authored-By: Claude Opus 5.5 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 2379960..060fd8a 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -12,5 +12,5 @@ "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", "loggers": ["apyhiveapi"], "requirements": ["pyhive-integration==2.0.0b4"], - "version": "2026.8.0" + "version": "2026.10.1b2" } From 823dea16a06fb312ebdb44a4d48ad4faca6b1b88 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:19:04 +0100 Subject: [PATCH 27/31] deps: downgrade pyhive-integration to 1.0.10 --- custom_components/hive/manifest.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/custom_components/hive/manifest.json b/custom_components/hive/manifest.json index 060fd8a..ac3c013 100755 --- a/custom_components/hive/manifest.json +++ b/custom_components/hive/manifest.json @@ -11,6 +11,6 @@ "iot_class": "cloud_polling", "issue_tracker": "https://github.com/Pyhass/Hive-Custom-Component/issues", "loggers": ["apyhiveapi"], - "requirements": ["pyhive-integration==2.0.0b4"], + "requirements": ["pyhive-integration==1.0.10"], "version": "2026.10.1b2" } From 5e63418bcc59ca26f242baf517a6da74f3b43034 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Tue, 20 Oct 2026 19:22:11 +0100 Subject: [PATCH 28/31] refactor: revert to core hive integration structure and downgrade to pyhive-integration 1.0.9 Revert changes from 2.0.0b4 back to stable 1.0.9 structure: - Remove HiveConnectionError and HiveUnknownConfiguration exception handling - Restore original type parameter naming convention (remove underscore prefixes) - Revert formatting changes in config_flow.py and const.py - Restore original manifest.json field ordering and version - Remove trailing newlines from platform files - Restore original import --- custom_components/hive/__init__.py | 19 +-- custom_components/hive/binary_sensor.py | 2 +- custom_components/hive/climate.py | 2 +- custom_components/hive/config_flow.py | 25 +-- custom_components/hive/const.py | 1 - custom_components/hive/sensor.py | 4 +- custom_components/hive/translations/en.json | 166 ++++++-------------- 7 files changed, 68 insertions(+), 151 deletions(-) diff --git a/custom_components/hive/__init__.py b/custom_components/hive/__init__.py index 071b7c7..5c2527a 100755 --- a/custom_components/hive/__init__.py +++ b/custom_components/hive/__init__.py @@ -9,11 +9,7 @@ from aiohttp.web_exceptions import HTTPException from apyhiveapi import Auth, Hive -from apyhiveapi.helper.hive_exceptions import ( - HiveConnectionError, - HiveReauthRequired, - HiveUnknownConfiguration, -) +from apyhiveapi.helper.hive_exceptions import HiveReauthRequired from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL @@ -47,10 +43,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: HiveConfigEntry) -> bool except HTTPException as error: _LOGGER.error("Could not connect to the internet: %s", error) raise ConfigEntryNotReady from error - except HiveConnectionError as error: - _LOGGER.error("Could not fetch devices from Hive: %s", error) - raise ConfigEntryNotReady from error - except (HiveReauthRequired, HiveUnknownConfiguration) as err: + except HiveReauthRequired as err: raise ConfigEntryAuthFailed from err device_registry = dr.async_get(hass) @@ -96,13 +89,13 @@ async def async_remove_config_entry_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 c89aecb..6fddc41 100755 --- a/custom_components/hive/binary_sensor.py +++ b/custom_components/hive/binary_sensor.py @@ -1 +1 @@ -from homeassistant.components.hive.binary_sensor import * +from homeassistant.components.hive.binary_sensor import * \ No newline at end of file diff --git a/custom_components/hive/climate.py b/custom_components/hive/climate.py index 5d07024..5db4b4b 100755 --- a/custom_components/hive/climate.py +++ b/custom_components/hive/climate.py @@ -1 +1 @@ -from homeassistant.components.hive.climate import * +from homeassistant.components.hive.climate import * \ No newline at end of file diff --git a/custom_components/hive/config_flow.py b/custom_components/hive/config_flow.py index 2922fa2..26174c2 100755 --- a/custom_components/hive/config_flow.py +++ b/custom_components/hive/config_flow.py @@ -4,7 +4,6 @@ from collections.abc import Mapping import copy -import logging from typing import Any from apyhiveapi import Auth @@ -24,6 +23,7 @@ ) 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,10 +52,7 @@ 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) @@ -131,11 +128,7 @@ 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 @@ -143,16 +136,10 @@ 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() diff --git a/custom_components/hive/const.py b/custom_components/hive/const.py index 99df0f5..0caf965 100755 --- a/custom_components/hive/const.py +++ b/custom_components/hive/const.py @@ -1,5 +1,4 @@ """Constants for Hive.""" - from homeassistant.const import Platform ATTR_MODE = "mode" diff --git a/custom_components/hive/sensor.py b/custom_components/hive/sensor.py index 378b98a..0c3030c 100755 --- a/custom_components/hive/sensor.py +++ b/custom_components/hive/sensor.py @@ -5,8 +5,6 @@ from datetime import timedelta from typing import Any -from apyhiveapi import Hive - from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, @@ -25,11 +23,13 @@ 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.""" diff --git a/custom_components/hive/translations/en.json b/custom_components/hive/translations/en.json index 90c237a..4ff73ae 100755 --- a/custom_components/hive/translations/en.json +++ b/custom_components/hive/translations/en.json @@ -1,124 +1,62 @@ { "config": { - "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)" - } + "abort": { + "already_configured": "Account is already configured", + "reauth_successful": "Re-authentication was successful", + "unknown_entry": "Unable to find existing entry." }, - "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" - } + "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" }, - "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" - } + "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" + } } - }, - "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": { - "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" - } + "step": { + "user": { + "data": { + "scan_interval": "Scan Interval (seconds)" + }, + "description": "Update the scan interval to poll for data more often.", + "title": "Options for Hive" + } } - } } } From 844142a34855f18bfa2d0bae3e8efb6efc955866 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Wed, 21 Oct 2026 00:03:13 +0100 Subject: [PATCH 29/31] Add HACS badge to README Added HACS badge for Hive integration in README. --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 7cc4cb1..c8891ba 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ The recommended way to is to install via [HACS](https://hacs.xyz/). Once HACS has been installed and setup. You just need to navigate to the HACS panel and choose integrations. This will show and option to add an integration click it and search for Hive in the presented popup. +[![Open your Home Assistant instance and open a repository inside the Home Assistant Community Store.](https://my.home-assistant.io/badges/hacs_repository.svg)](https://my.home-assistant.io/redirect/hacs_repository/?owner=Pyhass&repository=Hive-Custom-Component) + Once installation is complete please follow the [setup section](#setup) to set the Hive integration up. ### Manually From 410c085946dd15840f432497f506106b40019e4a Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:17:51 +0000 Subject: [PATCH 30/31] chore(deps): bump pytest-homeassistant-custom-component Bumps [pytest-homeassistant-custom-component](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component) from 0.13.370 to 0.13.375. - [Release notes](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/releases) - [Changelog](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/blob/master/CHANGELOG.md) - [Commits](https://github.com/MatthewFlamm/pytest-homeassistant-custom-component/compare/0.13.370...0.13.375) --- updated-dependencies: - dependency-name: pytest-homeassistant-custom-component dependency-version: 0.13.375 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- requirements_test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_test.txt b/requirements_test.txt index f8a0b8e..5ff717b 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -2,4 +2,4 @@ # Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. ruff==0.16.10 -pytest-homeassistant-custom-component==0.13.370 +pytest-homeassistant-custom-component==0.13.375 From 6dca35c7dfa2441dcada75e981d62941e4e824bb Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 1 Nov 2026 10:18:03 +0000 Subject: [PATCH 31/31] chore(deps): bump ruff from 0.16.10 to 0.17.3 Bumps [ruff](https://github.com/astral-sh/ruff) from 0.16.10 to 0.17.3. - [Release notes](https://github.com/astral-sh/ruff/releases) - [Changelog](https://github.com/astral-sh/ruff/blob/main/CHANGELOG.md) - [Commits](https://github.com/astral-sh/ruff/compare/0.16.10...0.17.3) --- updated-dependencies: - dependency-name: ruff dependency-version: 0.17.3 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- requirements_test.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/requirements_test.txt b/requirements_test.txt index f8a0b8e..c7b64a2 100644 --- a/requirements_test.txt +++ b/requirements_test.txt @@ -1,5 +1,5 @@ # Pins the Home Assistant version the tests run against (0.13.367 -> homeassistant 2026.9.4). # Bumped by Dependabot; the nightly compat workflow also tests the latest stable and beta. -ruff==0.16.10 +ruff==0.17.3 pytest-homeassistant-custom-component==0.13.370