sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:homeassistant/components/openhome/services.py
"""Support for Openhome Devices.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_INVOKE_PIN = "invoke_pin" ATTR_PIN_INDEX = "pin" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_INVOKE_PIN, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_PIN_INDEX): cv.positive_int}, func="async_invoke_pin", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openhome/services.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/squeezebox/services.py
"""Support for interfacing to the SqueezeBox API.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.const import ATTR_COMMAND from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_CALL_METHOD = "call_method" SERVICE_CALL_QUERY = "call_query" ATTR_PARAMETERS = "parameters" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_CALL_METHOD, entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PARAMETERS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), }, func="async_call_method", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_CALL_QUERY, entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PARAMETERS): vol.All( cv.ensure_list, vol.Length(min=1), [cv.string] ), }, func="async_call_query", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/squeezebox/services.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/songpal/services.py
"""Support for Songpal-enabled (Sony) media devices.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN PARAM_NAME = "name" PARAM_VALUE = "value" SET_SOUND_SETTING = "set_sound_setting" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SET_SOUND_SETTING, entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Required(PARAM_NAME): cv.string, vol.Required(PARAM_VALUE): cv.string, }, func="async_set_sound_setting", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/songpal/services.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/snapcast/services.py
"""Support for interacting with Snapcast clients.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_SNAPSHOT = "snapshot" SERVICE_RESTORE = "restore" SERVICE_SET_LATENCY = "set_latency" ATTR_LATENCY = "latency" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SNAPSHOT, entity_domain=MEDIA_PLAYER_DOMAIN, schema=None, func="async_snapshot", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_RESTORE, entity_domain=MEDIA_PLAYER_DOMAIN, schema=None, func="async_restore", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_LATENCY, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_LATENCY): cv.positive_int}, func="async_set_latency", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/snapcast/services.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/roon/services.py
"""MediaPlayer platform for Roon integration.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_TRANSFER = "transfer" ATTR_TRANSFER = "transfer_id" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_TRANSFER, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_TRANSFER): cv.entity_id}, func="async_transfer", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/roon/services.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/roku/services.py
"""Support for the Roku media player.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import service from homeassistant.helpers.typing import VolDictType from .const import DOMAIN ATTR_KEYWORD = "keyword" SERVICE_SEARCH = "search" SEARCH_SCHEMA: VolDictType = {vol.Required(ATTR_KEYWORD): str} @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SEARCH, entity_domain=MEDIA_PLAYER_DOMAIN, schema=SEARCH_SCHEMA, func="search", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/roku/services.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/linkplay/services.py
"""Support for LinkPlay media players.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_PLAY_PRESET = "play_preset" ATTR_PRESET_NUMBER = "preset_number" SERVICE_PLAY_PRESET_SCHEMA = cv.make_entity_service_schema( { vol.Required(ATTR_PRESET_NUMBER): cv.positive_int, } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_PLAY_PRESET, entity_domain=MEDIA_PLAYER_DOMAIN, schema=SERVICE_PLAY_PRESET_SCHEMA, func="async_play_preset", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/linkplay/services.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/denonavr/services.py
"""Support for Denon AVR receivers using their HTTP interface.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.const import ATTR_COMMAND from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import ATTR_DYNAMIC_EQ, DOMAIN # Services SERVICE_GET_COMMAND = "get_command" SERVICE_SET_DYNAMIC_EQ = "set_dynamic_eq" SERVICE_UPDATE_AUDYSSEY = "update_audyssey" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_GET_COMMAND, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_COMMAND): cv.string}, func=f"async_{SERVICE_GET_COMMAND}", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_DYNAMIC_EQ, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_DYNAMIC_EQ): cv.boolean}, func=f"async_{SERVICE_SET_DYNAMIC_EQ}", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_UPDATE_AUDYSSEY, entity_domain=MEDIA_PLAYER_DOMAIN, schema=None, func=f"async_{SERVICE_UPDATE_AUDYSSEY}", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/denonavr/services.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/vizio/services.py
"""Vizio SmartCast services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.typing import VolDictType from .const import DOMAIN SERVICE_UPDATE_SETTING = "update_setting" ATTR_SETTING_TYPE = "setting_type" ATTR_SETTING_NAME = "setting_name" ATTR_NEW_VALUE = "new_value" UPDATE_SETTING_SCHEMA: VolDictType = { vol.Required(ATTR_SETTING_TYPE): vol.All(cv.string, vol.Lower, cv.slugify), vol.Required(ATTR_SETTING_NAME): vol.All(cv.string, vol.Lower, cv.slugify), vol.Required(ATTR_NEW_VALUE): vol.Any(vol.Coerce(int), cv.string), } @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_UPDATE_SETTING, entity_domain=MEDIA_PLAYER_DOMAIN, schema=UPDATE_SETTING_SCHEMA, func="async_update_setting", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vizio/services.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/kodi/services.py
"""Support for interfacing with the XBMC/Kodi JSON-RPC API.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.typing import VolDictType from .const import DOMAIN SERVICE_ADD_MEDIA = "add_to_playlist" SERVICE_CALL_METHOD = "call_method" ATTR_MEDIA_TYPE = "media_type" ATTR_MEDIA_NAME = "media_name" ATTR_MEDIA_ARTIST_NAME = "artist_name" ATTR_MEDIA_ID = "media_id" ATTR_METHOD = "method" KODI_ADD_MEDIA_SCHEMA: VolDictType = { vol.Required(ATTR_MEDIA_TYPE): cv.string, vol.Optional(ATTR_MEDIA_ID): cv.string, vol.Optional(ATTR_MEDIA_NAME): cv.string, vol.Optional(ATTR_MEDIA_ARTIST_NAME): cv.string, } KODI_CALL_METHOD_SCHEMA = cv.make_entity_service_schema( {vol.Required(ATTR_METHOD): cv.string}, extra=vol.ALLOW_EXTRA ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_ADD_MEDIA, entity_domain=MEDIA_PLAYER_DOMAIN, schema=KODI_ADD_MEDIA_SCHEMA, func="async_add_media_to_playlist", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_CALL_METHOD, entity_domain=MEDIA_PLAYER_DOMAIN, schema=KODI_CALL_METHOD_SCHEMA, func="async_call_method", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/kodi/services.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/epson/services.py
"""Support for Epson projector.""" from __future__ import annotations from epson_projector.const import CMODE_LIST_SET import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import ATTR_CMODE, DOMAIN SERVICE_SELECT_CMODE = "select_cmode" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SELECT_CMODE, entity_domain=MEDIA_PLAYER_DOMAIN, schema={vol.Required(ATTR_CMODE): vol.All(cv.string, vol.Any(*CMODE_LIST_SET))}, func=SERVICE_SELECT_CMODE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/epson/services.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/frontend/pr_download.py
"""GitHub PR artifact download functionality for frontend development.""" from __future__ import annotations import io import logging import pathlib import shutil import zipfile from aiogithubapi import ( GitHubAPI, GitHubAuthenticationException, GitHubException, GitHubNotFoundException, GitHubPermissionException, GitHubRatelimitException, ) from aiohttp import ClientError, ClientResponseError, ClientTimeout from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession _LOGGER = logging.getLogger(__name__) GITHUB_REPO = "home-assistant/frontend" ARTIFACT_NAME = "frontend-build" # Zip bomb protection limits (10x typical frontend build size) # Typical frontend build: ~4500 files, ~135MB uncompressed MAX_ZIP_FILES = 50000 MAX_ZIP_SIZE = 1500 * 1024 * 1024 # 1.5GB ERROR_INVALID_TOKEN = ( "GitHub token is invalid or expired. " "Please check your github_token in the frontend configuration. " "Generate a new token at https://github.com/settings/tokens" ) ERROR_RATE_LIMIT = ( "GitHub API rate limit exceeded or token lacks permissions. " "Ensure your token has 'repo' or 'public_repo' scope" ) async def _get_pr_shas(client: GitHubAPI, pr_number: int) -> tuple[str, str]: """Get the head and base SHAs for a PR.""" try: response = await client.generic( endpoint=f"/repos/home-assistant/frontend/pulls/{pr_number}", ) return str(response.data["head"]["sha"]), str(response.data["base"]["sha"]) except GitHubAuthenticationException as err: raise HomeAssistantError(ERROR_INVALID_TOKEN) from err except (GitHubRatelimitException, GitHubPermissionException) as err: raise HomeAssistantError(ERROR_RATE_LIMIT) from err except GitHubNotFoundException as err: raise HomeAssistantError( f"PR #{pr_number} does not exist in repository {GITHUB_REPO}" ) from err except GitHubException as err: raise HomeAssistantError(f"GitHub API error: {err}") from err async def _find_pr_artifact(client: GitHubAPI, pr_number: int, head_sha: str) -> str: """Find the build artifact for the given PR and commit SHA. Returns the artifact download URL. """ try: response = await client.generic( endpoint="/repos/home-assistant/frontend/actions/workflows/ci.yaml/runs", params={"head_sha": head_sha, "per_page": 10}, ) for run in response.data.get("workflow_runs", []): if run["status"] == "completed" and run["conclusion"] == "success": artifacts_response = await client.generic( endpoint=f"/repos/home-assistant/frontend/actions/runs/{run['id']}/artifacts", ) for artifact in artifacts_response.data.get("artifacts", []): if artifact["name"] == ARTIFACT_NAME: _LOGGER.info( "Found artifact '%s' from CI run #%s", ARTIFACT_NAME, run["id"], ) return str(artifact["archive_download_url"]) raise HomeAssistantError( f"No '{ARTIFACT_NAME}' artifact found for PR #{pr_number}. " "Possible reasons: CI has not run yet or is running, " "or the build failed, or the PR artifact expired. " f"Check https://github.com/{GITHUB_REPO}/pull/{pr_number}/checks" ) except GitHubAuthenticationException as err: raise HomeAssistantError(ERROR_INVALID_TOKEN) from err except (GitHubRatelimitException, GitHubPermissionException) as err: raise HomeAssistantError(ERROR_RATE_LIMIT) from err except GitHubException as err: raise HomeAssistantError(f"GitHub API error: {err}") from err async def _download_artifact_data( hass: HomeAssistant, artifact_url: str, github_token: str ) -> bytes: """Download artifact data from GitHub.""" session = async_get_clientsession(hass) headers = { "Authorization": f"token {github_token}", "Accept": "application/vnd.github+json", } try: response = await session.get( artifact_url, headers=headers, timeout=ClientTimeout(total=60) ) response.raise_for_status() return await response.read() except ClientResponseError as err: if err.status == 401: raise HomeAssistantError(ERROR_INVALID_TOKEN) from err if err.status == 403: raise HomeAssistantError(ERROR_RATE_LIMIT) from err raise HomeAssistantError( f"Failed to download artifact: HTTP {err.status}" ) from err except TimeoutError as err: raise HomeAssistantError( "Timeout downloading artifact (>60s). Check your network connection" ) from err except ClientError as err: raise HomeAssistantError(f"Network error downloading artifact: {err}") from err def _extract_artifact( artifact_data: bytes, cache_dir: pathlib.Path, cache_key: str, ) -> None: """Extract artifact and save cache key (runs in executor).""" frontend_dir = cache_dir / "hass_frontend" if cache_dir.exists(): shutil.rmtree(cache_dir) frontend_dir.mkdir(parents=True, exist_ok=True) with zipfile.ZipFile(io.BytesIO(artifact_data)) as zip_file: # Validate zip contents to protect against zip bombs # See: https://github.com/python/cpython/issues/80643 total_size = 0 for file_count, info in enumerate(zip_file.infolist(), start=1): total_size += info.file_size if file_count > MAX_ZIP_FILES: raise ValueError( f"Zip contains too many files (>{MAX_ZIP_FILES}), possible zip bomb" ) if total_size > MAX_ZIP_SIZE: raise ValueError( f"Zip uncompressed size too large (>{MAX_ZIP_SIZE} bytes), " "possible zip bomb" ) zip_file.extractall(str(frontend_dir)) sha_file = cache_dir / ".sha" sha_file.write_text(cache_key) async def download_pr_artifact( hass: HomeAssistant, pr_number: int, github_token: str, tmp_dir: pathlib.Path, ) -> pathlib.Path: """Download and extract frontend PR artifact from GitHub. Returns the path to the tmp directory containing hass_frontend/. Raises HomeAssistantError on failure. """ try: session = async_get_clientsession(hass) except Exception as err: raise HomeAssistantError(f"Failed to get HTTP client session: {err}") from err client = GitHubAPI(token=github_token, session=session) head_sha, base_sha = await _get_pr_shas(client, pr_number) cache_key = f"{head_sha}:{base_sha}" frontend_dir = tmp_dir / "hass_frontend" sha_file = tmp_dir / ".sha" if frontend_dir.exists() and sha_file.exists(): try: cached_key = await hass.async_add_executor_job(sha_file.read_text) cached_key = cached_key.strip() if cached_key == cache_key: _LOGGER.info( "Using cached PR #%s (commit %s) from %s", pr_number, cache_key, tmp_dir, ) return tmp_dir _LOGGER.info( "PR #%s cache outdated (cached: %s, current: %s), re-downloading", pr_number, cached_key, cache_key, ) except OSError as err: _LOGGER.debug("Failed to read cache SHA file: %s", err) artifact_url = await _find_pr_artifact(client, pr_number, head_sha) _LOGGER.info("Downloading frontend PR #%s artifact", pr_number) artifact_data = await _download_artifact_data(hass, artifact_url, github_token) try: await hass.async_add_executor_job( _extract_artifact, artifact_data, tmp_dir, cache_key ) except zipfile.BadZipFile as err: raise HomeAssistantError( f"Downloaded artifact for PR #{pr_number} is corrupted or invalid" ) from err except ValueError as err: raise HomeAssistantError( f"Downloaded artifact for PR #{pr_number} failed validation: {err}" ) from err except OSError as err: raise HomeAssistantError( f"Failed to extract artifact for PR #{pr_number}: {err}" ) from err _LOGGER.info( "Successfully downloaded and extracted PR #%s (commit %s) to %s", pr_number, head_sha[:8], tmp_dir, ) return tmp_dir
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/frontend/pr_download.py", "license": "Apache License 2.0", "lines": 208, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/frontend/test_pr_download.py
"""Tests for frontend PR download functionality.""" from __future__ import annotations from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch from aiogithubapi import ( GitHubAuthenticationException, GitHubException, GitHubNotFoundException, GitHubPermissionException, GitHubRatelimitException, ) from aiohttp import ClientError import pytest from homeassistant.components.frontend import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.test_util.aiohttp import AiohttpClientMocker async def test_pr_download_success( hass: HomeAssistant, tmp_path: Path, mock_github_api, aioclient_mock: AiohttpClientMocker, mock_zipfile, ) -> None: """Test successful PR artifact download.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert mock_github_api.generic.call_count >= 2 # PR + workflow runs assert len(aioclient_mock.mock_calls) == 1 mock_zipfile.extractall.assert_called_once() async def test_pr_download_uses_cache( hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture ) -> None: """Test that cached PR is used when commit hasn't changed.""" hass.config.config_dir = str(tmp_path) pr_cache_dir = tmp_path / ".cache" / "frontend" / "development_artifacts" frontend_dir = pr_cache_dir / "hass_frontend" frontend_dir.mkdir(parents=True) (frontend_dir / "index.html").write_text("test") (pr_cache_dir / ".sha").write_text("abc123def456:base789abc012") with patch( "homeassistant.components.frontend.pr_download.GitHubAPI" ) as mock_gh_class: mock_client = AsyncMock() mock_gh_class.return_value = mock_client pr_response = AsyncMock() pr_response.data = { "head": {"sha": "abc123def456"}, "base": {"sha": "base789abc012"}, } mock_client.generic.return_value = pr_response config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Using cached PR #12345" in caplog.text calls = list(mock_client.generic.call_args_list) assert len(calls) == 1 # Only PR check assert "pulls" in str(calls[0]) @pytest.mark.parametrize( ("cache_key"), [ ("old_head_sha:base789abc012"), ("abc123def456:old_base_sha"), ], ) async def test_pr_download_cache_invalidated( hass: HomeAssistant, tmp_path: Path, mock_github_api, aioclient_mock: AiohttpClientMocker, mock_zipfile, cache_key: str, ) -> None: """Test that cache is invalidated when head commit changes.""" hass.config.config_dir = str(tmp_path) pr_cache_dir = tmp_path / ".cache" / "frontend" / "development_artifacts" frontend_dir = pr_cache_dir / "hass_frontend" frontend_dir.mkdir(parents=True) (frontend_dir / "index.html").write_text("test") (pr_cache_dir / ".sha").write_text(cache_key) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() # Should download - head commit changed assert len(aioclient_mock.mock_calls) == 1 async def test_pr_download_cache_sha_read_error( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, mock_zipfile: MagicMock, caplog: pytest.LogCaptureFixture, ) -> None: """Test that cache SHA read errors are handled gracefully.""" hass.config.config_dir = str(tmp_path) pr_cache_dir = tmp_path / ".cache" / "frontend" / "development_artifacts" frontend_dir = pr_cache_dir / "hass_frontend" frontend_dir.mkdir(parents=True) (frontend_dir / "index.html").write_text("test") sha_file = pr_cache_dir / ".sha" sha_file.write_text("abc123def456") sha_file.chmod(0o000) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) try: config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert len(aioclient_mock.mock_calls) == 1 assert "Failed to read cache SHA file" in caplog.text finally: sha_file.chmod(0o644) async def test_pr_download_session_error( hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling of session creation errors.""" hass.config.config_dir = str(tmp_path) with patch( "homeassistant.components.frontend.pr_download.async_get_clientsession", side_effect=RuntimeError("Session error"), ): config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text @pytest.mark.parametrize( ("exc", "error_message"), [ (GitHubAuthenticationException("Unauthorized"), "invalid or expired"), (GitHubRatelimitException("Rate limit exceeded"), "rate limit"), (GitHubPermissionException("Forbidden"), "rate limit"), (GitHubNotFoundException("Not found"), "does not exist"), (GitHubException("API error"), "api error"), ], ) async def test_pr_download_github_errors( hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture, exc: Exception, error_message: str, ) -> None: """Test handling of various GitHub API errors.""" hass.config.config_dir = str(tmp_path) with patch( "homeassistant.components.frontend.pr_download.GitHubAPI" ) as mock_gh_class: mock_client = AsyncMock() mock_gh_class.return_value = mock_client mock_client.generic.side_effect = exc config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert error_message in caplog.text.lower() assert "Failed to download PR #12345" in caplog.text @pytest.mark.parametrize( ("exc", "error_message"), [ (GitHubAuthenticationException("Unauthorized"), "invalid or expired"), (GitHubRatelimitException("Rate limit exceeded"), "rate limit"), (GitHubPermissionException("Forbidden"), "rate limit"), (GitHubException("API error"), "api error"), ], ) async def test_pr_download_artifact_search_github_errors( hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture, exc: Exception, error_message: str, ) -> None: """Test handling of GitHub API errors during artifact search.""" hass.config.config_dir = str(tmp_path) with patch( "homeassistant.components.frontend.pr_download.GitHubAPI" ) as mock_gh_class: mock_client = AsyncMock() mock_gh_class.return_value = mock_client pr_response = AsyncMock() pr_response.data = { "head": {"sha": "abc123def456"}, "base": {"sha": "base789abc012"}, } async def generic_side_effect(endpoint, **_kwargs): if "pulls" in endpoint: return pr_response raise exc mock_client.generic.side_effect = generic_side_effect config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert error_message in caplog.text.lower() assert "Failed to download PR #12345" in caplog.text async def test_pr_download_artifact_not_found( hass: HomeAssistant, tmp_path: Path, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling when artifact is not found.""" hass.config.config_dir = str(tmp_path) with patch( "homeassistant.components.frontend.pr_download.GitHubAPI" ) as mock_gh_class: mock_client = AsyncMock() mock_gh_class.return_value = mock_client pr_response = AsyncMock() pr_response.data = { "head": {"sha": "abc123def456"}, "base": {"sha": "base789abc012"}, } workflow_response = AsyncMock() workflow_response.data = {"workflow_runs": []} async def generic_side_effect(endpoint, **kwargs): if "pulls" in endpoint: return pr_response if "workflows" in endpoint: return workflow_response raise ValueError(f"Unexpected endpoint: {endpoint}") mock_client.generic.side_effect = generic_side_effect config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "No 'frontend-build' artifact found" in caplog.text async def test_pr_download_http_error( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling of HTTP download errors.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", exc=ClientError("Download failed"), ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text @pytest.mark.parametrize( ("status", "error_message"), [ (401, "invalid or expired"), (403, "rate limit"), (500, "http 500"), ], ) async def test_pr_download_http_status_errors( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, status: int, error_message: str, ) -> None: """Test handling of HTTP status errors during artifact download.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", status=status, ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert error_message in caplog.text.lower() assert "Failed to download PR #12345" in caplog.text async def test_pr_download_timeout_error( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling of timeout during artifact download.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", exc=TimeoutError("Connection timed out"), ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "timeout" in caplog.text.lower() assert "Failed to download PR #12345" in caplog.text async def test_pr_download_bad_zip_file( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling of corrupted zip file.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"not a valid zip file", ) config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text assert "corrupted or invalid" in caplog.text.lower() async def test_pr_download_zip_bomb_too_many_files( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test that zip bombs with too many files are rejected.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) with patch("zipfile.ZipFile") as mock_zip: mock_zip_instance = MagicMock() mock_info = MagicMock() mock_info.file_size = 100 mock_zip_instance.infolist.return_value = [mock_info] * 55000 mock_zip.return_value.__enter__.return_value = mock_zip_instance config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text assert "too many files" in caplog.text.lower() async def test_pr_download_zip_bomb_too_large( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test that zip bombs with excessive uncompressed size are rejected.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) with patch("zipfile.ZipFile") as mock_zip: mock_zip_instance = MagicMock() mock_info = MagicMock() mock_info.file_size = 2 * 1024 * 1024 * 1024 # 2GB per file mock_zip_instance.infolist.return_value = [mock_info] mock_zip.return_value.__enter__.return_value = mock_zip_instance config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text assert "too large" in caplog.text.lower() async def test_pr_download_extraction_os_error( hass: HomeAssistant, tmp_path: Path, mock_github_api: AsyncMock, aioclient_mock: AiohttpClientMocker, caplog: pytest.LogCaptureFixture, ) -> None: """Test handling of OS errors during extraction.""" hass.config.config_dir = str(tmp_path) aioclient_mock.get( "https://api.github.com/artifact/download", content=b"fake zip data", ) with patch("zipfile.ZipFile") as mock_zip: mock_zip_instance = MagicMock() mock_info = MagicMock() mock_info.file_size = 100 mock_zip_instance.infolist.return_value = [mock_info] mock_zip_instance.extractall.side_effect = OSError("Disk full") mock_zip.return_value.__enter__.return_value = mock_zip_instance config = { DOMAIN: { "development_pr": 12345, "github_token": "test_token", } } assert await async_setup_component(hass, DOMAIN, config) await hass.async_block_till_done() assert "Failed to download PR #12345" in caplog.text assert "failed to extract" in caplog.text.lower()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/frontend/test_pr_download.py", "license": "Apache License 2.0", "lines": 466, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/liebherr/number.py
"""Number platform for Liebherr integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING from pyliebherrhomeapi import TemperatureControl, TemperatureUnit from homeassistant.components.number import ( DEFAULT_MAX_VALUE, DEFAULT_MIN_VALUE, NumberDeviceClass, NumberEntity, NumberEntityDescription, ) from homeassistant.const import UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import LiebherrConfigEntry, LiebherrCoordinator from .entity import LiebherrZoneEntity PARALLEL_UPDATES = 1 @dataclass(frozen=True, kw_only=True) class LiebherrNumberEntityDescription(NumberEntityDescription): """Describes Liebherr number entity.""" value_fn: Callable[[TemperatureControl], float | None] min_fn: Callable[[TemperatureControl], float | None] max_fn: Callable[[TemperatureControl], float | None] unit_fn: Callable[[TemperatureControl], str] NUMBER_TYPES: tuple[LiebherrNumberEntityDescription, ...] = ( LiebherrNumberEntityDescription( key="setpoint_temperature", translation_key="setpoint_temperature", device_class=NumberDeviceClass.TEMPERATURE, native_step=1, value_fn=lambda control: control.target, min_fn=lambda control: control.min, max_fn=lambda control: control.max, unit_fn=lambda control: ( UnitOfTemperature.FAHRENHEIT if control.unit == TemperatureUnit.FAHRENHEIT else UnitOfTemperature.CELSIUS ), ), ) def _create_number_entities( coordinators: list[LiebherrCoordinator], ) -> list[LiebherrNumber]: """Create number entities for the given coordinators.""" return [ LiebherrNumber( coordinator=coordinator, zone_id=temp_control.zone_id, description=description, ) for coordinator in coordinators for temp_control in coordinator.data.get_temperature_controls().values() for description in NUMBER_TYPES ] async def async_setup_entry( hass: HomeAssistant, entry: LiebherrConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Liebherr number entities.""" async_add_entities( _create_number_entities(list(entry.runtime_data.coordinators.values())) ) @callback def _async_new_device(coordinators: list[LiebherrCoordinator]) -> None: """Add number entities for new devices.""" async_add_entities(_create_number_entities(coordinators)) entry.async_on_unload( async_dispatcher_connect( hass, f"{DOMAIN}_new_device_{entry.entry_id}", _async_new_device ) ) class LiebherrNumber(LiebherrZoneEntity, NumberEntity): """Representation of a Liebherr number entity.""" entity_description: LiebherrNumberEntityDescription def __init__( self, coordinator: LiebherrCoordinator, zone_id: int, description: LiebherrNumberEntityDescription, ) -> None: """Initialize the number entity.""" super().__init__(coordinator, zone_id) self.entity_description = description self._attr_unique_id = f"{coordinator.device_id}_{description.key}_{zone_id}" # If device has only one zone, use translation key without zone suffix temp_controls = coordinator.data.get_temperature_controls() if len(temp_controls) > 1 and (zone_key := self._get_zone_translation_key()): self._attr_translation_key = f"{description.translation_key}_{zone_key}" @property def native_unit_of_measurement(self) -> str | None: """Return the unit of measurement.""" if (temp_control := self.temperature_control) is None: return None return self.entity_description.unit_fn(temp_control) @property def native_value(self) -> float | None: """Return the current value.""" if TYPE_CHECKING: assert self.temperature_control is not None return self.entity_description.value_fn(self.temperature_control) @property def native_min_value(self) -> float: """Return the minimum value.""" if (temp_control := self.temperature_control) is None: return DEFAULT_MIN_VALUE if (min_val := self.entity_description.min_fn(temp_control)) is None: return DEFAULT_MIN_VALUE return min_val @property def native_max_value(self) -> float: """Return the maximum value.""" if (temp_control := self.temperature_control) is None: return DEFAULT_MAX_VALUE if (max_val := self.entity_description.max_fn(temp_control)) is None: return DEFAULT_MAX_VALUE return max_val @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.temperature_control is not None async def async_set_native_value(self, value: float) -> None: """Set new value.""" if TYPE_CHECKING: assert self.temperature_control is not None temp_control = self.temperature_control unit = ( TemperatureUnit.FAHRENHEIT if temp_control.unit == TemperatureUnit.FAHRENHEIT else TemperatureUnit.CELSIUS ) await self._async_send_command( self.coordinator.client.set_temperature( device_id=self.coordinator.device_id, zone_id=self._zone_id, target=int(value), unit=unit, ), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/number.py", "license": "Apache License 2.0", "lines": 143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/liebherr/test_number.py
"""Test the Liebherr number platform.""" import copy from datetime import timedelta from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory from pyliebherrhomeapi import ( Device, DeviceState, DeviceType, TemperatureControl, TemperatureUnit, ZonePosition, ) from pyliebherrhomeapi.exceptions import LiebherrConnectionError import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.number import ( ATTR_VALUE, DEFAULT_MAX_VALUE, DEFAULT_MIN_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from .conftest import MOCK_DEVICE from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.NUMBER] @pytest.fixture(autouse=True) def enable_all_entities(entity_registry_enabled_by_default: None) -> None: """Make sure all entities are enabled.""" @pytest.mark.usefixtures("init_integration") async def test_numbers( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test all number entities with multi-zone device.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_single_zone_number( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, platforms: list[Platform], ) -> None: """Test single zone device uses device name without zone suffix.""" device = Device( device_id="single_zone_id", nickname="Single Zone Fridge", device_type=DeviceType.FRIDGE, device_name="K2601", ) mock_liebherr_client.get_devices.return_value = [device] single_zone_state = DeviceState( device=device, controls=[ TemperatureControl( zone_id=1, zone_position=ZonePosition.TOP, name="Fridge", type="fridge", value=4, target=4, min=2, max=8, unit=TemperatureUnit.CELSIUS, ) ], ) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( single_zone_state ) mock_config_entry.add_to_hass(hass) with patch("homeassistant.components.liebherr.PLATFORMS", platforms): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("init_integration") async def test_set_temperature( hass: HomeAssistant, mock_liebherr_client: MagicMock, ) -> None: """Test setting the temperature.""" entity_id = "number.test_fridge_top_zone_setpoint" initial_call_count = mock_liebherr_client.get_device_state.call_count await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, {ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 6}, blocking=True, ) mock_liebherr_client.set_temperature.assert_called_once_with( device_id="test_device_id", zone_id=1, target=6, unit=TemperatureUnit.CELSIUS, ) # Verify coordinator refresh was triggered assert mock_liebherr_client.get_device_state.call_count > initial_call_count @pytest.mark.usefixtures("init_integration") async def test_set_temperature_failure( hass: HomeAssistant, mock_liebherr_client: MagicMock, ) -> None: """Test setting temperature fails gracefully.""" entity_id = "number.test_fridge_top_zone_setpoint" mock_liebherr_client.set_temperature.side_effect = LiebherrConnectionError( "Connection failed" ) with pytest.raises( HomeAssistantError, match="An error occurred while communicating with the device", ): await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, {ATTR_ENTITY_ID: entity_id, ATTR_VALUE: 6}, blocking=True, ) @pytest.mark.usefixtures("init_integration") async def test_number_when_control_missing( hass: HomeAssistant, mock_liebherr_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test number entity behavior when temperature control is removed.""" entity_id = "number.test_fridge_top_zone_setpoint" # Initial values should be from the control state = hass.states.get(entity_id) assert state is not None assert state.state == "4" assert state.attributes["min"] == 2 assert state.attributes["max"] == 8 assert state.attributes["unit_of_measurement"] == "°C" # Device stops reporting controls mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: DeviceState( device=MOCK_DEVICE, controls=[] ) # Advance time to trigger coordinator refresh freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # State should be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE async def test_number_with_none_min_max( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, platforms: list[Platform], ) -> None: """Test number entity returns defaults when control has None min/max.""" device = Device( device_id="none_min_max_device", nickname="Test Fridge", device_type=DeviceType.FRIDGE, device_name="K2601", ) mock_liebherr_client.get_devices.return_value = [device] none_min_max_state = DeviceState( device=device, controls=[ TemperatureControl( zone_id=1, zone_position=ZonePosition.TOP, name="Fridge", type="fridge", value=4, target=4, min=None, # None min max=None, # None max unit=TemperatureUnit.CELSIUS, ) ], ) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( none_min_max_state ) mock_config_entry.add_to_hass(hass) with patch("homeassistant.components.liebherr.PLATFORMS", platforms): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() entity_id = "number.test_fridge_setpoint" state = hass.states.get(entity_id) assert state is not None # Should return defaults when min/max are None assert state.attributes["min"] == DEFAULT_MIN_VALUE assert state.attributes["max"] == DEFAULT_MAX_VALUE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_number.py", "license": "Apache License 2.0", "lines": 197, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/bond/services.py
"""Support for Bond services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.fan import DOMAIN as FAN_DOMAIN from homeassistant.components.light import ATTR_BRIGHTNESS, DOMAIN as LIGHT_DOMAIN from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN ATTR_POWER_STATE = "power_state" # Fan SERVICE_SET_FAN_SPEED_TRACKED_STATE = "set_fan_speed_tracked_state" # Switch SERVICE_SET_POWER_TRACKED_STATE = "set_switch_power_tracked_state" # Light SERVICE_SET_LIGHT_POWER_TRACKED_STATE = "set_light_power_tracked_state" SERVICE_SET_LIGHT_BRIGHTNESS_TRACKED_STATE = "set_light_brightness_tracked_state" SERVICE_START_INCREASING_BRIGHTNESS = "start_increasing_brightness" SERVICE_START_DECREASING_BRIGHTNESS = "start_decreasing_brightness" SERVICE_STOP = "stop" @callback def async_setup_services(hass: HomeAssistant) -> None: """Home Assistant services.""" # Fan entity services service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_FAN_SPEED_TRACKED_STATE, entity_domain=FAN_DOMAIN, schema={vol.Required("speed"): vol.All(vol.Number(scale=0), vol.Range(0, 100))}, func="async_set_speed_belief", ) # Light entity services service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_START_INCREASING_BRIGHTNESS, entity_domain=LIGHT_DOMAIN, schema=None, func="async_start_increasing_brightness", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_START_DECREASING_BRIGHTNESS, entity_domain=LIGHT_DOMAIN, schema=None, func="async_start_decreasing_brightness", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_STOP, entity_domain=LIGHT_DOMAIN, schema=None, func="async_stop", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_LIGHT_BRIGHTNESS_TRACKED_STATE, entity_domain=LIGHT_DOMAIN, schema={ vol.Required(ATTR_BRIGHTNESS): vol.All( vol.Number(scale=0), vol.Range(0, 255) ) }, func="async_set_brightness_belief", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_LIGHT_POWER_TRACKED_STATE, entity_domain=LIGHT_DOMAIN, schema={vol.Required(ATTR_POWER_STATE): vol.All(cv.boolean)}, func="async_set_power_belief", ) # Switch entity services service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_POWER_TRACKED_STATE, entity_domain=SWITCH_DOMAIN, schema={vol.Required(ATTR_POWER_STATE): cv.boolean}, func="async_set_power_belief", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bond/services.py", "license": "Apache License 2.0", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/rainbird/services.py
"""Rain Bird Irrigation system services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.typing import VolDictType from .const import ATTR_DURATION, DOMAIN SERVICE_START_IRRIGATION = "start_irrigation" SERVICE_SCHEMA_IRRIGATION: VolDictType = { vol.Required(ATTR_DURATION): cv.positive_float, } @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_START_IRRIGATION, entity_domain=SWITCH_DOMAIN, schema=SERVICE_SCHEMA_IRRIGATION, func="async_turn_on", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/rainbird/services.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/webostv/services.py
"""LG webOS TV services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.const import ATTR_COMMAND from homeassistant.core import HomeAssistant, SupportsResponse, callback from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.typing import VolDictType from .const import ATTR_PAYLOAD, ATTR_SOUND_OUTPUT, DOMAIN ATTR_BUTTON = "button" SERVICE_BUTTON = "button" SERVICE_COMMAND = "command" SERVICE_SELECT_SOUND_OUTPUT = "select_sound_output" BUTTON_SCHEMA: VolDictType = {vol.Required(ATTR_BUTTON): cv.string} COMMAND_SCHEMA: VolDictType = { vol.Required(ATTR_COMMAND): cv.string, vol.Optional(ATTR_PAYLOAD): dict, } SOUND_OUTPUT_SCHEMA: VolDictType = {vol.Required(ATTR_SOUND_OUTPUT): cv.string} SERVICES = ( ( SERVICE_BUTTON, BUTTON_SCHEMA, "async_button", SupportsResponse.NONE, ), ( SERVICE_COMMAND, COMMAND_SCHEMA, "async_command", SupportsResponse.OPTIONAL, ), ( SERVICE_SELECT_SOUND_OUTPUT, SOUND_OUTPUT_SCHEMA, "async_select_sound_output", SupportsResponse.OPTIONAL, ), ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" for service_name, schema, method, supports_response in SERVICES: service.async_register_platform_entity_service( hass, DOMAIN, service_name, entity_domain=MEDIA_PLAYER_DOMAIN, schema=schema, func=method, supports_response=supports_response, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/webostv/services.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/husqvarna_automower/services.py
"""Husqvarna Automower services.""" from datetime import timedelta import voluptuous as vol from homeassistant.components.lawn_mower import DOMAIN as LAWN_MOWER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN, MOW, PARK OVERRIDE_MODES = [MOW, PARK] @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, "override_schedule", entity_domain=LAWN_MOWER_DOMAIN, schema={ vol.Required("override_mode"): vol.In(OVERRIDE_MODES), vol.Required("duration"): vol.All( cv.time_period, cv.positive_timedelta, vol.Range(min=timedelta(minutes=1), max=timedelta(days=42)), ), }, func="async_override_schedule", ) service.async_register_platform_entity_service( hass, DOMAIN, "override_schedule_work_area", entity_domain=LAWN_MOWER_DOMAIN, schema={ vol.Required("work_area_id"): vol.Coerce(int), vol.Required("duration"): vol.All( cv.time_period, cv.positive_timedelta, vol.Range(min=timedelta(minutes=1), max=timedelta(days=42)), ), }, func="async_override_schedule_work_area", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/husqvarna_automower/services.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/litterrobot/services.py
"""Litter-Robot services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_SET_SLEEP_MODE = "set_sleep_mode" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_SET_SLEEP_MODE, entity_domain=VACUUM_DOMAIN, schema={ vol.Required("enabled"): cv.boolean, vol.Optional("start_time"): cv.time, }, func="async_set_sleep_mode", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/litterrobot/services.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/roborock/services.py
"""Roborock services.""" import voluptuous as vol from homeassistant.components.vacuum import DOMAIN as VACUUM_DOMAIN from homeassistant.core import HomeAssistant, SupportsResponse, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN GET_MAPS_SERVICE_NAME = "get_maps" SET_VACUUM_GOTO_POSITION_SERVICE_NAME = "set_vacuum_goto_position" GET_VACUUM_CURRENT_POSITION_SERVICE_NAME = "get_vacuum_current_position" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, GET_MAPS_SERVICE_NAME, entity_domain=VACUUM_DOMAIN, schema=None, func="get_maps", supports_response=SupportsResponse.ONLY, ) service.async_register_platform_entity_service( hass, DOMAIN, GET_VACUUM_CURRENT_POSITION_SERVICE_NAME, entity_domain=VACUUM_DOMAIN, schema=None, func="get_vacuum_current_position", supports_response=SupportsResponse.ONLY, ) service.async_register_platform_entity_service( hass, DOMAIN, SET_VACUUM_GOTO_POSITION_SERVICE_NAME, entity_domain=VACUUM_DOMAIN, schema=cv.make_entity_service_schema( { vol.Required("x"): vol.Coerce(int), vol.Required("y"): vol.Coerce(int), }, ), func="async_set_vacuum_goto_position", supports_response=SupportsResponse.NONE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/roborock/services.py", "license": "Apache License 2.0", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/elgato/services.py
"""Support for Elgato services.""" from __future__ import annotations from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import service from .const import DOMAIN SERVICE_IDENTIFY = "identify" @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_IDENTIFY, entity_domain=LIGHT_DOMAIN, schema=None, func="async_identify", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/elgato/services.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/alarmdecoder/services.py
"""Support for AlarmDecoder-based alarm control panels (Honeywell/DSC).""" from __future__ import annotations import voluptuous as vol from homeassistant.components.alarm_control_panel import ( DOMAIN as ALARM_CONTROL_PANEL_DOMAIN, ) from homeassistant.const import ATTR_CODE from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN ATTR_KEYPRESS = "keypress" @callback def async_setup_services(hass: HomeAssistant) -> None: """Home Assistant services.""" service.async_register_platform_entity_service( hass, DOMAIN, "alarm_toggle_chime", entity_domain=ALARM_CONTROL_PANEL_DOMAIN, schema={ vol.Required(ATTR_CODE): cv.string, }, func="alarm_toggle_chime", ) service.async_register_platform_entity_service( hass, DOMAIN, "alarm_keypress", entity_domain=ALARM_CONTROL_PANEL_DOMAIN, schema={ vol.Required(ATTR_KEYPRESS): cv.string, }, func="alarm_keypress", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/alarmdecoder/services.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/agent_dvr/services.py
"""Services for Agent DVR.""" from __future__ import annotations from homeassistant.components.camera import DOMAIN as CAMERA_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import service from .const import DOMAIN CAMERA_SERVICES = { "enable_alerts": "async_enable_alerts", "disable_alerts": "async_disable_alerts", "start_recording": "async_start_recording", "stop_recording": "async_stop_recording", "snapshot": "async_snapshot", } @callback def async_setup_services(hass: HomeAssistant) -> None: """Home Assistant services.""" for service_name, method in CAMERA_SERVICES.items(): service.async_register_platform_entity_service( hass, DOMAIN, service_name, entity_domain=CAMERA_DOMAIN, schema=None, func=method, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/agent_dvr/services.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/bthome/repairs.py
"""Repairs for the BTHome integration.""" from __future__ import annotations from typing import Any from homeassistant import data_entry_flow from homeassistant.components.repairs import RepairsFlow from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from . import get_encryption_issue_id from .const import CONF_BINDKEY, DOMAIN class EncryptionRemovedRepairFlow(RepairsFlow): """Handle the repair flow when encryption is disabled.""" def __init__(self, entry_id: str, entry_title: str) -> None: """Initialize the repair flow.""" self._entry_id = entry_id self._entry_title = entry_title async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> data_entry_flow.FlowResult: """Handle the initial step of the repair flow.""" return await self.async_step_confirm() async def async_step_confirm( self, user_input: dict[str, Any] | None = None ) -> data_entry_flow.FlowResult: """Handle confirmation, remove the bindkey, and reload the entry.""" if user_input is not None: entry = self.hass.config_entries.async_get_entry(self._entry_id) if not entry: return self.async_abort(reason="entry_removed") new_data = {k: v for k, v in entry.data.items() if k != CONF_BINDKEY} self.hass.config_entries.async_update_entry(entry, data=new_data) ir.async_delete_issue( self.hass, DOMAIN, get_encryption_issue_id(self._entry_id) ) await self.hass.config_entries.async_reload(self._entry_id) return self.async_create_entry(data={}) return self.async_show_form( step_id="confirm", description_placeholders={"name": self._entry_title}, ) async def async_create_fix_flow( hass: HomeAssistant, issue_id: str, data: dict[str, Any] | None ) -> RepairsFlow: """Create the repair flow for removing the encryption key.""" if not data or "entry_id" not in data: raise ValueError("Missing data for repair flow") entry_id = data["entry_id"] entry = hass.config_entries.async_get_entry(entry_id) entry_title = entry.title if entry else "Unknown device" return EncryptionRemovedRepairFlow(entry_id, entry_title)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bthome/repairs.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/bthome/test_repairs.py
"""Tests for BTHome repair handling.""" from __future__ import annotations from collections.abc import Callable import logging from unittest.mock import patch import pytest from homeassistant.components.bluetooth import BluetoothChange from homeassistant.components.bthome import get_encryption_issue_id from homeassistant.components.bthome.const import CONF_BINDKEY, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from homeassistant.setup import async_setup_component from . import PRST_SERVICE_INFO, TEMP_HUMI_ENCRYPTED_SERVICE_INFO from tests.common import MockConfigEntry from tests.components.repairs import ( async_process_repairs_platforms, process_repair_fix_flow, start_repair_fix_flow, ) from tests.typing import ClientSessionGenerator BINDKEY = "231d39c1d7cc1ab1aee224cd096db932" async def _setup_entry( hass: HomeAssistant, ) -> tuple[MockConfigEntry, Callable[[object, BluetoothChange], None]]: """Set up a BTHome config entry and capture the Bluetooth callback.""" entry = MockConfigEntry( domain=DOMAIN, unique_id="54:48:E6:8F:80:A5", title="Test Device", data={CONF_BINDKEY: BINDKEY}, ) entry.add_to_hass(hass) saved_callback: Callable[[object, BluetoothChange], None] | None = None def _async_register_callback(_hass, _callback, _matcher, _mode): nonlocal saved_callback saved_callback = _callback return lambda: None with patch( "homeassistant.components.bluetooth.update_coordinator.async_register_callback", _async_register_callback, ): assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() assert saved_callback is not None return entry, saved_callback async def test_encryption_downgrade_creates_issue( hass: HomeAssistant, issue_registry: ir.IssueRegistry, ) -> None: """Test unencrypted payloads create a repair issue.""" entry, callback = await _setup_entry(hass) issue_id = get_encryption_issue_id(entry.entry_id) # Send encrypted data first to establish the device callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert issue_registry.async_get_issue(DOMAIN, issue_id) is None # Send unencrypted data - should create issue callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() issue = issue_registry.async_get_issue(DOMAIN, issue_id) assert issue is not None assert issue.data is not None assert issue.data["entry_id"] == entry.entry_id assert issue.is_fixable is True async def test_encryption_downgrade_warning_only_logged_once( hass: HomeAssistant, issue_registry: ir.IssueRegistry, caplog: pytest.LogCaptureFixture, ) -> None: """Test warning is only logged once per session.""" _, callback = await _setup_entry(hass) # Send encrypted data first callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() caplog.clear() # First unencrypted - should warn callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert ( sum( record.levelno == logging.WARNING and "unencrypted" in record.message for record in caplog.records ) == 1 ) caplog.clear() # Second unencrypted - should not warn again callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert not any( record.levelno == logging.WARNING and "unencrypted" in record.message for record in caplog.records ) async def test_issue_cleared_when_encryption_resumes( hass: HomeAssistant, issue_registry: ir.IssueRegistry, ) -> None: """Test issue is cleared when encrypted data resumes.""" entry, callback = await _setup_entry(hass) issue_id = get_encryption_issue_id(entry.entry_id) # Send encrypted, then unencrypted to create the issue callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None # Send encrypted data again - should clear issue callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert issue_registry.async_get_issue(DOMAIN, issue_id) is None async def test_repair_flow_removes_bindkey_and_reloads_entry( hass: HomeAssistant, hass_client: ClientSessionGenerator, issue_registry: ir.IssueRegistry, ) -> None: """Test the repair flow clears the bindkey and reloads the entry.""" entry, callback = await _setup_entry(hass) issue_id = get_encryption_issue_id(entry.entry_id) # Send encrypted, then unencrypted to create the issue callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None assert await async_setup_component(hass, "repairs", {}) await async_process_repairs_platforms(hass) http_client = await hass_client() # Start the repair flow data = await start_repair_fix_flow(http_client, DOMAIN, issue_id) flow_id = data["flow_id"] assert data["step_id"] == "confirm" # Confirm the repair data = await process_repair_fix_flow(http_client, flow_id, {}) assert data["type"] == "create_entry" # Verify bindkey was removed and issue cleared assert CONF_BINDKEY not in entry.data assert issue_registry.async_get_issue(DOMAIN, issue_id) is None async def test_repair_flow_aborts_when_entry_removed( hass: HomeAssistant, hass_client: ClientSessionGenerator, issue_registry: ir.IssueRegistry, ) -> None: """Test the repair flow aborts gracefully when entry is removed.""" entry, callback = await _setup_entry(hass) issue_id = get_encryption_issue_id(entry.entry_id) # Send encrypted, then unencrypted to create the issue callback(TEMP_HUMI_ENCRYPTED_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() callback(PRST_SERVICE_INFO, BluetoothChange.ADVERTISEMENT) await hass.async_block_till_done() assert issue_registry.async_get_issue(DOMAIN, issue_id) is not None assert await async_setup_component(hass, "repairs", {}) await async_process_repairs_platforms(hass) http_client = await hass_client() # Start the repair flow data = await start_repair_fix_flow(http_client, DOMAIN, issue_id) flow_id = data["flow_id"] assert data["step_id"] == "confirm" # Remove entry before confirming await hass.config_entries.async_remove(entry.entry_id) await hass.async_block_till_done() # Confirm the repair - should abort data = await process_repair_fix_flow(http_client, flow_id, {}) assert data["type"] == "abort" assert data["reason"] == "entry_removed"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/bthome/test_repairs.py", "license": "Apache License 2.0", "lines": 165, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/portainer/services.py
"""Services for the Portainer integration.""" from datetime import timedelta from pyportainer import ( PortainerAuthenticationError, PortainerConnectionError, PortainerTimeoutError, ) import voluptuous as vol from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.helpers.service import async_extract_config_entry_ids from .const import DOMAIN from .coordinator import PortainerConfigEntry ATTR_DATE_UNTIL = "until" ATTR_DANGLING = "dangling" SERVICE_PRUNE_IMAGES = "prune_images" SERVICE_PRUNE_IMAGES_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Optional(ATTR_DATE_UNTIL): vol.All( cv.time_period, vol.Range(min=timedelta(minutes=1)) ), vol.Optional(ATTR_DANGLING): cv.boolean, }, ) async def _extract_config_entry(service_call: ServiceCall) -> PortainerConfigEntry: """Extract config entry from the service call.""" target_entry_ids = await async_extract_config_entry_ids(service_call) target_entries: list[PortainerConfigEntry] = [ loaded_entry for loaded_entry in service_call.hass.config_entries.async_loaded_entries( DOMAIN ) if loaded_entry.entry_id in target_entry_ids ] if not target_entries: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_target", ) return target_entries[0] async def _get_endpoint_id( call: ServiceCall, config_entry: PortainerConfigEntry, ) -> int: """Get endpoint data from device ID.""" device_reg = dr.async_get(call.hass) device_id = call.data[ATTR_DEVICE_ID] device = device_reg.async_get(device_id) assert device coordinator = config_entry.runtime_data endpoint_data = None for data in coordinator.data.values(): if ( DOMAIN, f"{config_entry.entry_id}_{data.endpoint.id}", ) in device.identifiers: endpoint_data = data break assert endpoint_data return endpoint_data.endpoint.id async def prune_images(call: ServiceCall) -> None: """Prune unused images in Portainer, with more controls.""" config_entry = await _extract_config_entry(call) coordinator = config_entry.runtime_data endpoint_id = await _get_endpoint_id(call, config_entry) try: await coordinator.portainer.images_prune( endpoint_id=endpoint_id, until=call.data.get(ATTR_DATE_UNTIL), dangling=call.data.get(ATTR_DANGLING, False), ) except PortainerAuthenticationError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="invalid_auth_no_details", ) from err except PortainerConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect_no_details", ) from err except PortainerTimeoutError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="timeout_connect_no_details", ) from err async def async_setup_services(hass: HomeAssistant) -> None: """Set up services.""" hass.services.async_register( DOMAIN, SERVICE_PRUNE_IMAGES, prune_images, SERVICE_PRUNE_IMAGES_SCHEMA, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/portainer/services.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/portainer/test_services.py
"""Test for Portainer services.""" from datetime import timedelta from unittest.mock import AsyncMock from pyportainer import ( PortainerAuthenticationError, PortainerConnectionError, PortainerTimeoutError, ) import pytest from voluptuous import MultipleInvalid from homeassistant.components.portainer.const import DOMAIN from homeassistant.components.portainer.services import ( ATTR_DANGLING, ATTR_DATE_UNTIL, SERVICE_PRUNE_IMAGES, ) from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.device_registry import DeviceRegistry from . import setup_integration from .conftest import TEST_ENTRY from tests.common import MockConfigEntry TEST_ENDPOINT_ID = 1 TEST_DEVICE_IDENTIFIER = f"{TEST_ENTRY}_{TEST_ENDPOINT_ID}" async def test_services( hass: HomeAssistant, device_registry: DeviceRegistry, mock_portainer_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Tests that the services are correct.""" await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device( identifiers={(DOMAIN, TEST_DEVICE_IDENTIFIER)} ) assert device is not None await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, { ATTR_DEVICE_ID: device.id, ATTR_DATE_UNTIL: timedelta(hours=24), }, blocking=True, ) mock_portainer_client.images_prune.assert_called_once_with( endpoint_id=TEST_ENDPOINT_ID, until=timedelta(hours=24), dangling=False, ) @pytest.mark.parametrize( ("call_arguments", "expected_until", "expected_dangling"), [ ({}, None, False), ({ATTR_DATE_UNTIL: timedelta(hours=12)}, timedelta(hours=12), False), ( {ATTR_DATE_UNTIL: timedelta(hours=12), ATTR_DANGLING: True}, timedelta(hours=12), True, ), ], ids=["no optional", "with duration", "with duration and dangling"], ) async def test_service_prune_images( hass: HomeAssistant, device_registry: DeviceRegistry, mock_portainer_client: AsyncMock, mock_config_entry: MockConfigEntry, call_arguments: dict, expected_until: timedelta | None, expected_dangling: bool, ) -> None: """Test prune images service with the variants.""" await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device( identifiers={(DOMAIN, TEST_DEVICE_IDENTIFIER)} ) assert device is not None await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, {ATTR_DEVICE_ID: device.id, **call_arguments}, blocking=True, ) mock_portainer_client.images_prune.assert_called_once_with( endpoint_id=TEST_ENDPOINT_ID, until=expected_until, dangling=expected_dangling, ) async def test_service_validation_errors( hass: HomeAssistant, device_registry: DeviceRegistry, mock_portainer_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Tests that the Portainer services handle bad data.""" await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device( identifiers={(DOMAIN, TEST_DEVICE_IDENTIFIER)} ) assert device is not None # Test missing device_id with pytest.raises(MultipleInvalid, match="required key not provided"): await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, {}, blocking=True, ) mock_portainer_client.images_prune.assert_not_called() # Test invalid until (too short, needs to be at least 1 minute) with pytest.raises(MultipleInvalid, match="value must be at least"): await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, {ATTR_DEVICE_ID: device.id, ATTR_DATE_UNTIL: timedelta(seconds=30)}, blocking=True, ) mock_portainer_client.images_prune.assert_not_called() # Test invalid device with pytest.raises(ServiceValidationError, match="Invalid device targeted"): await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, {ATTR_DEVICE_ID: "invalid_device_id"}, blocking=True, ) mock_portainer_client.images_prune.assert_not_called() @pytest.mark.parametrize( ("exception", "message"), [ ( PortainerAuthenticationError("auth"), "An error occurred while trying to authenticate", ), ( PortainerConnectionError("conn"), "An error occurred while trying to connect to the Portainer instance", ), ( PortainerTimeoutError("timeout"), "A timeout occurred while trying to connect to the Portainer instance", ), ], ) async def test_service_portainer_exceptions( hass: HomeAssistant, device_registry: DeviceRegistry, mock_portainer_client: AsyncMock, mock_config_entry: MockConfigEntry, exception: HomeAssistantError, message: str, ) -> None: """Test service handles Portainer exceptions.""" await setup_integration(hass, mock_config_entry) device = device_registry.async_get_device( identifiers={(DOMAIN, TEST_DEVICE_IDENTIFIER)} ) mock_portainer_client.images_prune.side_effect = exception with pytest.raises(HomeAssistantError, match=message): await hass.services.async_call( DOMAIN, SERVICE_PRUNE_IMAGES, {ATTR_DEVICE_ID: device.id}, blocking=True, ) mock_portainer_client.images_prune.assert_called_once()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/portainer/test_services.py", "license": "Apache License 2.0", "lines": 168, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/liebherr/config_flow.py
"""Config flow for the liebherr integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from pyliebherrhomeapi import LiebherrClient from pyliebherrhomeapi.exceptions import ( LiebherrAuthenticationError, LiebherrConnectionError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_KEY from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_API_KEY): str, } ) class LiebherrConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for liebherr.""" async def _validate_api_key(self, api_key: str) -> tuple[list, dict[str, str]]: """Validate the API key and return devices and errors.""" errors: dict[str, str] = {} devices: list = [] client = LiebherrClient( api_key=api_key, session=async_get_clientsession(self.hass), ) try: devices = await client.get_devices() except LiebherrAuthenticationError: errors["base"] = "invalid_auth" except LiebherrConnectionError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" return devices, errors async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: user_input[CONF_API_KEY] = user_input[CONF_API_KEY].strip() self._async_abort_entries_match({CONF_API_KEY: user_input[CONF_API_KEY]}) devices, errors = await self._validate_api_key(user_input[CONF_API_KEY]) if not errors: if not devices: return self.async_abort(reason="no_devices") return self.async_create_entry( title="Liebherr", data=user_input, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle re-authentication.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm re-authentication.""" errors: dict[str, str] = {} if user_input is not None: api_key = user_input[CONF_API_KEY].strip() _, errors = await self._validate_api_key(api_key) if not errors: return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates={CONF_API_KEY: api_key}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/config_flow.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/liebherr/const.py
"""Constants for the liebherr integration.""" from datetime import timedelta from typing import Final DOMAIN: Final = "liebherr" MANUFACTURER: Final = "Liebherr" SCAN_INTERVAL: Final = timedelta(seconds=60) DEVICE_SCAN_INTERVAL: Final = timedelta(minutes=5) REFRESH_DELAY: Final = timedelta(seconds=5)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/const.py", "license": "Apache License 2.0", "lines": 8, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/liebherr/coordinator.py
"""DataUpdateCoordinator for Liebherr integration.""" from __future__ import annotations from dataclasses import dataclass, field import logging from pyliebherrhomeapi import ( DeviceState, LiebherrAuthenticationError, LiebherrClient, LiebherrConnectionError, LiebherrTimeoutError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, SCAN_INTERVAL _LOGGER = logging.getLogger(__name__) @dataclass class LiebherrData: """Runtime data for the Liebherr integration.""" client: LiebherrClient coordinators: dict[str, LiebherrCoordinator] = field(default_factory=dict) type LiebherrConfigEntry = ConfigEntry[LiebherrData] class LiebherrCoordinator(DataUpdateCoordinator[DeviceState]): """Class to manage fetching Liebherr data from the API for a single device.""" def __init__( self, hass: HomeAssistant, config_entry: LiebherrConfigEntry, client: LiebherrClient, device_id: str, ) -> None: """Initialize coordinator.""" super().__init__( hass, logger=_LOGGER, name=f"{DOMAIN}_{device_id}", update_interval=SCAN_INTERVAL, config_entry=config_entry, ) self.client = client self.device_id = device_id async def _async_setup(self) -> None: """Set up the coordinator by validating device access.""" try: await self.client.get_device(self.device_id) except LiebherrAuthenticationError as err: raise ConfigEntryAuthFailed("Invalid API key") from err except LiebherrConnectionError as err: raise ConfigEntryNotReady( f"Failed to connect to device {self.device_id}: {err}" ) from err async def _async_update_data(self) -> DeviceState: """Fetch data from API for this device.""" try: return await self.client.get_device_state(self.device_id) except LiebherrAuthenticationError as err: raise ConfigEntryAuthFailed("API key is no longer valid") from err except LiebherrTimeoutError as err: raise UpdateFailed( f"Timeout communicating with device {self.device_id}" ) from err except LiebherrConnectionError as err: raise UpdateFailed( f"Error communicating with device {self.device_id}" ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/coordinator.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/liebherr/entity.py
"""Base entity for Liebherr integration.""" from __future__ import annotations import asyncio from collections.abc import Coroutine from typing import Any from pyliebherrhomeapi import ( LiebherrConnectionError, LiebherrTimeoutError, TemperatureControl, ZonePosition, ) from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER, REFRESH_DELAY from .coordinator import LiebherrCoordinator # Zone position to translation key mapping ZONE_POSITION_MAP = { ZonePosition.TOP: "top_zone", ZonePosition.MIDDLE: "middle_zone", ZonePosition.BOTTOM: "bottom_zone", } class LiebherrEntity(CoordinatorEntity[LiebherrCoordinator]): """Base entity for Liebherr devices.""" _attr_has_entity_name = True def __init__( self, coordinator: LiebherrCoordinator, ) -> None: """Initialize the Liebherr entity.""" super().__init__(coordinator) device = coordinator.data.device model = None if device.device_type: model = device.device_type.title() self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.device_id)}, name=device.nickname or device.device_name, manufacturer=MANUFACTURER, model=model, model_id=device.device_name, ) async def _async_send_command( self, command: Coroutine[Any, Any, None], ) -> None: """Send a command with error handling and delayed refresh.""" try: await command except (LiebherrConnectionError, LiebherrTimeoutError) as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from err await asyncio.sleep(REFRESH_DELAY.total_seconds()) await self.coordinator.async_request_refresh() class LiebherrZoneEntity(LiebherrEntity): """Base entity for zone-based Liebherr entities. This class should be used for entities that are associated with a specific temperature control zone (e.g., climate, zone sensors). """ def __init__( self, coordinator: LiebherrCoordinator, zone_id: int, ) -> None: """Initialize the zone entity.""" super().__init__(coordinator) self._zone_id = zone_id @property def temperature_control(self) -> TemperatureControl | None: """Get the temperature control for this zone.""" return self.coordinator.data.get_temperature_controls().get(self._zone_id) def _get_zone_translation_key(self) -> str | None: """Get the translation key for this zone.""" control = self.temperature_control if control and isinstance(control.zone_position, ZonePosition): return ZONE_POSITION_MAP.get(control.zone_position) # Fallback to None to use device model name return None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/entity.py", "license": "Apache License 2.0", "lines": 80, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/liebherr/sensor.py
"""Sensor platform for Liebherr integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from pyliebherrhomeapi import TemperatureControl, TemperatureUnit from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .const import DOMAIN from .coordinator import LiebherrConfigEntry, LiebherrCoordinator from .entity import LiebherrZoneEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class LiebherrSensorEntityDescription(SensorEntityDescription): """Describes Liebherr sensor entity.""" value_fn: Callable[[TemperatureControl], StateType] unit_fn: Callable[[TemperatureControl], str] SENSOR_TYPES: tuple[LiebherrSensorEntityDescription, ...] = ( LiebherrSensorEntityDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, value_fn=lambda control: control.value, unit_fn=lambda control: ( UnitOfTemperature.FAHRENHEIT if control.unit == TemperatureUnit.FAHRENHEIT else UnitOfTemperature.CELSIUS ), ), ) def _create_sensor_entities( coordinators: list[LiebherrCoordinator], ) -> list[LiebherrSensor]: """Create sensor entities for the given coordinators.""" return [ LiebherrSensor( coordinator=coordinator, zone_id=temp_control.zone_id, description=description, ) for coordinator in coordinators for temp_control in coordinator.data.get_temperature_controls().values() for description in SENSOR_TYPES ] async def async_setup_entry( hass: HomeAssistant, entry: LiebherrConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Liebherr sensor entities.""" async_add_entities( _create_sensor_entities(list(entry.runtime_data.coordinators.values())) ) @callback def _async_new_device(coordinators: list[LiebherrCoordinator]) -> None: """Add sensor entities for new devices.""" async_add_entities(_create_sensor_entities(coordinators)) entry.async_on_unload( async_dispatcher_connect( hass, f"{DOMAIN}_new_device_{entry.entry_id}", _async_new_device ) ) class LiebherrSensor(LiebherrZoneEntity, SensorEntity): """Representation of a Liebherr sensor.""" entity_description: LiebherrSensorEntityDescription def __init__( self, coordinator: LiebherrCoordinator, zone_id: int, description: LiebherrSensorEntityDescription, ) -> None: """Initialize the sensor entity.""" super().__init__(coordinator, zone_id) self.entity_description = description self._attr_unique_id = f"{coordinator.device_id}_{description.key}_{zone_id}" # If device has only one zone, use model name instead of zone name temp_controls = coordinator.data.get_temperature_controls() if len(temp_controls) == 1: self._attr_name = None else: # Set translation key based on zone position for multi-zone devices self._attr_translation_key = self._get_zone_translation_key() @property def native_unit_of_measurement(self) -> str | None: """Return the unit of measurement.""" if (temp_control := self.temperature_control) is None: return None return self.entity_description.unit_fn(temp_control) @property def native_value(self) -> StateType: """Return the current value.""" # temperature_control is guaranteed to exist when entity is available assert self.temperature_control is not None return self.entity_description.value_fn(self.temperature_control) @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.temperature_control is not None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/sensor.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/liebherr/test_config_flow.py
"""Test the liebherr config flow.""" from ipaddress import ip_address from unittest.mock import AsyncMock, MagicMock from pyliebherrhomeapi.exceptions import ( LiebherrAuthenticationError, LiebherrConnectionError, ) import pytest from homeassistant import config_entries from homeassistant.components.liebherr.const import DOMAIN from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from tests.common import MockConfigEntry MOCK_API_KEY = "test-api-key" MOCK_USER_INPUT = {CONF_API_KEY: MOCK_API_KEY} MOCK_ZEROCONF_SERVICE_INFO = ZeroconfServiceInfo( ip_address=ip_address("192.168.1.100"), ip_addresses=[ip_address("192.168.1.100")], port=80, hostname="liebherr-device.local.", type="_http._tcp.local.", name="liebherr-fridge._http._tcp.local.", properties={}, ) async def test_form( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_liebherr_client: MagicMock, ) -> None: """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "user" assert result.get("errors") == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.CREATE_ENTRY assert result.get("title") == "Liebherr" assert result.get("data") == MOCK_USER_INPUT assert len(mock_setup_entry.mock_calls) == 1 @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (LiebherrAuthenticationError("Invalid"), "invalid_auth"), (LiebherrConnectionError("Failed"), "cannot_connect"), (Exception("Unexpected"), "unknown"), ], ) async def test_form_errors_with_recovery( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_liebherr_client: MagicMock, side_effect: Exception, expected_error: str, ) -> None: """Test error handling with successful recovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") is FlowResultType.FORM assert result.get("errors") == {} # Trigger error mock_liebherr_client.get_devices.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.FORM assert result.get("errors") == {"base": expected_error} # Recover and complete successfully mock_liebherr_client.get_devices.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.CREATE_ENTRY assert result.get("title") == "Liebherr" assert result.get("data") == MOCK_USER_INPUT async def test_form_no_devices( hass: HomeAssistant, mock_liebherr_client: MagicMock, ) -> None: """Test we handle no devices found.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") is FlowResultType.FORM mock_liebherr_client.get_devices.return_value = [] result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "no_devices" async def test_form_already_configured( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test we abort if already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" async def test_zeroconf_discovery( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_liebherr_client: MagicMock, ) -> None: """Test zeroconf discovery triggers the config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=MOCK_ZEROCONF_SERVICE_INFO, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], MOCK_USER_INPUT ) assert result.get("type") is FlowResultType.CREATE_ENTRY assert result.get("title") == "Liebherr" assert result.get("data") == MOCK_USER_INPUT async def test_zeroconf_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test zeroconf discovery aborts if already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_ZEROCONF}, data=MOCK_ZEROCONF_SERVICE_INFO, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" async def test_reauth_flow( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reauth flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "reauth_confirm" new_api_key = "new-api-key" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: new_api_key} ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "reauth_successful" assert mock_config_entry.data[CONF_API_KEY] == new_api_key @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (LiebherrAuthenticationError("Invalid"), "invalid_auth"), (LiebherrConnectionError("Failed"), "cannot_connect"), (Exception("Unexpected"), "unknown"), ], ) async def test_reauth_flow_errors_with_recovery( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, side_effect: Exception, expected_error: str, ) -> None: """Test reauth flow error handling with successful recovery.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "reauth_confirm" # Trigger error mock_liebherr_client.get_devices.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: "new-api-key"} ) assert result.get("type") is FlowResultType.FORM assert result.get("errors") == {"base": expected_error} # Recover and complete successfully mock_liebherr_client.get_devices.side_effect = None new_api_key = "new-api-key-recovered" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_API_KEY: new_api_key} ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "reauth_successful" assert mock_config_entry.data[CONF_API_KEY] == new_api_key
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_config_flow.py", "license": "Apache License 2.0", "lines": 199, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/liebherr/test_init.py
"""Test the liebherr integration init.""" import copy from datetime import timedelta from typing import Any from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory from pyliebherrhomeapi import ( Device, DeviceState, DeviceType, IceMakerControl, IceMakerMode, TemperatureControl, TemperatureUnit, ToggleControl, ZonePosition, ) from pyliebherrhomeapi.exceptions import ( LiebherrAuthenticationError, LiebherrConnectionError, ) import pytest from homeassistant.components.liebherr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import Platform from homeassistant.core import HomeAssistant from .conftest import MOCK_DEVICE, MOCK_DEVICE_STATE from tests.common import MockConfigEntry, async_fire_time_changed # Test errors during initial get_devices() call in async_setup_entry @pytest.mark.parametrize( ("side_effect", "expected_state"), [ (LiebherrAuthenticationError("Invalid API key"), ConfigEntryState.SETUP_ERROR), (LiebherrConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY), ], ids=["auth_failed", "connection_error"], ) async def test_setup_entry_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_liebherr_client: MagicMock, side_effect: Any, expected_state: ConfigEntryState, ) -> None: """Test setup handles various error conditions.""" mock_config_entry.add_to_hass(hass) mock_liebherr_client.get_devices.side_effect = side_effect await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is expected_state # Test errors during get_device() call in coordinator setup (after successful get_devices) @pytest.mark.parametrize( ("side_effect", "expected_state"), [ (LiebherrAuthenticationError("Invalid API key"), ConfigEntryState.SETUP_ERROR), (LiebherrConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY), ], ids=["auth_failed", "connection_error"], ) async def test_coordinator_setup_errors( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_liebherr_client: MagicMock, side_effect: Exception, expected_state: ConfigEntryState, ) -> None: """Test coordinator setup handles device access errors.""" mock_config_entry.add_to_hass(hass) mock_liebherr_client.get_devices.return_value = [MOCK_DEVICE] mock_liebherr_client.get_device.side_effect = side_effect await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is expected_state async def test_unload_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_liebherr_client: MagicMock, ) -> None: """Test successful unload of entry.""" 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 ConfigEntryState.LOADED 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 NEW_DEVICE = Device( device_id="new_device_id", nickname="New Fridge", device_type=DeviceType.FRIDGE, device_name="K2601", ) NEW_DEVICE_STATE = DeviceState( device=NEW_DEVICE, controls=[ TemperatureControl( zone_id=1, zone_position=ZonePosition.TOP, name="Fridge", type="fridge", value=4, target=5, min=2, max=8, unit=TemperatureUnit.CELSIUS, ), ToggleControl( name="supercool", type="ToggleControl", zone_id=1, zone_position=ZonePosition.TOP, value=False, ), IceMakerControl( name="icemaker", type="IceMakerControl", zone_id=1, zone_position=ZonePosition.TOP, ice_maker_mode=IceMakerMode.OFF, has_max_ice=False, ), ], ) @pytest.mark.usefixtures("init_integration") async def test_dynamic_device_discovery_no_new_devices( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test device scan with no new devices does not create entities.""" # Same devices returned mock_liebherr_client.get_devices.return_value = [MOCK_DEVICE] initial_states = len(hass.states.async_all()) freezer.tick(timedelta(minutes=5, seconds=1)) async_fire_time_changed(hass) await hass.async_block_till_done() # No new entities should be created assert len(hass.states.async_all()) == initial_states @pytest.mark.usefixtures("init_integration") @pytest.mark.parametrize( "exception", [ LiebherrConnectionError("Connection failed"), LiebherrAuthenticationError("Auth failed"), ], ids=["connection_error", "auth_error"], ) async def test_dynamic_device_discovery_api_error( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, exception: Exception, ) -> None: """Test device scan gracefully handles API errors.""" mock_liebherr_client.get_devices.side_effect = exception initial_states = len(hass.states.async_all()) freezer.tick(timedelta(minutes=5, seconds=1)) async_fire_time_changed(hass) await hass.async_block_till_done() # No crash, no new entities assert len(hass.states.async_all()) == initial_states assert mock_config_entry.state is ConfigEntryState.LOADED @pytest.mark.usefixtures("init_integration") async def test_dynamic_device_discovery_coordinator_setup_failure( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test device scan skips devices that fail coordinator setup.""" # New device appears but its state fetch fails mock_liebherr_client.get_devices.return_value = [MOCK_DEVICE, NEW_DEVICE] original_state = copy.deepcopy(MOCK_DEVICE_STATE) mock_liebherr_client.get_device_state.side_effect = lambda device_id, **kw: ( copy.deepcopy(original_state) if device_id == "test_device_id" else (_ for _ in ()).throw(LiebherrConnectionError("Device offline")) ) freezer.tick(timedelta(minutes=5, seconds=1)) async_fire_time_changed(hass) await hass.async_block_till_done() # New device should NOT be added assert "new_device_id" not in mock_config_entry.runtime_data.coordinators assert mock_config_entry.state is ConfigEntryState.LOADED async def test_dynamic_device_discovery( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_liebherr_client: MagicMock, freezer: FrozenDateTimeFactory, ) -> None: """Test new devices are automatically discovered on all platforms.""" mock_config_entry.add_to_hass(hass) all_platforms = [ Platform.SENSOR, Platform.NUMBER, Platform.SWITCH, Platform.SELECT, ] with patch(f"homeassistant.components.{DOMAIN}.PLATFORMS", all_platforms): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Initially only the original device exists assert hass.states.get("sensor.test_fridge_top_zone") is not None assert hass.states.get("sensor.new_fridge") is None # Simulate a new device appearing on the account mock_liebherr_client.get_devices.return_value = [MOCK_DEVICE, NEW_DEVICE] mock_liebherr_client.get_device_state.side_effect = lambda device_id, **kw: ( copy.deepcopy( NEW_DEVICE_STATE if device_id == "new_device_id" else MOCK_DEVICE_STATE ) ) # Advance time to trigger device scan (5 minute interval) freezer.tick(timedelta(minutes=5, seconds=1)) async_fire_time_changed(hass) await hass.async_block_till_done() # New device should have entities on all platforms state = hass.states.get("sensor.new_fridge") assert state is not None assert state.state == "4" assert hass.states.get("number.new_fridge_setpoint") is not None assert hass.states.get("switch.new_fridge_supercool") is not None assert hass.states.get("select.new_fridge_icemaker") is not None # Original device should still exist assert hass.states.get("sensor.test_fridge_top_zone") is not None # Runtime data should have both coordinators assert "new_device_id" in mock_config_entry.runtime_data.coordinators assert "test_device_id" in mock_config_entry.runtime_data.coordinators
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_init.py", "license": "Apache License 2.0", "lines": 229, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/liebherr/test_sensor.py
"""Test the Liebherr sensor platform.""" import copy from datetime import timedelta from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory from pyliebherrhomeapi import ( Device, DeviceState, DeviceType, TemperatureControl, TemperatureUnit, ZonePosition, ) from pyliebherrhomeapi.exceptions import ( LiebherrAuthenticationError, LiebherrConnectionError, LiebherrTimeoutError, ) import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.liebherr.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .conftest import MOCK_DEVICE, MOCK_DEVICE_STATE from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_sensors( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test all sensor entities with multi-zone device.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_single_zone_sensor( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, platforms: list[Platform], ) -> None: """Test single zone device uses device name without zone suffix.""" device = Device( device_id="single_zone_id", nickname="Single Zone Fridge", device_type=DeviceType.FRIDGE, device_name="K2601", ) mock_liebherr_client.get_devices.return_value = [device] single_zone_state = DeviceState( device=device, controls=[ TemperatureControl( zone_id=1, zone_position=ZonePosition.TOP, name="Fridge", type="fridge", value=4, unit=TemperatureUnit.CELSIUS, ) ], ) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( single_zone_state ) mock_config_entry.add_to_hass(hass) with patch("homeassistant.components.liebherr.PLATFORMS", platforms): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_multi_zone_with_none_position( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: """Test multi-zone device with None zone_position falls back to no translation key.""" device = Device( device_id="multi_zone_none", nickname="Multi Zone Fridge", device_type=DeviceType.COMBI, device_name="CBNes9999", ) mock_liebherr_client.get_devices.return_value = [device] multi_zone_state = DeviceState( device=device, controls=[ TemperatureControl( zone_id=1, zone_position=None, # None triggers fallback in _get_zone_translation_key name="Fridge", type="fridge", value=5, unit=TemperatureUnit.CELSIUS, ), TemperatureControl( zone_id=2, zone_position=ZonePosition.BOTTOM, name="Freezer", type="freezer", value=-18, unit=TemperatureUnit.CELSIUS, ), ], ) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( multi_zone_state ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Zone with None position should have no translation key (fallback) zone1_entity = entity_registry.async_get("sensor.multi_zone_fridge_temperature") assert zone1_entity is not None assert zone1_entity.translation_key is None # Zone with valid position should have translation key zone2_entity = entity_registry.async_get("sensor.multi_zone_fridge_bottom_zone") assert zone2_entity is not None assert zone2_entity.translation_key == "bottom_zone" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") @pytest.mark.parametrize( "exception", [ LiebherrConnectionError("Connection failed"), LiebherrTimeoutError("Timeout"), ], ids=["connection_error", "timeout_error"], ) async def test_sensor_update_failure( hass: HomeAssistant, mock_liebherr_client: MagicMock, freezer: FrozenDateTimeFactory, exception: Exception, ) -> None: """Test sensor becomes unavailable when coordinator update fails.""" entity_id = "sensor.test_fridge_top_zone" # Initial state should be available with value state = hass.states.get(entity_id) assert state is not None assert state.state == "5" # Simulate update error mock_liebherr_client.get_device_state.side_effect = exception # Advance time to trigger coordinator refresh (60 second interval) freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should now be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE # Simulate recovery mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: copy.deepcopy( MOCK_DEVICE_STATE ) freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should recover state = hass.states.get(entity_id) assert state is not None assert state.state == "5" @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_sensor_update_auth_failure_triggers_reauth( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test authentication error triggers reauth flow.""" entity_id = "sensor.test_fridge_top_zone" # Initial state should be available with value state = hass.states.get(entity_id) assert state is not None assert state.state == "5" # Simulate auth error mock_liebherr_client.get_device_state.side_effect = LiebherrAuthenticationError( "API key revoked" ) # Advance time to trigger coordinator refresh (60 second interval) freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should now be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE # Config entry should be in reauth state assert mock_config_entry.state is ConfigEntryState.LOADED flows = hass.config_entries.flow.async_progress() assert any( flow["handler"] == DOMAIN and flow["context"]["source"] == "reauth" for flow in flows ) @pytest.mark.usefixtures("entity_registry_enabled_by_default", "init_integration") async def test_sensor_unavailable_when_control_missing( hass: HomeAssistant, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test sensor becomes unavailable when temperature control is removed from device.""" entity_id = "sensor.test_fridge_top_zone" # Initial state should be available state = hass.states.get(entity_id) assert state is not None assert state.state == "5" # Device stops reporting controls (e.g., zone removed or API issue) mock_liebherr_client.get_device_state.side_effect = lambda *a, **kw: DeviceState( device=MOCK_DEVICE, controls=[] ) # Advance time to trigger coordinator refresh freezer.tick(timedelta(seconds=61)) async_fire_time_changed(hass) await hass.async_block_till_done() # Sensor should now be unavailable state = hass.states.get(entity_id) assert state is not None assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_sensor.py", "license": "Apache License 2.0", "lines": 223, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/switchbot/services.py
"""Services for the SwitchBot integration.""" from __future__ import annotations import voluptuous as vol from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_DEVICE_ID, CONF_SENSOR_TYPE from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from .const import DOMAIN, SupportedModels from .coordinator import SwitchbotConfigEntry, SwitchbotDataUpdateCoordinator SERVICE_ADD_PASSWORD = "add_password" ATTR_PASSWORD = "password" _PASSWORD_VALIDATOR = vol.All(cv.string, cv.matches_regex(r"^\d{6,12}$")) SCHEMA_ADD_PASSWORD_SERVICE = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Required(ATTR_PASSWORD): _PASSWORD_VALIDATOR, }, extra=vol.ALLOW_EXTRA, ) @callback def _async_get_switchbot_entry_for_device_id( hass: HomeAssistant, device_id: str ) -> SwitchbotConfigEntry: """Return the loaded SwitchBot config entry for a device id.""" device_registry = dr.async_get(hass) if not (device_entry := device_registry.async_get(device_id)): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id", translation_placeholders={"device_id": device_id}, ) entries = [ hass.config_entries.async_get_entry(entry_id) for entry_id in device_entry.config_entries ] switchbot_entries = [ entry for entry in entries if entry is not None and entry.domain == DOMAIN ] if not switchbot_entries: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="device_not_belonging", translation_placeholders={"device_id": device_id}, ) if not ( loaded_entry := next( ( entry for entry in switchbot_entries if entry.state is ConfigEntryState.LOADED ), None, ) ): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="device_entry_not_loaded", translation_placeholders={"device_id": device_id}, ) return loaded_entry def _is_supported_keypad(entry: SwitchbotConfigEntry) -> bool: """Return if the entry is a supported keypad model.""" allowed_sensor_types = { SupportedModels.KEYPAD_VISION.value, SupportedModels.KEYPAD_VISION_PRO.value, } return entry.data.get(CONF_SENSOR_TYPE) in allowed_sensor_types @callback def _async_target( hass: HomeAssistant, device_id: str ) -> SwitchbotDataUpdateCoordinator: """Return coordinator for a single target device.""" entry = _async_get_switchbot_entry_for_device_id(hass, device_id) if not _is_supported_keypad(entry): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="not_keypad_vision_device", ) return entry.runtime_data async def async_add_password(call: ServiceCall) -> None: """Add a password to a SwitchBot keypad device.""" password: str = call.data[ATTR_PASSWORD] device_id = call.data[ATTR_DEVICE_ID] coordinator = _async_target(call.hass, device_id) await coordinator.device.add_password(password) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for the SwitchBot integration.""" hass.services.async_register( DOMAIN, SERVICE_ADD_PASSWORD, async_add_password, schema=SCHEMA_ADD_PASSWORD_SERVICE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switchbot/services.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/switchbot/test_services.py
"""Test the switchbot services.""" from collections.abc import Callable from unittest.mock import AsyncMock, patch import pytest from homeassistant.components.bluetooth import BluetoothServiceInfoBleak from homeassistant.components.switchbot.const import DOMAIN from homeassistant.components.switchbot.services import ( SERVICE_ADD_PASSWORD, async_setup_services, ) from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import device_registry as dr from . import ( KEYPAD_VISION_INFO, KEYPAD_VISION_PRO_INFO, SMART_THERMOSTAT_RADIATOR_SERVICE_INFO, ) from tests.common import MockConfigEntry from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.parametrize( ("ble_service_info", "sensor_type"), [ (KEYPAD_VISION_INFO, "keypad_vision"), (KEYPAD_VISION_PRO_INFO, "keypad_vision_pro"), ], ) async def test_add_password_service( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], ble_service_info: BluetoothServiceInfoBleak, sensor_type: str, device_registry: dr.DeviceRegistry, ) -> None: """Test the add_password service.""" inject_bluetooth_service_info(hass, ble_service_info) entry = mock_entry_encrypted_factory(sensor_type=sensor_type) entry.add_to_hass(hass) mocked_instance = AsyncMock(return_value=True) with patch.multiple( "homeassistant.components.switchbot.switchbot.SwitchbotKeypadVision", update=AsyncMock(return_value=None), add_password=mocked_instance, ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() device_entry = dr.async_entries_for_config_entry( device_registry, entry.entry_id )[0] await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: device_entry.id, "password": "123456", }, blocking=True, ) mocked_instance.assert_called_once_with("123456") async def test_device_not_found( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], ) -> None: """Test the add_password service with non-existent device.""" inject_bluetooth_service_info(hass, KEYPAD_VISION_INFO) entry = mock_entry_encrypted_factory(sensor_type="keypad_vision") entry.add_to_hass(hass) with patch.multiple( "homeassistant.components.switchbot.switchbot.SwitchbotKeypadVision", update=AsyncMock(return_value=None), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: "nonexistent_device", "password": "123456", }, blocking=True, ) assert err.value.translation_domain == DOMAIN assert err.value.translation_key == "invalid_device_id" assert err.value.translation_placeholders == {"device_id": "nonexistent_device"} async def test_device_not_belonging( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], device_registry: dr.DeviceRegistry, ) -> None: """Test service errors when device belongs to a different integration.""" inject_bluetooth_service_info(hass, KEYPAD_VISION_INFO) entry = mock_entry_encrypted_factory(sensor_type="keypad_vision") entry.add_to_hass(hass) with patch.multiple( "homeassistant.components.switchbot.switchbot.SwitchbotKeypadVision", update=AsyncMock(return_value=None), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() other_entry = MockConfigEntry(domain="not_switchbot", data={}, title="Other") other_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=other_entry.entry_id, identifiers={("not_switchbot", "other_unique_id")}, name="Other device", ) with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: device_entry.id, "password": "123456", }, blocking=True, ) assert err.value.translation_domain == DOMAIN assert err.value.translation_key == "device_not_belonging" assert err.value.translation_placeholders == {"device_id": device_entry.id} async def test_device_entry_not_loaded( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], device_registry: dr.DeviceRegistry, ) -> None: """Test service errors when the config entry is not loaded.""" inject_bluetooth_service_info(hass, KEYPAD_VISION_INFO) entry = mock_entry_encrypted_factory(sensor_type="keypad_vision") entry.add_to_hass(hass) with patch.multiple( "homeassistant.components.switchbot.switchbot.SwitchbotKeypadVision", update=AsyncMock(return_value=None), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() second_entry = mock_entry_encrypted_factory(sensor_type="keypad_vision") second_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=second_entry.entry_id, identifiers={(DOMAIN, "not_loaded_unique_id")}, name="Not loaded device", ) with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: device_entry.id, "password": "123456", }, blocking=True, ) assert err.value.translation_domain == DOMAIN assert err.value.translation_key == "device_entry_not_loaded" assert err.value.translation_placeholders == {"device_id": device_entry.id} async def test_service_unsupported_device( hass: HomeAssistant, mock_entry_encrypted_factory: Callable[[str], MockConfigEntry], device_registry: dr.DeviceRegistry, ) -> None: """Test service errors when the device does not support the service.""" inject_bluetooth_service_info(hass, SMART_THERMOSTAT_RADIATOR_SERVICE_INFO) entry = mock_entry_encrypted_factory(sensor_type="smart_thermostat_radiator") entry.add_to_hass(hass) with patch.multiple( "homeassistant.components.switchbot.switchbot.SwitchbotSmartThermostatRadiator", update=AsyncMock(return_value=None), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() device_entry = dr.async_entries_for_config_entry(device_registry, entry.entry_id)[0] with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: device_entry.id, "password": "123456", }, blocking=True, ) assert err.value.translation_domain == DOMAIN assert err.value.translation_key == "not_keypad_vision_device" async def test_device_without_config_entry_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, ) -> None: """Test service errors when device has no config entry id.""" async_setup_services(hass) entry = MockConfigEntry(domain=DOMAIN, data={}, title="No entry device") entry.add_to_hass(hass) with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_PASSWORD, { ATTR_DEVICE_ID: "abc", "password": "123456", }, blocking=True, ) assert err.value.translation_domain == DOMAIN assert err.value.translation_key == "invalid_device_id" assert err.value.translation_placeholders == {"device_id": "abc"}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switchbot/test_services.py", "license": "Apache License 2.0", "lines": 206, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/arve/test_init.py
"""Tests for the Arve component.""" from unittest.mock import patch from homeassistant.components.arve.const import DOMAIN from homeassistant.const import CONF_ACCESS_TOKEN, CONF_CLIENT_SECRET from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None: """Test migrating a 1.1 config entry to 1.2.""" with patch("homeassistant.components.arve.async_setup_entry", return_value=True): entry = MockConfigEntry( domain=DOMAIN, data={CONF_ACCESS_TOKEN: "mock", CONF_CLIENT_SECRET: "mock"}, version=1, minor_version=1, unique_id=12345, ) entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) assert entry.version == 1 assert entry.minor_version == 2 assert entry.unique_id == "12345"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/arve/test_init.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/microbees/test_init.py
"""Tests for the microBees component.""" from unittest.mock import patch from homeassistant.components.microbees.const import DOMAIN from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_migrate_entry_minor_version_1_2(hass: HomeAssistant) -> None: """Test migrating a 1.1 config entry to 1.2.""" with patch( "homeassistant.components.microbees.async_setup_entry", return_value=True ): entry = MockConfigEntry( domain=DOMAIN, data={ "auth_implementation": DOMAIN, "token": { "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "type": "Bearer", "expires_in": 60, }, }, version=1, minor_version=1, unique_id=54321, ) entry.add_to_hass(hass) assert await hass.config_entries.async_setup(entry.entry_id) assert entry.version == 1 assert entry.minor_version == 2 assert entry.unique_id == "54321"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/microbees/test_init.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/actron_air/entity.py
"""Base entity classes for Actron Air integration.""" from collections.abc import Callable, Coroutine from functools import wraps from typing import Any, Concatenate from actron_neo_api import ActronAirAPIError, ActronAirZone from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import ActronAirSystemCoordinator def handle_actron_api_errors[_EntityT: ActronAirEntity, **_P]( func: Callable[Concatenate[_EntityT, _P], Coroutine[Any, Any, Any]], ) -> Callable[Concatenate[_EntityT, _P], Coroutine[Any, Any, None]]: """Decorate Actron Air API calls to handle ActronAirAPIError exceptions.""" @wraps(func) async def wrapper(self: _EntityT, *args: _P.args, **kwargs: _P.kwargs) -> None: """Wrap API calls with exception handling.""" try: await func(self, *args, **kwargs) except ActronAirAPIError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="api_error", translation_placeholders={"error": str(err)}, ) from err return wrapper class ActronAirEntity(CoordinatorEntity[ActronAirSystemCoordinator]): """Base class for Actron Air entities.""" _attr_has_entity_name = True def __init__(self, coordinator: ActronAirSystemCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._serial_number = coordinator.serial_number @property def available(self) -> bool: """Return True if entity is available.""" return not self.coordinator.is_device_stale() class ActronAirAcEntity(ActronAirEntity): """Base class for Actron Air entities.""" def __init__(self, coordinator: ActronAirSystemCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self._serial_number)}, name=coordinator.data.ac_system.system_name, manufacturer="Actron Air", model_id=coordinator.data.ac_system.master_wc_model, sw_version=coordinator.data.ac_system.master_wc_firmware_version, serial_number=self._serial_number, ) class ActronAirZoneEntity(ActronAirEntity): """Base class for Actron Air zone entities.""" def __init__( self, coordinator: ActronAirSystemCoordinator, zone: ActronAirZone, ) -> None: """Initialize the entity.""" super().__init__(coordinator) self._zone_id: int = zone.zone_id self._zone_identifier = f"{self._serial_number}_zone_{zone.zone_id}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self._zone_identifier)}, name=zone.title, manufacturer="Actron Air", model="Zone", suggested_area=zone.title, via_device=(DOMAIN, self._serial_number), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/actron_air/entity.py", "license": "Apache License 2.0", "lines": 69, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/actron_air/switch.py
"""Switch platform for Actron Air integration.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import ActronAirConfigEntry, ActronAirSystemCoordinator from .entity import ActronAirAcEntity, handle_actron_api_errors PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class ActronAirSwitchEntityDescription(SwitchEntityDescription): """Class describing Actron Air switch entities.""" is_on_fn: Callable[[ActronAirSystemCoordinator], bool] set_fn: Callable[[ActronAirSystemCoordinator, bool], Awaitable[None]] is_supported_fn: Callable[[ActronAirSystemCoordinator], bool] = lambda _: True SWITCHES: tuple[ActronAirSwitchEntityDescription, ...] = ( ActronAirSwitchEntityDescription( key="away_mode", translation_key="away_mode", is_on_fn=lambda coordinator: coordinator.data.user_aircon_settings.away_mode, set_fn=lambda coordinator, enabled: ( coordinator.data.user_aircon_settings.set_away_mode(enabled) ), ), ActronAirSwitchEntityDescription( key="continuous_fan", translation_key="continuous_fan", is_on_fn=lambda coordinator: ( coordinator.data.user_aircon_settings.continuous_fan_enabled ), set_fn=lambda coordinator, enabled: ( coordinator.data.user_aircon_settings.set_continuous_mode(enabled) ), ), ActronAirSwitchEntityDescription( key="quiet_mode", translation_key="quiet_mode", is_on_fn=lambda coordinator: ( coordinator.data.user_aircon_settings.quiet_mode_enabled ), set_fn=lambda coordinator, enabled: ( coordinator.data.user_aircon_settings.set_quiet_mode(enabled) ), ), ActronAirSwitchEntityDescription( key="turbo_mode", translation_key="turbo_mode", is_on_fn=lambda coordinator: ( coordinator.data.user_aircon_settings.turbo_enabled ), set_fn=lambda coordinator, enabled: ( coordinator.data.user_aircon_settings.set_turbo_mode(enabled) ), is_supported_fn=lambda coordinator: ( coordinator.data.user_aircon_settings.turbo_supported ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: ActronAirConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Actron Air switch entities.""" system_coordinators = entry.runtime_data.system_coordinators async_add_entities( ActronAirSwitch(coordinator, description) for coordinator in system_coordinators.values() for description in SWITCHES if description.is_supported_fn(coordinator) ) class ActronAirSwitch(ActronAirAcEntity, SwitchEntity): """Actron Air switch.""" _attr_entity_category = EntityCategory.CONFIG entity_description: ActronAirSwitchEntityDescription def __init__( self, coordinator: ActronAirSystemCoordinator, description: ActronAirSwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.serial_number}_{description.key}" @property def is_on(self) -> bool: """Return true if the switch is on.""" return self.entity_description.is_on_fn(self.coordinator) @handle_actron_api_errors async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.entity_description.set_fn(self.coordinator, True) @handle_actron_api_errors async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.entity_description.set_fn(self.coordinator, False)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/actron_air/switch.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/diagnostics.py
"""Diagnostics support for Airobot.""" from __future__ import annotations from dataclasses import asdict from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from .coordinator import AirobotConfigEntry TO_REDACT_CONFIG = [CONF_HOST, CONF_MAC, CONF_PASSWORD, CONF_USERNAME] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: AirobotConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data # Build device capabilities info device_capabilities = None if coordinator.data: device_capabilities = { "has_floor_sensor": coordinator.data.status.has_floor_sensor, "has_co2_sensor": coordinator.data.status.has_co2_sensor, "hw_version": coordinator.data.status.hw_version, "fw_version": coordinator.data.status.fw_version, } return { "entry_data": async_redact_data(entry.data, TO_REDACT_CONFIG), "device_capabilities": device_capabilities, "status": asdict(coordinator.data.status) if coordinator.data else None, "settings": asdict(coordinator.data.settings) if coordinator.data else None, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/diagnostics.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/number.py
"""Number platform for Airobot thermostat.""" from __future__ import annotations from collections.abc import Awaitable, Callable from dataclasses import dataclass from pyairobotrest.const import HYSTERESIS_BAND_MAX, HYSTERESIS_BAND_MIN from pyairobotrest.exceptions import AirobotError from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberEntityDescription, ) from homeassistant.const import EntityCategory, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import AirobotConfigEntry from .const import DOMAIN from .coordinator import AirobotDataUpdateCoordinator from .entity import AirobotEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class AirobotNumberEntityDescription(NumberEntityDescription): """Describes Airobot number entity.""" value_fn: Callable[[AirobotDataUpdateCoordinator], float] set_value_fn: Callable[[AirobotDataUpdateCoordinator, float], Awaitable[None]] NUMBERS: tuple[AirobotNumberEntityDescription, ...] = ( AirobotNumberEntityDescription( key="hysteresis_band", translation_key="hysteresis_band", device_class=NumberDeviceClass.TEMPERATURE, entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, native_unit_of_measurement=UnitOfTemperature.CELSIUS, native_min_value=HYSTERESIS_BAND_MIN / 10.0, native_max_value=HYSTERESIS_BAND_MAX / 10.0, native_step=0.1, value_fn=lambda coordinator: coordinator.data.settings.hysteresis_band, set_value_fn=lambda coordinator, value: coordinator.client.set_hysteresis_band( value ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: AirobotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Airobot number platform.""" coordinator = entry.runtime_data async_add_entities( AirobotNumber(coordinator, description) for description in NUMBERS ) class AirobotNumber(AirobotEntity, NumberEntity): """Representation of an Airobot number entity.""" entity_description: AirobotNumberEntityDescription def __init__( self, coordinator: AirobotDataUpdateCoordinator, description: AirobotNumberEntityDescription, ) -> None: """Initialize the number entity.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.data.status.device_id}_{description.key}" @property def native_value(self) -> float: """Return the current value.""" return self.entity_description.value_fn(self.coordinator) async def async_set_native_value(self, value: float) -> None: """Set the value.""" try: await self.entity_description.set_value_fn(self.coordinator, value) except AirobotError as err: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="set_value_failed", ) from err else: await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/number.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/sensor.py
"""Sensor platform for Airobot thermostat.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta from pyairobotrest.models import ThermostatStatus from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, PERCENTAGE, EntityCategory, UnitOfTemperature, UnitOfTime, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.util.dt import utcnow from homeassistant.util.variance import ignore_variance from . import AirobotConfigEntry from .coordinator import AirobotDataUpdateCoordinator from .entity import AirobotEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class AirobotSensorEntityDescription(SensorEntityDescription): """Describes Airobot sensor entity.""" value_fn: Callable[[ThermostatStatus], StateType | datetime] supported_fn: Callable[[ThermostatStatus], bool] = lambda _: True uptime_to_stable_datetime = ignore_variance( lambda value: utcnow().replace(microsecond=0) - timedelta(seconds=value), timedelta(minutes=2), ) SENSOR_TYPES: tuple[AirobotSensorEntityDescription, ...] = ( AirobotSensorEntityDescription( key="air_temperature", translation_key="air_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=1, value_fn=lambda status: status.temp_air, ), AirobotSensorEntityDescription( key="humidity", device_class=SensorDeviceClass.HUMIDITY, native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.hum_air, ), AirobotSensorEntityDescription( key="floor_temperature", translation_key="floor_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.temp_floor, supported_fn=lambda status: status.has_floor_sensor, ), AirobotSensorEntityDescription( key="co2", device_class=SensorDeviceClass.CO2, native_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.co2, supported_fn=lambda status: status.has_co2_sensor, ), AirobotSensorEntityDescription( key="air_quality_index", device_class=SensorDeviceClass.AQI, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda status: status.aqi, supported_fn=lambda status: status.has_co2_sensor, ), AirobotSensorEntityDescription( key="heating_uptime", translation_key="heating_uptime", device_class=SensorDeviceClass.DURATION, native_unit_of_measurement=UnitOfTime.SECONDS, suggested_unit_of_measurement=UnitOfTime.HOURS, state_class=SensorStateClass.TOTAL_INCREASING, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda status: status.heating_uptime, entity_registry_enabled_default=False, ), AirobotSensorEntityDescription( key="errors", translation_key="errors", state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda status: status.errors, ), AirobotSensorEntityDescription( key="device_uptime", translation_key="device_uptime", device_class=SensorDeviceClass.TIMESTAMP, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda status: uptime_to_stable_datetime(status.device_uptime), entity_registry_enabled_default=False, ), ) async def async_setup_entry( hass: HomeAssistant, entry: AirobotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Airobot sensor platform.""" coordinator = entry.runtime_data async_add_entities( AirobotSensor(coordinator, description) for description in SENSOR_TYPES if description.supported_fn(coordinator.data.status) ) class AirobotSensor(AirobotEntity, SensorEntity): """Representation of an Airobot sensor.""" entity_description: AirobotSensorEntityDescription def __init__( self, coordinator: AirobotDataUpdateCoordinator, description: AirobotSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.data.status.device_id}_{description.key}" @property def native_value(self) -> StateType | datetime: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data.status)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/sensor.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airpatrol/climate.py
"""Climate platform for AirPatrol integration.""" from __future__ import annotations from typing import Any from homeassistant.components.climate import ( FAN_AUTO, FAN_HIGH, FAN_LOW, SWING_OFF, SWING_ON, ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import AirPatrolConfigEntry from .coordinator import AirPatrolDataUpdateCoordinator from .entity import AirPatrolEntity PARALLEL_UPDATES = 0 AP_TO_HA_HVAC_MODES = { "heat": HVACMode.HEAT, "cool": HVACMode.COOL, "off": HVACMode.OFF, } HA_TO_AP_HVAC_MODES = {value: key for key, value in AP_TO_HA_HVAC_MODES.items()} AP_TO_HA_FAN_MODES = { "min": FAN_LOW, "max": FAN_HIGH, "auto": FAN_AUTO, } HA_TO_AP_FAN_MODES = {value: key for key, value in AP_TO_HA_FAN_MODES.items()} AP_TO_HA_SWING_MODES = { "on": SWING_ON, "off": SWING_OFF, } HA_TO_AP_SWING_MODES = {value: key for key, value in AP_TO_HA_SWING_MODES.items()} async def async_setup_entry( hass: HomeAssistant, config_entry: AirPatrolConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up AirPatrol climate entities.""" coordinator = config_entry.runtime_data units = coordinator.data async_add_entities( AirPatrolClimate(coordinator, unit_id) for unit_id, unit in units.items() if "climate" in unit ) class AirPatrolClimate(AirPatrolEntity, ClimateEntity): """AirPatrol climate entity.""" _attr_name = None _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.FAN_MODE | ClimateEntityFeature.SWING_MODE | ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON ) _attr_hvac_modes = [HVACMode.HEAT, HVACMode.COOL, HVACMode.OFF] _attr_fan_modes = [FAN_LOW, FAN_HIGH, FAN_AUTO] _attr_swing_modes = [SWING_ON, SWING_OFF] _attr_min_temp = 16.0 _attr_max_temp = 30.0 def __init__( self, coordinator: AirPatrolDataUpdateCoordinator, unit_id: str, ) -> None: """Initialize the climate entity.""" super().__init__(coordinator, unit_id) self._attr_unique_id = f"{coordinator.config_entry.unique_id}-{unit_id}" @property def params(self) -> dict[str, Any]: """Return the current parameters for the climate entity.""" return self.climate_data.get("ParametersData") or {} @property def current_humidity(self) -> float | None: """Return the current humidity.""" if humidity := self.climate_data.get("RoomHumidity"): return float(humidity) return None @property def current_temperature(self) -> float | None: """Return the current temperature.""" if temp := self.climate_data.get("RoomTemp"): return float(temp) return None @property def target_temperature(self) -> float | None: """Return the target temperature.""" if temp := self.params.get("PumpTemp"): return float(temp) return None @property def hvac_mode(self) -> HVACMode | None: """Return the current HVAC mode.""" pump_power = self.params.get("PumpPower") pump_mode = self.params.get("PumpMode") if pump_power and pump_power == "on" and pump_mode: return AP_TO_HA_HVAC_MODES.get(pump_mode) return HVACMode.OFF @property def fan_mode(self) -> str | None: """Return the current fan mode.""" fan_speed = self.params.get("FanSpeed") if fan_speed: return AP_TO_HA_FAN_MODES.get(fan_speed) return None @property def swing_mode(self) -> str | None: """Return the current swing mode.""" swing = self.params.get("Swing") if swing: return AP_TO_HA_SWING_MODES.get(swing) return None async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" params = self.params.copy() if ATTR_TEMPERATURE in kwargs: temp = kwargs[ATTR_TEMPERATURE] params["PumpTemp"] = f"{temp:.3f}" await self._async_set_params(params) async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target hvac mode.""" params = self.params.copy() if hvac_mode == HVACMode.OFF: params["PumpPower"] = "off" else: params["PumpPower"] = "on" params["PumpMode"] = HA_TO_AP_HVAC_MODES.get(hvac_mode) await self._async_set_params(params) async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new target fan mode.""" params = self.params.copy() params["FanSpeed"] = HA_TO_AP_FAN_MODES.get(fan_mode) await self._async_set_params(params) async def async_set_swing_mode(self, swing_mode: str) -> None: """Set new target swing mode.""" params = self.params.copy() params["Swing"] = HA_TO_AP_SWING_MODES.get(swing_mode) await self._async_set_params(params) async def async_turn_on(self) -> None: """Turn the entity on.""" params = self.params.copy() if mode := AP_TO_HA_HVAC_MODES.get(params["PumpMode"]): await self.async_set_hvac_mode(mode) async def async_turn_off(self) -> None: """Turn the entity off.""" await self.async_set_hvac_mode(HVACMode.OFF) async def _async_set_params(self, params: dict[str, Any]) -> None: """Set the unit to dry mode.""" new_climate_data = self.climate_data.copy() new_climate_data["ParametersData"] = params await self.coordinator.api.set_unit_climate_data( self._unit_id, new_climate_data ) await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/climate.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/airpatrol/config_flow.py
"""Config flow for the AirPatrol integration.""" from __future__ import annotations from collections.abc import Mapping from typing import Any from airpatrol.api import AirPatrolAPI, AirPatrolAuthenticationError, AirPatrolError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import DOMAIN DATA_SCHEMA = vol.Schema( { vol.Required(CONF_EMAIL): TextSelector( TextSelectorConfig( type=TextSelectorType.EMAIL, autocomplete="email", ) ), vol.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password", ) ), } ) async def validate_api( hass: HomeAssistant, user_input: dict[str, str] ) -> tuple[str | None, str | None, dict[str, str]]: """Validate the API connection.""" errors: dict[str, str] = {} session = async_get_clientsession(hass) access_token = None unique_id = None try: api = await AirPatrolAPI.authenticate( session, user_input[CONF_EMAIL], user_input[CONF_PASSWORD] ) except AirPatrolAuthenticationError: errors["base"] = "invalid_auth" except AirPatrolError: errors["base"] = "cannot_connect" else: access_token = api.get_access_token() unique_id = api.get_unique_id() return (access_token, unique_id, errors) class AirPatrolConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for AirPatrol.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: access_token, unique_id, errors = await validate_api(self.hass, user_input) if access_token and unique_id: user_input[CONF_ACCESS_TOKEN] = access_token await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_input[CONF_EMAIL], data=user_input ) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, user_input: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauthentication with new credentials.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauthentication confirmation.""" errors: dict[str, str] = {} if user_input: access_token, unique_id, errors = await validate_api(self.hass, user_input) if access_token and unique_id: await self.async_set_unique_id(unique_id) self._abort_if_unique_id_mismatch() user_input[CONF_ACCESS_TOKEN] = access_token return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=user_input ) return self.async_show_form( step_id="reauth_confirm", data_schema=DATA_SCHEMA, errors=errors )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/config_flow.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airpatrol/const.py
"""Constants for the AirPatrol integration.""" from datetime import timedelta import logging from airpatrol.api import AirPatrolAuthenticationError, AirPatrolError from homeassistant.const import Platform DOMAIN = "airpatrol" LOGGER = logging.getLogger(__package__) PLATFORMS = [Platform.CLIMATE, Platform.SENSOR] SCAN_INTERVAL = timedelta(minutes=1) AIRPATROL_ERRORS = (AirPatrolAuthenticationError, AirPatrolError)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/const.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airpatrol/coordinator.py
"""Data update coordinator for AirPatrol.""" from __future__ import annotations from typing import Any from airpatrol.api import AirPatrolAPI, AirPatrolAuthenticationError, AirPatrolError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN, CONF_EMAIL, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, LOGGER, SCAN_INTERVAL type AirPatrolConfigEntry = ConfigEntry[AirPatrolDataUpdateCoordinator] class AirPatrolDataUpdateCoordinator(DataUpdateCoordinator[dict[str, dict[str, Any]]]): """Class to manage fetching AirPatrol data.""" config_entry: AirPatrolConfigEntry api: AirPatrolAPI def __init__(self, hass: HomeAssistant, config_entry: AirPatrolConfigEntry) -> None: """Initialize.""" super().__init__( hass, LOGGER, name=f"{DOMAIN.capitalize()} {config_entry.title}", update_interval=SCAN_INTERVAL, config_entry=config_entry, ) async def _async_setup(self) -> None: try: await self._setup_client() except AirPatrolError as api_err: raise UpdateFailed( f"Error communicating with AirPatrol API: {api_err}" ) from api_err async def _async_update_data(self) -> dict[str, dict[str, Any]]: """Update unit data from AirPatrol API.""" return {unit_data["unit_id"]: unit_data for unit_data in await self._get_data()} async def _get_data(self, retry: bool = False) -> list[dict[str, Any]]: """Fetch data from API.""" try: return await self.api.get_data() except AirPatrolAuthenticationError as auth_err: if retry: raise ConfigEntryAuthFailed( "Authentication with AirPatrol failed" ) from auth_err await self._update_token() return await self._get_data(retry=True) except AirPatrolError as err: raise UpdateFailed( f"Error communicating with AirPatrol API: {err}" ) from err async def _update_token(self) -> None: """Refresh the AirPatrol API client and update the access token.""" session = async_get_clientsession(self.hass) try: self.api = await AirPatrolAPI.authenticate( session, self.config_entry.data[CONF_EMAIL], self.config_entry.data[CONF_PASSWORD], ) except AirPatrolAuthenticationError as auth_err: raise ConfigEntryAuthFailed( "Authentication with AirPatrol failed" ) from auth_err self.hass.config_entries.async_update_entry( self.config_entry, data={ **self.config_entry.data, CONF_ACCESS_TOKEN: self.api.get_access_token(), }, ) async def _setup_client(self) -> None: """Set up the AirPatrol API client from stored access_token.""" session = async_get_clientsession(self.hass) api = AirPatrolAPI( session, self.config_entry.data[CONF_ACCESS_TOKEN], self.config_entry.unique_id, ) try: await api.get_data() except AirPatrolAuthenticationError: await self._update_token() self.api = api
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/coordinator.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/airpatrol/entity.py
"""Base entity for AirPatrol integration.""" from __future__ import annotations from typing import Any from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import AirPatrolDataUpdateCoordinator class AirPatrolEntity(CoordinatorEntity[AirPatrolDataUpdateCoordinator]): """Base entity for AirPatrol devices.""" _attr_has_entity_name = True def __init__( self, coordinator: AirPatrolDataUpdateCoordinator, unit_id: str, ) -> None: """Initialize the AirPatrol entity.""" super().__init__(coordinator) self._unit_id = unit_id device = coordinator.data[unit_id] self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, unit_id)}, name=device["name"], manufacturer=device["manufacturer"], model=device["model"], serial_number=device["hwid"], ) @property def device_data(self) -> dict[str, Any]: """Return the device data.""" return self.coordinator.data[self._unit_id] @property def climate_data(self) -> dict[str, Any]: """Return the climate data for this unit.""" return self.device_data["climate"] @property def available(self) -> bool: """Return if entity is available.""" return ( super().available and self._unit_id in self.coordinator.data and "climate" in self.device_data and self.climate_data is not None )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/entity.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airpatrol/sensor.py
"""Sensors for AirPatrol integration.""" from __future__ import annotations from dataclasses import dataclass from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import PERCENTAGE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import AirPatrolConfigEntry from .coordinator import AirPatrolDataUpdateCoordinator from .entity import AirPatrolEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class AirPatrolSensorEntityDescription(SensorEntityDescription): """Describes AirPatrol sensor entity.""" data_field: str SENSOR_DESCRIPTIONS = ( AirPatrolSensorEntityDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, data_field="RoomTemp", ), AirPatrolSensorEntityDescription( key="humidity", device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, data_field="RoomHumidity", ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: AirPatrolConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up AirPatrol sensors.""" coordinator = config_entry.runtime_data units = coordinator.data async_add_entities( AirPatrolSensor(coordinator, unit_id, description) for unit_id, unit in units.items() for description in SENSOR_DESCRIPTIONS if "climate" in unit and unit["climate"] is not None ) class AirPatrolSensor(AirPatrolEntity, SensorEntity): """AirPatrol sensor entity.""" entity_description: AirPatrolSensorEntityDescription def __init__( self, coordinator: AirPatrolDataUpdateCoordinator, unit_id: str, description: AirPatrolSensorEntityDescription, ) -> None: """Initialize AirPatrol sensor.""" super().__init__(coordinator, unit_id) self.entity_description = description self._attr_unique_id = ( f"{coordinator.config_entry.unique_id}-{unit_id}-{description.key}" ) @property def native_value(self) -> float | None: """Return the state of the sensor.""" if value := self.climate_data.get(self.entity_description.data_field): return float(value) return None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airpatrol/sensor.py", "license": "Apache License 2.0", "lines": 71, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/backblaze_b2/b2_client.py
"""Backblaze B2 client with extended timeouts. The b2sdk library uses class-level timeout attributes. To avoid modifying global library state, we subclass the relevant classes to provide extended timeouts suitable for backup operations involving large files. """ from b2sdk.v2 import B2Api as BaseB2Api, InMemoryAccountInfo from b2sdk.v2.b2http import B2Http as BaseB2Http from b2sdk.v2.session import B2Session as BaseB2Session # Extended timeouts for Home Assistant backup operations # Default CONNECTION_TIMEOUT is 46 seconds, which can be too short for slow connections CONNECTION_TIMEOUT = 120 # 2 minutes # Default TIMEOUT_FOR_UPLOAD is 128 seconds, which is too short for large backups TIMEOUT_FOR_UPLOAD = 43200 # 12 hours # Reduced retry count for download operations # Default is 20 retries with exponential backoff, which can hang for 30+ minutes # when there are persistent connection errors (e.g., SSL failures) TRY_COUNT_DOWNLOAD = 3 class B2Http(BaseB2Http): # type: ignore[misc] """B2Http with extended timeouts for backup operations.""" CONNECTION_TIMEOUT = CONNECTION_TIMEOUT TIMEOUT_FOR_UPLOAD = TIMEOUT_FOR_UPLOAD TRY_COUNT_DOWNLOAD = TRY_COUNT_DOWNLOAD class B2Session(BaseB2Session): # type: ignore[misc] """B2Session using custom B2Http with extended timeouts.""" B2HTTP_CLASS = B2Http class B2Api(BaseB2Api): # type: ignore[misc] """B2Api using custom session with extended timeouts.""" SESSION_CLASS = B2Session __all__ = ["B2Api", "InMemoryAccountInfo"]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/b2_client.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/blue_current/services.py
"""The Blue Current integration.""" from __future__ import annotations import voluptuous as vol from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.const import CONF_DEVICE_ID from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from .const import BCU_APP, CHARGING_CARD_ID, DOMAIN, SERVICE_START_CHARGE_SESSION SERVICE_START_CHARGE_SESSION_SCHEMA = vol.Schema( { vol.Required(CONF_DEVICE_ID): cv.string, # When no charging card is provided, use no charging card (BCU_APP = no charging card). vol.Optional(CHARGING_CARD_ID, default=BCU_APP): cv.string, } ) async def start_charge_session(service_call: ServiceCall) -> None: """Start a charge session with the provided device and charge card ID.""" # When no charge card is provided, use the default charge card set in the config flow. charging_card_id = service_call.data[CHARGING_CARD_ID] device_id = service_call.data[CONF_DEVICE_ID] # Get the device based on the given device ID. device = dr.async_get(service_call.hass).devices.get(device_id) if device is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id" ) blue_current_config_entry: ConfigEntry | None = None for config_entry_id in device.config_entries: config_entry = service_call.hass.config_entries.async_get_entry(config_entry_id) if not config_entry or config_entry.domain != DOMAIN: # Not the blue_current config entry. continue if config_entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="config_entry_not_loaded" ) blue_current_config_entry = config_entry break if not blue_current_config_entry: # The device is not connected to a valid blue_current config entry. raise ServiceValidationError( translation_domain=DOMAIN, translation_key="no_config_entry" ) connector = blue_current_config_entry.runtime_data # Get the evse_id from the identifier of the device. evse_id = next( identifier[1] for identifier in device.identifiers if identifier[0] == DOMAIN ) await connector.client.start_session(evse_id, charging_card_id) @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the services.""" hass.services.async_register( DOMAIN, SERVICE_START_CHARGE_SESSION, start_charge_session, SERVICE_START_CHARGE_SESSION_SCHEMA, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/blue_current/services.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/bsblan/services.py
"""Support for BSB-LAN services.""" from __future__ import annotations from datetime import time import logging from typing import TYPE_CHECKING from bsblan import BSBLANError, DaySchedule, DHWSchedule, TimeSlot import voluptuous as vol from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from .const import DOMAIN from .helpers import async_sync_device_time if TYPE_CHECKING: from . import BSBLanConfigEntry LOGGER = logging.getLogger(__name__) ATTR_DEVICE_ID = "device_id" ATTR_MONDAY_SLOTS = "monday_slots" ATTR_TUESDAY_SLOTS = "tuesday_slots" ATTR_WEDNESDAY_SLOTS = "wednesday_slots" ATTR_THURSDAY_SLOTS = "thursday_slots" ATTR_FRIDAY_SLOTS = "friday_slots" ATTR_SATURDAY_SLOTS = "saturday_slots" ATTR_SUNDAY_SLOTS = "sunday_slots" # Schema for a single time slot _SLOT_SCHEMA = vol.Schema( { vol.Required("start_time"): cv.time, vol.Required("end_time"): cv.time, } ) SERVICE_SET_HOT_WATER_SCHEDULE_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Optional(ATTR_MONDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_TUESDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_WEDNESDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_THURSDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_FRIDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_SATURDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), vol.Optional(ATTR_SUNDAY_SLOTS): vol.All(cv.ensure_list, [_SLOT_SCHEMA]), } ) def _convert_time_slots_to_day_schedule( slots: list[dict[str, time]] | None, ) -> DaySchedule | None: """Convert list of time slot dicts to a DaySchedule object. Example: [{"start_time": time(6, 0), "end_time": time(8, 0)}, {"start_time": time(17, 0), "end_time": time(21, 0)}] becomes: DaySchedule with two TimeSlot objects None returns None (don't modify this day). Empty list returns DaySchedule with empty slots (clear this day). """ if slots is None: return None if not slots: return DaySchedule(slots=[]) time_slots = [] for slot in slots: start_time = slot["start_time"] end_time = slot["end_time"] # Validate that end time is after start time if end_time <= start_time: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="end_time_before_start_time", translation_placeholders={ "start_time": start_time.strftime("%H:%M"), "end_time": end_time.strftime("%H:%M"), }, ) time_slots.append(TimeSlot(start=start_time, end=end_time)) LOGGER.debug( "Created time slot: %s-%s", start_time.strftime("%H:%M"), end_time.strftime("%H:%M"), ) LOGGER.debug("Created DaySchedule with %d slots", len(time_slots)) return DaySchedule(slots=time_slots) async def set_hot_water_schedule(service_call: ServiceCall) -> None: """Set hot water heating schedule.""" device_id = service_call.data[ATTR_DEVICE_ID] # Get the device and config entry device_registry = dr.async_get(service_call.hass) device_entry = device_registry.async_get(device_id) if device_entry is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id", translation_placeholders={"device_id": device_id}, ) # Find the config entry for this device matching_entries: list[BSBLanConfigEntry] = [ entry for entry in service_call.hass.config_entries.async_entries(DOMAIN) if entry.entry_id in device_entry.config_entries ] if not matching_entries: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="no_config_entry_for_device", translation_placeholders={"device_id": device_entry.name or device_id}, ) entry = matching_entries[0] # Verify the config entry is loaded if entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="config_entry_not_loaded", translation_placeholders={"device_name": device_entry.name or device_id}, ) client = entry.runtime_data.client # Convert time slots to DaySchedule objects monday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_MONDAY_SLOTS) ) tuesday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_TUESDAY_SLOTS) ) wednesday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_WEDNESDAY_SLOTS) ) thursday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_THURSDAY_SLOTS) ) friday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_FRIDAY_SLOTS) ) saturday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_SATURDAY_SLOTS) ) sunday = _convert_time_slots_to_day_schedule( service_call.data.get(ATTR_SUNDAY_SLOTS) ) # Create the DHWSchedule object dhw_schedule = DHWSchedule( monday=monday, tuesday=tuesday, wednesday=wednesday, thursday=thursday, friday=friday, saturday=saturday, sunday=sunday, ) LOGGER.debug( "Setting hot water schedule - Monday: %s, Tuesday: %s, Wednesday: %s, " "Thursday: %s, Friday: %s, Saturday: %s, Sunday: %s", monday, tuesday, wednesday, thursday, friday, saturday, sunday, ) try: # Call the BSB-LAN API to set the schedule await client.set_hot_water_schedule(dhw_schedule) except BSBLANError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_schedule_failed", translation_placeholders={"error": str(err)}, ) from err # Refresh the slow coordinator to get the updated schedule await entry.runtime_data.slow_coordinator.async_request_refresh() async def async_sync_time(service_call: ServiceCall) -> None: """Synchronize BSB-LAN device time with Home Assistant.""" device_id: str = service_call.data[ATTR_DEVICE_ID] # Get the device and config entry device_registry = dr.async_get(service_call.hass) device_entry = device_registry.async_get(device_id) if device_entry is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id", translation_placeholders={"device_id": device_id}, ) # Find the config entry for this device matching_entries: list[BSBLanConfigEntry] = [ entry for entry in service_call.hass.config_entries.async_entries(DOMAIN) if entry.entry_id in device_entry.config_entries ] if not matching_entries: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="no_config_entry_for_device", translation_placeholders={"device_id": device_entry.name or device_id}, ) entry = matching_entries[0] # Verify the config entry is loaded if entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="config_entry_not_loaded", translation_placeholders={"device_name": device_entry.name or device_id}, ) client = entry.runtime_data.client await async_sync_device_time(client, device_entry.name or device_id) SYNC_TIME_SCHEMA = vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the BSB-LAN services.""" hass.services.async_register( DOMAIN, "set_hot_water_schedule", set_hot_water_schedule, schema=SERVICE_SET_HOT_WATER_SCHEDULE_SCHEMA, ) hass.services.async_register( DOMAIN, "sync_time", async_sync_time, schema=SYNC_TIME_SCHEMA, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bsblan/services.py", "license": "Apache License 2.0", "lines": 220, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/button/trigger.py
"""Provides triggers for buttons.""" from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant, State from homeassistant.helpers.trigger import ( ENTITY_STATE_TRIGGER_SCHEMA, EntityTriggerBase, Trigger, ) from . import DOMAIN class ButtonPressedTrigger(EntityTriggerBase): """Trigger for button entity presses.""" _domain = DOMAIN _schema = ENTITY_STATE_TRIGGER_SCHEMA def is_valid_transition(self, from_state: State, to_state: State) -> bool: """Check if the origin state is valid and different from the current state.""" # UNKNOWN is a valid from_state, otherwise the first time the button is pressed # would not trigger if from_state.state == STATE_UNAVAILABLE: return False return from_state.state != to_state.state def is_valid_state(self, state: State) -> bool: """Check if the new state is not invalid.""" return state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN) TRIGGERS: dict[str, type[Trigger]] = { "pressed": ButtonPressedTrigger, } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for buttons.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/button/trigger.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/color_extractor/services.py
"""Module for color_extractor (RGB extraction from images) component.""" import asyncio import io import logging import aiohttp from colorthief import ColorThief from PIL import UnidentifiedImageError import voluptuous as vol from homeassistant.components.light import ( ATTR_RGB_COLOR, DOMAIN as LIGHT_DOMAIN, LIGHT_TURN_ON_SCHEMA, ) from homeassistant.const import SERVICE_TURN_ON as LIGHT_SERVICE_TURN_ON from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.helpers import aiohttp_client, config_validation as cv from .const import ATTR_PATH, ATTR_URL, DOMAIN, SERVICE_TURN_ON _LOGGER = logging.getLogger(__name__) # Extend the existing light.turn_on service schema SERVICE_SCHEMA = vol.All( cv.has_at_least_one_key(ATTR_URL, ATTR_PATH), cv.make_entity_service_schema( { **LIGHT_TURN_ON_SCHEMA, vol.Exclusive(ATTR_PATH, "color_extractor"): cv.isfile, vol.Exclusive(ATTR_URL, "color_extractor"): cv.url, } ), ) def _get_file(file_path: str) -> str: """Get a PIL acceptable input file reference. Allows us to mock patch during testing to make BytesIO stream. """ return file_path def _get_color(file_handler: io.BytesIO | str) -> tuple[int, int, int]: """Given an image file, extract the predominant color from it.""" color_thief = ColorThief(file_handler) # get_color returns a SINGLE RGB value for the given image color = color_thief.get_color(quality=1) _LOGGER.debug("Extracted RGB color %s from image", color) return color async def _async_extract_color_from_url( hass: HomeAssistant, url: str ) -> tuple[int, int, int] | None: """Handle call for URL based image.""" if not hass.config.is_allowed_external_url(url): _LOGGER.error( ( "External URL '%s' is not allowed, please add to" " 'allowlist_external_urls'" ), url, ) return None _LOGGER.debug("Getting predominant RGB from image URL '%s'", url) # Download the image into a buffer for ColorThief to check against try: session = aiohttp_client.async_get_clientsession(hass) async with asyncio.timeout(10): response = await session.get(url) except (TimeoutError, aiohttp.ClientError) as err: _LOGGER.error("Failed to get ColorThief image due to HTTPError: %s", err) return None content = await response.content.read() with io.BytesIO(content) as _file: _file.name = "color_extractor.jpg" _file.seek(0) return _get_color(_file) def _extract_color_from_path( hass: HomeAssistant, file_path: str ) -> tuple[int, int, int] | None: """Handle call for local file based image.""" if not hass.config.is_allowed_path(file_path): _LOGGER.error( "File path '%s' is not allowed, please add to 'allowlist_external_dirs'", file_path, ) return None _LOGGER.debug("Getting predominant RGB from file path '%s'", file_path) _file = _get_file(file_path) return _get_color(_file) async def async_handle_service(service_call: ServiceCall) -> None: """Decide which color_extractor method to call based on service.""" service_data = dict(service_call.data) try: if ATTR_URL in service_data: image_type = "URL" image_reference = service_data.pop(ATTR_URL) color = await _async_extract_color_from_url( service_call.hass, image_reference ) elif ATTR_PATH in service_data: image_type = "file path" image_reference = service_data.pop(ATTR_PATH) color = await service_call.hass.async_add_executor_job( _extract_color_from_path, service_call.hass, image_reference ) except UnidentifiedImageError as ex: _LOGGER.error( "Bad image from %s '%s' provided, are you sure it's an image? %s", image_type, image_reference, ex, ) return if color: service_data[ATTR_RGB_COLOR] = color await service_call.hass.services.async_call( LIGHT_DOMAIN, LIGHT_SERVICE_TURN_ON, service_data, blocking=True ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the services.""" hass.services.async_register( DOMAIN, SERVICE_TURN_ON, async_handle_service, schema=SERVICE_SCHEMA, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/color_extractor/services.py", "license": "Apache License 2.0", "lines": 119, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/cookidoo/calendar.py
"""Calendar platform for the Cookidoo integration.""" from __future__ import annotations from datetime import date, datetime, timedelta import logging from cookidoo_api import CookidooAuthException, CookidooException from cookidoo_api.types import CookidooCalendarDayRecipe from homeassistant.components.calendar import CalendarEntity, CalendarEvent from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import CookidooConfigEntry, CookidooDataUpdateCoordinator from .entity import CookidooBaseEntity _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: CookidooConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the calendar platform for entity.""" coordinator = config_entry.runtime_data async_add_entities([CookidooCalendarEntity(coordinator)]) def recipe_to_event(day_date: date, recipe: CookidooCalendarDayRecipe) -> CalendarEvent: """Convert a Cookidoo recipe to a CalendarEvent.""" return CalendarEvent( start=day_date, end=day_date + timedelta(days=1), # All-day event summary=recipe.name, description=f"Total Time: {recipe.total_time}", ) class CookidooCalendarEntity(CookidooBaseEntity, CalendarEntity): """A calendar entity.""" _attr_translation_key = "meal_plan" def __init__(self, coordinator: CookidooDataUpdateCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) assert coordinator.config_entry.unique_id self._attr_unique_id = coordinator.config_entry.unique_id @property def event(self) -> CalendarEvent | None: """Return the next upcoming event.""" if not self.coordinator.data.week_plan: return None today = date.today() for day_data in self.coordinator.data.week_plan: day_date = date.fromisoformat(day_data.id) if day_date >= today and day_data.recipes: recipe = day_data.recipes[0] return recipe_to_event(day_date, recipe) return None async def _fetch_week_plan(self, week_day: date) -> list: """Fetch a single Cookidoo week plan, retrying once on auth failure.""" try: return await self.coordinator.cookidoo.get_recipes_in_calendar_week( week_day ) except CookidooAuthException: await self.coordinator.cookidoo.refresh_token() return await self.coordinator.cookidoo.get_recipes_in_calendar_week( week_day ) except CookidooException as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="calendar_fetch_failed", ) from e async def async_get_events( self, hass: HomeAssistant, start_date: datetime, end_date: datetime ) -> list[CalendarEvent]: """Get all events in a specific time frame.""" events: list[CalendarEvent] = [] current_day = start_date.date() while current_day <= end_date.date(): week_plan = await self._fetch_week_plan(current_day) for day_data in week_plan: day_date = date.fromisoformat(day_data.id) if start_date.date() <= day_date <= end_date.date(): events.extend( recipe_to_event(day_date, recipe) for recipe in day_data.recipes ) current_day += timedelta(days=7) # Move to the next week return events
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cookidoo/calendar.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/device_tracker/trigger.py
"""Provides triggers for device_trackers.""" from homeassistant.const import STATE_HOME from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import ( Trigger, make_entity_origin_state_trigger, make_entity_target_state_trigger, ) from .const import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "entered_home": make_entity_target_state_trigger(DOMAIN, STATE_HOME), "left_home": make_entity_origin_state_trigger(DOMAIN, from_state=STATE_HOME), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for device trackers.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/device_tracker/trigger.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/duckdns/coordinator.py
"""Coordinator for the Duck DNS integration.""" from __future__ import annotations from datetime import timedelta import logging from aiohttp import ClientError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN from .helpers import update_duckdns _LOGGER = logging.getLogger(__name__) type DuckDnsConfigEntry = ConfigEntry[DuckDnsUpdateCoordinator] INTERVAL = timedelta(minutes=5) BACKOFF_INTERVALS = ( INTERVAL, timedelta(minutes=1), timedelta(minutes=5), timedelta(minutes=15), timedelta(minutes=30), ) class DuckDnsUpdateCoordinator(DataUpdateCoordinator[None]): """Duck DNS update coordinator.""" config_entry: DuckDnsConfigEntry def __init__(self, hass: HomeAssistant, config_entry: DuckDnsConfigEntry) -> None: """Initialize the Duck DNS update coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=INTERVAL, ) self.session = async_get_clientsession(hass) self.failed = 0 async def _async_update_data(self) -> None: """Update Duck DNS.""" retry_after = BACKOFF_INTERVALS[ min(self.failed, len(BACKOFF_INTERVALS)) ].total_seconds() try: if not await update_duckdns( self.session, self.config_entry.data[CONF_DOMAIN], self.config_entry.data[CONF_ACCESS_TOKEN], ): self.failed += 1 raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", translation_placeholders={ CONF_DOMAIN: self.config_entry.data[CONF_DOMAIN], }, retry_after=retry_after, ) except ClientError as e: self.failed += 1 raise UpdateFailed( translation_domain=DOMAIN, translation_key="connection_error", translation_placeholders={ CONF_DOMAIN: self.config_entry.data[CONF_DOMAIN], }, retry_after=retry_after, ) from e self.failed = 0
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/coordinator.py", "license": "Apache License 2.0", "lines": 67, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/duckdns/helpers.py
"""Helpers for Duck DNS integration.""" from aiohttp import ClientSession from homeassistant.helpers.typing import UNDEFINED, UndefinedType UPDATE_URL = "https://www.duckdns.org/update" async def update_duckdns( session: ClientSession, domain: str, token: str, *, txt: str | None | UndefinedType = UNDEFINED, clear: bool = False, ) -> bool: """Update DuckDNS.""" params = {"domains": domain, "token": token} if txt is not UNDEFINED: if txt is None: # Pass in empty txt value to indicate it's clearing txt record params["txt"] = "" clear = True else: params["txt"] = txt if clear: params["clear"] = "true" resp = await session.get(UPDATE_URL, params=params) body = await resp.text() return body == "OK"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/helpers.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/duckdns/services.py
"""Actions for Duck DNS.""" from __future__ import annotations from aiohttp import ClientError import voluptuous as vol from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import config_validation as cv, service from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ConfigEntrySelector from .const import ATTR_CONFIG_ENTRY, ATTR_TXT, DOMAIN, SERVICE_SET_TXT from .coordinator import DuckDnsConfigEntry from .helpers import update_duckdns from .issue import action_called_without_config_entry SERVICE_TXT_SCHEMA = vol.Schema( { vol.Optional(ATTR_CONFIG_ENTRY): ConfigEntrySelector({"integration": DOMAIN}), vol.Optional(ATTR_TXT): vol.Any(None, cv.string), } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services for Habitica integration.""" hass.services.async_register( DOMAIN, SERVICE_SET_TXT, update_domain_service, schema=SERVICE_TXT_SCHEMA, ) def get_config_entry( hass: HomeAssistant, entry_id: str | None = None ) -> DuckDnsConfigEntry: """Return config entry or raise if not found or not loaded.""" if entry_id is None: action_called_without_config_entry(hass) if len(entries := hass.config_entries.async_entries(DOMAIN)) != 1: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="entry_not_selected", ) entry_id = entries[0].entry_id return service.async_get_config_entry(hass, DOMAIN, entry_id) async def update_domain_service(call: ServiceCall) -> None: """Update the DuckDNS entry.""" entry = get_config_entry(call.hass, call.data.get(ATTR_CONFIG_ENTRY)) session = async_get_clientsession(call.hass) try: if not await update_duckdns( session, entry.data[CONF_DOMAIN], entry.data[CONF_ACCESS_TOKEN], txt=call.data.get(ATTR_TXT), ): raise HomeAssistantError( translation_domain=DOMAIN, translation_key="update_failed", translation_placeholders={ CONF_DOMAIN: entry.data[CONF_DOMAIN], }, ) except ClientError as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="connection_error", translation_placeholders={ CONF_DOMAIN: entry.data[CONF_DOMAIN], }, ) from e
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/services.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/egauge/config_flow.py
"""Config flow to configure the eGauge integration.""" from __future__ import annotations from typing import Any from egauge_async.exceptions import EgaugeAuthenticationError, EgaugePermissionError from egauge_async.json.client import EgaugeJsonClient from httpx import ConnectError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.helpers.httpx_client import get_async_client from .const import DOMAIN, LOGGER STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_SSL, default=True): bool, vol.Required(CONF_VERIFY_SSL, default=False): bool, } ) class EgaugeFlowHandler(ConfigFlow, domain=DOMAIN): """Handle an eGauge config flow.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow initiated by the user.""" errors: dict[str, str] = {} if user_input is not None: client = EgaugeJsonClient( host=user_input[CONF_HOST], username=user_input[CONF_USERNAME], password=user_input[CONF_PASSWORD], client=get_async_client( self.hass, verify_ssl=user_input[CONF_VERIFY_SSL] ), use_ssl=user_input[CONF_SSL], ) try: serial_number = await client.get_device_serial_number() hostname = await client.get_hostname() except EgaugeAuthenticationError: errors["base"] = "invalid_auth" except EgaugePermissionError: errors["base"] = "missing_permission" except ConnectError: errors["base"] = "cannot_connect" except Exception: # noqa: BLE001 LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: await self.async_set_unique_id(serial_number) self._abort_if_unique_id_configured() return self.async_create_entry(title=hostname, data=user_input) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, user_input ), errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/egauge/config_flow.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/egauge/const.py
"""Constants for the eGauge integration.""" import logging DOMAIN = "egauge" LOGGER = logging.getLogger(__package__) MANUFACTURER = "eGauge Systems" MODEL = "eGauge Energy Monitor" COORDINATOR_UPDATE_INTERVAL_SECONDS = 30
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/egauge/const.py", "license": "Apache License 2.0", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/egauge/coordinator.py
"""Data update coordinator for eGauge energy monitors.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta from egauge_async.exceptions import ( EgaugeAuthenticationError, EgaugeException, EgaugePermissionError, ) from egauge_async.json.client import EgaugeJsonClient from egauge_async.json.models import RegisterInfo from httpx import ConnectError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers.httpx_client import get_async_client from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import COORDINATOR_UPDATE_INTERVAL_SECONDS, DOMAIN, LOGGER type EgaugeConfigEntry = ConfigEntry[EgaugeDataCoordinator] @dataclass class EgaugeData: """Data from eGauge device.""" measurements: dict[str, float] # Instantaneous values (W, V, A, etc.) counters: dict[str, float] # Cumulative values (Ws) register_info: dict[str, RegisterInfo] # Metadata for all registers class EgaugeDataCoordinator(DataUpdateCoordinator[EgaugeData]): """Class to manage fetching eGauge data.""" serial_number: str hostname: str def __init__(self, hass: HomeAssistant, config_entry: ConfigEntry) -> None: """Initialize the coordinator.""" super().__init__( hass, logger=LOGGER, name=DOMAIN, update_interval=timedelta(seconds=COORDINATOR_UPDATE_INTERVAL_SECONDS), config_entry=config_entry, ) self.client = EgaugeJsonClient( host=config_entry.data[CONF_HOST], username=config_entry.data[CONF_USERNAME], password=config_entry.data[CONF_PASSWORD], client=get_async_client( hass, verify_ssl=config_entry.data[CONF_VERIFY_SSL] ), use_ssl=config_entry.data[CONF_SSL], ) # Populated in _async_setup self._register_info: dict[str, RegisterInfo] = {} async def _async_setup(self) -> None: try: self.serial_number = await self.client.get_device_serial_number() self.hostname = await self.client.get_hostname() self._register_info = await self.client.get_register_info() except ( EgaugeAuthenticationError, EgaugePermissionError, EgaugeException, ) as err: # EgaugeAuthenticationError and EgaugePermissionError will raise ConfigEntryAuthFailed once reauth is implemented raise ConfigEntryError from err except ConnectError as err: raise UpdateFailed(f"Error fetching device info: {err}") from err async def _async_update_data(self) -> EgaugeData: """Fetch data from eGauge device.""" try: measurements = await self.client.get_current_measurements() counters = await self.client.get_current_counters() except ( EgaugeAuthenticationError, EgaugePermissionError, EgaugeException, ) as err: # will raise ConfigEntryAuthFailed once reauth is implemented raise ConfigEntryError("Error fetching device info: {err}") from err except ConnectError as err: raise UpdateFailed(f"Error fetching device info: {err}") from err return EgaugeData( measurements=measurements, counters=counters, register_info=self._register_info, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/egauge/coordinator.py", "license": "Apache License 2.0", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/egauge/entity.py
"""Base entity for the eGauge integration.""" from __future__ import annotations from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER, MODEL from .coordinator import EgaugeDataCoordinator class EgaugeEntity(CoordinatorEntity[EgaugeDataCoordinator]): """Base entity for eGauge sensors.""" _attr_has_entity_name = True def __init__( self, coordinator: EgaugeDataCoordinator, register_name: str, ) -> None: """Initialize the eGauge entity.""" super().__init__(coordinator) register_identifier = f"{coordinator.serial_number}_{register_name}" register_name = f"{coordinator.hostname} {register_name}" # Device info using coordinator's cached data self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, register_identifier)}, name=register_name, manufacturer=MANUFACTURER, model=MODEL, via_device=(DOMAIN, coordinator.serial_number), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/egauge/entity.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/egauge/sensor.py
"""Sensor platform for eGauge energy monitors.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from egauge_async.json.models import RegisterInfo, RegisterType from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfPower, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import EgaugeConfigEntry, EgaugeData, EgaugeDataCoordinator from .entity import EgaugeEntity @dataclass(frozen=True, kw_only=True) class EgaugeSensorEntityDescription(SensorEntityDescription): """Extended sensor description for eGauge sensors.""" native_value_fn: Callable[[EgaugeData, str], float] available_fn: Callable[[EgaugeData, str], bool] supported_fn: Callable[[RegisterInfo], bool] SENSORS: tuple[EgaugeSensorEntityDescription, ...] = ( EgaugeSensorEntityDescription( key="power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, native_value_fn=lambda data, register: data.measurements[register], available_fn=lambda data, register: register in data.measurements, supported_fn=lambda register_info: register_info.type == RegisterType.POWER, ), EgaugeSensorEntityDescription( key="energy", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement=UnitOfEnergy.JOULE, suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, native_value_fn=lambda data, register: data.counters[register], available_fn=lambda data, register: register in data.counters, supported_fn=lambda register_info: register_info.type == RegisterType.POWER, ), EgaugeSensorEntityDescription( key="voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, native_value_fn=lambda data, register: data.measurements[register], available_fn=lambda data, register: register in data.measurements, supported_fn=lambda register_info: register_info.type == RegisterType.VOLTAGE, ), EgaugeSensorEntityDescription( key="current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, native_value_fn=lambda data, register: data.measurements[register], available_fn=lambda data, register: register in data.measurements, supported_fn=lambda register_info: register_info.type == RegisterType.CURRENT, ), ) async def async_setup_entry( hass: HomeAssistant, entry: EgaugeConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up eGauge sensor platform.""" coordinator = entry.runtime_data async_add_entities( EgaugeSensor(coordinator, register_name, sensor) for sensor in SENSORS for register_name, register_info in coordinator.data.register_info.items() if sensor.supported_fn(register_info) ) class EgaugeSensor(EgaugeEntity, SensorEntity): """Generic sensor entity using entity description pattern.""" entity_description: EgaugeSensorEntityDescription def __init__( self, coordinator: EgaugeDataCoordinator, register_name: str, description: EgaugeSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator, register_name) self._register_name = register_name self.entity_description = description self._attr_unique_id = ( f"{coordinator.serial_number}_{register_name}_{description.key}" ) @property def native_value(self) -> float: """Return the sensor value using the description's value function.""" return self.entity_description.native_value_fn( self.coordinator.data, self._register_name ) @property def available(self) -> bool: """Return true if the corresponding register is available.""" return super().available and self.entity_description.available_fn( self.coordinator.data, self._register_name )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/egauge/sensor.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/entur_public_transport/const.py
"""Constants for the Entur public transport integration.""" from datetime import timedelta DOMAIN = "entur_public_transport" API_CLIENT_NAME = "homeassistant-{}" CONF_STOP_IDS = "stop_ids" CONF_EXPAND_PLATFORMS = "expand_platforms" CONF_WHITELIST_LINES = "line_whitelist" CONF_OMIT_NON_BOARDING = "omit_non_boarding" CONF_NUMBER_OF_DEPARTURES = "number_of_departures" DEFAULT_NAME = "Entur" DEFAULT_ICON_KEY = "bus" ICONS = { "air": "mdi:airplane", "bus": "mdi:bus", "metro": "mdi:subway", "rail": "mdi:train", "tram": "mdi:tram", "water": "mdi:ferry", } SCAN_INTERVAL = timedelta(seconds=45) ATTR_STOP_ID = "stop_id" ATTR_ROUTE = "route" ATTR_ROUTE_ID = "route_id" ATTR_EXPECTED_AT = "due_at" ATTR_DELAY = "delay" ATTR_REALTIME = "real_time" ATTR_NEXT_UP_IN = "next_due_in" ATTR_NEXT_UP_ROUTE = "next_route" ATTR_NEXT_UP_ROUTE_ID = "next_route_id" ATTR_NEXT_UP_AT = "next_due_at" ATTR_NEXT_UP_DELAY = "next_delay" ATTR_NEXT_UP_REALTIME = "next_real_time" ATTR_TRANSPORT_MODE = "transport_mode"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/entur_public_transport/const.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fish_audio/config_flow.py
"""Config flow for the Fish Audio integration.""" from __future__ import annotations import logging from typing import Any from fishaudio import AsyncFishAudio from fishaudio.exceptions import AuthenticationError, FishAudioError import voluptuous as vol from homeassistant.config_entries import ( SOURCE_USER, ConfigEntry, ConfigEntryState, ConfigFlow, ConfigFlowResult, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.selector import ( LanguageSelector, LanguageSelectorConfig, SelectOptionDict, SelectSelector, SelectSelectorConfig, SelectSelectorMode, ) from .const import ( API_KEYS_URL, BACKEND_MODELS, CONF_API_KEY, CONF_BACKEND, CONF_LANGUAGE, CONF_LATENCY, CONF_NAME, CONF_SELF_ONLY, CONF_SORT_BY, CONF_TITLE, CONF_USER_ID, CONF_VOICE_ID, DOMAIN, LATENCY_OPTIONS, SIGNUP_URL, SORT_BY_OPTIONS, TTS_SUPPORTED_LANGUAGES, ) from .error import ( CannotConnectError, CannotGetModelsError, InvalidAuthError, UnexpectedError, ) _LOGGER = logging.getLogger(__name__) def get_api_key_schema(default: str | None = None) -> vol.Schema: """Return the schema for API key input.""" return vol.Schema( {vol.Required(CONF_API_KEY, default=default or vol.UNDEFINED): str} ) def get_filter_schema(options: dict[str, Any]) -> vol.Schema: """Return the schema for the filter step.""" return vol.Schema( { vol.Optional(CONF_TITLE, default=options.get(CONF_TITLE, "")): str, vol.Optional( CONF_LANGUAGE, default=options.get(CONF_LANGUAGE, "Any") ): LanguageSelector( LanguageSelectorConfig( languages=TTS_SUPPORTED_LANGUAGES, ) ), vol.Optional( CONF_SORT_BY, default=options.get(CONF_SORT_BY, "task_count") ): SelectSelector( SelectSelectorConfig( options=SORT_BY_OPTIONS, mode=SelectSelectorMode.DROPDOWN, translation_key="sort_by", ) ), vol.Optional( CONF_SELF_ONLY, default=options.get(CONF_SELF_ONLY, False) ): bool, } ) def get_model_selection_schema( options: dict[str, Any], model_options: list[SelectOptionDict], ) -> vol.Schema: """Return the schema for the model selection step.""" return vol.Schema( { vol.Required( CONF_VOICE_ID, default=options.get(CONF_VOICE_ID, ""), ): SelectSelector( SelectSelectorConfig( options=model_options, mode=SelectSelectorMode.DROPDOWN, custom_value=True, ) ), vol.Required( CONF_BACKEND, default=options.get(CONF_BACKEND, "s1"), ): SelectSelector( SelectSelectorConfig( options=[ SelectOptionDict(value=opt, label=opt) for opt in BACKEND_MODELS ], mode=SelectSelectorMode.DROPDOWN, ) ), vol.Required( CONF_LATENCY, default=options.get(CONF_LATENCY, "balanced"), ): SelectSelector( SelectSelectorConfig( options=[ SelectOptionDict(value=opt, label=opt) for opt in LATENCY_OPTIONS ], mode=SelectSelectorMode.DROPDOWN, ) ), vol.Required( CONF_NAME, default=options.get(CONF_NAME) or vol.UNDEFINED, ): str, } ) async def _validate_api_key( hass: HomeAssistant, api_key: str ) -> tuple[str, AsyncFishAudio]: """Validate the user input allows us to connect.""" client = AsyncFishAudio(api_key=api_key) try: # Validate API key and get user info credit_info = await client.account.get_credits() user_id = credit_info.user_id except AuthenticationError as exc: raise InvalidAuthError(exc) from exc except FishAudioError as exc: raise CannotConnectError(exc) from exc except Exception as exc: raise UnexpectedError(exc) from exc return user_id, client class FishAudioConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Fish Audio.""" VERSION = 1 client: AsyncFishAudio | None def __init__(self) -> None: """Initialize the config flow.""" self.client = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" if user_input is None: return self.async_show_form( step_id="user", data_schema=get_api_key_schema(), errors={}, description_placeholders={"signup_url": SIGNUP_URL}, ) errors: dict[str, str] = {} try: user_id, self.client = await _validate_api_key( self.hass, user_input[CONF_API_KEY] ) except InvalidAuthError: errors["base"] = "invalid_auth" except CannotConnectError: errors["base"] = "cannot_connect" except UnexpectedError: errors["base"] = "unknown" else: await self.async_set_unique_id(user_id) self._abort_if_unique_id_configured() data: dict[str, Any] = { CONF_API_KEY: user_input[CONF_API_KEY], CONF_USER_ID: user_id, } return self.async_create_entry( title="Fish Audio", data=data, ) return self.async_show_form( step_id="user", data_schema=get_api_key_schema(), errors=errors, description_placeholders={ "signup_url": SIGNUP_URL, "api_keys_url": API_KEYS_URL, }, ) @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type]: """Return subentries supported by this integration.""" return {"tts": FishAudioSubentryFlowHandler} class FishAudioSubentryFlowHandler(ConfigSubentryFlow): """Handle subentry flow for adding and modifying a tts entity.""" config_data: dict[str, Any] models: list[SelectOptionDict] client: AsyncFishAudio def __init__(self) -> None: """Initialize the subentry flow handler.""" super().__init__() self.models: list[SelectOptionDict] = [] async def _async_get_models( self, self_only: bool, language: str | None, title: str | None, sort_by: str ) -> list[SelectOptionDict]: """Get the available models.""" try: voices_response = await self.client.voices.list( self_only=self_only, language=language if language and language.strip() and language != "Any" else None, title=title if title and title.strip() else None, sort_by=sort_by, ) except Exception as exc: raise CannotGetModelsError(exc) from exc voices = voices_response.items return [ SelectOptionDict( value=voice.id, label=f"{voice.title} - {voice.task_count} uses", ) for voice in voices ] async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the initial step.""" self.config_data = {} return await self.async_step_init() async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle reconfiguration of a subentry.""" self.config_data = dict(self._get_reconfigure_subentry().data) return await self.async_step_init() async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Manage initial options.""" entry = self._get_entry() if entry.state != ConfigEntryState.LOADED: return self.async_abort(reason="entry_not_loaded") self.client = entry.runtime_data if user_input is not None: self.config_data.update(user_input) return await self.async_step_model() return self.async_show_form( step_id="init", data_schema=get_filter_schema(self.config_data), errors={}, ) async def async_step_model( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the model selection step.""" errors: dict[str, str] = {} if not self.models: try: self.models = await self._async_get_models( self_only=self.config_data.get(CONF_SELF_ONLY, False), language=self.config_data.get(CONF_LANGUAGE), title=self.config_data.get(CONF_TITLE), sort_by=self.config_data.get(CONF_SORT_BY, "task_count"), ) except CannotGetModelsError: return self.async_abort(reason="cannot_connect") if not self.models: return self.async_abort(reason="no_models_found") if CONF_VOICE_ID not in self.config_data and self.models: self.config_data[CONF_VOICE_ID] = self.models[0]["value"] if user_input is not None: if ( (voice_id := user_input.get(CONF_VOICE_ID)) and (backend := user_input.get(CONF_BACKEND)) and (name := user_input.get(CONF_NAME)) ): self.config_data.update(user_input) unique_id = f"{voice_id}-{backend}" if self.source == SOURCE_USER: return self.async_create_entry( title=name, data=self.config_data, unique_id=unique_id, ) return self.async_update_and_abort( self._get_entry(), self._get_reconfigure_subentry(), data=self.config_data, unique_id=unique_id, ) return self.async_show_form( step_id="model", data_schema=get_model_selection_schema(self.config_data, self.models), errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fish_audio/config_flow.py", "license": "Apache License 2.0", "lines": 304, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fish_audio/const.py
"""Constants for the FishAudio integration.""" from typing import Literal DOMAIN = "fish_audio" CONF_NAME: Literal["name"] = "name" CONF_USER_ID: Literal["user_id"] = "user_id" CONF_API_KEY: Literal["api_key"] = "api_key" CONF_VOICE_ID: Literal["voice_id"] = "voice_id" CONF_BACKEND: Literal["backend"] = "backend" CONF_SELF_ONLY: Literal["self_only"] = "self_only" CONF_LANGUAGE: Literal["language"] = "language" CONF_SORT_BY: Literal["sort_by"] = "sort_by" CONF_LATENCY: Literal["latency"] = "latency" CONF_TITLE: Literal["title"] = "title" DEVELOPER_ID = "1e9f9baadce144f5b16dd94cbc0314c8" TTS_SUPPORTED_LANGUAGES = [ "Any", "en", "zh", "de", "ja", "ar", "fr", "es", "ko", ] BACKEND_MODELS = ["s1", "speech-1.5", "speech-1.6"] SORT_BY_OPTIONS = ["task_count", "score", "created_at"] LATENCY_OPTIONS = ["normal", "balanced"] SIGNUP_URL = "https://fish.audio/" BILLING_URL = "https://fish.audio/app/billing/" API_KEYS_URL = "https://fish.audio/app/api-keys/"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fish_audio/const.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fish_audio/error.py
"""Exceptions for the Fish Audio integration.""" import logging from homeassistant.exceptions import HomeAssistantError _LOGGER = logging.getLogger(__package__) class FishAudioError(HomeAssistantError): """Base class for Fish Audio errors.""" class CannotConnectError(FishAudioError): """Error to indicate we cannot connect.""" def __init__(self, exc: Exception) -> None: """Initialize the connection error.""" super().__init__("Cannot connect") class InvalidAuthError(FishAudioError): """Error to indicate invalid authentication.""" def __init__(self, exc: Exception) -> None: """Initialize the invalid auth error.""" super().__init__("Invalid authentication") class CannotGetModelsError(FishAudioError): """Error to indicate we cannot get models.""" def __init__(self, exc: Exception) -> None: """Initialize the model fetch error.""" super().__init__("Cannot get models") class UnexpectedError(FishAudioError): """Error to indicate an unexpected error.""" def __init__(self, exc: Exception) -> None: """Initialize and log the unexpected error.""" super().__init__("Unexpected error") _LOGGER.exception("Unexpected exception: %s", exc) class AlreadyConfiguredError(FishAudioError): """Error to indicate already configured.""" def __init__(self, exc: Exception) -> None: """Initialize the already configured error.""" super().__init__("Already configured")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fish_audio/error.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fish_audio/tts.py
"""TTS platform for the Fish Audio integration.""" from __future__ import annotations import logging from typing import Any from fishaudio.exceptions import APIError, RateLimitError from homeassistant.components.tts import TextToSpeechEntity, TtsAudioType from homeassistant.config_entries import ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FishAudioConfigEntry from .const import ( CONF_BACKEND, CONF_LATENCY, CONF_VOICE_ID, DOMAIN, TTS_SUPPORTED_LANGUAGES, ) from .error import UnexpectedError PARALLEL_UPDATES = 1 _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: FishAudioConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Fish Audio TTS platform.""" _LOGGER.debug("Setting up Fish Audio TTS platform") _LOGGER.debug("Entry: %s", entry) # Iterate over values for subentry in entry.subentries.values(): _LOGGER.debug("Subentry: %s", subentry) if subentry.subentry_type != "tts": continue async_add_entities( [FishAudioTTSEntity(entry, subentry)], config_subentry_id=subentry.subentry_id, ) class FishAudioTTSEntity(TextToSpeechEntity): """Fish Audio TTS entity.""" _attr_has_entity_name = True _attr_supported_options = [CONF_VOICE_ID, CONF_BACKEND, CONF_LATENCY] def __init__(self, entry: FishAudioConfigEntry, sub_entry: ConfigSubentry) -> None: """Initialize the TTS entity.""" self.client = entry.runtime_data self.sub_entry = sub_entry self._attr_unique_id = sub_entry.subentry_id title = sub_entry.title backend = sub_entry.data[CONF_BACKEND] self._attr_name = title self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, sub_entry.subentry_id)}, manufacturer="Fish Audio", model=backend, name=title, entry_type=DeviceEntryType.SERVICE, ) @property def default_language(self) -> str: """Return the default language.""" return "en" @property def supported_languages(self) -> list[str]: """Return a list of supported languages.""" return TTS_SUPPORTED_LANGUAGES async def async_get_tts_audio( self, message: str, language: str, options: dict[str, Any], ) -> TtsAudioType: """Load tts audio file from engine.""" _LOGGER.debug("Getting TTS audio for %s", message) voice_id = options.get(CONF_VOICE_ID, self.sub_entry.data.get(CONF_VOICE_ID)) backend = options.get(CONF_BACKEND, self.sub_entry.data.get(CONF_BACKEND)) latency = options.get( CONF_LATENCY, self.sub_entry.data.get(CONF_LATENCY, "balanced") ) if voice_id is None: raise ServiceValidationError("Voice ID not configured") if backend is None: raise ServiceValidationError("Backend model not configured") try: audio = await self.client.tts.convert( text=message, reference_id=voice_id, latency=latency, model=backend, format="mp3", ) except RateLimitError as err: _LOGGER.error("Fish Audio TTS rate limited: %s", err) raise HomeAssistantError(f"Rate limited: {err}") from err except APIError as err: _LOGGER.error("Fish Audio TTS request failed: %s", err) raise HomeAssistantError(f"TTS request failed: {err}") from err except Exception as err: raise UnexpectedError(err) from err return "mp3", audio
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fish_audio/tts.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fish_audio/types.py
"""Type definitions for the Fish Audio integration.""" from __future__ import annotations from fishaudio import AsyncFishAudio from homeassistant.config_entries import ConfigEntry type FishAudioConfigEntry = ConfigEntry[AsyncFishAudio]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fish_audio/types.py", "license": "Apache License 2.0", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fluss/button.py
"""Support for Fluss Devices.""" from homeassistant.components.button import ButtonEntity from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import FlussApiClientError, FlussDataUpdateCoordinator from .entity import FlussEntity type FlussConfigEntry = ConfigEntry[FlussDataUpdateCoordinator] async def async_setup_entry( hass: HomeAssistant, entry: FlussConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Fluss Devices, filtering out any invalid payloads.""" coordinator = entry.runtime_data devices = coordinator.data async_add_entities( FlussButton(coordinator, device_id, device) for device_id, device in devices.items() ) class FlussButton(FlussEntity, ButtonEntity): """Representation of a Fluss button device.""" _attr_name = None async def async_press(self) -> None: """Handle the button press.""" try: await self.coordinator.api.async_trigger_device(self.device_id) except FlussApiClientError as err: raise HomeAssistantError(f"Failed to trigger device: {err}") from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fluss/button.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fluss/config_flow.py
"""Config flow for Fluss+ integration.""" from __future__ import annotations from typing import Any from fluss_api import ( FlussApiClient, FlussApiClientAuthenticationError, FlussApiClientCommunicationError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_KEY from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN, LOGGER STEP_USER_DATA_SCHEMA = vol.Schema({vol.Required(CONF_API_KEY): cv.string}) class FlussConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Fluss+.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: api_key = user_input[CONF_API_KEY] self._async_abort_entries_match({CONF_API_KEY: api_key}) client = FlussApiClient( user_input[CONF_API_KEY], session=async_get_clientsession(self.hass) ) try: await client.async_get_devices() except FlussApiClientCommunicationError: errors["base"] = "cannot_connect" except FlussApiClientAuthenticationError: errors["base"] = "invalid_auth" except Exception: # noqa: BLE001 LOGGER.exception("Unexpected exception occurred") errors["base"] = "unknown" if not errors: return self.async_create_entry( title="My Fluss+ Devices", data=user_input ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fluss/config_flow.py", "license": "Apache License 2.0", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fluss/const.py
"""Constants for the Fluss+ integration.""" from datetime import timedelta import logging DOMAIN = "fluss" LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = 60 # seconds UPDATE_INTERVAL_TIMEDELTA = timedelta(seconds=UPDATE_INTERVAL)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fluss/const.py", "license": "Apache License 2.0", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fluss/coordinator.py
"""DataUpdateCoordinator for Fluss+ integration.""" from __future__ import annotations from typing import Any from fluss_api import ( FlussApiClient, FlussApiClientAuthenticationError, FlussApiClientError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import slugify from .const import LOGGER, UPDATE_INTERVAL_TIMEDELTA type FlussConfigEntry = ConfigEntry[FlussDataUpdateCoordinator] class FlussDataUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Manages fetching Fluss device data on a schedule.""" def __init__( self, hass: HomeAssistant, config_entry: FlussConfigEntry, api_key: str ) -> None: """Initialize the coordinator.""" self.api = FlussApiClient(api_key, session=async_get_clientsession(hass)) super().__init__( hass, LOGGER, name=f"Fluss+ ({slugify(api_key[:8])})", config_entry=config_entry, update_interval=UPDATE_INTERVAL_TIMEDELTA, ) async def _async_update_data(self) -> dict[str, dict[str, Any]]: """Fetch data from the Fluss API and return as a dictionary keyed by deviceId.""" try: devices = await self.api.async_get_devices() except FlussApiClientAuthenticationError as err: raise ConfigEntryError(f"Authentication failed: {err}") from err except FlussApiClientError as err: raise UpdateFailed(f"Error fetching Fluss devices: {err}") from err return {device["deviceId"]: device for device in devices.get("devices", [])}
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fluss/coordinator.py", "license": "Apache License 2.0", "lines": 39, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fluss/entity.py
"""Base entities for the Fluss+ integration.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .coordinator import FlussDataUpdateCoordinator class FlussEntity(CoordinatorEntity[FlussDataUpdateCoordinator]): """Base class for Fluss entities.""" _attr_has_entity_name = True def __init__( self, coordinator: FlussDataUpdateCoordinator, device_id: str, device: dict, ) -> None: """Initialize the entity with a device ID and device data.""" super().__init__(coordinator) self.device_id = device_id self._attr_unique_id = device_id self._attr_device_info = DeviceInfo( identifiers={("fluss", device_id)}, name=device.get("deviceName"), manufacturer="Fluss", model="Fluss+ Device", ) @property def available(self) -> bool: """Return if the device is available.""" return super().available and self.device_id in self.coordinator.data @property def device(self) -> dict: """Return the stored device data.""" return self.coordinator.data[self.device_id]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fluss/entity.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/binary_sensor.py
"""Binary Sensor platform for fressnapf_tracker.""" from collections.abc import Callable from dataclasses import dataclass from fressnapftracker import Tracker from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FressnapfTrackerConfigEntry from .entity import FressnapfTrackerEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class FressnapfTrackerBinarySensorDescription(BinarySensorEntityDescription): """Class describing Fressnapf Tracker binary_sensor entities.""" value_fn: Callable[[Tracker], bool] BINARY_SENSOR_ENTITY_DESCRIPTIONS: tuple[ FressnapfTrackerBinarySensorDescription, ... ] = ( FressnapfTrackerBinarySensorDescription( key="charging", device_class=BinarySensorDeviceClass.BATTERY_CHARGING, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.charging, ), ) async def async_setup_entry( hass: HomeAssistant, entry: FressnapfTrackerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Fressnapf Tracker binary_sensors.""" async_add_entities( FressnapfTrackerBinarySensor(coordinator, sensor_description) for sensor_description in BINARY_SENSOR_ENTITY_DESCRIPTIONS for coordinator in entry.runtime_data ) class FressnapfTrackerBinarySensor(FressnapfTrackerEntity, BinarySensorEntity): """Fressnapf Tracker binary_sensor for general information.""" entity_description: FressnapfTrackerBinarySensorDescription @property def is_on(self) -> bool: """Return True if the binary sensor is on.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/binary_sensor.py", "license": "Apache License 2.0", "lines": 48, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/config_flow.py
"""Config flow for the Fressnapf Tracker integration.""" from collections.abc import Mapping import logging from typing import Any from fressnapftracker import ( AuthClient, FressnapfTrackerInvalidPhoneNumberError, FressnapfTrackerInvalidTokenError, ) import voluptuous as vol from homeassistant.config_entries import ( SOURCE_REAUTH, SOURCE_RECONFIGURE, ConfigFlow, ConfigFlowResult, ) from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.helpers.httpx_client import get_async_client from .const import CONF_PHONE_NUMBER, CONF_SMS_CODE, CONF_USER_ID, DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_PHONE_NUMBER): str, } ) STEP_SMS_CODE_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_SMS_CODE): str, } ) class FressnapfTrackerConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Fressnapf Tracker.""" VERSION = 1 def __init__(self) -> None: """Init Config Flow.""" self._context: dict[str, Any] = {} self._auth_client: AuthClient | None = None @property def auth_client(self) -> AuthClient: """Return the auth client, creating it if needed.""" if self._auth_client is None: self._auth_client = AuthClient(client=get_async_client(self.hass)) return self._auth_client async def _async_request_sms_code( self, phone_number: str ) -> tuple[dict[str, str], bool]: """Request SMS code and return errors dict and success flag.""" errors: dict[str, str] = {} try: response = await self.auth_client.request_sms_code( phone_number=phone_number ) except FressnapfTrackerInvalidPhoneNumberError: errors["base"] = "invalid_phone_number" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: _LOGGER.debug("SMS code request response: %s", response) self._context[CONF_USER_ID] = response.id self._context[CONF_PHONE_NUMBER] = phone_number return errors, True return errors, False async def _async_verify_sms_code( self, sms_code: str ) -> tuple[dict[str, str], str | None]: """Verify SMS code and return errors and access_token.""" errors: dict[str, str] = {} try: verification_response = await self.auth_client.verify_phone_number( user_id=self._context[CONF_USER_ID], sms_code=sms_code, ) except FressnapfTrackerInvalidTokenError: errors["base"] = "invalid_sms_code" except Exception: _LOGGER.exception("Unexpected exception during SMS code verification") errors["base"] = "unknown" else: _LOGGER.debug( "Phone number verification response: %s", verification_response ) return errors, verification_response.user_token.access_token return errors, None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: self._async_abort_entries_match( {CONF_PHONE_NUMBER: user_input[CONF_PHONE_NUMBER]} ) errors, success = await self._async_request_sms_code( user_input[CONF_PHONE_NUMBER] ) if success: await self.async_set_unique_id(str(self._context[CONF_USER_ID])) self._abort_if_unique_id_configured() return await self.async_step_sms_code() return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_sms_code( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the SMS code step.""" errors: dict[str, str] = {} if user_input is not None: errors, access_token = await self._async_verify_sms_code( user_input[CONF_SMS_CODE] ) if access_token: return self.async_create_entry( title=self._context[CONF_PHONE_NUMBER], data={ CONF_PHONE_NUMBER: self._context[CONF_PHONE_NUMBER], CONF_USER_ID: self._context[CONF_USER_ID], CONF_ACCESS_TOKEN: access_token, }, ) return self.async_show_form( step_id="sms_code", data_schema=STEP_SMS_CODE_DATA_SCHEMA, errors=errors, ) async def _async_reauth_reconfigure( self, user_input: dict[str, Any] | None, entry: Any, step_id: str, ) -> ConfigFlowResult: """Request a new sms code for reauth or reconfigure flows.""" errors: dict[str, str] = {} if user_input is not None: errors, success = await self._async_request_sms_code( user_input[CONF_PHONE_NUMBER] ) if success: if entry.data[CONF_USER_ID] != self._context[CONF_USER_ID]: errors["base"] = "account_change_not_allowed" elif self.source == SOURCE_REAUTH: return await self.async_step_reauth_sms_code() elif self.source == SOURCE_RECONFIGURE: return await self.async_step_reconfigure_sms_code() return self.async_show_form( step_id=step_id, data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, {CONF_PHONE_NUMBER: entry.data.get(CONF_PHONE_NUMBER)}, ), errors=errors, ) async def _async_reauth_reconfigure_sms_code( self, user_input: dict[str, Any] | None, entry: Any, step_id: str, ) -> ConfigFlowResult: """Verify SMS code for reauth or reconfigure flows.""" errors: dict[str, str] = {} if user_input is not None: errors, access_token = await self._async_verify_sms_code( user_input[CONF_SMS_CODE] ) if access_token: return self.async_update_reload_and_abort( entry, data_updates={ CONF_PHONE_NUMBER: self._context[CONF_PHONE_NUMBER], CONF_ACCESS_TOKEN: access_token, }, ) return self.async_show_form( step_id=step_id, data_schema=STEP_SMS_CODE_DATA_SCHEMA, errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle configuration by re-auth.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauth confirmation step.""" return await self._async_reauth_reconfigure( user_input, self._get_reauth_entry(), "reauth_confirm", ) async def async_step_reauth_sms_code( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the SMS code step during reauth.""" return await self._async_reauth_reconfigure_sms_code( user_input, self._get_reauth_entry(), "reauth_sms_code", ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" return await self._async_reauth_reconfigure( user_input, self._get_reconfigure_entry(), "reconfigure", ) async def async_step_reconfigure_sms_code( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the SMS code step during reconfiguration.""" return await self._async_reauth_reconfigure_sms_code( user_input, self._get_reconfigure_entry(), "reconfigure_sms_code", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/config_flow.py", "license": "Apache License 2.0", "lines": 219, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fressnapf_tracker/const.py
"""Constants for the Fressnapf Tracker integration.""" DOMAIN = "fressnapf_tracker" CONF_PHONE_NUMBER = "phone_number" CONF_SMS_CODE = "sms_code" CONF_USER_ID = "user_id"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/const.py", "license": "Apache License 2.0", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/coordinator.py
"""Data update coordinator for Fressnapf Tracker integration.""" from datetime import timedelta import logging from fressnapftracker import ( ApiClient, Device, FressnapfTrackerError, FressnapfTrackerInvalidDeviceTokenError, Tracker, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.httpx_client import get_async_client from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) type FressnapfTrackerConfigEntry = ConfigEntry[ list[FressnapfTrackerDataUpdateCoordinator] ] class FressnapfTrackerDataUpdateCoordinator(DataUpdateCoordinator[Tracker]): """Class to manage fetching data from the API.""" def __init__( self, hass: HomeAssistant, config_entry: FressnapfTrackerConfigEntry, device: Device, initial_data: Tracker, ) -> None: """Initialize.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=15), config_entry=config_entry, ) self.device = device self.client = ApiClient( serial_number=device.serialnumber, device_token=device.token, client=get_async_client(hass), ) self.data = initial_data async def _async_update_data(self) -> Tracker: try: return await self.client.get_tracker() except FressnapfTrackerInvalidDeviceTokenError as exception: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", ) from exception except FressnapfTrackerError as exception: raise UpdateFailed(exception) from exception
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/coordinator.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/device_tracker.py
"""Device tracker platform for fressnapf_tracker.""" from homeassistant.components.device_tracker import SourceType from homeassistant.components.device_tracker.config_entry import TrackerEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FressnapfTrackerConfigEntry, FressnapfTrackerDataUpdateCoordinator from .entity import FressnapfTrackerBaseEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, entry: FressnapfTrackerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the fressnapf_tracker device_trackers.""" async_add_entities( FressnapfTrackerDeviceTracker(coordinator) for coordinator in entry.runtime_data ) class FressnapfTrackerDeviceTracker(FressnapfTrackerBaseEntity, TrackerEntity): """fressnapf_tracker device tracker.""" _attr_name = None _attr_translation_key = "pet" def __init__( self, coordinator: FressnapfTrackerDataUpdateCoordinator, ) -> None: """Initialize the device tracker.""" super().__init__(coordinator) self._attr_unique_id = coordinator.device.serialnumber @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.coordinator.data.position is not None @property def entity_picture(self) -> str | None: """Return the entity picture url.""" return self.coordinator.data.icon @property def latitude(self) -> float | None: """Return latitude value of the device.""" if self.coordinator.data.position is not None: return self.coordinator.data.position.lat return None @property def longitude(self) -> float | None: """Return longitude value of the device.""" if self.coordinator.data.position is not None: return self.coordinator.data.position.lng return None @property def source_type(self) -> SourceType: """Return the source type, eg gps or router, of the device.""" return SourceType.GPS @property def location_accuracy(self) -> float: """Return the location accuracy of the device. Value in meters. """ if self.coordinator.data.position is not None: return float(self.coordinator.data.position.accuracy) return 0
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/device_tracker.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/entity.py
"""fressnapf_tracker class.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import FressnapfTrackerDataUpdateCoordinator from .const import DOMAIN class FressnapfTrackerBaseEntity( CoordinatorEntity[FressnapfTrackerDataUpdateCoordinator] ): """Base entity for Fressnapf Tracker.""" _attr_has_entity_name = True def __init__(self, coordinator: FressnapfTrackerDataUpdateCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self.id = coordinator.device.serialnumber self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, str(self.id))}, name=str(self.coordinator.data.name), model=str(self.coordinator.data.tracker_settings.generation), manufacturer="Fressnapf", serial_number=str(self.id), ) class FressnapfTrackerEntity(FressnapfTrackerBaseEntity): """Entity for fressnapf_tracker.""" def __init__( self, coordinator: FressnapfTrackerDataUpdateCoordinator, entity_description: EntityDescription, ) -> None: """Initialize the entity.""" super().__init__(coordinator) self.entity_description = entity_description self._attr_unique_id = f"{self.id}_{entity_description.key}"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/entity.py", "license": "Apache License 2.0", "lines": 33, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/light.py
"""Light platform for fressnapf_tracker.""" from typing import TYPE_CHECKING, Any from fressnapftracker import FressnapfTrackerError from homeassistant.components.light import ( ATTR_BRIGHTNESS, ColorMode, LightEntity, LightEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FressnapfTrackerConfigEntry from .const import DOMAIN from .entity import FressnapfTrackerEntity from .services import handle_fressnapf_tracker_exception PARALLEL_UPDATES = 1 LIGHT_ENTITY_DESCRIPTION = LightEntityDescription( translation_key="led", entity_category=EntityCategory.CONFIG, key="led_brightness_value", ) async def async_setup_entry( hass: HomeAssistant, entry: FressnapfTrackerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Fressnapf Tracker lights.""" async_add_entities( FressnapfTrackerLight(coordinator, LIGHT_ENTITY_DESCRIPTION) for coordinator in entry.runtime_data if coordinator.data.led_activatable is not None and coordinator.data.led_activatable.has_led and coordinator.data.tracker_settings.features.flash_light ) class FressnapfTrackerLight(FressnapfTrackerEntity, LightEntity): """Fressnapf Tracker light.""" _attr_color_mode: ColorMode = ColorMode.BRIGHTNESS _attr_supported_color_modes: set[ColorMode] = {ColorMode.BRIGHTNESS} @property def brightness(self) -> int: """Return the brightness of this light between 0..255.""" if TYPE_CHECKING: # The entity is not created if led_brightness_value is None assert self.coordinator.data.led_brightness_value is not None return int(round((self.coordinator.data.led_brightness_value / 100) * 255)) async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the device.""" self.raise_if_not_activatable() brightness = kwargs.get(ATTR_BRIGHTNESS, 255) brightness = int((brightness / 255) * 100) try: await self.coordinator.client.set_led_brightness(brightness) except FressnapfTrackerError as e: handle_fressnapf_tracker_exception(e) await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the device.""" try: await self.coordinator.client.set_led_brightness(0) except FressnapfTrackerError as e: handle_fressnapf_tracker_exception(e) await self.coordinator.async_request_refresh() def raise_if_not_activatable(self) -> None: """Raise error with reasoning if light is not activatable.""" if TYPE_CHECKING: # The entity is not created if led_activatable is None assert self.coordinator.data.led_activatable is not None error_type: str | None = None if not self.coordinator.data.led_activatable.seen_recently: error_type = "not_seen_recently" elif not self.coordinator.data.led_activatable.not_charging: error_type = "charging" elif not self.coordinator.data.led_activatable.nonempty_battery: error_type = "low_battery" if error_type is not None: raise HomeAssistantError( translation_domain=DOMAIN, translation_key=error_type, ) @property def is_on(self) -> bool: """Return true if device is on.""" if self.coordinator.data.led_brightness_value is not None: return self.coordinator.data.led_brightness_value > 0 return False
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/light.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fressnapf_tracker/sensor.py
"""Sensor platform for fressnapf_tracker.""" from collections.abc import Callable from dataclasses import dataclass from fressnapftracker import Tracker from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import PERCENTAGE, EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FressnapfTrackerConfigEntry from .entity import FressnapfTrackerEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class FressnapfTrackerSensorDescription(SensorEntityDescription): """Class describing Fressnapf Tracker sensor entities.""" value_fn: Callable[[Tracker], int] SENSOR_ENTITY_DESCRIPTIONS: tuple[FressnapfTrackerSensorDescription, ...] = ( FressnapfTrackerSensorDescription( key="battery", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.BATTERY, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.battery, ), ) async def async_setup_entry( hass: HomeAssistant, entry: FressnapfTrackerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Fressnapf Tracker sensors.""" async_add_entities( FressnapfTrackerSensor(coordinator, sensor_description) for sensor_description in SENSOR_ENTITY_DESCRIPTIONS for coordinator in entry.runtime_data ) class FressnapfTrackerSensor(FressnapfTrackerEntity, SensorEntity): """fressnapf_tracker sensor for general information.""" entity_description: FressnapfTrackerSensorDescription @property def native_value(self) -> int: """Return the state of the resources if it has been received yet.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/sensor.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/switch.py
"""Switch platform for Fressnapf Tracker.""" from typing import TYPE_CHECKING, Any from fressnapftracker import FressnapfTrackerError from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, SwitchEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FressnapfTrackerConfigEntry from .entity import FressnapfTrackerEntity from .services import handle_fressnapf_tracker_exception PARALLEL_UPDATES = 1 SWITCH_ENTITY_DESCRIPTION = SwitchEntityDescription( translation_key="energy_saving", entity_category=EntityCategory.CONFIG, device_class=SwitchDeviceClass.SWITCH, key="energy_saving", ) async def async_setup_entry( hass: HomeAssistant, entry: FressnapfTrackerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Fressnapf Tracker switches.""" async_add_entities( FressnapfTrackerSwitch(coordinator, SWITCH_ENTITY_DESCRIPTION) for coordinator in entry.runtime_data if coordinator.data.tracker_settings.features.energy_saving_mode ) class FressnapfTrackerSwitch(FressnapfTrackerEntity, SwitchEntity): """Fressnapf Tracker switch.""" async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the device.""" try: await self.coordinator.client.set_energy_saving(True) except FressnapfTrackerError as e: handle_fressnapf_tracker_exception(e) await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the device.""" try: await self.coordinator.client.set_energy_saving(False) except FressnapfTrackerError as e: handle_fressnapf_tracker_exception(e) await self.coordinator.async_request_refresh() @property def is_on(self) -> bool: """Return true if device is on.""" if TYPE_CHECKING: # The entity is not created if energy_saving is None assert self.coordinator.data.energy_saving is not None return self.coordinator.data.energy_saving.value == 1
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/switch.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/gentex_homelink/application_credentials.py
"""application_credentials platform for the gentex homelink integration.""" from homeassistant.components.application_credentials import ClientCredential from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from . import oauth2 async def async_get_auth_implementation( hass: HomeAssistant, auth_domain: str, _credential: ClientCredential ) -> config_entry_oauth2_flow.AbstractOAuth2Implementation: """Return custom SRPAuth implementation.""" return oauth2.SRPAuthImplementation(hass, auth_domain)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/gentex_homelink/application_credentials.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/gentex_homelink/config_flow.py
"""Config flow for homelink.""" from collections.abc import Mapping import logging from typing import Any import botocore.exceptions from homelink.auth.srp_auth import SRPAuth import jwt import voluptuous as vol from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, CONF_UNIQUE_ID from homeassistant.helpers.config_entry_oauth2_flow import AbstractOAuth2FlowHandler from .const import DOMAIN from .oauth2 import SRPAuthImplementation _LOGGER = logging.getLogger(__name__) class SRPFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): """Config flow to handle homelink OAuth2 authentication.""" DOMAIN = DOMAIN def __init__(self) -> None: """Set up the flow handler.""" super().__init__() self.flow_impl = SRPAuthImplementation(self.hass, DOMAIN) @property def logger(self): """Get the logger.""" return _LOGGER async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Ask for username and password.""" errors: dict[str, str] = {} if user_input is not None: srp_auth = SRPAuth() try: tokens = await self.hass.async_add_executor_job( srp_auth.async_get_access_token, user_input[CONF_EMAIL], user_input[CONF_PASSWORD], ) except botocore.exceptions.ClientError: errors["base"] = "srp_auth_failed" except Exception: _LOGGER.exception("An unexpected error occurred") errors["base"] = "unknown" else: access_token = jwt.decode( tokens["AuthenticationResult"]["AccessToken"], options={"verify_signature": False}, ) sub = access_token["sub"] await self.async_set_unique_id(sub) self.external_data = { "tokens": tokens, CONF_UNIQUE_ID: sub, CONF_EMAIL: user_input[CONF_EMAIL].strip().lower(), } return await self.async_step_creation() return self.async_show_form( step_id="user", data_schema=vol.Schema( {vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str} ), errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauth upon an API authentication error.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Dialog that informs the user that reauth is required.""" if user_input is None: return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema( {vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str} ), ) return await self.async_step_user(user_input) async def async_oauth_create_entry(self, data: dict) -> ConfigFlowResult: """Create an oauth config entry or update existing entry for reauth.""" await self.async_set_unique_id(self.external_data[CONF_UNIQUE_ID]) entry_title = self.context.get("title_placeholders", {"name": "HomeLink"})[ "name" ] if self.source == SOURCE_REAUTH: self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=data, title=entry_title ) self._abort_if_unique_id_configured() return self.async_create_entry(data=data, title=entry_title)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/gentex_homelink/config_flow.py", "license": "Apache License 2.0", "lines": 93, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/gentex_homelink/coordinator.py
"""Establish MQTT connection and listen for event data.""" from __future__ import annotations from collections.abc import Callable from functools import partial from typing import TypedDict from homelink.model.device import Device from homelink.mqtt_provider import MQTTProvider from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.util.ssl import get_default_context type HomeLinkConfigEntry = ConfigEntry[HomeLinkCoordinator] type EventCallback = Callable[[HomeLinkEventData], None] class HomeLinkEventData(TypedDict): """Data for a single event.""" requestId: str timestamp: int class HomeLinkMQTTMessage(TypedDict): """HomeLink MQTT Event message.""" type: str data: dict[str, HomeLinkEventData] # Each key is a button id class HomeLinkCoordinator: """HomeLink integration coordinator.""" def __init__( self, hass: HomeAssistant, provider: MQTTProvider, config_entry: HomeLinkConfigEntry, ) -> None: """Initialize my coordinator.""" self.hass = hass self.config_entry = config_entry self.provider = provider self.device_data: list[Device] = [] self._listeners: dict[str, EventCallback] = {} @callback def async_add_event_listener( self, update_callback: EventCallback, target_event_id: str ) -> Callable[[], None]: """Listen for updates.""" self._listeners[target_event_id] = update_callback return partial(self.__async_remove_listener_internal, target_event_id) def __async_remove_listener_internal(self, listener_id: str) -> None: del self._listeners[listener_id] @callback def async_handle_state_data(self, data: dict[str, HomeLinkEventData]) -> None: """Notify listeners.""" for button_id, event in data.items(): if listener := self._listeners.get(button_id): listener(event) async def async_config_entry_first_refresh(self) -> None: """Refresh data for the first time when a config entry is setup.""" await self._async_setup() async def async_on_unload(self, _event) -> None: """Disconnect and unregister when unloaded.""" await self.provider.disable() async def _async_setup(self) -> None: """Set up the coordinator.""" await self.provider.enable(get_default_context()) await self.discover_devices() self.provider.listen(self.on_message) async def discover_devices(self) -> None: """Discover devices and build the Entities.""" self.device_data = await self.provider.discover() def on_message(self, _topic: str, message: HomeLinkMQTTMessage) -> None: """MQTT Callback function.""" if message["type"] == "state": self.hass.add_job(self.async_handle_state_data, message["data"]) if message["type"] == "requestSync": self.hass.add_job( self.hass.config_entries.async_reload, self.config_entry.entry_id, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/gentex_homelink/coordinator.py", "license": "Apache License 2.0", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/gentex_homelink/event.py
"""Platform for Event integration.""" from __future__ import annotations from homeassistant.components.event import EventDeviceClass, EventEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN, EVENT_PRESSED from .coordinator import HomeLinkConfigEntry, HomeLinkCoordinator, HomeLinkEventData async def async_setup_entry( hass: HomeAssistant, config_entry: HomeLinkConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Add the entities for the event platform.""" coordinator = config_entry.runtime_data async_add_entities( HomeLinkEventEntity(coordinator, button.id, button.name, device.id, device.name) for device in coordinator.device_data for button in device.buttons ) # Updates are centralized by the coordinator. PARALLEL_UPDATES = 0 class HomeLinkEventEntity(EventEntity): """Event Entity.""" _attr_has_entity_name = True _attr_event_types = [EVENT_PRESSED] _attr_device_class = EventDeviceClass.BUTTON def __init__( self, coordinator: HomeLinkCoordinator, button_id: str, param_name: str, device_id: str, device_name: str, ) -> None: """Initialize the event entity.""" self.button_id = button_id self._attr_name = param_name self._attr_unique_id = button_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device_id)}, name=device_name, ) self.coordinator = coordinator self.last_request_id: str | None = None async def async_added_to_hass(self) -> None: """When entity is added to hass.""" await super().async_added_to_hass() self.async_on_remove( self.coordinator.async_add_event_listener( self._handle_event_data_update, self.button_id ) ) @callback def _handle_event_data_update(self, update_data: HomeLinkEventData) -> None: """Update this button.""" if update_data["requestId"] != self.last_request_id: self._trigger_event(EVENT_PRESSED) self.last_request_id = update_data["requestId"] self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/gentex_homelink/event.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/gentex_homelink/oauth2.py
"""API for homelink bound to Home Assistant OAuth.""" from json import JSONDecodeError import logging import time from typing import cast from aiohttp import ClientError, ClientSession from homelink.auth.abstract_auth import AbstractAuth from homelink.settings import COGNITO_CLIENT_ID from homeassistant.core import HomeAssistant from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import OAUTH2_TOKEN_URL _LOGGER = logging.getLogger(__name__) class SRPAuthImplementation(config_entry_oauth2_flow.AbstractOAuth2Implementation): """Base class to abstract OAuth2 authentication.""" def __init__(self, hass: HomeAssistant, domain: str) -> None: """Initialize the SRP Auth implementation.""" self.hass = hass self._domain = domain self.client_id = COGNITO_CLIENT_ID @property def name(self) -> str: """Name of the implementation.""" return "SRPAuth" @property def domain(self) -> str: """Domain that is providing the implementation.""" return self._domain async def async_generate_authorize_url(self, flow_id: str) -> str: """Left intentionally blank because the auth is handled by SRP.""" return "" async def async_resolve_external_data(self, external_data) -> dict: """Format the token from the source appropriately for HomeAssistant.""" tokens = external_data["tokens"] return { "access_token": tokens["AuthenticationResult"]["AccessToken"], "refresh_token": tokens["AuthenticationResult"]["RefreshToken"], "token_type": tokens["AuthenticationResult"]["TokenType"], "expires_in": tokens["AuthenticationResult"]["ExpiresIn"], "expires_at": (time.time() + tokens["AuthenticationResult"]["ExpiresIn"]), } async def _token_request(self, data: dict) -> dict: """Make a token request.""" session = async_get_clientsession(self.hass) data["client_id"] = self.client_id _LOGGER.debug("Sending token request to %s", OAUTH2_TOKEN_URL) resp = await session.post(OAUTH2_TOKEN_URL, data=data) if resp.status >= 400: try: error_response = await resp.json() except ClientError, JSONDecodeError: error_response = {} error_code = error_response.get("error", "unknown") error_description = error_response.get( "error_description", "unknown error" ) _LOGGER.error( "Token request for %s failed (%s): %s", self.domain, error_code, error_description, ) resp.raise_for_status() return cast(dict, await resp.json()) async def _async_refresh_token(self, token: dict) -> dict: """Refresh tokens.""" new_token = await self._token_request( { "grant_type": "refresh_token", "client_id": self.client_id, "refresh_token": token["refresh_token"], } ) return {**token, **new_token} class AsyncConfigEntryAuth(AbstractAuth): """Provide homelink authentication tied to an OAuth2 based config entry.""" def __init__( self, websession: ClientSession, oauth_session: config_entry_oauth2_flow.OAuth2Session, ) -> None: """Initialize homelink auth.""" super().__init__(websession) self._oauth_session = oauth_session async def async_get_access_token(self) -> str: """Return a valid access token.""" if not self._oauth_session.valid_token: await self._oauth_session.async_ensure_token_valid() return self._oauth_session.token["access_token"]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/gentex_homelink/oauth2.py", "license": "Apache License 2.0", "lines": 89, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_drive/coordinator.py
"""DataUpdateCoordinator for Google Drive.""" from __future__ import annotations from dataclasses import dataclass import logging from google_drive_api.exceptions import GoogleDriveApiError from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .api import DriveClient, StorageQuotaData from .const import DOMAIN, SCAN_INTERVAL type GoogleDriveConfigEntry = ConfigEntry[GoogleDriveDataUpdateCoordinator] _LOGGER = logging.getLogger(__name__) @dataclass class SensorData: """Class to represent sensor data.""" storage_quota: StorageQuotaData all_backups_size: int class GoogleDriveDataUpdateCoordinator(DataUpdateCoordinator[SensorData]): """Class to manage fetching Google Drive data from single endpoint.""" client: DriveClient config_entry: GoogleDriveConfigEntry email_address: str backup_folder_id: str def __init__( self, hass: HomeAssistant, *, client: DriveClient, backup_folder_id: str, entry: GoogleDriveConfigEntry, ) -> None: """Initialize Google Drive data updater.""" self.client = client self.backup_folder_id = backup_folder_id super().__init__( hass, _LOGGER, config_entry=entry, name=DOMAIN, update_interval=SCAN_INTERVAL, ) async def _async_setup(self) -> None: """Do initialization logic.""" self.email_address = await self.client.async_get_email_address() async def _async_update_data(self) -> SensorData: """Fetch data from Google Drive.""" try: storage_quota = await self.client.async_get_storage_quota() all_backups_size = await self.client.async_get_size_of_all_backups() return SensorData( storage_quota=storage_quota, all_backups_size=all_backups_size, ) except GoogleDriveApiError as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="invalid_response_google_drive_error", translation_placeholders={"error": str(error)}, ) from error
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_drive/coordinator.py", "license": "Apache License 2.0", "lines": 59, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_drive/diagnostics.py
"""Diagnostics support for Google Drive.""" from __future__ import annotations import dataclasses from typing import Any from homeassistant.components.backup import ( DATA_MANAGER as BACKUP_DATA_MANAGER, BackupManager, ) from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_ACCESS_TOKEN from homeassistant.core import HomeAssistant from .const import DOMAIN from .coordinator import GoogleDriveConfigEntry TO_REDACT = (CONF_ACCESS_TOKEN, "refresh_token") async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: GoogleDriveConfigEntry, ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data backup_manager: BackupManager = hass.data[BACKUP_DATA_MANAGER] backups = await coordinator.client.async_list_backups() data = { "coordinator_data": dataclasses.asdict(coordinator.data), "config": { **entry.data, **entry.options, }, "backup_folder_id": coordinator.backup_folder_id, "backup_agents": [ {"name": agent.name} for agent in backup_manager.backup_agents.values() if agent.domain == DOMAIN ], "backup": [backup.as_dict() for backup in backups], } return async_redact_data(data, TO_REDACT)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_drive/diagnostics.py", "license": "Apache License 2.0", "lines": 37, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_drive/entity.py
"""Define the Google Drive entity.""" from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, DRIVE_FOLDER_URL_PREFIX from .coordinator import GoogleDriveDataUpdateCoordinator class GoogleDriveEntity(CoordinatorEntity[GoogleDriveDataUpdateCoordinator]): """Defines a base Google Drive entity.""" _attr_has_entity_name = True @property def device_info(self) -> DeviceInfo: """Return device information about this Google Drive device.""" return DeviceInfo( identifiers={(DOMAIN, str(self.coordinator.config_entry.unique_id))}, name=self.coordinator.email_address, manufacturer="Google", model="Google Drive", configuration_url=f"{DRIVE_FOLDER_URL_PREFIX}{self.coordinator.backup_folder_id}", entry_type=DeviceEntryType.SERVICE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_drive/entity.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_drive/sensor.py
"""Support for GoogleDrive sensors.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, ) from homeassistant.const import EntityCategory, UnitOfInformation from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .coordinator import ( GoogleDriveConfigEntry, GoogleDriveDataUpdateCoordinator, SensorData, ) from .entity import GoogleDriveEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class GoogleDriveSensorEntityDescription(SensorEntityDescription): """Describes GoogleDrive sensor entity.""" exists_fn: Callable[[SensorData], bool] = lambda _: True value_fn: Callable[[SensorData], StateType] SENSORS: tuple[GoogleDriveSensorEntityDescription, ...] = ( GoogleDriveSensorEntityDescription( key="storage_total", translation_key="storage_total", native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.storage_quota.limit, exists_fn=lambda data: data.storage_quota.limit is not None, ), GoogleDriveSensorEntityDescription( key="storage_used", translation_key="storage_used", native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.storage_quota.usage, ), GoogleDriveSensorEntityDescription( key="storage_used_in_drive", translation_key="storage_used_in_drive", native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.storage_quota.usage_in_drive, entity_registry_enabled_default=False, ), GoogleDriveSensorEntityDescription( key="storage_used_in_drive_trash", translation_key="storage_used_in_drive_trash", native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.GIBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.storage_quota.usage_in_trash, entity_registry_enabled_default=False, ), GoogleDriveSensorEntityDescription( key="backups_size", translation_key="backups_size", native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, suggested_display_precision=0, device_class=SensorDeviceClass.DATA_SIZE, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: data.all_backups_size, entity_registry_enabled_default=False, ), ) async def async_setup_entry( hass: HomeAssistant, entry: GoogleDriveConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up GoogleDrive sensor based on a config entry.""" coordinator = entry.runtime_data async_add_entities( GoogleDriveSensorEntity(coordinator, description) for description in SENSORS if description.exists_fn(coordinator.data) ) class GoogleDriveSensorEntity(GoogleDriveEntity, SensorEntity): """Defines a Google Drive sensor entity.""" entity_description: GoogleDriveSensorEntityDescription def __init__( self, coordinator: GoogleDriveDataUpdateCoordinator, description: GoogleDriveSensorEntityDescription, ) -> None: """Initialize a Google Drive sensor entity.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{description.key}" @property def native_value(self) -> StateType: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_drive/sensor.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/growatt_server/services.py
"""Service handlers for Growatt Server integration.""" from __future__ import annotations from datetime import datetime from typing import TYPE_CHECKING, Any from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import device_registry as dr from .const import ( BATT_MODE_BATTERY_FIRST, BATT_MODE_GRID_FIRST, BATT_MODE_LOAD_FIRST, DOMAIN, ) if TYPE_CHECKING: from .coordinator import GrowattCoordinator @callback def async_setup_services(hass: HomeAssistant) -> None: """Register services for Growatt Server integration.""" def get_min_coordinators() -> dict[str, GrowattCoordinator]: """Get all MIN coordinators with V1 API from loaded config entries.""" min_coordinators: dict[str, GrowattCoordinator] = {} for entry in hass.config_entries.async_entries(DOMAIN): if entry.state != ConfigEntryState.LOADED: continue # Add MIN coordinators from this entry for coord in entry.runtime_data.devices.values(): if coord.device_type == "min" and coord.api_version == "v1": min_coordinators[coord.device_id] = coord return min_coordinators def get_coordinator(device_id: str) -> GrowattCoordinator: """Get coordinator by device_id. Args: device_id: Device registry ID (not serial number) """ # Get current coordinators (they may have changed since service registration) min_coordinators = get_min_coordinators() if not min_coordinators: raise ServiceValidationError( "No MIN devices with token authentication are configured. " "Services require MIN devices with V1 API access." ) # Device registry ID provided - map to serial number device_registry = dr.async_get(hass) device_entry = device_registry.async_get(device_id) if not device_entry: raise ServiceValidationError(f"Device '{device_id}' not found") # Extract serial number from device identifiers serial_number = None for identifier in device_entry.identifiers: if identifier[0] == DOMAIN: serial_number = identifier[1] break if not serial_number: raise ServiceValidationError( f"Device '{device_id}' is not a Growatt device" ) # Find coordinator by serial number if serial_number not in min_coordinators: raise ServiceValidationError( f"MIN device '{serial_number}' not found or not configured for services" ) return min_coordinators[serial_number] async def handle_update_time_segment(call: ServiceCall) -> None: """Handle update_time_segment service call.""" segment_id: int = int(call.data["segment_id"]) batt_mode_str: str = call.data["batt_mode"] start_time_str: str = call.data["start_time"] end_time_str: str = call.data["end_time"] enabled: bool = call.data["enabled"] device_id: str = call.data["device_id"] # Validate segment_id range if not 1 <= segment_id <= 9: raise ServiceValidationError( f"segment_id must be between 1 and 9, got {segment_id}" ) # Validate and convert batt_mode string to integer valid_modes = { "load_first": BATT_MODE_LOAD_FIRST, "battery_first": BATT_MODE_BATTERY_FIRST, "grid_first": BATT_MODE_GRID_FIRST, } if batt_mode_str not in valid_modes: raise ServiceValidationError( f"batt_mode must be one of {list(valid_modes.keys())}, got '{batt_mode_str}'" ) batt_mode: int = valid_modes[batt_mode_str] # Convert time strings to datetime.time objects # UI time selector sends HH:MM:SS, but we only need HH:MM (strip seconds) try: # Take only HH:MM part (ignore seconds if present) start_parts = start_time_str.split(":") start_time_hhmm = f"{start_parts[0]}:{start_parts[1]}" start_time = datetime.strptime(start_time_hhmm, "%H:%M").time() except (ValueError, IndexError) as err: raise ServiceValidationError( "start_time must be in HH:MM or HH:MM:SS format" ) from err try: # Take only HH:MM part (ignore seconds if present) end_parts = end_time_str.split(":") end_time_hhmm = f"{end_parts[0]}:{end_parts[1]}" end_time = datetime.strptime(end_time_hhmm, "%H:%M").time() except (ValueError, IndexError) as err: raise ServiceValidationError( "end_time must be in HH:MM or HH:MM:SS format" ) from err # Get the appropriate MIN coordinator coordinator: GrowattCoordinator = get_coordinator(device_id) await coordinator.update_time_segment( segment_id, batt_mode, start_time, end_time, enabled, ) async def handle_read_time_segments(call: ServiceCall) -> dict[str, Any]: """Handle read_time_segments service call.""" device_id: str = call.data["device_id"] # Get the appropriate MIN coordinator coordinator: GrowattCoordinator = get_coordinator(device_id) time_segments: list[dict[str, Any]] = await coordinator.read_time_segments() return {"time_segments": time_segments} # Register services without schema - services.yaml will provide UI definition # Schema validation happens in the handler functions hass.services.async_register( DOMAIN, "update_time_segment", handle_update_time_segment, supports_response=SupportsResponse.NONE, ) hass.services.async_register( DOMAIN, "read_time_segments", handle_read_time_segments, supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/growatt_server/services.py", "license": "Apache License 2.0", "lines": 137, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/hikvision/config_flow.py
"""Config flow for Hikvision integration.""" from __future__ import annotations import logging from typing import Any from pyhik.hikvision import HikCamera import requests import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, ) from homeassistant.helpers.typing import ConfigType from .const import DEFAULT_PORT, DOMAIN _LOGGER = logging.getLogger(__name__) class HikvisionConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Hikvision.""" VERSION = 1 MINOR_VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: host = user_input[CONF_HOST] port = user_input[CONF_PORT] username = user_input[CONF_USERNAME] password = user_input[CONF_PASSWORD] ssl = user_input[CONF_SSL] protocol = "https" if ssl else "http" url = f"{protocol}://{host}" try: camera = await self.hass.async_add_executor_job( HikCamera, url, port, username, password, ssl ) except requests.exceptions.RequestException: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: device_id = camera.get_id device_name = camera.get_name if device_id is None: errors["base"] = "cannot_connect" else: await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=device_name or host, data={ CONF_HOST: host, CONF_PORT: port, CONF_USERNAME: username, CONF_PASSWORD: password, CONF_SSL: ssl, }, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_PORT, default=DEFAULT_PORT): int, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(CONF_SSL, default=False): bool, } ), errors=errors, ) async def async_step_import(self, import_data: ConfigType) -> ConfigFlowResult: """Handle import from configuration.yaml.""" host = import_data[CONF_HOST] port = import_data.get(CONF_PORT, DEFAULT_PORT) username = import_data[CONF_USERNAME] password = import_data[CONF_PASSWORD] ssl = import_data.get(CONF_SSL, False) name = import_data.get(CONF_NAME) protocol = "https" if ssl else "http" url = f"{protocol}://{host}" try: camera = await self.hass.async_add_executor_job( HikCamera, url, port, username, password, ssl ) except requests.exceptions.RequestException: return self.async_abort(reason="cannot_connect") except Exception: _LOGGER.exception("Unexpected exception") return self.async_abort(reason="unknown") device_id = camera.get_id device_name = camera.get_name if device_id is None: return self.async_abort(reason="cannot_connect") await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured() return self.async_create_entry( title=name or device_name or host, data={ CONF_HOST: host, CONF_PORT: port, CONF_USERNAME: username, CONF_PASSWORD: password, CONF_SSL: ssl, }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hikvision/config_flow.py", "license": "Apache License 2.0", "lines": 111, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/humidifier/trigger.py
"""Provides triggers for humidifiers.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import ( Trigger, make_entity_numerical_state_attribute_changed_trigger, make_entity_numerical_state_attribute_crossed_threshold_trigger, make_entity_target_state_attribute_trigger, make_entity_target_state_trigger, ) from .const import ATTR_ACTION, ATTR_CURRENT_HUMIDITY, DOMAIN, HumidifierAction TRIGGERS: dict[str, type[Trigger]] = { "current_humidity_changed": make_entity_numerical_state_attribute_changed_trigger( DOMAIN, ATTR_CURRENT_HUMIDITY ), "current_humidity_crossed_threshold": make_entity_numerical_state_attribute_crossed_threshold_trigger( DOMAIN, ATTR_CURRENT_HUMIDITY ), "started_drying": make_entity_target_state_attribute_trigger( DOMAIN, ATTR_ACTION, HumidifierAction.DRYING ), "started_humidifying": make_entity_target_state_attribute_trigger( DOMAIN, ATTR_ACTION, HumidifierAction.HUMIDIFYING ), "turned_off": make_entity_target_state_trigger(DOMAIN, STATE_OFF), "turned_on": make_entity_target_state_trigger(DOMAIN, STATE_ON), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for humidifiers.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/humidifier/trigger.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/jewish_calendar/coordinator.py
"""Data update coordinator for Jewish calendar.""" from dataclasses import dataclass import datetime as dt import logging from hdate import HDateInfo, Location, Zmanim from hdate.translator import Language, set_language from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import event from homeassistant.helpers.update_coordinator import DataUpdateCoordinator import homeassistant.util.dt as dt_util from .const import DOMAIN _LOGGER = logging.getLogger(__name__) type JewishCalendarConfigEntry = ConfigEntry[JewishCalendarUpdateCoordinator] @dataclass(frozen=True) class JewishCalendarData: """Jewish Calendar runtime dataclass.""" language: Language diaspora: bool location: Location candle_lighting_offset: int havdalah_offset: int dateinfo: HDateInfo | None = None zmanim: Zmanim | None = None class JewishCalendarUpdateCoordinator(DataUpdateCoordinator[JewishCalendarData]): """Data update coordinator class for Jewish calendar.""" config_entry: JewishCalendarConfigEntry _attr_should_poll = False def __init__( self, hass: HomeAssistant, config_entry: JewishCalendarConfigEntry, data: JewishCalendarData, ) -> None: """Initialize the coordinator.""" super().__init__(hass, _LOGGER, name=DOMAIN, config_entry=config_entry) self.data = data set_language(data.language) async def _async_update_data(self) -> JewishCalendarData: """Return HDate and Zmanim for today.""" now = dt_util.now() _LOGGER.debug("Now: %s Location: %r", now, self.data.location) today = now.date() # Create new data object with today's information new_data = JewishCalendarData( language=self.data.language, diaspora=self.data.diaspora, location=self.data.location, candle_lighting_offset=self.data.candle_lighting_offset, havdalah_offset=self.data.havdalah_offset, dateinfo=HDateInfo(today, self.data.diaspora), zmanim=self.make_zmanim(today), ) # Schedule next update at midnight next_midnight = dt_util.start_of_local_day() + dt.timedelta(days=1) _LOGGER.debug("Scheduling next update at %s", next_midnight) # Schedule update at next midnight self._unsub_refresh = event.async_track_point_in_time( self.hass, self._handle_midnight_update, next_midnight ) return new_data @callback def _handle_midnight_update(self, _now: dt.datetime) -> None: """Handle midnight update callback.""" self.hass.async_create_task(self.async_request_refresh()) def make_zmanim(self, date: dt.date) -> Zmanim: """Create a Zmanim object.""" return Zmanim( date=date, location=self.data.location, candle_lighting_offset=self.data.candle_lighting_offset, havdalah_offset=self.data.havdalah_offset, ) @property def zmanim(self) -> Zmanim: """Return the current Zmanim.""" assert self.data.zmanim is not None, "Zmanim data not available" return self.data.zmanim @property def dateinfo(self) -> HDateInfo: """Return the current HDateInfo.""" assert self.data.dateinfo is not None, "HDateInfo data not available" return self.data.dateinfo
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/jewish_calendar/coordinator.py", "license": "Apache License 2.0", "lines": 83, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/knx/dpt.py
"""KNX DPT serializer.""" from collections.abc import Mapping from functools import cache from typing import Literal, TypedDict from xknx.dpt import DPTBase, DPTComplex, DPTEnum, DPTNumeric from xknx.dpt.dpt_16 import DPTString from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass HaDptClass = Literal["numeric", "enum", "complex", "string"] class DPTInfo(TypedDict): """DPT information.""" dpt_class: HaDptClass main: int sub: int | None name: str | None unit: str | None sensor_device_class: SensorDeviceClass | None sensor_state_class: SensorStateClass | None @cache def get_supported_dpts() -> Mapping[str, DPTInfo]: """Return a mapping of supported DPTs with HA specific attributes.""" dpts = {} for dpt_class in DPTBase.dpt_class_tree(): dpt_number_str = dpt_class.dpt_number_str() ha_dpt_class = _ha_dpt_class(dpt_class) dpts[dpt_number_str] = DPTInfo( dpt_class=ha_dpt_class, main=dpt_class.dpt_main_number, # type: ignore[typeddict-item] # checked in xknx unit tests sub=dpt_class.dpt_sub_number, name=dpt_class.value_type, unit=dpt_class.unit, sensor_device_class=_sensor_device_classes.get(dpt_number_str), sensor_state_class=_get_sensor_state_class(ha_dpt_class, dpt_number_str), ) return dpts def _ha_dpt_class(dpt_cls: type[DPTBase]) -> HaDptClass: """Return the DPT class identifier string.""" if issubclass(dpt_cls, DPTNumeric): return "numeric" if issubclass(dpt_cls, DPTEnum): return "enum" if issubclass(dpt_cls, DPTComplex): return "complex" if issubclass(dpt_cls, DPTString): return "string" raise ValueError("Unsupported DPT class") _sensor_device_classes: Mapping[str, SensorDeviceClass] = { "7.011": SensorDeviceClass.DISTANCE, "7.012": SensorDeviceClass.CURRENT, "7.013": SensorDeviceClass.ILLUMINANCE, "8.012": SensorDeviceClass.DISTANCE, "9.001": SensorDeviceClass.TEMPERATURE, "9.002": SensorDeviceClass.TEMPERATURE_DELTA, "9.004": SensorDeviceClass.ILLUMINANCE, "9.005": SensorDeviceClass.WIND_SPEED, "9.006": SensorDeviceClass.PRESSURE, "9.007": SensorDeviceClass.HUMIDITY, "9.020": SensorDeviceClass.VOLTAGE, "9.021": SensorDeviceClass.CURRENT, "9.024": SensorDeviceClass.POWER, "9.025": SensorDeviceClass.VOLUME_FLOW_RATE, "9.027": SensorDeviceClass.TEMPERATURE, "9.028": SensorDeviceClass.WIND_SPEED, "9.029": SensorDeviceClass.ABSOLUTE_HUMIDITY, "12.1200": SensorDeviceClass.VOLUME, "12.1201": SensorDeviceClass.VOLUME, "13.002": SensorDeviceClass.VOLUME_FLOW_RATE, "13.010": SensorDeviceClass.ENERGY, "13.012": SensorDeviceClass.REACTIVE_ENERGY, "13.013": SensorDeviceClass.ENERGY, "13.015": SensorDeviceClass.REACTIVE_ENERGY, "13.016": SensorDeviceClass.ENERGY, "13.1200": SensorDeviceClass.VOLUME, "13.1201": SensorDeviceClass.VOLUME, "14.010": SensorDeviceClass.AREA, "14.019": SensorDeviceClass.CURRENT, "14.027": SensorDeviceClass.VOLTAGE, "14.028": SensorDeviceClass.VOLTAGE, "14.030": SensorDeviceClass.VOLTAGE, "14.031": SensorDeviceClass.ENERGY, "14.033": SensorDeviceClass.FREQUENCY, "14.037": SensorDeviceClass.ENERGY_STORAGE, "14.039": SensorDeviceClass.DISTANCE, "14.051": SensorDeviceClass.WEIGHT, "14.056": SensorDeviceClass.POWER, "14.057": SensorDeviceClass.POWER_FACTOR, "14.058": SensorDeviceClass.PRESSURE, "14.065": SensorDeviceClass.SPEED, "14.068": SensorDeviceClass.TEMPERATURE, "14.069": SensorDeviceClass.TEMPERATURE, "14.070": SensorDeviceClass.TEMPERATURE_DELTA, "14.076": SensorDeviceClass.VOLUME, "14.077": SensorDeviceClass.VOLUME_FLOW_RATE, "14.080": SensorDeviceClass.APPARENT_POWER, "14.1200": SensorDeviceClass.VOLUME_FLOW_RATE, "14.1201": SensorDeviceClass.VOLUME_FLOW_RATE, "29.010": SensorDeviceClass.ENERGY, "29.012": SensorDeviceClass.REACTIVE_ENERGY, } _sensor_state_class_overrides: Mapping[str, SensorStateClass | None] = { "5.003": SensorStateClass.MEASUREMENT_ANGLE, # DPTAngle "5.006": None, # DPTTariff "7.010": None, # DPTPropDataType "8.011": SensorStateClass.MEASUREMENT_ANGLE, # DPTRotationAngle "9.026": SensorStateClass.TOTAL_INCREASING, # DPTRainAmount "12.1200": SensorStateClass.TOTAL, # DPTVolumeLiquidLitre "12.1201": SensorStateClass.TOTAL, # DPTVolumeM3 "13.010": SensorStateClass.TOTAL, # DPTActiveEnergy "13.011": SensorStateClass.TOTAL, # DPTApparantEnergy "13.012": SensorStateClass.TOTAL, # DPTReactiveEnergy "14.007": SensorStateClass.MEASUREMENT_ANGLE, # DPTAngleDeg "14.037": SensorStateClass.TOTAL, # DPTHeatQuantity "14.051": SensorStateClass.TOTAL, # DPTMass "14.055": SensorStateClass.MEASUREMENT_ANGLE, # DPTPhaseAngleDeg "14.031": SensorStateClass.TOTAL_INCREASING, # DPTEnergy "17.001": None, # DPTSceneNumber "29.010": SensorStateClass.TOTAL, # DPTActiveEnergy8Byte "29.011": SensorStateClass.TOTAL, # DPTApparantEnergy8Byte "29.012": SensorStateClass.TOTAL, # DPTReactiveEnergy8Byte } def _get_sensor_state_class( ha_dpt_class: HaDptClass, dpt_number_str: str ) -> SensorStateClass | None: """Return the SensorStateClass for a given DPT.""" if ha_dpt_class != "numeric": return None return _sensor_state_class_overrides.get( dpt_number_str, SensorStateClass.MEASUREMENT, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/knx/dpt.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple