sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:tests/components/transmission/test_services.py
"""Tests for the Transmission services.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest from homeassistant.components.transmission.const import ( ATTR_DELETE_DATA, ATTR_DOWNLOAD_PATH, ATTR_LABELS, ATTR_TORRENT, ATTR_TORRENT_FILTER, ATTR_TORRENTS, CONF_ENTRY_ID, DOMAIN, SERVICE_ADD_TORRENT, SERVICE_GET_TORRENTS, SERVICE_REMOVE_TORRENT, SERVICE_START_TORRENT, SERVICE_STOP_TORRENT, ) from homeassistant.config_entries import ConfigEntryState from homeassistant.const import CONF_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from tests.common import MockConfigEntry async def test_service_config_entry_not_loaded_state( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test service call when config entry is in failed state.""" mock_config_entry.add_to_hass(hass) assert mock_config_entry.state is ConfigEntryState.NOT_LOADED with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, ATTR_TORRENT: "magnet:?xt=urn:btih:test", }, blocking=True, ) assert err.value.translation_key == "service_not_found" async def test_service_integration_not_found( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test service call with non-existent config 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() with pytest.raises(ServiceValidationError) as err: await hass.services.async_call( DOMAIN, SERVICE_ADD_TORRENT, { CONF_ENTRY_ID: "non_existent_entry_id", ATTR_TORRENT: "magnet:?xt=urn:btih:test", }, blocking=True, ) assert err.value.translation_key == "service_config_entry_not_found" @pytest.mark.parametrize( ("payload", "expected_torrent", "kwargs"), [ ( {ATTR_TORRENT: "magnet:?xt=urn:btih:test", ATTR_LABELS: "Notify"}, "magnet:?xt=urn:btih:test", { "labels": ["Notify"], "download_dir": None, }, ), ( { ATTR_TORRENT: "magnet:?xt=urn:btih:test", ATTR_LABELS: "Movies,Notify", ATTR_DOWNLOAD_PATH: "/custom/path", }, "magnet:?xt=urn:btih:test", { "labels": ["Movies", "Notify"], "download_dir": "/custom/path", }, ), ( {ATTR_TORRENT: "http://example.com/test.torrent"}, "http://example.com/test.torrent", { "labels": None, "download_dir": None, }, ), ( {ATTR_TORRENT: "ftp://example.com/test.torrent"}, "ftp://example.com/test.torrent", { "labels": None, "download_dir": None, }, ), ( {ATTR_TORRENT: "/config/test.torrent"}, "/config/test.torrent", { "labels": None, "download_dir": None, }, ), ], ) async def test_add_torrent_service_success( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, payload: dict[str, str], expected_torrent: str, kwargs: dict[str, str | None], ) -> None: """Test successful torrent addition with url and path sources.""" client = mock_transmission_client.return_value client.add_torrent.return_value = MagicMock(id=123, name="test_torrent") mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() full_service_data = {CONF_ENTRY_ID: mock_config_entry.entry_id} | payload with patch.object(hass.config, "is_allowed_path", return_value=True): await hass.services.async_call( DOMAIN, SERVICE_ADD_TORRENT, full_service_data, blocking=True, ) client.add_torrent.assert_called_once_with(expected_torrent, **kwargs) async def test_add_torrent_service_invalid_path( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test torrent addition with invalid path.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() with pytest.raises(ServiceValidationError, match="Could not add torrent"): await hass.services.async_call( DOMAIN, SERVICE_ADD_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, ATTR_TORRENT: "/etc/bad.torrent", }, blocking=True, ) async def test_start_torrent_service_success( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful torrent start.""" client = mock_transmission_client.return_value mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( DOMAIN, SERVICE_START_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, CONF_ID: 123, }, blocking=True, ) client.start_torrent.assert_called_once_with(123) async def test_stop_torrent_service_success( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful torrent stop.""" client = mock_transmission_client.return_value mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( DOMAIN, SERVICE_STOP_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, CONF_ID: 456, }, blocking=True, ) client.stop_torrent.assert_called_once_with(456) async def test_remove_torrent_service_success( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful torrent removal without deleting data.""" client = mock_transmission_client.return_value mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( DOMAIN, SERVICE_REMOVE_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, CONF_ID: 789, }, blocking=True, ) client.remove_torrent.assert_called_once_with(789, delete_data=False) async def test_remove_torrent_service_with_delete_data( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful torrent removal with deleting data.""" client = mock_transmission_client.return_value mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( DOMAIN, SERVICE_REMOVE_TORRENT, { CONF_ENTRY_ID: mock_config_entry.entry_id, CONF_ID: 789, ATTR_DELETE_DATA: True, }, blocking=True, ) client.remove_torrent.assert_called_once_with(789, delete_data=True) @pytest.mark.parametrize( ("filter_mode", "expected_statuses", "expected_torrents"), [ ("all", ["seeding", "downloading", "stopped"], [1, 2, 3]), ("started", ["downloading"], [1]), ("completed", ["seeding"], [2]), ("paused", ["stopped"], [3]), ("active", ["seeding", "downloading"], [1, 2]), ], ) async def test_get_torrents_service( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, mock_torrent, filter_mode: str, expected_statuses: list[str], expected_torrents: list[int], ) -> None: """Test get torrents service with various filter modes.""" client = mock_transmission_client.return_value downloading_torrent = mock_torrent(torrent_id=1, name="Downloading", status=4) seeding_torrent = mock_torrent(torrent_id=2, name="Seeding", status=6) stopped_torrent = mock_torrent(torrent_id=3, name="Stopped", status=0) client.get_torrents.return_value = [ downloading_torrent, seeding_torrent, stopped_torrent, ] mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() response = await hass.services.async_call( DOMAIN, SERVICE_GET_TORRENTS, { CONF_ENTRY_ID: mock_config_entry.entry_id, ATTR_TORRENT_FILTER: filter_mode, }, blocking=True, return_response=True, ) assert response is not None assert ATTR_TORRENTS in response torrents = response[ATTR_TORRENTS] assert isinstance(torrents, dict) assert len(torrents) == len(expected_statuses) for torrent_name, torrent_data in torrents.items(): assert isinstance(torrent_data, dict) assert "id" in torrent_data assert "name" in torrent_data assert "status" in torrent_data assert torrent_data["name"] == torrent_name assert torrent_data["id"] in expected_torrents expected_torrents.remove(int(torrent_data["id"])) assert len(expected_torrents) == 0
{ "repo_id": "home-assistant/core", "file_path": "tests/components/transmission/test_services.py", "license": "Apache License 2.0", "lines": 290, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/transmission/test_switch.py
"""Tests for the Transmission switch platform.""" from unittest.mock import AsyncMock, patch import pytest from syrupy.assertion import SnapshotAssertion from transmission_rpc.session import Session from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform async def test_switches( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the switch entities.""" with patch("homeassistant.components.transmission.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( ("service", "api_method"), [ (SERVICE_TURN_ON, "start_all"), (SERVICE_TURN_OFF, "stop_torrent"), ], ) async def test_on_off_switch_without_torrents( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, mock_torrent, service: str, api_method: str, ) -> None: """Test on/off switch.""" client = mock_transmission_client.return_value client.get_torrents.return_value = [] mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.transmission_switch"}, blocking=True, ) getattr(client, api_method).assert_not_called() @pytest.mark.parametrize( ("service", "api_method"), [ (SERVICE_TURN_ON, "start_all"), (SERVICE_TURN_OFF, "stop_torrent"), ], ) async def test_on_off_switch_with_torrents( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, mock_torrent, service: str, api_method: str, ) -> None: """Test on/off switch.""" client = mock_transmission_client.return_value client.get_torrents.return_value = [mock_torrent()] mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.transmission_switch"}, blocking=True, ) getattr(client, api_method).assert_called_once() @pytest.mark.parametrize( ("service", "alt_speed_enabled", "expected_state"), [ (SERVICE_TURN_ON, True, "on"), (SERVICE_TURN_OFF, False, "off"), ], ) async def test_turtle_mode_switch( hass: HomeAssistant, mock_transmission_client: AsyncMock, mock_config_entry: MockConfigEntry, service: str, alt_speed_enabled: bool, expected_state: str, ) -> None: """Test turtle mode switch.""" client = mock_transmission_client.return_value current_alt_speed = not alt_speed_enabled def set_session_side_effect(**kwargs): nonlocal current_alt_speed if "alt_speed_enabled" in kwargs: current_alt_speed = kwargs["alt_speed_enabled"] client.set_session.side_effect = set_session_side_effect client.get_session.side_effect = lambda: Session( fields={"alt-speed-enabled": current_alt_speed} ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.transmission_turtle_mode"}, blocking=True, ) client.set_session.assert_called_once_with(alt_speed_enabled=alt_speed_enabled) state = hass.states.get("switch.transmission_turtle_mode") assert state is not None assert state.state == expected_state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/transmission/test_switch.py", "license": "Apache License 2.0", "lines": 122, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/update/test_trigger.py
"""Test update triggers.""" from typing import Any import pytest from homeassistant.components.update import DOMAIN from homeassistant.const import ATTR_LABEL_ID, CONF_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant, ServiceCall from tests.components import ( TriggerStateDescription, arm_trigger, parametrize_target_entities, parametrize_trigger_states, set_or_remove_state, target_entities, ) @pytest.fixture async def target_updates(hass: HomeAssistant) -> list[str]: """Create multiple update entities associated with different targets.""" return (await target_entities(hass, DOMAIN))["included"] @pytest.mark.parametrize( "trigger_key", [ "update.update_became_available", ], ) async def test_update_triggers_gated_by_labs_flag( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, trigger_key: str ) -> None: """Test the update triggers are gated by the labs flag.""" await arm_trigger(hass, trigger_key, None, {ATTR_LABEL_ID: "test_label"}) assert ( "Unnamed automation failed to setup triggers and has been disabled: Trigger " f"'{trigger_key}' requires the experimental 'New triggers and conditions' " "feature to be enabled in Home Assistant Labs settings (feature flag: " "'new_triggers_conditions')" ) in caplog.text @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="update.update_became_available", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_update_state_trigger_behavior_any( hass: HomeAssistant, service_calls: list[ServiceCall], target_updates: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the update state trigger fires when any update state changes to a specific state.""" other_entity_ids = set(target_updates) - {entity_id} # Set all updates, including the tested one, to the initial state for eid in target_updates: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Check if changing other updates also triggers for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == (entities_in_target - 1) * state["count"] service_calls.clear() @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="update.update_became_available", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_update_state_trigger_behavior_first( hass: HomeAssistant, service_calls: list[ServiceCall], target_updates: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the update state trigger fires when the first update changes to a specific state.""" other_entity_ids = set(target_updates) - {entity_id} # Set all updates, including the tested one, to the initial state for eid in target_updates: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "first"}, trigger_target_config) for state in states[1:]: included_state = state["included"] set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear() # Triggering other updates should not cause the trigger to fire again for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 @pytest.mark.usefixtures("enable_labs_preview_features") @pytest.mark.parametrize( ("trigger_target_config", "entity_id", "entities_in_target"), parametrize_target_entities(DOMAIN), ) @pytest.mark.parametrize( ("trigger", "trigger_options", "states"), [ *parametrize_trigger_states( trigger="update.update_became_available", target_states=[STATE_ON], other_states=[STATE_OFF], ), ], ) async def test_update_state_trigger_behavior_last( hass: HomeAssistant, service_calls: list[ServiceCall], target_updates: list[str], trigger_target_config: dict, entity_id: str, entities_in_target: int, trigger: str, trigger_options: dict[str, Any], states: list[TriggerStateDescription], ) -> None: """Test that the update state trigger fires when the last update changes to a specific state.""" other_entity_ids = set(target_updates) - {entity_id} # Set all updates, including the tested one, to the initial state for eid in target_updates: set_or_remove_state(hass, eid, states[0]["included"]) await hass.async_block_till_done() await arm_trigger(hass, trigger, {"behavior": "last"}, trigger_target_config) for state in states[1:]: included_state = state["included"] for other_entity_id in other_entity_ids: set_or_remove_state(hass, other_entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == 0 set_or_remove_state(hass, entity_id, included_state) await hass.async_block_till_done() assert len(service_calls) == state["count"] for service_call in service_calls: assert service_call.data[CONF_ENTITY_ID] == entity_id service_calls.clear()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/update/test_trigger.py", "license": "Apache License 2.0", "lines": 173, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/velux/test_init.py
"""Tests for Velux integration initialization and retry behavior. These tests verify that setup retries (ConfigEntryNotReady) are triggered when scene or node loading fails. They also verify that unloading the integration properly disconnects. """ from __future__ import annotations from unittest.mock import patch import pytest from pyvlx.exception import PyVLXException from homeassistant.components.velux.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.setup import async_setup_component from tests.common import AsyncMock, ConfigEntry, MockConfigEntry async def test_setup_retry_on_nodes_failure( mock_config_entry: ConfigEntry, hass: HomeAssistant, mock_pyvlx: AsyncMock ) -> None: """Test that a failure loading nodes triggers setup retry. The integration loads scenes first, then nodes. If loading raises PyVLXException, (which could have a multitude of reasons, unfortunately there are no specialized exceptions that give a reason), the ConfigEntry should enter SETUP_RETRY. """ mock_pyvlx.load_nodes.side_effect = PyVLXException("nodes boom") 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.SETUP_RETRY mock_pyvlx.load_scenes.assert_awaited_once() mock_pyvlx.load_nodes.assert_awaited_once() async def test_setup_retry_on_oserror_during_scenes( mock_config_entry: ConfigEntry, hass: HomeAssistant, mock_pyvlx: AsyncMock ) -> None: """Test that OSError during scene loading triggers setup retry. OSError typically indicates network/connection issues when the gateway refuses connections or is unreachable. """ mock_pyvlx.load_scenes.side_effect = OSError("Connection refused") 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.SETUP_RETRY mock_pyvlx.load_scenes.assert_awaited_once() mock_pyvlx.load_nodes.assert_not_called() async def test_setup_auth_error( mock_config_entry: ConfigEntry, hass: HomeAssistant, mock_pyvlx: AsyncMock ) -> None: """Test that PyVLXException with auth message raises ConfigEntryAuthFailed and starts reauth flow.""" mock_pyvlx.load_scenes.side_effect = PyVLXException( "Login to KLF 200 failed, check credentials" ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # ConfigEntryAuthFailed results in SETUP_ERROR state assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR flows = hass.config_entries.flow.async_progress() assert len(flows) == 1 assert flows[0]["step_id"] == "reauth_confirm" mock_pyvlx.load_scenes.assert_awaited_once() mock_pyvlx.load_nodes.assert_not_called() @pytest.fixture def platform() -> Platform: """Fixture to specify platform to test.""" return Platform.COVER @pytest.mark.usefixtures("setup_integration") async def test_unload_calls_disconnect( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pyvlx ) -> None: """Test that unloading the config entry disconnects from the gateway.""" # Unload the entry await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() # Verify disconnect was called mock_pyvlx.disconnect.assert_awaited_once() @pytest.mark.usefixtures("setup_integration") async def test_unload_does_not_disconnect_if_platform_unload_fails( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pyvlx ) -> None: """Test that disconnect is not called if platform unload fails.""" # Mock platform unload to fail with patch( "homeassistant.config_entries.ConfigEntries.async_unload_platforms", return_value=False, ): result = await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() # Verify unload failed assert result is False # Verify disconnect was NOT called since platform unload failed mock_pyvlx.disconnect.assert_not_awaited() @pytest.mark.usefixtures("setup_integration") async def test_reboot_gateway_service_raises_on_exception( hass: HomeAssistant, mock_pyvlx: AsyncMock ) -> None: """Test that reboot_gateway service raises HomeAssistantError on exception.""" mock_pyvlx.reboot_gateway.side_effect = OSError("Connection failed") with pytest.raises(HomeAssistantError, match="Failed to reboot gateway"): await hass.services.async_call( "velux", "reboot_gateway", blocking=True, ) mock_pyvlx.reboot_gateway.side_effect = PyVLXException("Reboot failed") with pytest.raises(HomeAssistantError, match="Failed to reboot gateway"): await hass.services.async_call( "velux", "reboot_gateway", blocking=True, ) async def test_reboot_gateway_service_raises_validation_error( hass: HomeAssistant, ) -> None: """Test that reboot_gateway service raises ServiceValidationError when no gateway is loaded.""" # Set up the velux integration's async_setup to register the service await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() with pytest.raises(ServiceValidationError, match="No loaded Velux gateway found"): await hass.services.async_call( "velux", "reboot_gateway", blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/velux/test_init.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/vesync/test_services.py
"""Tests for VeSync services.""" from unittest.mock import AsyncMock import pytest from pyvesync import VeSync from homeassistant.components.vesync import async_setup from homeassistant.components.vesync.const import DOMAIN, SERVICE_UPDATE_DEVS from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import entity_registry as er async def test_async_new_device_discovery_no_entry( hass: HomeAssistant, ) -> None: """Service should raise when no config entry exists.""" # Ensure the integration is set up so the service is registered assert await async_setup(hass, {}) # No entries for the domain, service should raise with pytest.raises(ServiceValidationError, match="Entry not found"): await hass.services.async_call("vesync", SERVICE_UPDATE_DEVS, {}, blocking=True) async def test_async_new_device_discovery_entry_not_loaded( hass: HomeAssistant, config_entry: ConfigEntry ) -> None: """Service should raise when entry exists but is not loaded.""" # Add a config entry but do not set it up (state is not LOADED) assert config_entry.state is ConfigEntryState.NOT_LOADED # Ensure the integration is set up so the service is registered assert await async_setup(hass, {}) with pytest.raises(ServiceValidationError, match="Entry not loaded"): await hass.services.async_call("vesync", SERVICE_UPDATE_DEVS, {}, blocking=True) async def test_async_new_device_discovery( hass: HomeAssistant, config_entry: ConfigEntry, manager: VeSync, fan, entity_registry: er.EntityRegistry, ) -> None: """Test new device discovery.""" # Entry should not be set up yet; we'll install a fan before setup assert config_entry.state is ConfigEntryState.NOT_LOADED # Set up the config entry (no devices initially) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED # Simulate the manager discovering a new fan when get_devices is called manager.get_devices = AsyncMock( side_effect=lambda: manager._dev_list["fans"].append(fan) ) # Call the service that should trigger discovery and platform setup await hass.services.async_call(DOMAIN, SERVICE_UPDATE_DEVS, {}, blocking=True) await hass.async_block_till_done() assert manager.get_devices.call_count == 1 # Verify an entity for the new fan was created in Home Assistant fan_entry = next( ( e for e in entity_registry.entities.values() if e.unique_id == fan.cid and e.domain == "fan" ), None, ) assert fan_entry is not None
{ "repo_id": "home-assistant/core", "file_path": "tests/components/vesync/test_services.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/vivotek/test_camera.py
"""Tests for the Vivotek camera integration.""" from unittest.mock import AsyncMock, patch from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform async def test_all_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_vivotek_camera: AsyncMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, ) -> None: """Test all entities.""" with patch("random.SystemRandom.getrandbits", return_value=123123123123): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/vivotek/test_camera.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/vivotek/test_config_flow.py
"""Tests for the Vivotek config flow.""" from unittest.mock import AsyncMock from libpyvivotek.vivotek import VivotekCameraError import pytest from homeassistant.components.vivotek.camera import DEFAULT_FRAMERATE, DEFAULT_NAME from homeassistant.components.vivotek.const import ( CONF_FRAMERATE, CONF_SECURITY_LEVEL, CONF_STREAM_PATH, DOMAIN, ) from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import ( CONF_AUTHENTICATION, CONF_IP_ADDRESS, CONF_PASSWORD, CONF_PORT, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, HTTP_BASIC_AUTHENTICATION, ) from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry USER_DATA = { CONF_IP_ADDRESS: "1.2.3.4", CONF_PORT: 80, CONF_USERNAME: "admin", CONF_PASSWORD: "pass1234", CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION, CONF_SSL: False, CONF_VERIFY_SSL: True, CONF_SECURITY_LEVEL: "admin", CONF_STREAM_PATH: "/live.sdp", } IMPORT_DATA = { CONF_IP_ADDRESS: "1.2.3.4", CONF_USERNAME: "admin", CONF_PASSWORD: "pass1234", CONF_AUTHENTICATION: HTTP_BASIC_AUTHENTICATION, CONF_SSL: False, CONF_VERIFY_SSL: True, CONF_SECURITY_LEVEL: "admin", CONF_STREAM_PATH: "/live.sdp", CONF_FRAMERATE: DEFAULT_FRAMERATE, } async def test_full_flow( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_vivotek_camera: AsyncMock ) -> None: """Test full user initiated flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], USER_DATA ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == DEFAULT_NAME assert result["data"] == USER_DATA assert result["options"] == {CONF_FRAMERATE: DEFAULT_FRAMERATE} assert result["result"].unique_id == "11:22:33:44:55:66" @pytest.mark.parametrize( ("exception", "error"), [ (VivotekCameraError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_user_exceptions( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_vivotek_camera: AsyncMock, exception: Exception, error: str, ) -> None: """Test user initiated flow with exceptions.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} mock_vivotek_camera.get_mac.side_effect = exception result = await hass.config_entries.flow.async_configure( result["flow_id"], USER_DATA ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {"base": error} mock_vivotek_camera.get_mac.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], USER_DATA ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_duplicate_entry( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test flow abort on duplicate entry.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], USER_DATA ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_duplicate_entry_mac( hass: HomeAssistant, mock_vivotek_camera: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test flow abort on duplicate MAC address.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], {**USER_DATA, CONF_IP_ADDRESS: "1.1.1.1"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_import_flow( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_vivotek_camera: AsyncMock ) -> None: """Test import initiated flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == DEFAULT_NAME assert result["data"] == USER_DATA assert result["options"] == {CONF_FRAMERATE: DEFAULT_FRAMERATE} assert result["result"].unique_id == "11:22:33:44:55:66" @pytest.mark.parametrize( ("exception", "reason"), [ (VivotekCameraError, "cannot_connect"), (Exception, "unknown"), ], ) async def test_import_flow_exceptions( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_vivotek_camera: AsyncMock, exception: Exception, reason: str, ) -> None: """Test import initiated flow with exceptions.""" mock_vivotek_camera.get_mac.side_effect = exception result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == reason async def test_import_flow_duplicate( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test import initiated flow.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=IMPORT_DATA ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_import_flow_duplicate_mac( hass: HomeAssistant, mock_vivotek_camera: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test import initiated flow.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={**IMPORT_DATA, CONF_IP_ADDRESS: "1.1.1.1"}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_options_flow( hass: HomeAssistant, mock_vivotek_camera: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test options flow.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.options.async_init(mock_config_entry.entry_id) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], { CONF_FRAMERATE: 15, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert mock_config_entry.options[CONF_FRAMERATE] == 15
{ "repo_id": "home-assistant/core", "file_path": "tests/components/vivotek/test_config_flow.py", "license": "Apache License 2.0", "lines": 207, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/watts/test_application_credentials.py
"""Test application credentials for Watts integration.""" from homeassistant.components.watts.application_credentials import ( async_get_authorization_server, ) from homeassistant.components.watts.const import OAUTH2_AUTHORIZE, OAUTH2_TOKEN from homeassistant.core import HomeAssistant async def test_async_get_authorization_server(hass: HomeAssistant) -> None: """Test getting authorization server.""" auth_server = await async_get_authorization_server(hass) assert auth_server.authorize_url == OAUTH2_AUTHORIZE assert auth_server.token_url == OAUTH2_TOKEN
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_application_credentials.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/watts/test_climate.py
"""Tests for the Watts Vision climate platform.""" from datetime import timedelta from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from visionpluspython.models import ThermostatMode from homeassistant.components.climate import ( ATTR_HVAC_MODE, ATTR_TEMPERATURE, DOMAIN as CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, SERVICE_SET_TEMPERATURE, HVACMode, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform async def test_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the climate entities.""" with patch("homeassistant.components.watts.PLATFORMS", [Platform.CLIMATE]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_set_temperature( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting temperature.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("climate.living_room_thermostat") assert state is not None assert state.attributes.get(ATTR_TEMPERATURE) == 22.0 await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_TEMPERATURE: 23.5, }, blocking=True, ) mock_watts_client.set_thermostat_temperature.assert_called_once_with( "thermostat_123", 23.5 ) async def test_fast_polling( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test that setting temperature triggers fast polling and it stops after duration.""" await setup_integration(hass, mock_config_entry) # Trigger fast polling await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_TEMPERATURE: 23.5, }, blocking=True, ) mock_watts_client.get_device.reset_mock() # Fast polling should be active freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_watts_client.get_device.called mock_watts_client.get_device.assert_called_with("thermostat_123", refresh=True) # Should still be in fast polling after 55s mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=50)) async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_watts_client.get_device.called mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=10)) async_fire_time_changed(hass) await hass.async_block_till_done() # Fast polling should be done now mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() assert not mock_watts_client.get_device.called async def test_set_hvac_mode_heat( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting HVAC mode to heat.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_HVAC_MODE: HVACMode.HEAT, }, blocking=True, ) mock_watts_client.set_thermostat_mode.assert_called_once_with( "thermostat_123", ThermostatMode.COMFORT ) async def test_set_hvac_mode_auto( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting HVAC mode to auto.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: "climate.bedroom_thermostat", ATTR_HVAC_MODE: HVACMode.AUTO, }, blocking=True, ) mock_watts_client.set_thermostat_mode.assert_called_once_with( "thermostat_456", ThermostatMode.PROGRAM ) async def test_set_hvac_mode_off( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting HVAC mode to off.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_HVAC_MODE: HVACMode.OFF, }, blocking=True, ) mock_watts_client.set_thermostat_mode.assert_called_once_with( "thermostat_123", ThermostatMode.OFF ) async def test_set_temperature_api_error( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test error handling when setting temperature fails.""" await setup_integration(hass, mock_config_entry) # Make the API call fail mock_watts_client.set_thermostat_temperature.side_effect = RuntimeError("API Error") with pytest.raises( HomeAssistantError, match="An error occurred while setting the temperature" ): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_TEMPERATURE: 23.5, }, blocking=True, ) async def test_set_hvac_mode_value_error( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test error handling when setting mode fails.""" await setup_integration(hass, mock_config_entry) mock_watts_client.set_thermostat_mode.side_effect = ValueError("Invalid mode") with pytest.raises( HomeAssistantError, match="An error occurred while setting the HVAC mode" ): await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_HVAC_MODE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_HVAC_MODE: HVACMode.HEAT, }, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_climate.py", "license": "Apache License 2.0", "lines": 193, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/watts/test_config_flow.py
"""Test the Watts Vision config flow.""" from unittest.mock import patch import pytest from homeassistant import config_entries from homeassistant.components.watts.const import DOMAIN, OAUTH2_AUTHORIZE, OAUTH2_TOKEN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers import config_entry_oauth2_flow from tests.common import MockConfigEntry from tests.test_util.aiohttp import AiohttpClientMocker from tests.typing import ClientSessionGenerator @pytest.mark.usefixtures("current_request_with_host", "mock_setup_entry") async def test_full_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test the full OAuth2 config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result.get("type") is FlowResultType.EXTERNAL_STEP assert "url" in result assert OAUTH2_AUTHORIZE in result.get("url", "") assert "response_type=code" in result.get("url", "") assert "scope=" in result.get("url", "") state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 assert resp.headers["content-type"] == "text/html; charset=utf-8" aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="user123", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.CREATE_ENTRY assert result.get("title") == "Watts Vision +" assert "token" in result.get("data", {}) assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert hass.config_entries.async_entries(DOMAIN)[0].unique_id == "user123" @pytest.mark.usefixtures("current_request_with_host") async def test_invalid_token_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test the OAuth2 config flow with invalid token.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "mock-refresh-token", "access_token": "invalid-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value=None, ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "invalid_token" @pytest.mark.usefixtures("current_request_with_host") async def test_oauth_error( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test OAuth error handling.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={"error": "invalid_grant"}, ) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "oauth_error" @pytest.mark.usefixtures("current_request_with_host") async def test_oauth_timeout( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test OAuth timeout handling.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post(OAUTH2_TOKEN, exc=TimeoutError()) result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "oauth_timeout" @pytest.mark.usefixtures("current_request_with_host") async def test_oauth_invalid_response( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test OAuth invalid response handling.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post(OAUTH2_TOKEN, status=500, text="invalid json") result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "oauth_failed" @pytest.mark.usefixtures("current_request_with_host", "mock_setup_entry") async def test_reauth_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test the reauthentication flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="test-user-id", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" mock_config_entry.data["token"].pop("expires_at") assert mock_config_entry.data["token"] == { "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, } @pytest.mark.usefixtures("current_request_with_host") async def test_reauth_account_mismatch( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test reauthentication with a different account aborts.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="different-user-id", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "account_mismatch" @pytest.mark.usefixtures("current_request_with_host", "mock_setup_entry") async def test_reconfigure_flow( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test the reconfiguration flow.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reconfigure_flow(hass) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="test-user-id", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" mock_config_entry.data["token"].pop("expires_at") assert mock_config_entry.data["token"] == { "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, } @pytest.mark.usefixtures("current_request_with_host") async def test_reconfigure_account_mismatch( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, mock_config_entry: MockConfigEntry, ) -> None: """Test reconfiguration with a different account aborts.""" mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reconfigure_flow(hass) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "new-refresh-token", "access_token": "new-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="different-user-id", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "account_mismatch" @pytest.mark.usefixtures("current_request_with_host") async def test_unique_config_entry( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test that duplicate config entries are not allowed.""" mock_config_entry = MockConfigEntry( domain=DOMAIN, unique_id="user123", ) mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) state = config_entry_oauth2_flow._encode_jwt( hass, { "flow_id": result["flow_id"], "redirect_uri": "https://example.com/auth/external/callback", }, ) client = await hass_client_no_auth() resp = await client.get(f"/auth/external/callback?code=abcd&state={state}") assert resp.status == 200 aioclient_mock.post( OAUTH2_TOKEN, json={ "refresh_token": "mock-refresh-token", "access_token": "mock-access-token", "token_type": "Bearer", "expires_in": 3600, }, ) with patch( "homeassistant.components.watts.config_flow.WattsVisionAuth.extract_user_id_from_token", return_value="user123", ): result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" assert len(hass.config_entries.async_entries(DOMAIN)) == 1
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_config_flow.py", "license": "Apache License 2.0", "lines": 373, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/watts/test_init.py
"""Test the Watts Vision integration initialization.""" from datetime import timedelta from unittest.mock import AsyncMock from aiohttp import ClientError from freezegun.api import FrozenDateTimeFactory import pytest from visionpluspython.exceptions import ( WattsVisionAuthError, WattsVisionConnectionError, WattsVisionDeviceError, WattsVisionError, WattsVisionTimeoutError, ) from visionpluspython.models import create_device_from_data from homeassistant.components.climate import ( ATTR_TEMPERATURE, DOMAIN as CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, ) from homeassistant.components.watts.const import ( DISCOVERY_INTERVAL_MINUTES, DOMAIN, FAST_POLLING_INTERVAL_SECONDS, OAUTH2_TOKEN, UPDATE_INTERVAL_SECONDS, ) from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from . import setup_integration from tests.common import MockConfigEntry, async_fire_time_changed from tests.test_util.aiohttp import AiohttpClientMocker async def test_setup_entry_success( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test successful setup and unload of entry.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED mock_watts_client.discover_devices.assert_called_once() unload_result = await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert unload_result is True assert mock_config_entry.state is ConfigEntryState.NOT_LOADED @pytest.mark.usefixtures("setup_credentials") async def test_setup_entry_auth_failed( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, ) -> None: """Test setup with authentication failure.""" config_entry = MockConfigEntry( domain="watts", unique_id="test-device-id", data={ "device_id": "test-device-id", "auth_implementation": "watts", "token": { "access_token": "test-access-token", "refresh_token": "test-refresh-token", "expires_at": 0, # Expired token to force refresh }, }, ) config_entry.add_to_hass(hass) aioclient_mock.post(OAUTH2_TOKEN, status=401) result = await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert result is False assert config_entry.state is ConfigEntryState.SETUP_ERROR @pytest.mark.usefixtures("setup_credentials") async def test_setup_entry_not_ready( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, ) -> None: """Test setup when network is temporarily unavailable.""" config_entry = MockConfigEntry( domain="watts", unique_id="test-device-id", data={ "device_id": "test-device-id", "auth_implementation": "watts", "token": { "access_token": "test-access-token", "refresh_token": "test-refresh-token", "expires_at": 0, # Expired token to force refresh }, }, ) config_entry.add_to_hass(hass) aioclient_mock.post(OAUTH2_TOKEN, exc=ClientError("Connection timeout")) result = await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert result is False assert config_entry.state is ConfigEntryState.SETUP_RETRY async def test_setup_entry_hub_coordinator_update_failed( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setup when hub coordinator update fails.""" # Make discover_devices fail mock_watts_client.discover_devices.side_effect = ConnectionError("API error") mock_config_entry.add_to_hass(hass) result = await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert result is False assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY @pytest.mark.usefixtures("setup_credentials") async def test_setup_entry_server_error_5xx( hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, ) -> None: """Test setup when server returns error.""" config_entry = MockConfigEntry( domain="watts", unique_id="test-device-id", data={ "device_id": "test-device-id", "auth_implementation": "watts", "token": { "access_token": "test-access-token", "refresh_token": "test-refresh-token", "expires_at": 0, # Expired token to force refresh }, }, ) config_entry.add_to_hass(hass) aioclient_mock.post(OAUTH2_TOKEN, status=500) result = await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert result is False assert config_entry.state is ConfigEntryState.SETUP_RETRY @pytest.mark.parametrize( ("exception", "expected_state"), [ (WattsVisionAuthError("Auth failed"), ConfigEntryState.SETUP_ERROR), (WattsVisionConnectionError("Connection lost"), ConfigEntryState.SETUP_RETRY), (WattsVisionTimeoutError("Request timeout"), ConfigEntryState.SETUP_RETRY), (WattsVisionDeviceError("Device error"), ConfigEntryState.SETUP_RETRY), (WattsVisionError("API error"), ConfigEntryState.SETUP_RETRY), (ValueError("Value error"), ConfigEntryState.SETUP_RETRY), ], ) async def test_setup_entry_discover_devices_errors( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, exception: Exception, expected_state: ConfigEntryState, ) -> None: """Test setup errors during device discovery.""" mock_watts_client.discover_devices.side_effect = exception mock_config_entry.add_to_hass(hass) result = await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert result is False assert mock_config_entry.state is expected_state async def test_dynamic_device_creation( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, freezer: FrozenDateTimeFactory, ) -> None: """Test new devices are created dynamically.""" await setup_integration(hass, mock_config_entry) assert device_registry.async_get_device(identifiers={(DOMAIN, "thermostat_123")}) assert device_registry.async_get_device(identifiers={(DOMAIN, "thermostat_456")}) assert ( device_registry.async_get_device(identifiers={(DOMAIN, "thermostat_789")}) is None ) new_device_data = { "deviceId": "thermostat_789", "deviceName": "Kitchen Thermostat", "deviceType": "thermostat", "interface": "homeassistant.components.THERMOSTAT", "roomName": "Kitchen", "isOnline": True, "currentTemperature": 21.0, "setpoint": 20.0, "thermostatMode": "Comfort", "minAllowedTemperature": 5.0, "maxAllowedTemperature": 30.0, "temperatureUnit": "C", "availableThermostatModes": ["Program", "Eco", "Comfort", "Off"], } new_device = create_device_from_data(new_device_data) current_devices = list(mock_watts_client.discover_devices.return_value) mock_watts_client.discover_devices.return_value = [*current_devices, new_device] freezer.tick(timedelta(minutes=DISCOVERY_INTERVAL_MINUTES)) async_fire_time_changed(hass) await hass.async_block_till_done() new_device_entry = device_registry.async_get_device( identifiers={(DOMAIN, "thermostat_789")} ) assert new_device_entry is not None assert new_device_entry.name == "Kitchen Thermostat" state = hass.states.get("climate.kitchen_thermostat") assert state is not None async def test_stale_device_removal( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, freezer: FrozenDateTimeFactory, ) -> None: """Test stale devices are removed dynamically.""" await setup_integration(hass, mock_config_entry) device_123 = device_registry.async_get_device( identifiers={(DOMAIN, "thermostat_123")} ) device_456 = device_registry.async_get_device( identifiers={(DOMAIN, "thermostat_456")} ) assert device_123 is not None assert device_456 is not None current_devices = list(mock_watts_client.discover_devices.return_value) # remove thermostat_456 mock_watts_client.discover_devices.return_value = [ d for d in current_devices if d.device_id != "thermostat_456" ] freezer.tick(timedelta(minutes=DISCOVERY_INTERVAL_MINUTES)) async_fire_time_changed(hass) await hass.async_block_till_done() # Verify thermostat_456 has been removed device_456_after_removal = device_registry.async_get_device( identifiers={(DOMAIN, "thermostat_456")} ) assert device_456_after_removal is None @pytest.mark.parametrize( ("exception", "has_reauth_flow"), [ (WattsVisionAuthError("expired"), True), (WattsVisionConnectionError("lost"), False), ], ) async def test_hub_coordinator_update_errors( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, exception: Exception, has_reauth_flow: bool, ) -> None: """Test hub coordinator handles errors during regular update.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("climate.living_room_thermostat") assert state is not None assert state.state != STATE_UNAVAILABLE mock_watts_client.get_devices_report.side_effect = exception freezer.tick(timedelta(seconds=UPDATE_INTERVAL_SECONDS)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("climate.living_room_thermostat") assert state is not None assert state.state != STATE_UNAVAILABLE assert ( any(mock_config_entry.async_get_active_flows(hass, {SOURCE_REAUTH})) == has_reauth_flow ) async def test_device_coordinator_refresh_error( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test device coordinator handles refresh error.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("climate.living_room_thermostat") assert state is not None assert state.state != STATE_UNAVAILABLE # Activate fast polling await hass.services.async_call( CLIMATE_DOMAIN, SERVICE_SET_TEMPERATURE, { ATTR_ENTITY_ID: "climate.living_room_thermostat", ATTR_TEMPERATURE: 23.5, }, blocking=True, ) await hass.async_block_till_done() # Device refresh fail on the next fast poll mock_watts_client.get_device.side_effect = WattsVisionConnectionError("lost") freezer.tick(timedelta(seconds=FAST_POLLING_INTERVAL_SECONDS)) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("climate.living_room_thermostat") assert state is not None assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_init.py", "license": "Apache License 2.0", "lines": 293, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/web_rtc/test_init.py
"""Test the WebRTC integration.""" from webrtc_models import RTCIceServer from homeassistant.components.web_rtc import ( async_get_ice_servers, async_register_ice_servers, ) from homeassistant.core import HomeAssistant, callback from homeassistant.core_config import async_process_ha_core_config from homeassistant.setup import async_setup_component from tests.typing import WebSocketGenerator async def test_async_setup(hass: HomeAssistant) -> None: """Test setting up the web_rtc integration.""" assert await async_setup_component(hass, "web_rtc", {}) await hass.async_block_till_done() # Verify default ICE servers are registered ice_servers = async_get_ice_servers(hass) assert len(ice_servers) == 1 assert ice_servers[0].urls == [ "stun:stun.home-assistant.io:3478", "stun:stun.home-assistant.io:80", ] async def test_async_setup_custom_ice_servers_core(hass: HomeAssistant) -> None: """Test setting up web_rtc with custom ICE servers in config.""" await async_process_ha_core_config( hass, {"webrtc": {"ice_servers": [{"url": "stun:custom_stun_server:3478"}]}}, ) assert await async_setup_component(hass, "web_rtc", {}) await hass.async_block_till_done() ice_servers = async_get_ice_servers(hass) assert len(ice_servers) == 1 assert ice_servers[0].urls == ["stun:custom_stun_server:3478"] async def test_async_setup_custom_ice_servers_integration(hass: HomeAssistant) -> None: """Test setting up web_rtc with custom ICE servers in config.""" assert await async_setup_component( hass, "web_rtc", { "web_rtc": { "ice_servers": [ {"url": "stun:custom_stun_server:3478"}, { "url": "stun:custom_stun_server:3478", "credential": "mock-credential", }, { "url": "stun:custom_stun_server:3478", "username": "mock-username", }, { "url": "stun:custom_stun_server:3478", "credential": "mock-credential", "username": "mock-username", }, ] } }, ) await hass.async_block_till_done() ice_servers = async_get_ice_servers(hass) assert ice_servers == [ RTCIceServer( urls=["stun:custom_stun_server:3478"], ), RTCIceServer( urls=["stun:custom_stun_server:3478"], credential="mock-credential", ), RTCIceServer( urls=["stun:custom_stun_server:3478"], username="mock-username", ), RTCIceServer( urls=["stun:custom_stun_server:3478"], username="mock-username", credential="mock-credential", ), ] async def test_async_setup_custom_ice_servers_core_and_integration( hass: HomeAssistant, ) -> None: """Test setting up web_rtc with custom ICE servers in config.""" await async_process_ha_core_config( hass, {"webrtc": {"ice_servers": [{"url": "stun:custom_stun_server_core:3478"}]}}, ) assert await async_setup_component( hass, "web_rtc", { "web_rtc": { "ice_servers": [{"url": "stun:custom_stun_server_integration:3478"}] } }, ) await hass.async_block_till_done() ice_servers = async_get_ice_servers(hass) assert ice_servers == [ RTCIceServer( urls=["stun:custom_stun_server_core:3478"], ), RTCIceServer( urls=["stun:custom_stun_server_integration:3478"], ), ] async def test_async_register_ice_servers(hass: HomeAssistant) -> None: """Test registering ICE servers.""" assert await async_setup_component(hass, "web_rtc", {}) await hass.async_block_till_done() default_servers = async_get_ice_servers(hass) called = 0 @callback def get_ice_servers() -> list[RTCIceServer]: nonlocal called called += 1 return [ RTCIceServer(urls="stun:example.com"), RTCIceServer(urls="turn:example.com"), ] unregister = async_register_ice_servers(hass, get_ice_servers) assert called == 0 # Getting ice servers should call the callback ice_servers = async_get_ice_servers(hass) assert called == 1 assert ice_servers == [ *default_servers, RTCIceServer(urls="stun:example.com"), RTCIceServer(urls="turn:example.com"), ] # Unregister and verify servers are removed unregister() ice_servers = async_get_ice_servers(hass) assert ice_servers == default_servers async def test_multiple_ice_server_registrations(hass: HomeAssistant) -> None: """Test registering multiple ICE server providers.""" assert await async_setup_component(hass, "web_rtc", {}) await hass.async_block_till_done() default_servers = async_get_ice_servers(hass) @callback def get_ice_servers_1() -> list[RTCIceServer]: return [RTCIceServer(urls="stun:server1.com")] @callback def get_ice_servers_2() -> list[RTCIceServer]: return [ RTCIceServer( urls=["stun:server2.com", "turn:server2.com"], username="user", credential="pass", ) ] unregister_1 = async_register_ice_servers(hass, get_ice_servers_1) unregister_2 = async_register_ice_servers(hass, get_ice_servers_2) ice_servers = async_get_ice_servers(hass) assert ice_servers == [ *default_servers, RTCIceServer(urls="stun:server1.com"), RTCIceServer( urls=["stun:server2.com", "turn:server2.com"], username="user", credential="pass", ), ] # Unregister first provider unregister_1() ice_servers = async_get_ice_servers(hass) assert ice_servers == [ *default_servers, RTCIceServer( urls=["stun:server2.com", "turn:server2.com"], username="user", credential="pass", ), ] # Unregister second provider unregister_2() ice_servers = async_get_ice_servers(hass) assert ice_servers == default_servers async def test_ws_ice_servers_with_registered_servers( hass: HomeAssistant, hass_ws_client: WebSocketGenerator ) -> None: """Test WebSocket ICE servers endpoint with registered servers.""" assert await async_setup_component(hass, "web_rtc", {}) await hass.async_block_till_done() @callback def get_ice_server() -> list[RTCIceServer]: return [ RTCIceServer( urls=["stun:example2.com", "turn:example2.com"], username="user", credential="pass", ) ] async_register_ice_servers(hass, get_ice_server) client = await hass_ws_client(hass) await client.send_json_auto_id({"type": "web_rtc/ice_servers"}) msg = await client.receive_json() # Assert WebSocket response includes registered ICE servers assert msg["type"] == "result" assert msg["success"] assert msg["result"] == [ { "urls": [ "stun:stun.home-assistant.io:3478", "stun:stun.home-assistant.io:80", ] }, { "urls": ["stun:example2.com", "turn:example2.com"], "username": "user", "credential": "pass", }, ]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/web_rtc/test_init.py", "license": "Apache License 2.0", "lines": 212, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/wmspro/test_switch.py
"""Test the wmspro switch support.""" from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.wmspro.const import DOMAIN from homeassistant.components.wmspro.switch import SCAN_INTERVAL from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, STATE_ON, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from . import setup_config_entry from tests.common import MockConfigEntry, async_fire_time_changed async def test_switch_device( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hub_ping: AsyncMock, mock_hub_configuration_prod_load_switch: AsyncMock, mock_hub_status_prod_load_switch: AsyncMock, device_registry: dr.DeviceRegistry, snapshot: SnapshotAssertion, ) -> None: """Test that a switch device is created correctly.""" assert await setup_config_entry(hass, mock_config_entry) assert len(mock_hub_ping.mock_calls) == 1 assert len(mock_hub_configuration_prod_load_switch.mock_calls) == 1 assert len(mock_hub_status_prod_load_switch.mock_calls) >= 2 device_entry = device_registry.async_get_device(identifiers={(DOMAIN, "499120")}) assert device_entry is not None assert device_entry == snapshot async def test_switch_update( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hub_ping: AsyncMock, mock_hub_configuration_prod_load_switch: AsyncMock, mock_hub_status_prod_load_switch: AsyncMock, freezer: FrozenDateTimeFactory, snapshot: SnapshotAssertion, ) -> None: """Test that a switch entity is created and updated correctly.""" assert await setup_config_entry(hass, mock_config_entry) assert len(mock_hub_ping.mock_calls) == 1 assert len(mock_hub_configuration_prod_load_switch.mock_calls) == 1 assert len(mock_hub_status_prod_load_switch.mock_calls) >= 2 entity = hass.states.get("switch.heizung_links") assert entity is not None assert entity == snapshot before = len(mock_hub_status_prod_load_switch.mock_calls) # Move time to next update freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) assert len(mock_hub_status_prod_load_switch.mock_calls) > before async def test_switch_turn_on_and_off( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hub_ping: AsyncMock, mock_hub_configuration_prod_load_switch: AsyncMock, mock_hub_status_prod_load_switch: AsyncMock, mock_action_call: AsyncMock, ) -> None: """Test that a switch entity is turned on and off correctly.""" assert await setup_config_entry(hass, mock_config_entry) assert len(mock_hub_ping.mock_calls) == 1 assert len(mock_hub_configuration_prod_load_switch.mock_calls) == 1 assert len(mock_hub_status_prod_load_switch.mock_calls) >= 1 entity = hass.states.get("switch.heizung_links") assert entity is not None assert entity.state == STATE_OFF with patch( "wmspro.destination.Destination.refresh", return_value=True, ): before = len(mock_hub_status_prod_load_switch.mock_calls) await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id}, blocking=True, ) entity = hass.states.get("switch.heizung_links") assert entity is not None assert entity.state == STATE_ON assert len(mock_hub_status_prod_load_switch.mock_calls) == before with patch( "wmspro.destination.Destination.refresh", return_value=True, ): before = len(mock_hub_status_prod_load_switch.mock_calls) await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity.entity_id}, blocking=True, ) entity = hass.states.get("switch.heizung_links") assert entity is not None assert entity.state == STATE_OFF assert len(mock_hub_status_prod_load_switch.mock_calls) == before
{ "repo_id": "home-assistant/core", "file_path": "tests/components/wmspro/test_switch.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/wsdot/test_config_flow.py
"""Define tests for the wsdot config flow.""" from typing import Any from unittest.mock import AsyncMock import pytest from wsdot import WsdotTravelError from homeassistant.components.wsdot.const import ( CONF_TRAVEL_TIMES, DOMAIN, SUBENTRY_TRAVEL_TIMES, ) from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER from homeassistant.const import CONF_API_KEY, CONF_ID, CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry VALID_USER_CONFIG = { CONF_API_KEY: "abcd-1234", } VALID_USER_TRAVEL_TIME_CONFIG = { CONF_NAME: "Seattle-Bellevue via I-90 (EB AM)", } async def test_create_user_entry( hass: HomeAssistant, mock_travel_time: AsyncMock ) -> None: """Test that the user step works.""" # No user data; form is being show for the first time result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # User data; the user entered data and hit submit result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=VALID_USER_CONFIG, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == DOMAIN assert result["data"][CONF_API_KEY] == "abcd-1234" @pytest.mark.parametrize( ("failed_travel_time_status", "errors"), [ (400, {CONF_API_KEY: "invalid_api_key"}), (404, {"base": "cannot_connect"}), ], ) async def test_errors( hass: HomeAssistant, mock_travel_time: AsyncMock, mock_setup_entry: AsyncMock, failed_travel_time_status: int, errors: dict[str, str], ) -> None: """Test that the user step works.""" mock_travel_time.get_all_travel_times.side_effect = WsdotTravelError( status=failed_travel_time_status ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=VALID_USER_CONFIG, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == errors mock_travel_time.get_all_travel_times.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=VALID_USER_CONFIG, ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.parametrize( "mock_subentries", [ [], ], ) async def test_create_travel_time_subentry( hass: HomeAssistant, mock_travel_time: AsyncMock, init_integration: MockConfigEntry, ) -> None: """Test that the user step for Travel Time works.""" # No user data; form is being show for the first time result = await hass.config_entries.subentries.async_init( (init_integration.entry_id, SUBENTRY_TRAVEL_TIMES), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" # User data; the user made a choice and hit submit result = await hass.config_entries.subentries.async_init( (init_integration.entry_id, SUBENTRY_TRAVEL_TIMES), context={"source": SOURCE_USER}, data=VALID_USER_TRAVEL_TIME_CONFIG, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"][CONF_NAME] == "Seattle-Bellevue via I-90 (EB AM)" assert result["data"][CONF_ID] == 96 @pytest.mark.parametrize( "import_config", [ { CONF_API_KEY: "abcd-5678", CONF_TRAVEL_TIMES: [{CONF_ID: 96, CONF_NAME: "I-90 EB"}], }, { CONF_API_KEY: "abcd-5678", CONF_TRAVEL_TIMES: [{CONF_ID: "96", CONF_NAME: "I-90 EB"}], }, ], ids=["with-int-id", "with-str-id"], ) async def test_create_import_entry( hass: HomeAssistant, mock_travel_time: AsyncMock, import_config: dict[str, str | int], ) -> None: """Test that the yaml import works.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=import_config, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "wsdot" assert result["data"][CONF_API_KEY] == "abcd-5678" entry = result["result"] assert entry is not None assert len(entry.subentries) == 1 subentry = next(iter(entry.subentries.values())) assert subentry.subentry_type == SUBENTRY_TRAVEL_TIMES assert subentry.title == "Seattle-Bellevue via I-90 (EB AM)" assert subentry.data[CONF_NAME] == "Seattle-Bellevue via I-90 (EB AM)" assert subentry.data[CONF_ID] == 96 @pytest.mark.parametrize( ("failed_travel_time_status", "abort_reason"), [ (400, "invalid_api_key"), (404, "cannot_connect"), ], ) async def test_failed_import_entry( hass: HomeAssistant, mock_failed_travel_time: AsyncMock, mock_config_data: dict[str, Any], failed_travel_time_status: int, abort_reason: str, ) -> None: """Test the failure modes of a yaml import.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data=mock_config_data, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == abort_reason async def test_incorrect_import_entry( hass: HomeAssistant, mock_travel_time: AsyncMock, mock_config_data: dict[str, Any], ) -> None: """Test a yaml import of a non-existent route.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_API_KEY: "abcd-5678", CONF_TRAVEL_TIMES: [{CONF_ID: "100001", CONF_NAME: "nowhere"}], }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "invalid_travel_time_id" async def test_import_integration_already_exists( hass: HomeAssistant, mock_travel_time: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, init_integration: MockConfigEntry, ) -> None: """Test we only allow one entry per API key.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_IMPORT}, data={ CONF_API_KEY: "abcd-1234", CONF_TRAVEL_TIMES: [{CONF_ID: "100001", CONF_NAME: "nowhere"}], }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_integration_already_exists( hass: HomeAssistant, mock_travel_time: AsyncMock, mock_config_entry: MockConfigEntry, init_integration: MockConfigEntry, ) -> None: """Test we only allow one entry per API key.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert not result["errors"] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=VALID_USER_CONFIG, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_travel_route_already_exists( hass: HomeAssistant, mock_travel_time: AsyncMock, mock_config_entry: MockConfigEntry, init_integration: MockConfigEntry, ) -> None: """Test we only allow choosing a travel time route once.""" result = await hass.config_entries.subentries.async_init( (init_integration.entry_id, SUBENTRY_TRAVEL_TIMES), context={"source": SOURCE_USER}, ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert not result["errors"] result = await hass.config_entries.subentries.async_configure( result["flow_id"], user_input=VALID_USER_TRAVEL_TIME_CONFIG, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/wsdot/test_config_flow.py", "license": "Apache License 2.0", "lines": 235, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/wsdot/test_init.py
"""The tests for the WSDOT platform.""" from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from tests.common import MockConfigEntry async def test_travel_sensor_setup_no_auth( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_failed_travel_time: None, issue_registry: ir.IssueRegistry, ) -> None: """Test the wsdot Travel Time sensor does not create an entry with a bad API key.""" 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.SETUP_ERROR
{ "repo_id": "home-assistant/core", "file_path": "tests/components/wsdot/test_init.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/labs/helpers.py
"""Helper functions for the Home Assistant Labs integration.""" from __future__ import annotations from collections.abc import Callable, Coroutine from typing import Any from homeassistant.const import EVENT_LABS_UPDATED from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers.frame import report_usage from .const import LABS_DATA from .models import EventLabsUpdatedData @callback def async_is_preview_feature_enabled( hass: HomeAssistant, domain: str, preview_feature: str ) -> bool: """Check if a lab preview feature is enabled. Args: hass: HomeAssistant instance domain: Integration domain preview_feature: Preview feature name Returns: True if the preview feature is enabled, False otherwise """ if LABS_DATA not in hass.data: return False labs_data = hass.data[LABS_DATA] return (domain, preview_feature) in labs_data.data.preview_feature_status @callback def async_subscribe_preview_feature( hass: HomeAssistant, domain: str, preview_feature: str, listener: Callable[[EventLabsUpdatedData], Coroutine[Any, Any, None]], ) -> Callable[[], None]: """Listen for changes to a specific preview feature. Args: hass: HomeAssistant instance domain: Integration domain preview_feature: Preview feature name listener: Coroutine function to invoke when the preview feature is toggled. Receives the event data as argument. Runs eagerly. Returns: Callable to unsubscribe from the listener """ @callback def _async_event_filter(event_data: EventLabsUpdatedData) -> bool: """Filter labs events for this integration's preview feature.""" return ( event_data["domain"] == domain and event_data["preview_feature"] == preview_feature ) async def _handler(event: Event[EventLabsUpdatedData]) -> None: """Handle labs feature update event.""" await listener(event.data) return hass.bus.async_listen( EVENT_LABS_UPDATED, _handler, event_filter=_async_event_filter ) @callback def async_listen( hass: HomeAssistant, domain: str, preview_feature: str, listener: Callable[[], None], ) -> Callable[[], None]: """Listen for changes to a specific preview feature. Deprecated: use async_subscribe_preview_feature instead. Args: hass: HomeAssistant instance domain: Integration domain preview_feature: Preview feature name listener: Callback to invoke when the preview feature is toggled Returns: Callable to unsubscribe from the listener """ report_usage( "calls `async_listen` which is deprecated, " "use `async_subscribe_preview_feature` instead", breaks_in_ha_version="2027.3.0", ) async def _listener(_event_data: EventLabsUpdatedData) -> None: listener() return async_subscribe_preview_feature(hass, domain, preview_feature, _listener) async def async_update_preview_feature( hass: HomeAssistant, domain: str, preview_feature: str, enabled: bool, ) -> None: """Update a lab preview feature state.""" labs_data = hass.data[LABS_DATA] preview_feature_id = f"{domain}.{preview_feature}" if preview_feature_id not in labs_data.preview_features: raise ValueError(f"Preview feature {preview_feature_id} not found") if enabled: labs_data.data.preview_feature_status.add((domain, preview_feature)) else: labs_data.data.preview_feature_status.discard((domain, preview_feature)) await labs_data.store.async_save(labs_data.data.to_store_format()) event_data: EventLabsUpdatedData = { "domain": domain, "preview_feature": preview_feature, "enabled": enabled, } hass.bus.async_fire(EVENT_LABS_UPDATED, event_data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/labs/helpers.py", "license": "Apache License 2.0", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/adguard/update.py
"""AdGuard Home Update platform.""" from __future__ import annotations from datetime import timedelta from typing import Any from adguardhome import AdGuardHomeError from homeassistant.components.update import UpdateEntity, UpdateEntityFeature from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import AdGuardConfigEntry, AdGuardData from .const import DOMAIN from .entity import AdGuardHomeEntity SCAN_INTERVAL = timedelta(seconds=300) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: AdGuardConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up AdGuard Home update entity based on a config entry.""" data = entry.runtime_data if (await data.client.update.update_available()).disabled: return async_add_entities([AdGuardHomeUpdate(data, entry)], True) class AdGuardHomeUpdate(AdGuardHomeEntity, UpdateEntity): """Defines an AdGuard Home update.""" _attr_supported_features = UpdateEntityFeature.INSTALL _attr_name = None def __init__( self, data: AdGuardData, entry: AdGuardConfigEntry, ) -> None: """Initialize AdGuard Home update.""" super().__init__(data, entry) self._attr_unique_id = "_".join( [DOMAIN, self.adguard.host, str(self.adguard.port), "update"] ) async def _adguard_update(self) -> None: """Update AdGuard Home entity.""" value = await self.adguard.update.update_available() self._attr_installed_version = self.data.version self._attr_latest_version = value.new_version self._attr_release_summary = value.announcement self._attr_release_url = value.announcement_url async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Install latest update.""" try: await self.adguard.update.begin_update() except AdGuardHomeError as err: raise HomeAssistantError(f"Failed to install update: {err}") from err self.hass.config_entries.async_schedule_reload(self._entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/adguard/update.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/airobot/climate.py
"""Climate platform for Airobot thermostat.""" from __future__ import annotations from typing import Any from pyairobotrest.const import ( MODE_AWAY, MODE_HOME, SETPOINT_TEMP_MAX, SETPOINT_TEMP_MIN, ) from pyairobotrest.exceptions import AirobotError from pyairobotrest.models import ThermostatSettings, ThermostatStatus from homeassistant.components.climate import ( PRESET_AWAY, PRESET_BOOST, PRESET_HOME, ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, 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 = 1 _PRESET_MODE_2_MODE = { PRESET_AWAY: MODE_AWAY, PRESET_HOME: MODE_HOME, } async def async_setup_entry( hass: HomeAssistant, entry: AirobotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Airobot climate platform.""" coordinator = entry.runtime_data async_add_entities([AirobotClimate(coordinator)]) class AirobotClimate(AirobotEntity, ClimateEntity): """Representation of an Airobot thermostat.""" _attr_name = None _attr_translation_key = "thermostat" _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_hvac_modes = [HVACMode.HEAT] _attr_preset_modes = [PRESET_HOME, PRESET_AWAY, PRESET_BOOST] _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.PRESET_MODE ) _attr_min_temp = SETPOINT_TEMP_MIN _attr_max_temp = SETPOINT_TEMP_MAX def __init__(self, coordinator: AirobotDataUpdateCoordinator) -> None: """Initialize the climate entity.""" super().__init__(coordinator) self._attr_unique_id = coordinator.data.status.device_id @property def _status(self) -> ThermostatStatus: """Get status from coordinator data.""" return self.coordinator.data.status @property def _settings(self) -> ThermostatSettings: """Get settings from coordinator data.""" return self.coordinator.data.settings @property def current_temperature(self) -> float | None: """Return the current temperature. If floor temperature is available, thermostat is set up for floor heating. """ if self._status.temp_floor is not None: return self._status.temp_floor return self._status.temp_air @property def current_humidity(self) -> float | None: """Return the current humidity.""" return self._status.hum_air @property def target_temperature(self) -> float | None: """Return the target temperature.""" if self._settings.is_home_mode: return self._settings.setpoint_temp return self._settings.setpoint_temp_away @property def hvac_mode(self) -> HVACMode: """Return current HVAC mode.""" if self._status.is_heating: return HVACMode.HEAT return HVACMode.OFF @property def hvac_action(self) -> HVACAction: """Return current HVAC action.""" if self._status.is_heating: return HVACAction.HEATING return HVACAction.IDLE @property def preset_mode(self) -> str | None: """Return current preset mode.""" if self._settings.setting_flags.boost_enabled: return PRESET_BOOST if self._settings.is_home_mode: return PRESET_HOME return PRESET_AWAY async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" temperature = kwargs[ATTR_TEMPERATURE] try: if self._settings.is_home_mode: await self.coordinator.client.set_home_temperature(float(temperature)) else: await self.coordinator.client.set_away_temperature(float(temperature)) except AirobotError as err: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="set_temperature_failed", translation_placeholders={"temperature": str(temperature)}, ) from err await self.coordinator.async_request_refresh() async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set HVAC mode. This thermostat only supports HEAT mode. The climate platform validates that only supported modes are passed, so this method is a no-op. """ async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" try: if preset_mode == PRESET_BOOST: # Enable boost mode if not self._settings.setting_flags.boost_enabled: await self.coordinator.client.set_boost_mode(True) else: # Disable boost mode if it's enabled if self._settings.setting_flags.boost_enabled: await self.coordinator.client.set_boost_mode(False) # Set the mode (HOME or AWAY) await self.coordinator.client.set_mode(_PRESET_MODE_2_MODE[preset_mode]) except AirobotError as err: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="set_preset_mode_failed", translation_placeholders={"preset_mode": preset_mode}, ) from err await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/climate.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:homeassistant/components/airobot/config_flow.py
"""Config flow for the Airobot integration.""" from __future__ import annotations import asyncio from collections.abc import Mapping from dataclasses import dataclass import logging from typing import Any from pyairobotrest import AirobotClient from pyairobotrest.exceptions import ( AirobotAuthError, AirobotConnectionError, AirobotError, AirobotTimeoutError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow as BaseConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ) @dataclass class DeviceInfo: """Device information.""" title: str device_id: str async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> DeviceInfo: """Validate the user input allows us to connect. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. """ session = async_get_clientsession(hass) client = AirobotClient( host=data[CONF_HOST], username=data[CONF_USERNAME], password=data[CONF_PASSWORD], session=session, ) try: # Try to fetch data to validate connection and authentication status, settings = await asyncio.gather( client.get_statuses(), client.get_settings() ) except AirobotAuthError as err: raise InvalidAuth from err except ( AirobotConnectionError, AirobotTimeoutError, AirobotError, TimeoutError, ) as err: raise CannotConnect from err # Use device name or device ID as title title = settings.device_name or status.device_id return DeviceInfo(title=title, device_id=status.device_id) class AirobotConfigFlow(BaseConfigFlow, domain=DOMAIN): """Handle a config flow for Airobot.""" VERSION = 1 MINOR_VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._discovered_host: str | None = None self._discovered_mac: str | None = None self._discovered_device_id: str | None = None async def async_step_dhcp( self, discovery_info: DhcpServiceInfo ) -> ConfigFlowResult: """Handle DHCP discovery.""" # Store the discovered IP address and MAC self._discovered_host = discovery_info.ip self._discovered_mac = discovery_info.macaddress # Extract device_id from hostname (format: airobot-thermostat-t01xxxxxx) hostname = discovery_info.hostname.lower() device_id = hostname.replace("airobot-thermostat-", "").upper() self._discovered_device_id = device_id # Set unique_id to device_id for duplicate detection await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.ip}) # Show the confirmation form return await self.async_step_dhcp_confirm() async def async_step_dhcp_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle DHCP discovery confirmation - ask for credentials only.""" errors: dict[str, str] = {} if user_input is not None: # Combine discovered host and device_id with user-provided password data = { CONF_HOST: self._discovered_host, CONF_USERNAME: self._discovered_device_id, CONF_PASSWORD: user_input[CONF_PASSWORD], } try: info = await validate_input(self.hass, data) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Store MAC address in config entry data if self._discovered_mac: data[CONF_MAC] = self._discovered_mac return self.async_create_entry(title=info.title, data=data) # Only ask for password since we already have the device_id from discovery return self.async_show_form( step_id="dhcp_confirm", data_schema=vol.Schema( { vol.Required(CONF_PASSWORD): str, } ), description_placeholders={ "host": self._discovered_host or "", "device_id": self._discovered_device_id or "", }, errors=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: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Use device ID as unique ID to prevent duplicates await self.async_set_unique_id(info.device_id) self._abort_if_unique_id_configured() return self.async_create_entry(title=info.title, data=user_input) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" errors: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: try: info = await validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: # Verify the device ID matches the existing config entry await self.async_set_unique_id(info.device_id) self._abort_if_unique_id_mismatch(reason="wrong_device") return self.async_update_reload_and_abort( reconfigure_entry, data_updates=user_input, title=info.title, ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, reconfigure_entry.data ), errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauthentication 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: """Confirm reauthentication dialog.""" errors: dict[str, str] = {} reauth_entry = self._get_reauth_entry() if user_input is not None: # Combine existing data with new password data = { CONF_HOST: reauth_entry.data[CONF_HOST], CONF_USERNAME: reauth_entry.data[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], } try: await validate_input(self.hass, data) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_update_reload_and_abort( reauth_entry, data_updates={CONF_PASSWORD: user_input[CONF_PASSWORD]}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema( { vol.Required(CONF_PASSWORD): str, } ), description_placeholders={ "username": reauth_entry.data[CONF_USERNAME], "host": reauth_entry.data[CONF_HOST], }, errors=errors, ) class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(HomeAssistantError): """Error to indicate there is invalid auth."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/config_flow.py", "license": "Apache License 2.0", "lines": 232, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/airobot/coordinator.py
"""Coordinator for the Airobot integration.""" from __future__ import annotations import asyncio from datetime import timedelta import logging from pyairobotrest import AirobotClient from pyairobotrest.exceptions import AirobotAuthError, AirobotConnectionError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME 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 from .models import AirobotData _LOGGER = logging.getLogger(__name__) # Update interval - thermostat measures air every 30 seconds UPDATE_INTERVAL = timedelta(seconds=30) type AirobotConfigEntry = ConfigEntry[AirobotDataUpdateCoordinator] class AirobotDataUpdateCoordinator(DataUpdateCoordinator[AirobotData]): """Class to manage fetching Airobot data.""" config_entry: AirobotConfigEntry def __init__(self, hass: HomeAssistant, entry: AirobotConfigEntry) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, config_entry=entry, ) session = async_get_clientsession(hass) self.client = AirobotClient( host=entry.data[CONF_HOST], username=entry.data[CONF_USERNAME], password=entry.data[CONF_PASSWORD], session=session, ) async def _async_update_data(self) -> AirobotData: """Fetch data from API endpoint.""" try: status, settings = await asyncio.gather( self.client.get_statuses(), self.client.get_settings(), ) except AirobotAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_failed", ) from err except AirobotConnectionError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="connection_failed", ) from err return AirobotData(status=status, settings=settings)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/coordinator.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/entity.py
"""Base entity for Airobot integration.""" from __future__ import annotations from homeassistant.const import CONF_MAC from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import AirobotDataUpdateCoordinator class AirobotEntity(CoordinatorEntity[AirobotDataUpdateCoordinator]): """Base class for Airobot entities.""" _attr_has_entity_name = True def __init__( self, coordinator: AirobotDataUpdateCoordinator, ) -> None: """Initialize the entity.""" super().__init__(coordinator) status = coordinator.data.status settings = coordinator.data.settings connections = set() if (mac := coordinator.config_entry.data.get(CONF_MAC)) is not None: connections.add((CONNECTION_NETWORK_MAC, mac)) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, status.device_id)}, connections=connections, name=settings.device_name or status.device_id, manufacturer="Airobot", model="Thermostat", model_id="TE1", sw_version=status.fw_version_string, hw_version=status.hw_version_string, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/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/airobot/models.py
"""Models for the Airobot integration.""" from __future__ import annotations from dataclasses import dataclass from pyairobotrest.models import ThermostatSettings, ThermostatStatus @dataclass class AirobotData: """Data from the Airobot coordinator.""" status: ThermostatStatus settings: ThermostatSettings
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/models.py", "license": "Apache License 2.0", "lines": 9, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/alarm_control_panel/trigger.py
"""Provides triggers for alarm control panels.""" from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity import get_supported_features from homeassistant.helpers.trigger import ( EntityTargetStateTriggerBase, Trigger, make_entity_target_state_trigger, make_entity_transition_trigger, ) from .const import DOMAIN, AlarmControlPanelEntityFeature, AlarmControlPanelState def supports_feature(hass: HomeAssistant, entity_id: str, features: int) -> bool: """Test if an entity supports the specified features.""" try: return bool(get_supported_features(hass, entity_id) & features) except HomeAssistantError: return False class EntityStateTriggerRequiredFeatures(EntityTargetStateTriggerBase): """Trigger for entity state changes.""" _required_features: int def entity_filter(self, entities: set[str]) -> set[str]: """Filter entities of this domain.""" entities = super().entity_filter(entities) return { entity_id for entity_id in entities if supports_feature(self._hass, entity_id, self._required_features) } def make_entity_state_trigger_required_features( domain: str, to_state: str, required_features: int ) -> type[EntityTargetStateTriggerBase]: """Create an entity state trigger class with required feature filtering.""" class CustomTrigger(EntityStateTriggerRequiredFeatures): """Trigger for entity state changes.""" _domain = domain _to_states = {to_state} _required_features = required_features return CustomTrigger TRIGGERS: dict[str, type[Trigger]] = { "armed": make_entity_transition_trigger( DOMAIN, from_states={ AlarmControlPanelState.ARMING, AlarmControlPanelState.DISARMED, AlarmControlPanelState.DISARMING, AlarmControlPanelState.PENDING, AlarmControlPanelState.TRIGGERED, }, to_states={ AlarmControlPanelState.ARMED_AWAY, AlarmControlPanelState.ARMED_CUSTOM_BYPASS, AlarmControlPanelState.ARMED_HOME, AlarmControlPanelState.ARMED_NIGHT, AlarmControlPanelState.ARMED_VACATION, }, ), "armed_away": make_entity_state_trigger_required_features( DOMAIN, AlarmControlPanelState.ARMED_AWAY, AlarmControlPanelEntityFeature.ARM_AWAY, ), "armed_home": make_entity_state_trigger_required_features( DOMAIN, AlarmControlPanelState.ARMED_HOME, AlarmControlPanelEntityFeature.ARM_HOME, ), "armed_night": make_entity_state_trigger_required_features( DOMAIN, AlarmControlPanelState.ARMED_NIGHT, AlarmControlPanelEntityFeature.ARM_NIGHT, ), "armed_vacation": make_entity_state_trigger_required_features( DOMAIN, AlarmControlPanelState.ARMED_VACATION, AlarmControlPanelEntityFeature.ARM_VACATION, ), "disarmed": make_entity_target_state_trigger( DOMAIN, AlarmControlPanelState.DISARMED ), "triggered": make_entity_target_state_trigger( DOMAIN, AlarmControlPanelState.TRIGGERED ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for alarm control panels.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/alarm_control_panel/trigger.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/anglian_water/config_flow.py
"""Config flow for the Anglian Water integration.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from aiohttp import CookieJar from pyanglianwater import AnglianWater from pyanglianwater.auth import MSOB2CAuth from pyanglianwater.exceptions import ( InvalidAccountIdError, SelfAssertedError, SmartMeterUnavailableError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_ACCESS_TOKEN, CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import selector from homeassistant.helpers.aiohttp_client import async_create_clientsession from .const import CONF_ACCOUNT_NUMBER, DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME): selector.TextSelector(), vol.Required(CONF_PASSWORD): selector.TextSelector( selector.TextSelectorConfig(type=selector.TextSelectorType.PASSWORD) ), } ) async def validate_credentials(auth: MSOB2CAuth) -> str | MSOB2CAuth: """Validate the provided credentials.""" try: await auth.send_login_request() except SelfAssertedError: return "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") return "unknown" return auth def humanize_account_data(account: dict) -> str: """Convert an account data into a human-readable format.""" if account["address"]["company_name"] != "": return f"{account['account_number']} - {account['address']['company_name']}" if account["address"]["building_name"] != "": return f"{account['account_number']} - {account['address']['building_name']}" return f"{account['account_number']} - {account['address']['postcode']}" async def get_accounts(auth: MSOB2CAuth) -> list[selector.SelectOptionDict]: """Retrieve the list of accounts associated with the authenticated user.""" _aw = AnglianWater(authenticator=auth) accounts = await _aw.api.get_associated_accounts() return [ selector.SelectOptionDict( value=str(account["account_number"]), label=humanize_account_data(account), ) for account in accounts["result"]["active"] ] async def validate_account(auth: MSOB2CAuth, account_number: str) -> str | MSOB2CAuth: """Validate the provided account number.""" _aw = AnglianWater(authenticator=auth) try: await _aw.validate_smart_meter(account_number) except InvalidAccountIdError, SmartMeterUnavailableError: return "smart_meter_unavailable" return auth class AnglianWaterConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Anglian Water.""" def __init__(self) -> None: """Initialize the config flow.""" self.authenticator: MSOB2CAuth | None = None self.accounts: list[selector.SelectOptionDict] = [] self.user_input: dict[str, Any] | None = 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.authenticator = MSOB2CAuth( username=user_input[CONF_USERNAME], password=user_input[CONF_PASSWORD], session=async_create_clientsession( self.hass, cookie_jar=CookieJar(quote_cookie=False), ), ) validation_response = await validate_credentials(self.authenticator) if isinstance(validation_response, str): errors["base"] = validation_response else: self.accounts = await get_accounts(self.authenticator) if len(self.accounts) > 1: self.user_input = user_input return await self.async_step_select_account() account_number = self.accounts[0]["value"] self.user_input = user_input return await self.async_step_complete( { CONF_ACCOUNT_NUMBER: account_number, } ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_select_account( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the account selection step.""" errors = {} if user_input is not None: if TYPE_CHECKING: assert self.authenticator validation_result = await validate_account( self.authenticator, user_input[CONF_ACCOUNT_NUMBER], ) if isinstance(validation_result, str): errors["base"] = validation_result else: return await self.async_step_complete(user_input) return self.async_show_form( step_id="select_account", data_schema=vol.Schema( { vol.Required(CONF_ACCOUNT_NUMBER): selector.SelectSelector( selector.SelectSelectorConfig( options=self.accounts, multiple=False, mode=selector.SelectSelectorMode.DROPDOWN, ) ) } ), errors=errors, ) async def async_step_complete(self, user_input: dict[str, Any]) -> ConfigFlowResult: """Handle the final configuration step.""" await self.async_set_unique_id(user_input[CONF_ACCOUNT_NUMBER]) self._abort_if_unique_id_configured() if TYPE_CHECKING: assert self.authenticator assert self.user_input config_entry_data = { **self.user_input, CONF_ACCOUNT_NUMBER: user_input[CONF_ACCOUNT_NUMBER], CONF_ACCESS_TOKEN: self.authenticator.refresh_token, } return self.async_create_entry( title=user_input[CONF_ACCOUNT_NUMBER], data=config_entry_data, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anglian_water/config_flow.py", "license": "Apache License 2.0", "lines": 149, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/anglian_water/coordinator.py
"""Anglian Water data coordinator.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from pyanglianwater import AnglianWater from pyanglianwater.exceptions import ExpiredAccessTokenError, UnknownEndpointError from homeassistant.components.recorder import get_instance from homeassistant.components.recorder.models import ( StatisticData, StatisticMeanType, StatisticMetaData, ) from homeassistant.components.recorder.statistics import ( async_add_external_statistics, get_last_statistics, statistics_during_period, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import UnitOfVolume from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from homeassistant.util.unit_conversion import VolumeConverter from .const import CONF_ACCOUNT_NUMBER, DOMAIN type AnglianWaterConfigEntry = ConfigEntry[AnglianWaterUpdateCoordinator] _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(minutes=60) class AnglianWaterUpdateCoordinator(DataUpdateCoordinator[None]): """Anglian Water data update coordinator.""" config_entry: AnglianWaterConfigEntry def __init__( self, hass: HomeAssistant, api: AnglianWater, config_entry: AnglianWaterConfigEntry, ) -> None: """Initialize update coordinator.""" super().__init__( hass=hass, logger=_LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, config_entry=config_entry, ) self.api = api async def _async_update_data(self) -> None: """Update data from Anglian Water's API.""" try: await self.api.update(self.config_entry.data[CONF_ACCOUNT_NUMBER]) await self._insert_statistics() except (ExpiredAccessTokenError, UnknownEndpointError) as err: raise UpdateFailed from err async def _insert_statistics(self) -> None: """Insert statistics for water meters into Home Assistant.""" for meter in self.api.meters.values(): id_prefix = ( f"{self.config_entry.data[CONF_ACCOUNT_NUMBER]}_{meter.serial_number}" ) usage_statistic_id = f"{DOMAIN}:{id_prefix}_usage".lower() _LOGGER.debug("Updating statistics for meter %s", meter.serial_number) name_prefix = ( f"Anglian Water {self.config_entry.data[CONF_ACCOUNT_NUMBER]} " f"{meter.serial_number}" ) usage_metadata = StatisticMetaData( mean_type=StatisticMeanType.NONE, has_sum=True, name=f"{name_prefix} Usage", source=DOMAIN, statistic_id=usage_statistic_id, unit_class=VolumeConverter.UNIT_CLASS, unit_of_measurement=UnitOfVolume.CUBIC_METERS, ) last_stat = await get_instance(self.hass).async_add_executor_job( get_last_statistics, self.hass, 1, usage_statistic_id, True, set() ) if not last_stat: _LOGGER.debug("Updating statistics for the first time") usage_sum = 0.0 last_stats_time = None else: if not meter.readings or len(meter.readings) == 0: _LOGGER.debug("No recent usage statistics found, skipping update") continue # Anglian Water stats are hourly, the read_at time is the time that the meter took the reading # We remove 1 hour from this so that the data is shown in the correct hour on the dashboards parsed_read_at = dt_util.parse_datetime(meter.readings[0]["read_at"]) if not parsed_read_at: _LOGGER.debug( "Could not parse read_at time %s, skipping update", meter.readings[0]["read_at"], ) continue start = dt_util.as_local(parsed_read_at) - timedelta(hours=1) _LOGGER.debug("Getting statistics at %s", start) for end in (start + timedelta(seconds=1), None): stats = await get_instance(self.hass).async_add_executor_job( statistics_during_period, self.hass, start, end, { usage_statistic_id, }, "hour", None, {"sum"}, ) if stats: break if end: _LOGGER.debug( "Not found, trying to find oldest statistic after %s", start, ) assert stats def _safe_get_sum(records: list[Any]) -> float: if records and "sum" in records[0]: return float(records[0]["sum"]) return 0.0 usage_sum = _safe_get_sum(stats.get(usage_statistic_id, [])) last_stats_time = stats[usage_statistic_id][0]["start"] usage_statistics = [] for read in meter.readings: parsed_read_at = dt_util.parse_datetime(read["read_at"]) if not parsed_read_at: _LOGGER.debug( "Could not parse read_at time %s, skipping reading", read["read_at"], ) continue start = dt_util.as_local(parsed_read_at) - timedelta(hours=1) if last_stats_time is not None and start.timestamp() <= last_stats_time: continue usage_state = max(0, read["consumption"] / 1000) usage_sum = max(0, read["read"]) usage_statistics.append( StatisticData( start=start, state=usage_state, sum=usage_sum, ) ) _LOGGER.debug( "Adding %s statistics for %s", len(usage_statistics), usage_statistic_id ) async_add_external_statistics(self.hass, usage_metadata, usage_statistics)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anglian_water/coordinator.py", "license": "Apache License 2.0", "lines": 148, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/anglian_water/entity.py
"""Anglian Water entity.""" from __future__ import annotations import logging from pyanglianwater.meter import SmartMeter from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import AnglianWaterUpdateCoordinator _LOGGER = logging.getLogger(__name__) class AnglianWaterEntity(CoordinatorEntity[AnglianWaterUpdateCoordinator]): """Defines a Anglian Water entity.""" _attr_has_entity_name = True def __init__( self, coordinator: AnglianWaterUpdateCoordinator, smart_meter: SmartMeter, key: str, ) -> None: """Initialize Anglian Water entity.""" super().__init__(coordinator) self.smart_meter = smart_meter self._attr_unique_id = f"{smart_meter.serial_number}_{key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, smart_meter.serial_number)}, name=smart_meter.serial_number, manufacturer="Anglian Water", serial_number=smart_meter.serial_number, ) async def async_added_to_hass(self) -> None: """When entity is loaded.""" self.coordinator.api.updated_data_callbacks.append(self.async_write_ha_state) await super().async_added_to_hass() async def async_will_remove_from_hass(self) -> None: """When will be removed from HASS.""" self.coordinator.api.updated_data_callbacks.remove(self.async_write_ha_state) await super().async_will_remove_from_hass()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anglian_water/entity.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/anglian_water/sensor.py
"""Anglian Water sensor platform.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from enum import StrEnum from pyanglianwater.meter import SmartMeter from homeassistant.components.sensor import ( EntityCategory, SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfVolume from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import AnglianWaterConfigEntry, AnglianWaterUpdateCoordinator from .entity import AnglianWaterEntity PARALLEL_UPDATES = 0 class AnglianWaterSensor(StrEnum): """Store keys for Anglian Water sensors.""" YESTERDAY_CONSUMPTION = "yesterday_consumption" YESTERDAY_WATER_COST = "yesterday_water_cost" YESTERDAY_SEWERAGE_COST = "yesterday_sewerage_cost" LATEST_READING = "latest_reading" @dataclass(frozen=True, kw_only=True) class AnglianWaterSensorEntityDescription(SensorEntityDescription): """Describes AnglianWater sensor entity.""" value_fn: Callable[[SmartMeter], float] ENTITY_DESCRIPTIONS: tuple[AnglianWaterSensorEntityDescription, ...] = ( AnglianWaterSensorEntityDescription( key=AnglianWaterSensor.YESTERDAY_CONSUMPTION, native_unit_of_measurement=UnitOfVolume.LITERS, device_class=SensorDeviceClass.WATER, value_fn=lambda entity: entity.get_yesterday_consumption, state_class=SensorStateClass.TOTAL, translation_key=AnglianWaterSensor.YESTERDAY_CONSUMPTION, entity_category=EntityCategory.DIAGNOSTIC, ), AnglianWaterSensorEntityDescription( key=AnglianWaterSensor.LATEST_READING, native_unit_of_measurement=UnitOfVolume.CUBIC_METERS, device_class=SensorDeviceClass.WATER, value_fn=lambda entity: entity.latest_read, state_class=SensorStateClass.TOTAL_INCREASING, translation_key=AnglianWaterSensor.LATEST_READING, entity_category=EntityCategory.DIAGNOSTIC, ), AnglianWaterSensorEntityDescription( key=AnglianWaterSensor.YESTERDAY_WATER_COST, native_unit_of_measurement="GBP", device_class=SensorDeviceClass.MONETARY, value_fn=lambda entity: entity.yesterday_water_cost, translation_key=AnglianWaterSensor.YESTERDAY_WATER_COST, entity_category=EntityCategory.DIAGNOSTIC, ), AnglianWaterSensorEntityDescription( key=AnglianWaterSensor.YESTERDAY_SEWERAGE_COST, native_unit_of_measurement="GBP", device_class=SensorDeviceClass.MONETARY, value_fn=lambda entity: entity.yesterday_sewerage_cost, translation_key=AnglianWaterSensor.YESTERDAY_SEWERAGE_COST, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, entry: AnglianWaterConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensor platform.""" async_add_devices( AnglianWaterSensorEntity( coordinator=entry.runtime_data, description=entity_description, smart_meter=smart_meter, ) for entity_description in ENTITY_DESCRIPTIONS for smart_meter in entry.runtime_data.api.meters.values() ) class AnglianWaterSensorEntity(AnglianWaterEntity, SensorEntity): """Defines a Anglian Water sensor.""" entity_description: AnglianWaterSensorEntityDescription def __init__( self, coordinator: AnglianWaterUpdateCoordinator, smart_meter: SmartMeter, description: AnglianWaterSensorEntityDescription, ) -> None: """Initialize Anglian Water sensor.""" super().__init__(coordinator, smart_meter, description.key) self.entity_description = description @property def native_value(self) -> float | None: """Return the state of the sensor.""" return self.entity_description.value_fn(self.smart_meter)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anglian_water/sensor.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/anthropic/ai_task.py
"""AI Task integration for Anthropic.""" from __future__ import annotations from json import JSONDecodeError import logging from typing import TYPE_CHECKING from homeassistant.components import ai_task, conversation from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util.json import json_loads from .entity import AnthropicBaseLLMEntity if TYPE_CHECKING: from . import AnthropicConfigEntry _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: AnthropicConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up AI Task entities.""" for subentry in config_entry.subentries.values(): if subentry.subentry_type != "ai_task_data": continue async_add_entities( [AnthropicTaskEntity(config_entry, subentry)], config_subentry_id=subentry.subentry_id, ) class AnthropicTaskEntity( ai_task.AITaskEntity, AnthropicBaseLLMEntity, ): """Anthropic AI Task entity.""" _attr_supported_features = ( ai_task.AITaskEntityFeature.GENERATE_DATA | ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS ) _attr_translation_key = "ai_task_data" async def _async_generate_data( self, task: ai_task.GenDataTask, chat_log: conversation.ChatLog, ) -> ai_task.GenDataTaskResult: """Handle a generate data task.""" await self._async_handle_chat_log( chat_log, task.name, task.structure, max_iterations=1000 ) if not isinstance(chat_log.content[-1], conversation.AssistantContent): raise HomeAssistantError( "Last content in chat log is not an AssistantContent" ) text = chat_log.content[-1].content or "" if not task.structure: return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=text, ) try: data = json_loads(text) except JSONDecodeError as err: _LOGGER.error( "Failed to parse JSON response: %s. Response: %s", err, text, ) raise HomeAssistantError("Error with Claude structured response") from err return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=data, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anthropic/ai_task.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/assist_satellite/trigger.py
"""Provides triggers for assist satellites.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN from .entity import AssistSatelliteState TRIGGERS: dict[str, type[Trigger]] = { "idle": make_entity_target_state_trigger(DOMAIN, AssistSatelliteState.IDLE), "listening": make_entity_target_state_trigger( DOMAIN, AssistSatelliteState.LISTENING ), "processing": make_entity_target_state_trigger( DOMAIN, AssistSatelliteState.PROCESSING ), "responding": make_entity_target_state_trigger( DOMAIN, AssistSatelliteState.RESPONDING ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for assist satellites.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/assist_satellite/trigger.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/backblaze_b2/backup.py
"""Backup platform for the Backblaze B2 integration.""" import asyncio from collections.abc import AsyncIterator, Callable, Coroutine import functools import json import logging import mimetypes from time import time from typing import Any from b2sdk.v2 import FileVersion from b2sdk.v2.exception import B2Error from homeassistant.components.backup import ( AgentBackup, BackupAgent, BackupAgentError, BackupNotFound, suggested_filename, ) from homeassistant.core import HomeAssistant, callback from homeassistant.util.async_iterator import AsyncIteratorReader from . import BackblazeConfigEntry from .const import ( CONF_PREFIX, DATA_BACKUP_AGENT_LISTENERS, DOMAIN, METADATA_FILE_SUFFIX, METADATA_VERSION, ) _LOGGER = logging.getLogger(__name__) # Cache TTL for backup list (in seconds) CACHE_TTL = 300 # Timeout for upload operations (in seconds) # This prevents uploads from hanging indefinitely UPLOAD_TIMEOUT = 43200 # 12 hours (matches B2 HTTP timeout) # Timeout for metadata download operations (in seconds) # This prevents the backup system from hanging when B2 connections fail METADATA_DOWNLOAD_TIMEOUT = 60 def suggested_filenames(backup: AgentBackup) -> tuple[str, str]: """Return the suggested filenames for the backup and metadata files.""" base_name = suggested_filename(backup).rsplit(".", 1)[0] return f"{base_name}.tar", f"{base_name}.metadata.json" def _parse_metadata(raw_content: str) -> dict[str, Any]: """Parse metadata content from JSON.""" try: data = json.loads(raw_content) except json.JSONDecodeError as err: raise ValueError(f"Invalid JSON format: {err}") from err else: if not isinstance(data, dict): raise TypeError("JSON content is not a dictionary") return data def _find_backup_file_for_metadata( metadata_filename: str, all_files: dict[str, FileVersion], prefix: str ) -> FileVersion | None: """Find corresponding backup file for metadata file.""" base_name = metadata_filename[len(prefix) :].removesuffix(METADATA_FILE_SUFFIX) return next( ( file for name, file in all_files.items() if name.startswith(prefix + base_name) and name.endswith(".tar") and name != metadata_filename ), None, ) def _create_backup_from_metadata( metadata_content: dict[str, Any], backup_file: FileVersion ) -> AgentBackup: """Construct an AgentBackup from parsed metadata content and the associated backup file.""" metadata = metadata_content["backup_metadata"] metadata["size"] = backup_file.size return AgentBackup.from_dict(metadata) def handle_b2_errors[T]( func: Callable[..., Coroutine[Any, Any, T]], ) -> Callable[..., Coroutine[Any, Any, T]]: """Handle B2Errors by converting them to BackupAgentError.""" @functools.wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> T: """Catch B2Error and raise BackupAgentError.""" try: return await func(*args, **kwargs) except B2Error as err: error_msg = f"Failed during {func.__name__}" raise BackupAgentError(error_msg) from err return wrapper async def async_get_backup_agents( hass: HomeAssistant, ) -> list[BackupAgent]: """Return a list of backup agents for all configured Backblaze B2 entries.""" entries: list[BackblazeConfigEntry] = hass.config_entries.async_loaded_entries( DOMAIN ) return [BackblazeBackupAgent(hass, entry) for entry in entries] @callback def async_register_backup_agents_listener( hass: HomeAssistant, *, listener: Callable[[], None], **kwargs: Any, ) -> Callable[[], None]: """Register a listener to be called when backup agents are added or removed. :return: A function to unregister the listener. """ hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener) @callback def remove_listener() -> None: """Remove the listener.""" hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener) if not hass.data[DATA_BACKUP_AGENT_LISTENERS]: hass.data.pop(DATA_BACKUP_AGENT_LISTENERS, None) return remove_listener class BackblazeBackupAgent(BackupAgent): """Backup agent for Backblaze B2 cloud storage.""" domain = DOMAIN def __init__(self, hass: HomeAssistant, entry: BackblazeConfigEntry) -> None: """Initialize the Backblaze B2 agent.""" super().__init__() self._hass = hass self._bucket = entry.runtime_data self._prefix = entry.data[CONF_PREFIX] self.name = entry.title self.unique_id = entry.entry_id self._all_files_cache: dict[str, FileVersion] = {} self._all_files_cache_expiration: float = 0.0 self._backup_list_cache: dict[str, AgentBackup] = {} self._backup_list_cache_expiration: float = 0.0 self._all_files_cache_lock = asyncio.Lock() self._backup_list_cache_lock = asyncio.Lock() def _is_cache_valid(self, expiration_time: float) -> bool: """Check if cache is still valid based on expiration time.""" return time() <= expiration_time async def _cleanup_failed_upload(self, filename: str) -> None: """Clean up a partially uploaded file after upload failure.""" _LOGGER.warning( "Attempting to delete partially uploaded main backup file %s " "due to metadata upload failure", filename, ) try: uploaded_main_file_info = await self._hass.async_add_executor_job( self._bucket.get_file_info_by_name, filename ) await self._hass.async_add_executor_job(uploaded_main_file_info.delete) except B2Error: _LOGGER.debug( "Failed to clean up partially uploaded main backup file %s. " "Manual intervention may be required to delete it from Backblaze B2", filename, exc_info=True, ) else: _LOGGER.debug( "Successfully deleted partially uploaded main backup file %s", filename ) async def _get_file_for_download(self, backup_id: str) -> FileVersion: """Get backup file for download, raising if not found.""" file, _ = await self._find_file_and_metadata_version_by_id(backup_id) if not file: raise BackupNotFound(f"Backup {backup_id} not found") return file @handle_b2_errors async def async_download_backup( self, backup_id: str, **kwargs: Any ) -> AsyncIterator[bytes]: """Download a backup from Backblaze B2.""" file = await self._get_file_for_download(backup_id) _LOGGER.debug("Downloading %s", file.file_name) downloaded_file = await self._hass.async_add_executor_job(file.download) response = downloaded_file.response async def stream_response() -> AsyncIterator[bytes]: """Stream the response into an AsyncIterator.""" try: iterator = response.iter_content(chunk_size=1024 * 1024) while True: chunk = await self._hass.async_add_executor_job( next, iterator, None ) if chunk is None: break yield chunk finally: _LOGGER.debug("Finished streaming download for %s", file.file_name) return stream_response() @handle_b2_errors async def async_upload_backup( self, *, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], backup: AgentBackup, **kwargs: Any, ) -> None: """Upload a backup to Backblaze B2. This involves uploading the main backup archive and a separate metadata JSON file. """ tar_filename, metadata_filename = suggested_filenames(backup) prefixed_tar_filename = self._prefix + tar_filename prefixed_metadata_filename = self._prefix + metadata_filename metadata_content_bytes = json.dumps( { "metadata_version": METADATA_VERSION, "backup_id": backup.backup_id, "backup_metadata": backup.as_dict(), } ).encode("utf-8") _LOGGER.debug( "Uploading backup: %s, and metadata: %s", prefixed_tar_filename, prefixed_metadata_filename, ) upload_successful = False try: await self._upload_backup_file(prefixed_tar_filename, open_stream, {}) _LOGGER.debug( "Main backup file upload finished for %s", prefixed_tar_filename ) _LOGGER.debug("Uploading metadata file: %s", prefixed_metadata_filename) await self._upload_metadata_file( metadata_content_bytes, prefixed_metadata_filename ) _LOGGER.debug( "Metadata file upload finished for %s", prefixed_metadata_filename ) upload_successful = True finally: if upload_successful: _LOGGER.debug("Backup upload complete: %s", prefixed_tar_filename) self._invalidate_caches( backup.backup_id, prefixed_tar_filename, prefixed_metadata_filename ) else: await self._cleanup_failed_upload(prefixed_tar_filename) def _upload_metadata_file_sync( self, metadata_content: bytes, filename: str ) -> None: """Synchronously upload metadata file to B2.""" self._bucket.upload_bytes( metadata_content, filename, content_type="application/json", file_info={"metadata_only": "true"}, ) async def _upload_metadata_file( self, metadata_content: bytes, filename: str ) -> None: """Upload metadata file to B2.""" await self._hass.async_add_executor_job( self._upload_metadata_file_sync, metadata_content, filename, ) def _upload_unbound_stream_sync( self, reader: AsyncIteratorReader, filename: str, content_type: str, file_info: dict[str, Any], ) -> FileVersion: """Synchronously upload unbound stream to B2.""" return self._bucket.upload_unbound_stream( reader, filename, content_type=content_type, file_info=file_info, ) def _download_and_parse_metadata_sync( self, metadata_file_version: FileVersion ) -> dict[str, Any]: """Synchronously download and parse metadata file.""" return _parse_metadata( metadata_file_version.download().response.content.decode("utf-8") ) async def _upload_backup_file( self, filename: str, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], file_info: dict[str, Any], ) -> None: """Upload backup file to B2 using streaming.""" _LOGGER.debug("Starting streaming upload for %s", filename) stream = await open_stream() reader = AsyncIteratorReader(self._hass.loop, stream) _LOGGER.debug("Uploading backup file %s with streaming", filename) try: content_type, _ = mimetypes.guess_type(filename) file_version = await asyncio.wait_for( self._hass.async_add_executor_job( self._upload_unbound_stream_sync, reader, filename, content_type or "application/x-tar", file_info, ), timeout=UPLOAD_TIMEOUT, ) except TimeoutError: _LOGGER.error( "Upload of %s timed out after %s seconds", filename, UPLOAD_TIMEOUT ) reader.abort() raise BackupAgentError( f"Upload timed out after {UPLOAD_TIMEOUT} seconds" ) from None except asyncio.CancelledError: _LOGGER.warning("Upload of %s was cancelled", filename) reader.abort() raise finally: reader.close() _LOGGER.debug("Successfully uploaded %s (ID: %s)", filename, file_version.id_) @handle_b2_errors async def async_delete_backup(self, backup_id: str, **kwargs: Any) -> None: """Delete a backup and its associated metadata file from Backblaze B2.""" file, metadata_file = await self._find_file_and_metadata_version_by_id( backup_id ) if not file: raise BackupNotFound(f"Backup {backup_id} not found") # Invariant: when file is not None, metadata_file is also not None assert metadata_file is not None _LOGGER.debug( "Deleting backup file: %s and metadata file: %s", file.file_name, metadata_file.file_name, ) await self._hass.async_add_executor_job(file.delete) await self._hass.async_add_executor_job(metadata_file.delete) self._invalidate_caches( backup_id, file.file_name, metadata_file.file_name, remove_files=True, ) @handle_b2_errors async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]: """List all backups by finding their associated metadata files in Backblaze B2.""" async with self._backup_list_cache_lock: if self._backup_list_cache and self._is_cache_valid( self._backup_list_cache_expiration ): _LOGGER.debug("Returning backups from cache") return list(self._backup_list_cache.values()) _LOGGER.debug( "Cache expired or empty, fetching all files from B2 to build backup list" ) all_files_in_prefix = await self._get_all_files_in_prefix() _LOGGER.debug( "Files found in prefix '%s': %s", self._prefix, list(all_files_in_prefix.keys()), ) # Process metadata files sequentially to avoid exhausting executor pool backups = {} for file_name, file_version in all_files_in_prefix.items(): if file_name.endswith(METADATA_FILE_SUFFIX): try: backup = await asyncio.wait_for( self._hass.async_add_executor_job( self._process_metadata_file_sync, file_name, file_version, all_files_in_prefix, ), timeout=METADATA_DOWNLOAD_TIMEOUT, ) except TimeoutError: _LOGGER.warning( "Timeout downloading metadata file %s", file_name ) continue if backup: backups[backup.backup_id] = backup self._backup_list_cache = backups self._backup_list_cache_expiration = time() + CACHE_TTL return list(backups.values()) @handle_b2_errors async def async_get_backup(self, backup_id: str, **kwargs: Any) -> AgentBackup: """Get a specific backup by its ID from Backblaze B2.""" if self._backup_list_cache and self._is_cache_valid( self._backup_list_cache_expiration ): if backup := self._backup_list_cache.get(backup_id): _LOGGER.debug("Returning backup %s from cache", backup_id) return backup file, metadata_file_version = await self._find_file_and_metadata_version_by_id( backup_id ) if not file or not metadata_file_version: raise BackupNotFound(f"Backup {backup_id} not found") try: metadata_content = await asyncio.wait_for( self._hass.async_add_executor_job( self._download_and_parse_metadata_sync, metadata_file_version, ), timeout=METADATA_DOWNLOAD_TIMEOUT, ) except TimeoutError: raise BackupAgentError( f"Timeout downloading metadata for backup {backup_id}" ) from None _LOGGER.debug( "Successfully retrieved metadata for backup ID %s from file %s", backup_id, metadata_file_version.file_name, ) backup = _create_backup_from_metadata(metadata_content, file) if self._is_cache_valid(self._backup_list_cache_expiration): self._backup_list_cache[backup.backup_id] = backup return backup async def _find_file_and_metadata_version_by_id( self, backup_id: str ) -> tuple[FileVersion | None, FileVersion | None]: """Find the main backup file and its associated metadata file version by backup ID.""" all_files_in_prefix = await self._get_all_files_in_prefix() # Process metadata files sequentially to avoid exhausting executor pool for file_name, file_version in all_files_in_prefix.items(): if file_name.endswith(METADATA_FILE_SUFFIX): try: ( result_backup_file, result_metadata_file_version, ) = await asyncio.wait_for( self._hass.async_add_executor_job( self._process_metadata_file_for_id_sync, file_name, file_version, backup_id, all_files_in_prefix, ), timeout=METADATA_DOWNLOAD_TIMEOUT, ) except TimeoutError: _LOGGER.warning( "Timeout downloading metadata file %s while searching for backup %s", file_name, backup_id, ) continue if result_backup_file and result_metadata_file_version: return result_backup_file, result_metadata_file_version _LOGGER.debug("Backup %s not found", backup_id) return None, None def _process_metadata_file_for_id_sync( self, file_name: str, file_version: FileVersion, target_backup_id: str, all_files_in_prefix: dict[str, FileVersion], ) -> tuple[FileVersion | None, FileVersion | None]: """Synchronously process a single metadata file for a specific backup ID. Called within a thread pool executor. """ try: download_response = file_version.download().response except B2Error as err: _LOGGER.warning( "Failed to download metadata file %s during ID search: %s", file_name, err, ) return None, None try: metadata_content = _parse_metadata( download_response.content.decode("utf-8") ) except ValueError: return None, None if metadata_content["backup_id"] != target_backup_id: _LOGGER.debug( "Metadata file %s does not match target backup ID %s", file_name, target_backup_id, ) return None, None found_backup_file = _find_backup_file_for_metadata( file_name, all_files_in_prefix, self._prefix ) if not found_backup_file: _LOGGER.warning( "Found metadata file %s for backup ID %s, but no corresponding backup file", file_name, target_backup_id, ) return None, None _LOGGER.debug( "Found backup file %s and metadata file %s for ID %s", found_backup_file.file_name, file_name, target_backup_id, ) return found_backup_file, file_version async def _get_all_files_in_prefix(self) -> dict[str, FileVersion]: """Get all file versions in the configured prefix from Backblaze B2. Uses a cache to minimize API calls. This fetches a flat list of all files, including main backups and metadata files. """ async with self._all_files_cache_lock: if self._is_cache_valid(self._all_files_cache_expiration): _LOGGER.debug("Returning all files from cache") return self._all_files_cache _LOGGER.debug("Cache for all files expired or empty, fetching from B2") all_files_in_prefix = await self._hass.async_add_executor_job( self._fetch_all_files_in_prefix ) self._all_files_cache = all_files_in_prefix self._all_files_cache_expiration = time() + CACHE_TTL return all_files_in_prefix def _fetch_all_files_in_prefix(self) -> dict[str, FileVersion]: """Fetch all files in the configured prefix from B2.""" all_files: dict[str, FileVersion] = {} for file, _ in self._bucket.ls(self._prefix): all_files[file.file_name] = file return all_files def _process_metadata_file_sync( self, file_name: str, file_version: FileVersion, all_files_in_prefix: dict[str, FileVersion], ) -> AgentBackup | None: """Synchronously process a single metadata file and return an AgentBackup if valid.""" try: download_response = file_version.download().response except B2Error as err: _LOGGER.warning("Failed to download metadata file %s: %s", file_name, err) return None try: metadata_content = _parse_metadata( download_response.content.decode("utf-8") ) except ValueError: return None found_backup_file = _find_backup_file_for_metadata( file_name, all_files_in_prefix, self._prefix ) if not found_backup_file: _LOGGER.warning( "Found metadata file %s but no corresponding backup file", file_name, ) return None _LOGGER.debug( "Successfully processed metadata file %s for backup ID %s", file_name, metadata_content["backup_id"], ) return _create_backup_from_metadata(metadata_content, found_backup_file) def _invalidate_caches( self, backup_id: str, tar_filename: str, metadata_filename: str | None, *, remove_files: bool = False, ) -> None: """Invalidate caches after upload/deletion operations. Args: backup_id: The backup ID to remove from backup cache tar_filename: The tar filename to remove from files cache metadata_filename: The metadata filename to remove from files cache remove_files: If True, remove specific files from cache; if False, expire entire cache """ if remove_files: if self._is_cache_valid(self._all_files_cache_expiration): self._all_files_cache.pop(tar_filename, None) if metadata_filename: self._all_files_cache.pop(metadata_filename, None) if self._is_cache_valid(self._backup_list_cache_expiration): self._backup_list_cache.pop(backup_id, None) else: # For uploads, we can't easily add new FileVersion objects without API calls, # so we expire the entire cache for simplicity self._all_files_cache_expiration = 0.0 self._backup_list_cache_expiration = 0.0
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/backup.py", "license": "Apache License 2.0", "lines": 574, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/backblaze_b2/config_flow.py
"""Config flow for the Backblaze B2 integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from b2sdk.v2 import exception import voluptuous as vol from homeassistant.config_entries import ConfigEntry, ConfigFlow, ConfigFlowResult from homeassistant.helpers import config_validation as cv from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) # Import from b2_client to ensure timeout configuration is applied from .b2_client import B2Api, InMemoryAccountInfo from .const import ( BACKBLAZE_REALM, CONF_APPLICATION_KEY, CONF_BUCKET, CONF_KEY_ID, CONF_PREFIX, DOMAIN, ) _LOGGER = logging.getLogger(__name__) # Constants REQUIRED_CAPABILITIES = {"writeFiles", "listFiles", "deleteFiles", "readFiles"} STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_KEY_ID): cv.string, vol.Required(CONF_APPLICATION_KEY): TextSelector( config=TextSelectorConfig(type=TextSelectorType.PASSWORD) ), vol.Required(CONF_BUCKET): cv.string, vol.Optional(CONF_PREFIX, default=""): cv.string, } ) class BackblazeConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Backblaze B2.""" VERSION = 1 reauth_entry: ConfigEntry[Any] | None def _abort_if_duplicate_credentials(self, user_input: dict[str, Any]) -> None: """Abort if credentials already exist in another entry.""" self._async_abort_entries_match( { CONF_KEY_ID: user_input[CONF_KEY_ID], CONF_APPLICATION_KEY: user_input[CONF_APPLICATION_KEY], } ) 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] = {} placeholders: dict[str, str] = {} if user_input is not None: self._abort_if_duplicate_credentials(user_input) errors, placeholders = await self._async_validate_backblaze_connection( user_input ) if not errors: if user_input[CONF_PREFIX] and not user_input[CONF_PREFIX].endswith( "/" ): user_input[CONF_PREFIX] += "/" return self.async_create_entry( title=user_input[CONF_BUCKET], 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, description_placeholders={"brand_name": "Backblaze B2", **placeholders}, ) async def _async_validate_backblaze_connection( self, user_input: dict[str, Any] ) -> tuple[dict[str, str], dict[str, str]]: """Validate Backblaze B2 credentials, bucket, capabilities, and prefix. Returns a tuple of (errors_dict, placeholders_dict). """ errors: dict[str, str] = {} placeholders: dict[str, str] = {} info = InMemoryAccountInfo() b2_api = B2Api(info) def _authorize_and_get_bucket_sync() -> None: """Synchronously authorize the account and get the bucket by name. This function is run in the executor because b2sdk operations are blocking. """ b2_api.authorize_account( BACKBLAZE_REALM, # Use the defined realm constant user_input[CONF_KEY_ID], user_input[CONF_APPLICATION_KEY], ) b2_api.get_bucket_by_name(user_input[CONF_BUCKET]) try: await self.hass.async_add_executor_job(_authorize_and_get_bucket_sync) allowed = b2_api.account_info.get_allowed() # Check if allowed info is available if allowed is None or not allowed.get("capabilities"): errors["base"] = "invalid_capability" placeholders["missing_capabilities"] = ", ".join( sorted(REQUIRED_CAPABILITIES) ) else: # Check if all required capabilities are present current_caps = set(allowed["capabilities"]) if not REQUIRED_CAPABILITIES.issubset(current_caps): missing_caps = REQUIRED_CAPABILITIES - current_caps _LOGGER.warning( "Missing required Backblaze B2 capabilities for Key ID '%s': %s", user_input[CONF_KEY_ID], ", ".join(sorted(missing_caps)), ) errors["base"] = "invalid_capability" placeholders["missing_capabilities"] = ", ".join( sorted(missing_caps) ) else: # Only check prefix if capabilities are valid configured_prefix: str = user_input[CONF_PREFIX] allowed_prefix = allowed.get("namePrefix") or "" # Ensure configured prefix starts with Backblaze B2's allowed prefix if allowed_prefix and not configured_prefix.startswith( allowed_prefix ): errors[CONF_PREFIX] = "invalid_prefix" placeholders["allowed_prefix"] = allowed_prefix except exception.Unauthorized: _LOGGER.debug( "Backblaze B2 authentication failed for Key ID '%s'", user_input[CONF_KEY_ID], ) errors["base"] = "invalid_credentials" except exception.RestrictedBucket as err: _LOGGER.debug( "Access to Backblaze B2 bucket '%s' is restricted: %s", user_input[CONF_BUCKET], err, ) placeholders["restricted_bucket_name"] = err.bucket_name errors[CONF_BUCKET] = "restricted_bucket" except exception.NonExistentBucket: _LOGGER.debug( "Backblaze B2 bucket '%s' does not exist", user_input[CONF_BUCKET] ) errors[CONF_BUCKET] = "invalid_bucket_name" except ( exception.B2ConnectionError, exception.B2RequestTimeout, exception.ConnectionReset, ) as err: _LOGGER.error("Failed to connect to Backblaze B2: %s", err) errors["base"] = "cannot_connect" except exception.MissingAccountData: # This generally indicates an issue with how InMemoryAccountInfo is used _LOGGER.error( "Missing account data during Backblaze B2 authorization for Key ID '%s'", user_input[CONF_KEY_ID], ) errors["base"] = "invalid_credentials" except Exception: _LOGGER.exception( "An unexpected error occurred during Backblaze B2 configuration for Key ID '%s'", user_input[CONF_KEY_ID], ) errors["base"] = "unknown" return errors, placeholders async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauthentication flow.""" self.reauth_entry = self.hass.config_entries.async_get_entry( self.context["entry_id"] ) assert self.reauth_entry is not None return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauthentication.""" assert self.reauth_entry is not None errors: dict[str, str] = {} placeholders: dict[str, str] = {} if user_input is not None: self._abort_if_duplicate_credentials(user_input) validation_input = { CONF_KEY_ID: user_input[CONF_KEY_ID], CONF_APPLICATION_KEY: user_input[CONF_APPLICATION_KEY], CONF_BUCKET: self.reauth_entry.data[CONF_BUCKET], CONF_PREFIX: self.reauth_entry.data[CONF_PREFIX], } errors, placeholders = await self._async_validate_backblaze_connection( validation_input ) if not errors: return self.async_update_reload_and_abort( self.reauth_entry, data_updates={ CONF_KEY_ID: user_input[CONF_KEY_ID], CONF_APPLICATION_KEY: user_input[CONF_APPLICATION_KEY], }, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema( { vol.Required(CONF_KEY_ID): cv.string, vol.Required(CONF_APPLICATION_KEY): TextSelector( config=TextSelectorConfig(type=TextSelectorType.PASSWORD) ), } ), errors=errors, description_placeholders={ "brand_name": "Backblaze B2", "bucket": self.reauth_entry.data[CONF_BUCKET], **placeholders, }, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration flow.""" entry = self.hass.config_entries.async_get_entry(self.context["entry_id"]) assert entry is not None if user_input is not None: self._abort_if_duplicate_credentials(user_input) errors, placeholders = await self._async_validate_backblaze_connection( user_input ) if not errors: if user_input[CONF_PREFIX] and not user_input[CONF_PREFIX].endswith( "/" ): user_input[CONF_PREFIX] += "/" return self.async_update_reload_and_abort( entry, data_updates=user_input, ) else: errors = {} placeholders = {} return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, user_input or entry.data ), errors=errors, description_placeholders={"brand_name": "Backblaze B2", **placeholders}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/config_flow.py", "license": "Apache License 2.0", "lines": 252, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/backblaze_b2/const.py
"""Constants for the Backblaze B2 integration.""" from collections.abc import Callable from typing import Final from homeassistant.util.hass_dict import HassKey DOMAIN: Final = "backblaze_b2" CONF_KEY_ID = "key_id" CONF_APPLICATION_KEY = "application_key" CONF_BUCKET = "bucket" CONF_PREFIX = "prefix" DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey( f"{DOMAIN}.backup_agent_listeners" ) METADATA_FILE_SUFFIX = ".metadata.json" METADATA_VERSION = "1" BACKBLAZE_REALM = "production"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/const.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/backblaze_b2/diagnostics.py
"""Diagnostics support for Backblaze B2.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.core import HomeAssistant from . import BackblazeConfigEntry from .const import CONF_APPLICATION_KEY, CONF_KEY_ID TO_REDACT_ENTRY_DATA = {CONF_APPLICATION_KEY, CONF_KEY_ID} TO_REDACT_ACCOUNT_DATA_ALLOWED = {"bucketId", "bucketName", "namePrefix"} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: BackblazeConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" bucket = entry.runtime_data try: bucket_info = { "name": bucket.name, "id": bucket.id_, "type": bucket.type_, "cors_rules": bucket.cors_rules, "lifecycle_rules": bucket.lifecycle_rules, "revision": bucket.revision, } account_info = bucket.api.account_info account_data: dict[str, Any] = { "account_id": account_info.get_account_id(), "api_url": account_info.get_api_url(), "download_url": account_info.get_download_url(), "minimum_part_size": account_info.get_minimum_part_size(), "allowed": account_info.get_allowed(), } if isinstance(account_data["allowed"], dict): account_data["allowed"] = async_redact_data( account_data["allowed"], TO_REDACT_ACCOUNT_DATA_ALLOWED ) except AttributeError, TypeError, ValueError, KeyError: bucket_info = {"name": "unknown", "id": "unknown"} account_data = {"error": "Failed to retrieve detailed account information"} return { "entry_data": async_redact_data(entry.data, TO_REDACT_ENTRY_DATA), "entry_options": entry.options, "bucket_info": bucket_info, "account_info": account_data, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/diagnostics.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/backblaze_b2/repairs.py
"""Repair issues for the Backblaze B2 integration.""" from __future__ import annotations import logging from b2sdk.v2.exception import ( B2Error, NonExistentBucket, RestrictedBucket, Unauthorized, ) from homeassistant.components.repairs import ConfirmRepairFlow from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from .const import CONF_BUCKET, DOMAIN _LOGGER = logging.getLogger(__name__) ISSUE_BUCKET_ACCESS_RESTRICTED = "bucket_access_restricted" ISSUE_BUCKET_NOT_FOUND = "bucket_not_found" def _create_issue( hass: HomeAssistant, entry: ConfigEntry, issue_type: str, bucket_name: str, ) -> None: """Create a repair issue with standard parameters.""" ir.async_create_issue( hass, DOMAIN, f"{issue_type}_{entry.entry_id}", is_fixable=False, issue_domain=DOMAIN, severity=ir.IssueSeverity.ERROR, translation_key=issue_type, translation_placeholders={ "brand_name": "Backblaze B2", "title": entry.title, "bucket_name": bucket_name, "entry_id": entry.entry_id, }, ) def create_bucket_access_restricted_issue( hass: HomeAssistant, entry: ConfigEntry, bucket_name: str ) -> None: """Create a repair issue for restricted bucket access.""" _create_issue(hass, entry, ISSUE_BUCKET_ACCESS_RESTRICTED, bucket_name) def create_bucket_not_found_issue( hass: HomeAssistant, entry: ConfigEntry, bucket_name: str ) -> None: """Create a repair issue for non-existent bucket.""" _create_issue(hass, entry, ISSUE_BUCKET_NOT_FOUND, bucket_name) async def async_check_for_repair_issues( hass: HomeAssistant, entry: ConfigEntry ) -> None: """Check for common issues that require user action.""" bucket = entry.runtime_data restricted_issue_id = f"{ISSUE_BUCKET_ACCESS_RESTRICTED}_{entry.entry_id}" not_found_issue_id = f"{ISSUE_BUCKET_NOT_FOUND}_{entry.entry_id}" try: await hass.async_add_executor_job(bucket.api.account_info.get_allowed) ir.async_delete_issue(hass, DOMAIN, restricted_issue_id) ir.async_delete_issue(hass, DOMAIN, not_found_issue_id) except Unauthorized: entry.async_start_reauth(hass) except RestrictedBucket as err: _create_issue(hass, entry, ISSUE_BUCKET_ACCESS_RESTRICTED, err.bucket_name) except NonExistentBucket: _create_issue(hass, entry, ISSUE_BUCKET_NOT_FOUND, entry.data[CONF_BUCKET]) except B2Error as err: _LOGGER.debug("B2 connectivity test failed: %s", err) async def async_create_fix_flow( hass: HomeAssistant, issue_id: str, data: dict[str, str | int | float | None] | None, ) -> ConfirmRepairFlow: """Create a fix flow for Backblaze B2 issues.""" return ConfirmRepairFlow()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backblaze_b2/repairs.py", "license": "Apache License 2.0", "lines": 75, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/binary_sensor/trigger.py
"""Provides triggers for binary sensors.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity import get_device_class from homeassistant.helpers.trigger import EntityTargetStateTriggerBase, Trigger from homeassistant.helpers.typing import UNDEFINED, UndefinedType from . import DOMAIN, BinarySensorDeviceClass def get_device_class_or_undefined( hass: HomeAssistant, entity_id: str ) -> str | None | UndefinedType: """Get the device class of an entity or UNDEFINED if not found.""" try: return get_device_class(hass, entity_id) except HomeAssistantError: return UNDEFINED class BinarySensorOnOffTrigger(EntityTargetStateTriggerBase): """Class for binary sensor on/off triggers.""" _device_class: BinarySensorDeviceClass | None _domain: str = DOMAIN def entity_filter(self, entities: set[str]) -> set[str]: """Filter entities of this domain.""" entities = super().entity_filter(entities) return { entity_id for entity_id in entities if get_device_class_or_undefined(self._hass, entity_id) == self._device_class } def make_binary_sensor_trigger( device_class: BinarySensorDeviceClass | None, to_state: str, ) -> type[BinarySensorOnOffTrigger]: """Create an entity state trigger class.""" class CustomTrigger(BinarySensorOnOffTrigger): """Trigger for entity state changes.""" _device_class = device_class _to_states = {to_state} return CustomTrigger TRIGGERS: dict[str, type[Trigger]] = { "occupancy_detected": make_binary_sensor_trigger( BinarySensorDeviceClass.OCCUPANCY, STATE_ON ), "occupancy_cleared": make_binary_sensor_trigger( BinarySensorDeviceClass.OCCUPANCY, STATE_OFF ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for binary sensors.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/binary_sensor/trigger.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/brother/entity.py
"""Define the Brother entity.""" from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import BrotherDataUpdateCoordinator class BrotherPrinterEntity(CoordinatorEntity[BrotherDataUpdateCoordinator]): """Define a Brother Printer entity.""" _attr_has_entity_name = True def __init__( self, coordinator: BrotherDataUpdateCoordinator, ) -> None: """Initialize.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( configuration_url=f"http://{coordinator.brother.host}/", identifiers={(DOMAIN, coordinator.brother.serial)}, connections={(CONNECTION_NETWORK_MAC, coordinator.brother.mac)}, serial_number=coordinator.brother.serial, manufacturer="Brother", model_id=coordinator.brother.model, name=coordinator.brother.model, sw_version=coordinator.brother.firmware, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/brother/entity.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/climate/trigger.py
"""Provides triggers for climates.""" import voluptuous as vol from homeassistant.const import ATTR_TEMPERATURE, CONF_OPTIONS from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.trigger import ( ENTITY_STATE_TRIGGER_SCHEMA_FIRST_LAST, EntityTargetStateTriggerBase, Trigger, TriggerConfig, 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, make_entity_transition_trigger, ) from .const import ( ATTR_CURRENT_HUMIDITY, ATTR_CURRENT_TEMPERATURE, ATTR_HUMIDITY, ATTR_HVAC_ACTION, DOMAIN, HVACAction, HVACMode, ) CONF_HVAC_MODE = "hvac_mode" HVAC_MODE_CHANGED_TRIGGER_SCHEMA = ENTITY_STATE_TRIGGER_SCHEMA_FIRST_LAST.extend( { vol.Required(CONF_OPTIONS): { vol.Required(CONF_HVAC_MODE): vol.All( cv.ensure_list, vol.Length(min=1), [vol.Coerce(HVACMode)] ), }, } ) class HVACModeChangedTrigger(EntityTargetStateTriggerBase): """Trigger for entity state changes.""" _domain = DOMAIN _schema = HVAC_MODE_CHANGED_TRIGGER_SCHEMA def __init__(self, hass: HomeAssistant, config: TriggerConfig) -> None: """Initialize the state trigger.""" super().__init__(hass, config) self._to_states = set(self._options[CONF_HVAC_MODE]) 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 ), "current_temperature_changed": make_entity_numerical_state_attribute_changed_trigger( DOMAIN, ATTR_CURRENT_TEMPERATURE ), "current_temperature_crossed_threshold": make_entity_numerical_state_attribute_crossed_threshold_trigger( DOMAIN, ATTR_CURRENT_TEMPERATURE ), "hvac_mode_changed": HVACModeChangedTrigger, "started_cooling": make_entity_target_state_attribute_trigger( DOMAIN, ATTR_HVAC_ACTION, HVACAction.COOLING ), "started_drying": make_entity_target_state_attribute_trigger( DOMAIN, ATTR_HVAC_ACTION, HVACAction.DRYING ), "target_humidity_changed": make_entity_numerical_state_attribute_changed_trigger( DOMAIN, ATTR_HUMIDITY ), "target_humidity_crossed_threshold": make_entity_numerical_state_attribute_crossed_threshold_trigger( DOMAIN, ATTR_HUMIDITY ), "target_temperature_changed": make_entity_numerical_state_attribute_changed_trigger( DOMAIN, ATTR_TEMPERATURE ), "target_temperature_crossed_threshold": make_entity_numerical_state_attribute_crossed_threshold_trigger( DOMAIN, ATTR_TEMPERATURE ), "turned_off": make_entity_target_state_trigger(DOMAIN, HVACMode.OFF), "turned_on": make_entity_transition_trigger( DOMAIN, from_states={ HVACMode.OFF, }, to_states={ HVACMode.AUTO, HVACMode.COOL, HVACMode.DRY, HVACMode.FAN_ONLY, HVACMode.HEAT, HVACMode.HEAT_COOL, }, ), "started_heating": make_entity_target_state_attribute_trigger( DOMAIN, ATTR_HVAC_ACTION, HVACAction.HEATING ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for climates.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/climate/trigger.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/cloud/ai_task.py
"""AI Task integration for Home Assistant Cloud.""" from __future__ import annotations import io from json import JSONDecodeError import logging from hass_nabucasa.llm import ( LLMAuthenticationError, LLMError, LLMImageAttachment, LLMRateLimitError, LLMResponseError, LLMServiceError, ) from PIL import Image from homeassistant.components import ai_task, conversation from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util.json import json_loads from .const import AI_TASK_ENTITY_UNIQUE_ID, DATA_CLOUD from .entity import BaseCloudLLMEntity _LOGGER = logging.getLogger(__name__) def _convert_image_for_editing(data: bytes) -> tuple[bytes, str]: """Ensure the image data is in a format accepted by OpenAI image edits.""" img: Image.Image stream = io.BytesIO(data) with Image.open(stream) as img: mode = img.mode if mode not in ("RGBA", "LA", "L"): img = img.convert("RGBA") output = io.BytesIO() if img.mode in ("RGBA", "LA", "L"): img.save(output, format="PNG") return output.getvalue(), "image/png" img.save(output, format=img.format or "PNG") return output.getvalue(), f"image/{(img.format or 'png').lower()}" async def async_prepare_image_generation_attachments( hass: HomeAssistant, attachments: list[conversation.Attachment] ) -> list[LLMImageAttachment]: """Load attachment data for image generation.""" def prepare() -> list[LLMImageAttachment]: items: list[LLMImageAttachment] = [] for attachment in attachments: if not attachment.mime_type or not attachment.mime_type.startswith( "image/" ): raise HomeAssistantError( "Only image attachments are supported for image generation" ) path = attachment.path if not path.exists(): raise HomeAssistantError(f"`{path}` does not exist") data = path.read_bytes() mime_type = attachment.mime_type try: data, mime_type = _convert_image_for_editing(data) except HomeAssistantError: raise except Exception as err: raise HomeAssistantError("Failed to process image attachment") from err items.append( LLMImageAttachment( filename=path.name, mime_type=mime_type, data=data, ) ) return items return await hass.async_add_executor_job(prepare) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Home Assistant Cloud AI Task entity.""" cloud = hass.data[DATA_CLOUD] async_add_entities([CloudAITaskEntity(cloud, config_entry)]) class CloudAITaskEntity(BaseCloudLLMEntity, ai_task.AITaskEntity): """Home Assistant Cloud AI Task entity.""" _attr_has_entity_name = True _attr_supported_features = ( ai_task.AITaskEntityFeature.GENERATE_DATA | ai_task.AITaskEntityFeature.GENERATE_IMAGE | ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS ) _attr_translation_key = "cloud_ai" _attr_unique_id = AI_TASK_ENTITY_UNIQUE_ID @property def available(self) -> bool: """Return if the entity is available.""" return self._cloud.is_logged_in and self._cloud.valid_subscription async def _async_generate_data( self, task: ai_task.GenDataTask, chat_log: conversation.ChatLog, ) -> ai_task.GenDataTaskResult: """Handle a generate data task.""" await self._async_handle_chat_log( "ai_task", chat_log, task.name, task.structure ) if not isinstance(chat_log.content[-1], conversation.AssistantContent): raise HomeAssistantError( "Last content in chat log is not an AssistantContent" ) text = chat_log.content[-1].content or "" if not task.structure: return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=text, ) try: data = json_loads(text) except JSONDecodeError as err: _LOGGER.error( "Failed to parse JSON response: %s. Response: %s", err, text, ) raise HomeAssistantError("Error with OpenAI structured response") from err return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=data, ) async def _async_generate_image( self, task: ai_task.GenImageTask, chat_log: conversation.ChatLog, ) -> ai_task.GenImageTaskResult: """Handle a generate image task.""" attachments: list[LLMImageAttachment] | None = None if task.attachments: attachments = await async_prepare_image_generation_attachments( self.hass, task.attachments ) try: if attachments is None: image = await self._cloud.llm.async_generate_image( prompt=task.instructions, ) else: image = await self._cloud.llm.async_edit_image( prompt=task.instructions, attachments=attachments, ) except LLMAuthenticationError as err: raise HomeAssistantError("Cloud LLM authentication failed") from err except LLMRateLimitError as err: raise HomeAssistantError("Cloud LLM is rate limited") from err except LLMResponseError as err: raise HomeAssistantError(str(err)) from err except LLMServiceError as err: raise HomeAssistantError("Error talking to Cloud LLM") from err except LLMError as err: raise HomeAssistantError(str(err)) from err return ai_task.GenImageTaskResult( conversation_id=chat_log.conversation_id, mime_type=image["mime_type"], image_data=image["image_data"], model=image.get("model"), width=image.get("width"), height=image.get("height"), revised_prompt=image.get("revised_prompt"), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloud/ai_task.py", "license": "Apache License 2.0", "lines": 164, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/cloud/conversation.py
"""Conversation support for Home Assistant Cloud.""" from __future__ import annotations from typing import Literal from homeassistant.components import conversation from homeassistant.config_entries import ConfigEntry from homeassistant.const import MATCH_ALL from homeassistant.core import HomeAssistant from homeassistant.helpers import llm from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import CONVERSATION_ENTITY_UNIQUE_ID, DATA_CLOUD, DOMAIN from .entity import BaseCloudLLMEntity async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Home Assistant Cloud conversation entity.""" cloud = hass.data[DATA_CLOUD] async_add_entities([CloudConversationEntity(cloud, config_entry)]) class CloudConversationEntity( BaseCloudLLMEntity, conversation.ConversationEntity, ): """Home Assistant Cloud conversation agent.""" _attr_has_entity_name = True _attr_name = "Home Assistant Cloud" _attr_translation_key = "cloud_conversation" _attr_unique_id = CONVERSATION_ENTITY_UNIQUE_ID _attr_supported_features = conversation.ConversationEntityFeature.CONTROL @property def available(self) -> bool: """Return if the entity is available.""" return self._cloud.is_logged_in and self._cloud.valid_subscription @property def supported_languages(self) -> list[str] | Literal["*"]: """Return a list of supported languages.""" return MATCH_ALL async def _async_handle_message( self, user_input: conversation.ConversationInput, chat_log: conversation.ChatLog, ) -> conversation.ConversationResult: """Process a user input.""" try: await chat_log.async_provide_llm_data( user_input.as_llm_context(DOMAIN), llm.LLM_API_ASSIST, None, user_input.extra_system_prompt, ) except conversation.ConverseError as err: return err.as_conversation_result() await self._async_handle_chat_log("conversation", chat_log) return conversation.async_get_result_from_chat_log(user_input, chat_log)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloud/conversation.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/cloud/entity.py
"""Helpers for cloud LLM chat handling.""" import base64 from collections.abc import AsyncGenerator, Callable, Iterable from enum import StrEnum import json import logging import re from typing import Any, Literal, cast from hass_nabucasa import Cloud, NabuCasaBaseError from hass_nabucasa.llm import ( LLMAuthenticationError, LLMRateLimitError, LLMResponseCompletedEvent, LLMResponseError, LLMResponseErrorEvent, LLMResponseFailedEvent, LLMResponseFunctionCallArgumentsDeltaEvent, LLMResponseFunctionCallArgumentsDoneEvent, LLMResponseFunctionCallOutputItem, LLMResponseImageOutputItem, LLMResponseIncompleteEvent, LLMResponseMessageOutputItem, LLMResponseOutputItemAddedEvent, LLMResponseOutputItemDoneEvent, LLMResponseOutputTextDeltaEvent, LLMResponseReasoningOutputItem, LLMResponseReasoningSummaryTextDeltaEvent, LLMResponseWebSearchCallOutputItem, LLMResponseWebSearchCallSearchingEvent, LLMServiceError, ) from openai.types.responses import ( FunctionToolParam, ResponseInputItemParam, ResponseReasoningItem, ToolParam, WebSearchToolParam, ) from openai.types.responses.response_input_param import ( ImageGenerationCall as ImageGenerationCallParam, ) from openai.types.responses.response_output_item import ImageGenerationCall import voluptuous as vol from voluptuous_openapi import convert from homeassistant.components import conversation from homeassistant.config_entries import ConfigEntry from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import llm from homeassistant.helpers.entity import Entity from homeassistant.helpers.json import json_dumps from homeassistant.util import slugify from .client import CloudClient _LOGGER = logging.getLogger(__name__) _MAX_TOOL_ITERATIONS = 10 class ResponseItemType(StrEnum): """Response item types.""" FUNCTION_CALL = "function_call" MESSAGE = "message" REASONING = "reasoning" WEB_SEARCH_CALL = "web_search_call" IMAGE = "image" def _convert_content_to_param( chat_content: Iterable[conversation.Content], ) -> list[ResponseInputItemParam]: """Convert any native chat message for this agent to the native format.""" messages: list[ResponseInputItemParam] = [] reasoning_summary: list[str] = [] web_search_calls: dict[str, dict[str, Any]] = {} for content in chat_content: if isinstance(content, conversation.ToolResultContent): if ( content.tool_name == "web_search_call" and content.tool_call_id in web_search_calls ): web_search_call = web_search_calls.pop(content.tool_call_id) web_search_call["status"] = content.tool_result.get( "status", "completed" ) messages.append(cast("ResponseInputItemParam", web_search_call)) else: messages.append( { "type": "function_call_output", "call_id": content.tool_call_id, "output": json_dumps(content.tool_result), } ) continue if content.content: role: Literal["user", "assistant", "system", "developer"] = content.role if role == "system": role = "developer" messages.append( {"type": "message", "role": role, "content": content.content} ) if isinstance(content, conversation.AssistantContent): if content.tool_calls: for tool_call in content.tool_calls: if ( tool_call.external and tool_call.tool_name == "web_search_call" and "action" in tool_call.tool_args ): web_search_calls[tool_call.id] = { "type": "web_search_call", "id": tool_call.id, "action": tool_call.tool_args["action"], "status": "completed", } else: messages.append( { "type": "function_call", "name": tool_call.tool_name, "arguments": json_dumps(tool_call.tool_args), "call_id": tool_call.id, } ) if content.thinking_content: reasoning_summary.append(content.thinking_content) if isinstance(content.native, ResponseReasoningItem): messages.append( { "type": "reasoning", "id": content.native.id, "summary": ( [ { "type": "summary_text", "text": summary, } for summary in reasoning_summary ] if content.thinking_content else [] ), "encrypted_content": content.native.encrypted_content, } ) reasoning_summary = [] elif isinstance(content.native, ImageGenerationCall): messages.append( cast(ImageGenerationCallParam, content.native.to_dict()) ) return messages def _format_tool( tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None, ) -> ToolParam: """Format a Home Assistant tool for the OpenAI Responses API.""" parameters = convert(tool.parameters, custom_serializer=custom_serializer) spec: FunctionToolParam = { "type": "function", "name": tool.name, "strict": False, "description": tool.description, "parameters": parameters, } return spec def _adjust_schema(schema: dict[str, Any]) -> None: """Adjust the schema to be compatible with OpenAI API.""" if schema["type"] == "object": schema.setdefault("strict", True) schema.setdefault("additionalProperties", False) if "properties" not in schema: return if "required" not in schema: schema["required"] = [] # Ensure all properties are required for prop, prop_info in schema["properties"].items(): _adjust_schema(prop_info) if prop not in schema["required"]: prop_info["type"] = [prop_info["type"], "null"] schema["required"].append(prop) elif schema["type"] == "array": if "items" not in schema: return _adjust_schema(schema["items"]) def _format_structured_output( schema: vol.Schema, llm_api: llm.APIInstance | None ) -> dict[str, Any]: """Format the schema to be compatible with OpenAI API.""" result: dict[str, Any] = convert( schema, custom_serializer=( llm_api.custom_serializer if llm_api else llm.selector_serializer ), ) _ensure_schema_constraints(result) return result def _ensure_schema_constraints(schema: dict[str, Any]) -> None: """Ensure generated schemas match the Responses API expectations.""" schema_type = schema.get("type") if schema_type == "object": schema.setdefault("additionalProperties", False) properties = schema.get("properties") if isinstance(properties, dict): for property_schema in properties.values(): if isinstance(property_schema, dict): _ensure_schema_constraints(property_schema) elif schema_type == "array": items = schema.get("items") if isinstance(items, dict): _ensure_schema_constraints(items) # Borrowed and adapted from openai_conversation component async def _transform_stream( # noqa: C901 - This is complex, but better to have it in one place chat_log: conversation.ChatLog, stream: Any, remove_citations: bool = False, ) -> AsyncGenerator[ conversation.AssistantContentDeltaDict | conversation.ToolResultContentDeltaDict ]: """Transform stream result into HA format.""" last_summary_index = None last_role: Literal["assistant", "tool_result"] | None = None current_tool_call: LLMResponseFunctionCallOutputItem | None = None # Non-reasoning models don't follow our request to remove citations, so we remove # them manually here. They always follow the same pattern: the citation is always # in parentheses in Markdown format, the citation is always in a single delta event, # and sometimes the closing parenthesis is split into a separate delta event. remove_parentheses: bool = False citation_regexp = re.compile(r"\(\[([^\]]+)\]\((https?:\/\/[^\)]+)\)") async for event in stream: _LOGGER.debug("Event[%s]", getattr(event, "type", None)) if isinstance(event, LLMResponseOutputItemAddedEvent): if isinstance(event.item, LLMResponseFunctionCallOutputItem): # OpenAI has tool calls as individual events # while HA puts tool calls inside the assistant message. # We turn them into individual assistant content for HA # to ensure that tools are called as soon as possible. yield {"role": "assistant"} last_role = "assistant" last_summary_index = None current_tool_call = event.item elif ( isinstance(event.item, LLMResponseMessageOutputItem) or ( isinstance(event.item, LLMResponseReasoningOutputItem) and last_summary_index is not None ) # Subsequent ResponseReasoningItem or last_role != "assistant" ): yield {"role": "assistant"} last_role = "assistant" last_summary_index = None elif isinstance(event, LLMResponseOutputItemDoneEvent): if isinstance(event.item, LLMResponseReasoningOutputItem): encrypted_content = event.item.encrypted_content summary = event.item.summary yield { "native": LLMResponseReasoningOutputItem( type=event.item.type, id=event.item.id, summary=[], encrypted_content=encrypted_content, ) } last_summary_index = len(summary) - 1 if summary else None elif isinstance(event.item, LLMResponseWebSearchCallOutputItem): action_dict = event.item.action yield { "tool_calls": [ llm.ToolInput( id=event.item.id, tool_name="web_search_call", tool_args={"action": action_dict}, external=True, ) ] } yield { "role": "tool_result", "tool_call_id": event.item.id, "tool_name": "web_search_call", "tool_result": {"status": event.item.status}, } last_role = "tool_result" elif isinstance(event.item, LLMResponseImageOutputItem): yield {"native": event.item.raw} last_summary_index = -1 # Trigger new assistant message on next turn elif isinstance(event, LLMResponseOutputTextDeltaEvent): data = event.delta if remove_parentheses: data = data.removeprefix(")") remove_parentheses = False elif remove_citations and (match := citation_regexp.search(data)): match_start, match_end = match.span() # remove leading space if any if data[match_start - 1 : match_start] == " ": match_start -= 1 # remove closing parenthesis: if data[match_end : match_end + 1] == ")": match_end += 1 else: remove_parentheses = True data = data[:match_start] + data[match_end:] if data: yield {"content": data} elif isinstance(event, LLMResponseReasoningSummaryTextDeltaEvent): # OpenAI can output several reasoning summaries # in a single ResponseReasoningItem. We split them as separate # AssistantContent messages. Only last of them will have # the reasoning `native` field set. if ( last_summary_index is not None and event.summary_index != last_summary_index ): yield {"role": "assistant"} last_role = "assistant" last_summary_index = event.summary_index yield {"thinking_content": event.delta} elif isinstance(event, LLMResponseFunctionCallArgumentsDeltaEvent): if current_tool_call is not None: current_tool_call.arguments += event.delta elif isinstance(event, LLMResponseWebSearchCallSearchingEvent): yield {"role": "assistant"} elif isinstance(event, LLMResponseFunctionCallArgumentsDoneEvent): if current_tool_call is not None: current_tool_call.status = "completed" raw_args = json.loads(current_tool_call.arguments) for key in ("area", "floor"): if key in raw_args and not raw_args[key]: # Remove keys that are "" or None raw_args.pop(key, None) yield { "tool_calls": [ llm.ToolInput( id=current_tool_call.call_id, tool_name=current_tool_call.name, tool_args=raw_args, ) ] } elif isinstance(event, LLMResponseCompletedEvent): response = event.response if response and "usage" in response: usage = response["usage"] chat_log.async_trace( { "stats": { "input_tokens": usage.get("input_tokens"), "output_tokens": usage.get("output_tokens"), } } ) elif isinstance(event, LLMResponseIncompleteEvent): response = event.response if response and "usage" in response: usage = response["usage"] chat_log.async_trace( { "stats": { "input_tokens": usage.get("input_tokens"), "output_tokens": usage.get("output_tokens"), } } ) incomplete_details = response.get("incomplete_details") reason = "unknown reason" if incomplete_details is not None and incomplete_details.get("reason"): reason = incomplete_details["reason"] if reason == "max_output_tokens": reason = "max output tokens reached" elif reason == "content_filter": reason = "content filter triggered" raise HomeAssistantError(f"OpenAI response incomplete: {reason}") elif isinstance(event, LLMResponseFailedEvent): response = event.response if response and "usage" in response: usage = response["usage"] chat_log.async_trace( { "stats": { "input_tokens": usage.get("input_tokens"), "output_tokens": usage.get("output_tokens"), } } ) reason = "unknown reason" if isinstance(error := response.get("error"), dict): reason = error.get("message") or reason raise HomeAssistantError(f"OpenAI response failed: {reason}") elif isinstance(event, LLMResponseErrorEvent): raise HomeAssistantError(f"OpenAI response error: {event.message}") class BaseCloudLLMEntity(Entity): """Cloud LLM conversation agent.""" def __init__(self, cloud: Cloud[CloudClient], config_entry: ConfigEntry) -> None: """Initialize the entity.""" self._cloud = cloud self._entry = config_entry async def _prepare_chat_for_generation( self, chat_log: conversation.ChatLog, messages: list[ResponseInputItemParam], response_format: dict[str, Any] | None = None, ) -> dict[str, Any]: """Prepare kwargs for Cloud LLM from the chat log.""" last_content: Any = chat_log.content[-1] if last_content.role == "user" and last_content.attachments: files = await self._async_prepare_files_for_prompt(last_content.attachments) last_message = cast(dict[str, Any], messages[-1]) assert ( last_message["type"] == "message" and last_message["role"] == "user" and isinstance(last_message["content"], str) ) last_message["content"] = [ {"type": "input_text", "text": last_message["content"]}, *files, ] tools: list[ToolParam] = [] tool_choice: str | None = None if chat_log.llm_api: ha_tools: list[ToolParam] = [ _format_tool(tool, chat_log.llm_api.custom_serializer) for tool in chat_log.llm_api.tools ] if ha_tools: if not chat_log.unresponded_tool_results: tools = ha_tools tool_choice = "auto" else: tools = [] tool_choice = "none" web_search = WebSearchToolParam( type="web_search", search_context_size="medium", ) tools.append(web_search) response_kwargs: dict[str, Any] = { "messages": messages, "conversation_id": chat_log.conversation_id, } if response_format is not None: response_kwargs["response_format"] = response_format if tools is not None: response_kwargs["tools"] = tools if tool_choice is not None: response_kwargs["tool_choice"] = tool_choice response_kwargs["stream"] = True return response_kwargs async def _async_prepare_files_for_prompt( self, attachments: list[conversation.Attachment], ) -> list[dict[str, Any]]: """Prepare files for multimodal prompts.""" def prepare() -> list[dict[str, Any]]: content: list[dict[str, Any]] = [] for attachment in attachments: mime_type = attachment.mime_type path = attachment.path if not path.exists(): raise HomeAssistantError(f"`{path}` does not exist") data = base64.b64encode(path.read_bytes()).decode("utf-8") if mime_type and mime_type.startswith("image/"): content.append( { "type": "input_image", "image_url": f"data:{mime_type};base64,{data}", "detail": "auto", } ) elif mime_type and mime_type.startswith("application/pdf"): content.append( { "type": "input_file", "filename": str(path.name), "file_data": f"data:{mime_type};base64,{data}", } ) else: raise HomeAssistantError( "Only images and PDF are currently supported as attachments" ) return content return await self.hass.async_add_executor_job(prepare) async def _async_handle_chat_log( self, type: Literal["ai_task", "conversation"], chat_log: conversation.ChatLog, structure_name: str | None = None, structure: vol.Schema | None = None, ) -> None: """Generate a response for the chat log.""" for _ in range(_MAX_TOOL_ITERATIONS): response_format: dict[str, Any] | None = None if structure and structure_name: response_format = { "type": "json_schema", "json_schema": { "name": slugify(structure_name), "schema": _format_structured_output( structure, chat_log.llm_api ), "strict": False, }, } messages = _convert_content_to_param(chat_log.content) response_kwargs = await self._prepare_chat_for_generation( chat_log, messages, response_format, ) try: if type == "conversation": raw_stream = await self._cloud.llm.async_process_conversation( **response_kwargs, ) else: raw_stream = await self._cloud.llm.async_generate_data( **response_kwargs, ) messages.extend( _convert_content_to_param( [ content async for content in chat_log.async_add_delta_content_stream( self.entity_id, _transform_stream( chat_log, raw_stream, True, ), ) ] ) ) except LLMAuthenticationError as err: raise HomeAssistantError("Cloud LLM authentication failed") from err except LLMRateLimitError as err: raise HomeAssistantError("Cloud LLM is rate limited") from err except LLMResponseError as err: raise HomeAssistantError(str(err)) from err except LLMServiceError as err: raise HomeAssistantError("Error talking to Cloud LLM") from err except NabuCasaBaseError as err: raise HomeAssistantError(str(err)) from err if not chat_log.unresponded_tool_results: break
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloud/entity.py", "license": "Apache License 2.0", "lines": 539, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/duckdns/config_flow.py
"""Config flow for the Duck DNS integration.""" from __future__ import annotations import logging from typing import Any import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_ACCESS_TOKEN, CONF_DOMAIN, CONF_NAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import DOMAIN from .helpers import update_duckdns from .issue import deprecate_yaml_issue _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_DOMAIN): TextSelector( TextSelectorConfig(type=TextSelectorType.TEXT, suffix=".duckdns.org") ), vol.Required(CONF_ACCESS_TOKEN): str, } ) STEP_RECONFIGURE_DATA_SCHEMA = vol.Schema({vol.Required(CONF_ACCESS_TOKEN): str}) class DuckDnsConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Duck DNS.""" 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_DOMAIN: user_input[CONF_DOMAIN]}) session = async_get_clientsession(self.hass) try: if not await update_duckdns( session, user_input[CONF_DOMAIN], user_input[CONF_ACCESS_TOKEN], ): errors["base"] = "update_failed" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: return self.async_create_entry( title=f"{user_input[CONF_DOMAIN]}.duckdns.org", data=user_input ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input ), errors=errors, description_placeholders={"url": "https://www.duckdns.org/"}, ) async def async_step_import(self, import_info: dict[str, Any]) -> ConfigFlowResult: """Import config from yaml.""" self._async_abort_entries_match({CONF_DOMAIN: import_info[CONF_DOMAIN]}) result = await self.async_step_user(import_info) if errors := result.get("errors"): deprecate_yaml_issue(self.hass, import_success=False) return self.async_abort(reason=errors["base"]) deprecate_yaml_issue(self.hass, import_success=True) return result async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfigure flow.""" errors: dict[str, str] = {} entry = self._get_reconfigure_entry() if user_input is not None: session = async_get_clientsession(self.hass) try: if not await update_duckdns( session, entry.data[CONF_DOMAIN], user_input[CONF_ACCESS_TOKEN], ): errors["base"] = "update_failed" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: return self.async_update_reload_and_abort( entry, data_updates=user_input, ) return self.async_show_form( step_id="reconfigure", data_schema=STEP_RECONFIGURE_DATA_SCHEMA, errors=errors, description_placeholders={CONF_NAME: entry.title}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/config_flow.py", "license": "Apache License 2.0", "lines": 96, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/duckdns/const.py
"""Constants for the Duck DNS integration.""" from typing import Final DOMAIN = "duckdns" ATTR_CONFIG_ENTRY: Final = "config_entry_id" ATTR_TXT: Final = "txt" SERVICE_SET_TXT = "set_txt"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/const.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/duckdns/issue.py
"""Issues for Duck DNS integration.""" from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from .const import DOMAIN @callback def deprecate_yaml_issue(hass: HomeAssistant, *, import_success: bool) -> None: """Deprecate yaml issue.""" if import_success: async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}", is_fixable=False, issue_domain=DOMAIN, breaks_in_ha_version="2026.6.0", severity=IssueSeverity.WARNING, translation_key="deprecated_yaml", translation_placeholders={ "domain": DOMAIN, "integration_title": "Duck DNS", }, ) else: async_create_issue( hass, DOMAIN, "deprecated_yaml_import_issue_error", breaks_in_ha_version="2026.6.0", is_fixable=False, issue_domain=DOMAIN, severity=IssueSeverity.WARNING, translation_key="deprecated_yaml_import_issue_error", translation_placeholders={ "url": "/config/integrations/dashboard/add?domain=duckdns" }, ) def action_called_without_config_entry(hass: HomeAssistant) -> None: """Deprecate the use of action without config entry.""" async_create_issue( hass, DOMAIN, "deprecated_call_without_config_entry", breaks_in_ha_version="2026.9.0", is_fixable=False, issue_domain=DOMAIN, severity=IssueSeverity.WARNING, translation_key="deprecated_call_without_config_entry", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/duckdns/issue.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/energyid/config_flow.py
"""Config flow for EnergyID integration.""" import asyncio from collections.abc import Mapping import logging from typing import Any from aiohttp import ClientError, ClientResponseError from energyid_webhooks.client_v2 import WebhookClient import voluptuous as vol from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigFlowResult, ConfigSubentryFlow, ) from homeassistant.core import callback from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv from homeassistant.helpers.instance_id import async_get as async_get_instance_id from .const import ( CONF_DEVICE_ID, CONF_DEVICE_NAME, CONF_PROVISIONING_KEY, CONF_PROVISIONING_SECRET, DOMAIN, ENERGYID_DEVICE_ID_FOR_WEBHOOK_PREFIX, MAX_POLLING_ATTEMPTS, NAME, POLLING_INTERVAL, ) from .energyid_sensor_mapping_flow import EnergyIDSensorMappingFlowHandler _LOGGER = logging.getLogger(__name__) class EnergyIDConfigFlow(ConfigFlow, domain=DOMAIN): """Handle the configuration flow for the EnergyID integration.""" def __init__(self) -> None: """Initialize the config flow.""" self._flow_data: dict[str, Any] = {} self._polling_task: asyncio.Task | None = None async def _perform_auth_and_get_details(self) -> str | None: """Authenticate with EnergyID and retrieve device details.""" _LOGGER.debug("Starting authentication with EnergyID") client = WebhookClient( provisioning_key=self._flow_data[CONF_PROVISIONING_KEY], provisioning_secret=self._flow_data[CONF_PROVISIONING_SECRET], device_id=self._flow_data[CONF_DEVICE_ID], device_name=self._flow_data[CONF_DEVICE_NAME], session=async_get_clientsession(self.hass), ) try: is_claimed = await client.authenticate() except ClientResponseError as err: if err.status == 401: _LOGGER.debug("Invalid provisioning key or secret") return "invalid_auth" _LOGGER.debug( "Client response error during EnergyID authentication: %s", err ) return "cannot_connect" except ClientError as err: _LOGGER.debug( "Failed to connect to EnergyID during authentication: %s", err ) return "cannot_connect" except Exception: _LOGGER.exception("Unexpected error during EnergyID authentication") return "unknown_auth_error" else: _LOGGER.debug("Authentication successful, claimed: %s", is_claimed) if is_claimed: self._flow_data["record_number"] = client.recordNumber self._flow_data["record_name"] = client.recordName _LOGGER.debug( "Device claimed with record number: %s, record name: %s", client.recordNumber, client.recordName, ) return None self._flow_data["claim_info"] = client.get_claim_info() self._flow_data["claim_info"]["integration_name"] = NAME _LOGGER.debug( "Device needs claim, claim info: %s", self._flow_data["claim_info"] ) return "needs_claim" async def _async_poll_for_claim(self) -> None: """Poll EnergyID to check if device has been claimed.""" for _attempt in range(1, MAX_POLLING_ATTEMPTS + 1): await asyncio.sleep(POLLING_INTERVAL) auth_status = await self._perform_auth_and_get_details() if auth_status is None: # Device claimed - advance flow to async_step_create_entry _LOGGER.debug("Device claimed, advancing to create entry") self.hass.async_create_task( self.hass.config_entries.flow.async_configure(self.flow_id) ) return if auth_status != "needs_claim": # Stop polling on non-transient errors # No user notification needed here as the error will be handled # in the next flow step when the user continues the flow _LOGGER.debug("Polling stopped due to error: %s", auth_status) return _LOGGER.debug("Polling timeout after %s attempts", MAX_POLLING_ATTEMPTS) # No user notification here because: # 1. User may still be completing the claim process in EnergyID portal # 2. Immediate notification could interrupt their workflow or cause confusion # 3. When user clicks "Submit" to continue, the flow validates claim status # and will show appropriate error/success messages based on current state # 4. Timeout allows graceful fallback: user can retry claim or see proper error async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step of the configuration flow.""" _LOGGER.debug("Starting user step with input: %s", user_input) errors: dict[str, str] = {} if user_input is not None: instance_id = await async_get_instance_id(self.hass) # Note: This device_id is for EnergyID's webhook system, not related to HA's device registry device_suffix = f"{int(asyncio.get_event_loop().time() * 1000)}" device_id = ( f"{ENERGYID_DEVICE_ID_FOR_WEBHOOK_PREFIX}{instance_id}_{device_suffix}" ) self._flow_data = { **user_input, CONF_DEVICE_ID: device_id, CONF_DEVICE_NAME: self.hass.config.location_name, } _LOGGER.debug("Flow data after user input: %s", self._flow_data) auth_status = await self._perform_auth_and_get_details() if auth_status is None: await self.async_set_unique_id(device_id) self._abort_if_unique_id_configured() _LOGGER.debug( "Creating entry with title: %s", self._flow_data["record_name"] ) return self.async_create_entry( title=self._flow_data["record_name"], data=self._flow_data, description="add_sensor_mapping_hint", description_placeholders={"integration_name": NAME}, ) if auth_status == "needs_claim": _LOGGER.debug("Redirecting to auth and claim step") return await self.async_step_auth_and_claim() errors["base"] = auth_status _LOGGER.debug("Errors encountered during user step: %s", errors) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_PROVISIONING_KEY): str, vol.Required(CONF_PROVISIONING_SECRET): cv.string, } ), errors=errors, description_placeholders={ "docs_url": "https://app.energyid.eu/integrations/home-assistant", "integration_name": NAME, }, ) async def async_step_auth_and_claim( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the step for device claiming using external step with polling.""" _LOGGER.debug("Starting auth and claim step with input: %s", user_input) claim_info = self._flow_data.get("claim_info", {}) # Start polling when we first enter this step if self._polling_task is None: self._polling_task = self.hass.async_create_task( self._async_poll_for_claim() ) # Show external step to open the EnergyID website return self.async_external_step( step_id="auth_and_claim", url=claim_info.get("claim_url", ""), description_placeholders=claim_info, ) # Check if device has been claimed auth_status = await self._perform_auth_and_get_details() if auth_status is None: # Device has been claimed if self._polling_task and not self._polling_task.done(): self._polling_task.cancel() self._polling_task = None return self.async_external_step_done(next_step_id="create_entry") # Device not claimed yet, show the external step again if self._polling_task and not self._polling_task.done(): self._polling_task.cancel() self._polling_task = None return self.async_external_step( step_id="auth_and_claim", url=claim_info.get("claim_url", ""), description_placeholders=claim_info, ) async def async_step_create_entry( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Final step to create the entry after successful claim.""" _LOGGER.debug("Creating entry with title: %s", self._flow_data["record_name"]) return self.async_create_entry( title=self._flow_data["record_name"], data=self._flow_data, description="add_sensor_mapping_hint", description_placeholders={"integration_name": NAME}, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauthentication upon an API authentication error.""" # Note: This device_id is for EnergyID's webhook system, not related to HA's device registry self._flow_data = { CONF_DEVICE_ID: entry_data[CONF_DEVICE_ID], CONF_DEVICE_NAME: entry_data[CONF_DEVICE_NAME], } return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauthentication dialog.""" errors: dict[str, str] = {} if user_input is not None: self._flow_data.update(user_input) auth_status = await self._perform_auth_and_get_details() if auth_status is None: # Authentication successful and claimed await self.async_set_unique_id(self._flow_data["record_number"]) self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates={ CONF_PROVISIONING_KEY: user_input[CONF_PROVISIONING_KEY], CONF_PROVISIONING_SECRET: user_input[CONF_PROVISIONING_SECRET], }, ) if auth_status == "needs_claim": return await self.async_step_auth_and_claim() errors["base"] = auth_status return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema( { vol.Required(CONF_PROVISIONING_KEY): str, vol.Required(CONF_PROVISIONING_SECRET): cv.string, } ), errors=errors, description_placeholders={ "docs_url": "https://app.energyid.eu/integrations/home-assistant", "integration_name": NAME, }, ) @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by this integration.""" return {"sensor_mapping": EnergyIDSensorMappingFlowHandler}
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/energyid/config_flow.py", "license": "Apache License 2.0", "lines": 256, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/energyid/const.py
"""Constants for the EnergyID integration.""" from typing import Final DOMAIN: Final = "energyid" NAME: Final = "EnergyID" # --- Config Flow and Entry Data --- CONF_PROVISIONING_KEY: Final = "provisioning_key" CONF_PROVISIONING_SECRET: Final = "provisioning_secret" CONF_DEVICE_ID: Final = "device_id" CONF_DEVICE_NAME: Final = "device_name" # --- Subentry (Mapping) Data --- CONF_HA_ENTITY_UUID: Final = "ha_entity_uuid" CONF_ENERGYID_KEY: Final = "energyid_key" # --- Webhook and Polling Configuration --- ENERGYID_DEVICE_ID_FOR_WEBHOOK_PREFIX: Final = "homeassistant_eid_" POLLING_INTERVAL: Final = 2 # seconds MAX_POLLING_ATTEMPTS: Final = 60 # 2 minutes total
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/energyid/const.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/energyid/energyid_sensor_mapping_flow.py
"""Subentry flow for EnergyID integration, handling sensor mapping management.""" import logging from typing import Any import voluptuous as vol from homeassistant.components.sensor import SensorDeviceClass, SensorStateClass from homeassistant.config_entries import ConfigSubentryFlow, SubentryFlowResult from homeassistant.const import Platform from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import entity_registry as er from homeassistant.helpers.selector import EntitySelector, EntitySelectorConfig from .const import CONF_ENERGYID_KEY, CONF_HA_ENTITY_UUID, DOMAIN, NAME _LOGGER = logging.getLogger(__name__) @callback def _get_suggested_entities(hass: HomeAssistant) -> list[str]: """Return a sorted list of suggested sensor entity IDs for mapping.""" ent_reg = er.async_get(hass) suitable_entities = [] for entity_entry in ent_reg.entities.values(): if not ( entity_entry.domain == Platform.SENSOR and entity_entry.platform != DOMAIN ): continue if not hass.states.get(entity_entry.entity_id): continue state_class = (entity_entry.capabilities or {}).get("state_class") has_numeric_indicators = ( state_class in ( SensorStateClass.MEASUREMENT, SensorStateClass.TOTAL, SensorStateClass.TOTAL_INCREASING, ) or entity_entry.device_class in ( SensorDeviceClass.ENERGY, SensorDeviceClass.GAS, SensorDeviceClass.POWER, SensorDeviceClass.TEMPERATURE, SensorDeviceClass.VOLUME, ) or entity_entry.original_device_class in ( SensorDeviceClass.ENERGY, SensorDeviceClass.GAS, SensorDeviceClass.POWER, SensorDeviceClass.TEMPERATURE, SensorDeviceClass.VOLUME, ) ) if has_numeric_indicators: suitable_entities.append(entity_entry.entity_id) return sorted(suitable_entities) @callback def _validate_mapping_input( ha_entity_id: str | None, current_mappings: set[str], ent_reg: er.EntityRegistry, ) -> dict[str, str]: """Validate mapping input and return errors if any.""" errors: dict[str, str] = {} if not ha_entity_id: errors["base"] = "entity_required" return errors # Check if entity exists entity_entry = ent_reg.async_get(ha_entity_id) if not entity_entry: errors["base"] = "entity_not_found" return errors # Check if entity is already mapped (by UUID) entity_uuid = entity_entry.id if entity_uuid in current_mappings: errors["base"] = "entity_already_mapped" return errors class EnergyIDSensorMappingFlowHandler(ConfigSubentryFlow): """Handle EnergyID sensor mapping subentry flow for adding new mappings.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Handle the user step for adding a new sensor mapping.""" errors: dict[str, str] = {} config_entry = self._get_entry() ent_reg = er.async_get(self.hass) if user_input is not None: ha_entity_id = user_input.get("ha_entity_id") # Get current mappings by UUID current_mappings = { uuid for sub in config_entry.subentries.values() if (uuid := sub.data.get(CONF_HA_ENTITY_UUID)) is not None } errors = _validate_mapping_input(ha_entity_id, current_mappings, ent_reg) if not errors and ha_entity_id: # Get entity registry entry entity_entry = ent_reg.async_get(ha_entity_id) if entity_entry: energyid_key = ha_entity_id.split(".", 1)[-1] subentry_data = { CONF_HA_ENTITY_UUID: entity_entry.id, # Store UUID only CONF_ENERGYID_KEY: energyid_key, } title = f"{ha_entity_id.split('.', 1)[-1]} connection to {NAME}" _LOGGER.debug( "Creating subentry with title='%s', data=%s", title, subentry_data, ) _LOGGER.debug("Parent config entry ID: %s", config_entry.entry_id) _LOGGER.debug( "Creating subentry with parent: %s", self._get_entry().entry_id ) return self.async_create_entry(title=title, data=subentry_data) errors["base"] = "entity_not_found" suggested_entities = _get_suggested_entities(self.hass) data_schema = vol.Schema( { vol.Required("ha_entity_id"): EntitySelector( EntitySelectorConfig(include_entities=suggested_entities) ), } ) return self.async_show_form( step_id="user", data_schema=data_schema, errors=errors, description_placeholders={"integration_name": NAME}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/energyid/energyid_sensor_mapping_flow.py", "license": "Apache License 2.0", "lines": 126, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/esphome/websocket_api.py
"""ESPHome websocket API.""" import logging from typing import Any import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.core import HomeAssistant, callback from .const import CONF_NOISE_PSK _LOGGER = logging.getLogger(__name__) TYPE = "type" ENTRY_ID = "entry_id" @callback def async_setup(hass: HomeAssistant) -> None: """Set up the websocket API.""" websocket_api.async_register_command(hass, get_encryption_key) @callback @websocket_api.require_admin @websocket_api.websocket_command( { vol.Required(TYPE): "esphome/get_encryption_key", vol.Required(ENTRY_ID): str, } ) def get_encryption_key( hass: HomeAssistant, connection: websocket_api.connection.ActiveConnection, msg: dict[str, Any], ) -> None: """Get the encryption key for an ESPHome config entry.""" entry = hass.config_entries.async_get_entry(msg[ENTRY_ID]) if entry is None: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, "Config entry not found" ) return connection.send_result( msg["id"], { "encryption_key": entry.data.get(CONF_NOISE_PSK), }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/esphome/websocket_api.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/essent/config_flow.py
"""Config flow for Essent integration.""" from __future__ import annotations import logging from typing import Any from essent_dynamic_pricing import ( EssentClient, EssentConnectionError, EssentDataError, EssentResponseError, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) class EssentConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Essent.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" client = EssentClient(async_get_clientsession(self.hass)) try: await client.async_get_prices() except EssentConnectionError, EssentResponseError: return self.async_abort(reason="cannot_connect") except EssentDataError: return self.async_abort(reason="invalid_data") except Exception: _LOGGER.exception("Unexpected error while validating the connection") return self.async_abort(reason="unknown") if user_input is None: return self.async_show_form(step_id="user") return self.async_create_entry(title="Essent", data={})
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/essent/config_flow.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/essent/const.py
"""Constants for the Essent integration.""" from __future__ import annotations from datetime import timedelta from enum import StrEnum from typing import Final DOMAIN: Final = "essent" UPDATE_INTERVAL: Final = timedelta(hours=1) ATTRIBUTION: Final = "Data provided by Essent" class EnergyType(StrEnum): """Supported energy types for Essent pricing.""" ELECTRICITY = "electricity" GAS = "gas" class PriceGroup(StrEnum): """Price group types as provided in tariff groups. VAT is not emitted as a price group; use tariff.total_amount_vat for VAT. """ MARKET_PRICE = "MARKET_PRICE" PURCHASING_FEE = "PURCHASING_FEE" TAX = "TAX"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/essent/const.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/essent/coordinator.py
"""DataUpdateCoordinator for Essent integration.""" from __future__ import annotations from collections.abc import Callable from datetime import datetime, timedelta import logging from essent_dynamic_pricing import ( EssentClient, EssentConnectionError, EssentDataError, EssentError, EssentPrices, EssentResponseError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import DOMAIN, UPDATE_INTERVAL _LOGGER = logging.getLogger(__name__) type EssentConfigEntry = ConfigEntry[EssentDataUpdateCoordinator] class EssentDataUpdateCoordinator(DataUpdateCoordinator[EssentPrices]): """Class to manage fetching Essent data.""" config_entry: EssentConfigEntry def __init__(self, hass: HomeAssistant, config_entry: EssentConfigEntry) -> None: """Initialize.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=UPDATE_INTERVAL, ) self._client = EssentClient(async_get_clientsession(hass)) self._unsub_listener: Callable[[], None] | None = None def start_listener_schedule(self) -> None: """Start listener tick schedule after first successful data fetch.""" if self.config_entry.pref_disable_polling: _LOGGER.debug("Polling disabled by config entry, not starting listener") return if self._unsub_listener: return _LOGGER.info("Starting listener updates on the hour") self._schedule_listener_tick() async def async_shutdown(self) -> None: """Cancel any scheduled call, and ignore new runs.""" await super().async_shutdown() if self._unsub_listener: self._unsub_listener() self._unsub_listener = None def _schedule_listener_tick(self) -> None: """Schedule listener updates on the hour to advance cached tariffs.""" if self._unsub_listener: self._unsub_listener() now = dt_util.utcnow() next_hour = now + timedelta(hours=1) next_run = datetime( next_hour.year, next_hour.month, next_hour.day, next_hour.hour, tzinfo=dt_util.UTC, ) _LOGGER.debug("Scheduling next listener tick for %s", next_run) @callback def _handle(_: datetime) -> None: """Handle the scheduled listener tick to update sensors.""" self._unsub_listener = None _LOGGER.debug("Listener tick fired, updating sensors with cached data") self.async_update_listeners() self._schedule_listener_tick() self._unsub_listener = async_track_point_in_utc_time( self.hass, _handle, next_run, ) async def _async_update_data(self) -> EssentPrices: """Fetch data from API.""" try: return await self._client.async_get_prices() except EssentConnectionError as err: raise UpdateFailed(f"Error communicating with API: {err}") from err except EssentResponseError as err: raise UpdateFailed(str(err)) from err except EssentDataError as err: _LOGGER.debug("Invalid data received: %s", err) raise UpdateFailed(str(err)) from err except EssentError as err: raise UpdateFailed("Unexpected Essent error") from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/essent/coordinator.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/essent/entity.py
"""Base entity for Essent integration.""" from essent_dynamic_pricing.models import EnergyData from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ATTRIBUTION, DOMAIN, EnergyType from .coordinator import EssentDataUpdateCoordinator class EssentEntity(CoordinatorEntity[EssentDataUpdateCoordinator]): """Base class for Essent entities.""" _attr_has_entity_name = True _attr_attribution = ATTRIBUTION def __init__( self, coordinator: EssentDataUpdateCoordinator, energy_type: EnergyType, ) -> None: """Initialize the entity.""" super().__init__(coordinator) self.energy_type = energy_type self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, coordinator.config_entry.entry_id)}, name="Essent", manufacturer="Essent", ) @property def energy_data(self) -> EnergyData: """Return the energy data for this entity.""" return getattr(self.coordinator.data, self.energy_type.value)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/essent/entity.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/fan/trigger.py
"""Provides triggers for fans.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from . import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "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 fans.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fan/trigger.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/go2rtc/util.py
"""Go2rtc utility functions.""" from pathlib import Path _HA_MANAGED_UNIX_SOCKET_FILE = "go2rtc.sock" def get_go2rtc_unix_socket_path(path: str | Path) -> str: """Get the Go2rtc unix socket path.""" if not isinstance(path, Path): path = Path(path) return str(path / _HA_MANAGED_UNIX_SOCKET_FILE)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/go2rtc/util.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/google_air_quality/config_flow.py
"""Config flow for the Google Air Quality integration.""" from __future__ import annotations import logging from typing import Any from google_air_quality_api.api import GoogleAirQualityApi from google_air_quality_api.auth import Auth from google_air_quality_api.exceptions import GoogleAirQualityApiError import voluptuous as vol from homeassistant.config_entries import ( ConfigEntry, ConfigEntryState, ConfigFlow, ConfigFlowResult, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE, CONF_LOCATION, CONF_LONGITUDE, CONF_NAME, ) from homeassistant.core import HomeAssistant, callback from homeassistant.data_entry_flow import SectionConfig, section from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import LocationSelector, LocationSelectorConfig from .const import CONF_REFERRER, DOMAIN, SECTION_API_KEY_OPTIONS _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional(SECTION_API_KEY_OPTIONS): section( vol.Schema({vol.Optional(CONF_REFERRER): str}), SectionConfig(collapsed=True), ), } ) async def _validate_input( user_input: dict[str, Any], api: GoogleAirQualityApi, errors: dict[str, str], description_placeholders: dict[str, str], ) -> bool: try: await api.async_get_current_conditions( lat=user_input[CONF_LOCATION][CONF_LATITUDE], lon=user_input[CONF_LOCATION][CONF_LONGITUDE], ) except GoogleAirQualityApiError as err: errors["base"] = "cannot_connect" description_placeholders["error_message"] = str(err) except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return True return False def _get_location_schema(hass: HomeAssistant) -> vol.Schema: """Return the schema for a location with default values from the hass config.""" return vol.Schema( { vol.Required(CONF_NAME, default=hass.config.location_name): str, vol.Required( CONF_LOCATION, default={ CONF_LATITUDE: hass.config.latitude, CONF_LONGITUDE: hass.config.longitude, }, ): LocationSelector(LocationSelectorConfig(radius=False)), } ) def _is_location_already_configured( hass: HomeAssistant, new_data: dict[str, float], epsilon: float = 1e-4 ) -> bool: """Check if the location is already configured.""" for entry in hass.config_entries.async_entries(DOMAIN): for subentry in entry.subentries.values(): # A more accurate way is to use the haversine formula, but for simplicity # we use a simple distance check. The epsilon value is small anyway. # This is mostly to capture cases where the user has slightly moved the location pin. if ( abs(subentry.data[CONF_LATITUDE] - new_data[CONF_LATITUDE]) <= epsilon and abs(subentry.data[CONF_LONGITUDE] - new_data[CONF_LONGITUDE]) <= epsilon ): return True return False def _is_location_name_already_configured(hass: HomeAssistant, new_data: str) -> bool: """Check if the location name is already configured.""" for entry in hass.config_entries.async_entries(DOMAIN): for subentry in entry.subentries.values(): if subentry.title.lower() == new_data.lower(): return True return False class GoogleAirQualityConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Google AirQuality.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} description_placeholders: dict[str, str] = { "api_key_url": "https://developers.google.com/maps/documentation/air-quality/get-api-key", "restricting_api_keys_url": "https://developers.google.com/maps/api-security-best-practices#restricting-api-keys", } if user_input is not None: api_key = user_input[CONF_API_KEY] referrer = user_input.get(SECTION_API_KEY_OPTIONS, {}).get(CONF_REFERRER) self._async_abort_entries_match({CONF_API_KEY: api_key}) if _is_location_already_configured(self.hass, user_input[CONF_LOCATION]): return self.async_abort(reason="already_configured") session = async_get_clientsession(self.hass) referrer = user_input.get(SECTION_API_KEY_OPTIONS, {}).get(CONF_REFERRER) auth = Auth(session, user_input[CONF_API_KEY], referrer=referrer) api = GoogleAirQualityApi(auth) if await _validate_input(user_input, api, errors, description_placeholders): return self.async_create_entry( title="Google Air Quality", data={ CONF_API_KEY: api_key, CONF_REFERRER: referrer, }, subentries=[ { "subentry_type": "location", "data": user_input[CONF_LOCATION], "title": user_input[CONF_NAME], "unique_id": None, }, ], ) else: user_input = {} schema = STEP_USER_DATA_SCHEMA.schema.copy() schema.update(_get_location_schema(self.hass).schema) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( vol.Schema(schema), user_input ), errors=errors, description_placeholders=description_placeholders, ) @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by this integration.""" return {"location": LocationSubentryFlowHandler} class LocationSubentryFlowHandler(ConfigSubentryFlow): """Handle a subentry flow for location.""" async def async_step_location( self, user_input: dict[str, Any] | None = None, ) -> SubentryFlowResult: """Handle the location step.""" if self._get_entry().state != ConfigEntryState.LOADED: return self.async_abort(reason="entry_not_loaded") errors: dict[str, str] = {} description_placeholders: dict[str, str] = {} if user_input is not None: if _is_location_already_configured(self.hass, user_input[CONF_LOCATION]): errors["base"] = "location_already_configured" if _is_location_name_already_configured(self.hass, user_input[CONF_NAME]): errors["base"] = "location_name_already_configured" api: GoogleAirQualityApi = self._get_entry().runtime_data.api if errors: return self.async_show_form( step_id="location", data_schema=self.add_suggested_values_to_schema( _get_location_schema(self.hass), user_input ), errors=errors, description_placeholders=description_placeholders, ) if await _validate_input(user_input, api, errors, description_placeholders): return self.async_create_entry( title=user_input[CONF_NAME], data=user_input[CONF_LOCATION], ) else: user_input = {} return self.async_show_form( step_id="location", data_schema=self.add_suggested_values_to_schema( _get_location_schema(self.hass), user_input ), errors=errors, description_placeholders=description_placeholders, ) async_step_user = async_step_location
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_air_quality/config_flow.py", "license": "Apache License 2.0", "lines": 194, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/google_air_quality/const.py
"""Constants for the Google Air Quality integration.""" from typing import Final DOMAIN = "google_air_quality" SECTION_API_KEY_OPTIONS: Final = "api_key_options" CONF_REFERRER: Final = "referrer"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_air_quality/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/google_air_quality/coordinator.py
"""Coordinator for fetching data from Google Air Quality API.""" from dataclasses import dataclass from datetime import timedelta import logging from typing import Final from google_air_quality_api.api import GoogleAirQualityApi from google_air_quality_api.exceptions import GoogleAirQualityApiError from google_air_quality_api.model import AirQualityCurrentConditionsData from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL: Final = timedelta(hours=1) type GoogleAirQualityConfigEntry = ConfigEntry[GoogleAirQualityRuntimeData] class GoogleAirQualityUpdateCoordinator( DataUpdateCoordinator[AirQualityCurrentConditionsData] ): """Coordinator for fetching Google AirQuality data.""" config_entry: GoogleAirQualityConfigEntry def __init__( self, hass: HomeAssistant, config_entry: GoogleAirQualityConfigEntry, subentry_id: str, client: GoogleAirQualityApi, ) -> None: """Initialize DataUpdateCoordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"{DOMAIN}_{subentry_id}", update_interval=UPDATE_INTERVAL, ) self.client = client subentry = config_entry.subentries[subentry_id] self.lat = subentry.data[CONF_LATITUDE] self.long = subentry.data[CONF_LONGITUDE] async def _async_update_data(self) -> AirQualityCurrentConditionsData: """Fetch air quality data for this coordinate.""" try: return await self.client.async_get_current_conditions(self.lat, self.long) except GoogleAirQualityApiError as ex: _LOGGER.debug("Cannot fetch air quality data: %s", str(ex)) raise UpdateFailed( translation_domain=DOMAIN, translation_key="unable_to_fetch", ) from ex @dataclass class GoogleAirQualityRuntimeData: """Runtime data for the Google Air Quality integration.""" api: GoogleAirQualityApi subentries_runtime_data: dict[str, GoogleAirQualityUpdateCoordinator]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_air_quality/coordinator.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/google_air_quality/sensor.py
"""Creates the sensor entities for Google Air Quality.""" from collections.abc import Callable from dataclasses import dataclass import logging from typing import TYPE_CHECKING from google_air_quality_api.model import AirQualityCurrentConditionsData, Index from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.config_entries import ConfigSubentry from homeassistant.const import ( CONCENTRATION_PARTS_PER_MILLION, CONF_LATITUDE, CONF_LONGITUDE, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import GoogleAirQualityConfigEntry from .const import DOMAIN from .coordinator import GoogleAirQualityUpdateCoordinator _LOGGER = logging.getLogger(__name__) # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 def _uaqi(data: AirQualityCurrentConditionsData) -> Index: if TYPE_CHECKING: assert data.indexes.uaqi is not None return data.indexes.uaqi def _laqi(data: AirQualityCurrentConditionsData) -> Index: if TYPE_CHECKING: assert data.indexes.laqi is not None return data.indexes.laqi @dataclass(frozen=True, kw_only=True) class AirQualitySensorEntityDescription(SensorEntityDescription): """Describes Air Quality sensor entity.""" exists_fn: Callable[[AirQualityCurrentConditionsData], bool] = lambda _: True options_fn: Callable[[AirQualityCurrentConditionsData], list[str] | None] = ( lambda _: None ) value_fn: Callable[[AirQualityCurrentConditionsData], StateType] native_unit_of_measurement_fn: Callable[ [AirQualityCurrentConditionsData], str | None ] = lambda _: None translation_placeholders_fn: ( Callable[[AirQualityCurrentConditionsData], dict[str, str]] | None ) = None AIR_QUALITY_SENSOR_TYPES: tuple[AirQualitySensorEntityDescription, ...] = ( AirQualitySensorEntityDescription( key="uaqi", translation_key="uaqi", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.AQI, value_fn=lambda x: _uaqi(x).aqi, ), AirQualitySensorEntityDescription( key="uaqi_category", translation_key="uaqi_category", device_class=SensorDeviceClass.ENUM, value_fn=lambda x: _uaqi(x).category, options_fn=lambda x: _uaqi(x).category_options, ), AirQualitySensorEntityDescription( key="local_aqi", translation_key="local_aqi", exists_fn=lambda x: _laqi(x).aqi is not None, state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.AQI, value_fn=lambda x: _laqi(x).aqi, translation_placeholders_fn=lambda x: {"local_aqi": _laqi(x).display_name}, ), AirQualitySensorEntityDescription( key="local_category", translation_key="local_category", device_class=SensorDeviceClass.ENUM, value_fn=lambda x: _laqi(x).category, options_fn=lambda x: _laqi(x).category_options, translation_placeholders_fn=lambda x: {"local_aqi": _laqi(x).display_name}, ), AirQualitySensorEntityDescription( key="uaqi_dominant_pollutant", translation_key="uaqi_dominant_pollutant", device_class=SensorDeviceClass.ENUM, value_fn=lambda x: _uaqi(x).dominant_pollutant, options_fn=lambda x: _uaqi(x).pollutant_options, ), AirQualitySensorEntityDescription( key="local_dominant_pollutant", translation_key="local_dominant_pollutant", device_class=SensorDeviceClass.ENUM, value_fn=lambda x: _laqi(x).dominant_pollutant, options_fn=lambda x: _laqi(x).pollutant_options, translation_placeholders_fn=lambda x: {"local_aqi": _laqi(x).display_name}, ), AirQualitySensorEntityDescription( key="c6h6", translation_key="benzene", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement_fn=lambda x: x.pollutants.c6h6.concentration.units, value_fn=lambda x: x.pollutants.c6h6.concentration.value, exists_fn=lambda x: "c6h6" in {p.code for p in x.pollutants}, ), AirQualitySensorEntityDescription( key="co", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.CO, native_unit_of_measurement_fn=lambda x: x.pollutants.co.concentration.units, exists_fn=lambda x: "co" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.co.concentration.value, suggested_unit_of_measurement=CONCENTRATION_PARTS_PER_MILLION, ), AirQualitySensorEntityDescription( key="nh3", translation_key="ammonia", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement_fn=lambda x: x.pollutants.nh3.concentration.units, value_fn=lambda x: x.pollutants.nh3.concentration.value, exists_fn=lambda x: "nh3" in {p.code for p in x.pollutants}, ), AirQualitySensorEntityDescription( key="nmhc", translation_key="non_methane_hydrocarbons", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement_fn=lambda x: x.pollutants.nmhc.concentration.units, value_fn=lambda x: x.pollutants.nmhc.concentration.value, exists_fn=lambda x: "nmhc" in {p.code for p in x.pollutants}, ), AirQualitySensorEntityDescription( key="no", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.NITROGEN_MONOXIDE, native_unit_of_measurement_fn=lambda x: x.pollutants.no.concentration.units, value_fn=lambda x: x.pollutants.no.concentration.value, exists_fn=lambda x: "no" in {p.code for p in x.pollutants}, ), AirQualitySensorEntityDescription( key="no2", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.NITROGEN_DIOXIDE, native_unit_of_measurement_fn=lambda x: x.pollutants.no2.concentration.units, exists_fn=lambda x: "no2" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.no2.concentration.value, ), AirQualitySensorEntityDescription( key="o3", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.OZONE, native_unit_of_measurement_fn=lambda x: x.pollutants.o3.concentration.units, exists_fn=lambda x: "o3" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.o3.concentration.value, ), AirQualitySensorEntityDescription( key="pm10", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.PM10, native_unit_of_measurement_fn=lambda x: x.pollutants.pm10.concentration.units, exists_fn=lambda x: "pm10" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.pm10.concentration.value, ), AirQualitySensorEntityDescription( key="pm25", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.PM25, native_unit_of_measurement_fn=lambda x: x.pollutants.pm25.concentration.units, exists_fn=lambda x: "pm25" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.pm25.concentration.value, ), AirQualitySensorEntityDescription( key="so2", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.SULPHUR_DIOXIDE, native_unit_of_measurement_fn=lambda x: x.pollutants.so2.concentration.units, exists_fn=lambda x: "so2" in {p.code for p in x.pollutants}, value_fn=lambda x: x.pollutants.so2.concentration.value, ), ) async def async_setup_entry( hass: HomeAssistant, entry: GoogleAirQualityConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up sensor platform.""" coordinators = entry.runtime_data.subentries_runtime_data for subentry_id, subentry in entry.subentries.items(): coordinator = coordinators[subentry_id] _LOGGER.debug("subentry.data: %s", subentry.data) async_add_entities( ( AirQualitySensorEntity(coordinator, description, subentry_id, subentry) for description in AIR_QUALITY_SENSOR_TYPES if description.exists_fn(coordinator.data) ), config_subentry_id=subentry_id, ) class AirQualitySensorEntity( CoordinatorEntity[GoogleAirQualityUpdateCoordinator], SensorEntity ): """Defining the Air Quality Sensors with AirQualitySensorEntityDescription.""" entity_description: AirQualitySensorEntityDescription _attr_attribution = "Data provided by Google Air Quality" _attr_has_entity_name = True def __init__( self, coordinator: GoogleAirQualityUpdateCoordinator, description: AirQualitySensorEntityDescription, subentry_id: str, subentry: ConfigSubentry, ) -> None: """Set up Air Quality Sensors.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{description.key}_{subentry.data[CONF_LATITUDE]}_{subentry.data[CONF_LONGITUDE]}" self._attr_device_info = DeviceInfo( identifiers={ (DOMAIN, f"{self.coordinator.config_entry.entry_id}_{subentry_id}") }, name=subentry.title, entry_type=DeviceEntryType.SERVICE, ) if description.translation_placeholders_fn: self._attr_translation_placeholders = ( description.translation_placeholders_fn(coordinator.data) ) @property def native_value(self) -> StateType: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data) @property def options(self) -> list[str] | None: """Return the option of the sensor.""" return self.entity_description.options_fn(self.coordinator.data) @property def native_unit_of_measurement(self) -> str | None: """Return the native unit of measurement of the sensor.""" return self.entity_description.native_unit_of_measurement_fn( self.coordinator.data )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_air_quality/sensor.py", "license": "Apache License 2.0", "lines": 241, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/google_weather/config_flow.py
"""Config flow for the Google Weather integration.""" from __future__ import annotations import logging from typing import Any from google_weather_api import GoogleWeatherApi, GoogleWeatherApiError import voluptuous as vol from homeassistant.config_entries import ( ConfigEntry, ConfigEntryState, ConfigFlow, ConfigFlowResult, ConfigSubentryFlow, SubentryFlowResult, ) from homeassistant.const import ( CONF_API_KEY, CONF_LATITUDE, CONF_LOCATION, CONF_LONGITUDE, CONF_NAME, ) from homeassistant.core import HomeAssistant, callback from homeassistant.data_entry_flow import section from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import LocationSelector, LocationSelectorConfig from .const import CONF_REFERRER, DOMAIN, SECTION_API_KEY_OPTIONS _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Optional(SECTION_API_KEY_OPTIONS): section( vol.Schema({vol.Optional(CONF_REFERRER): str}), {"collapsed": True} ), } ) async def _validate_input( user_input: dict[str, Any], api: GoogleWeatherApi, errors: dict[str, str], description_placeholders: dict[str, str], ) -> bool: try: await api.async_get_current_conditions( latitude=user_input[CONF_LOCATION][CONF_LATITUDE], longitude=user_input[CONF_LOCATION][CONF_LONGITUDE], ) except GoogleWeatherApiError as err: errors["base"] = "cannot_connect" description_placeholders["error_message"] = str(err) except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return True return False def _get_location_schema(hass: HomeAssistant) -> vol.Schema: """Return the schema for a location with default values from the hass config.""" return vol.Schema( { vol.Required(CONF_NAME, default=hass.config.location_name): str, vol.Required( CONF_LOCATION, default={ CONF_LATITUDE: hass.config.latitude, CONF_LONGITUDE: hass.config.longitude, }, ): LocationSelector(LocationSelectorConfig(radius=False)), } ) def _is_location_already_configured( hass: HomeAssistant, new_data: dict[str, float], epsilon: float = 1e-4 ) -> bool: """Check if the location is already configured.""" for entry in hass.config_entries.async_entries(DOMAIN): for subentry in entry.subentries.values(): # A more accurate way is to use the haversine formula, but for simplicity # we use a simple distance check. The epsilon value is small anyway. # This is mostly to capture cases where the user has slightly moved the location pin. if ( abs(subentry.data[CONF_LATITUDE] - new_data[CONF_LATITUDE]) <= epsilon and abs(subentry.data[CONF_LONGITUDE] - new_data[CONF_LONGITUDE]) <= epsilon ): return True return False class GoogleWeatherConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Google Weather.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} description_placeholders: dict[str, str] = { "api_key_url": "https://developers.google.com/maps/documentation/weather/get-api-key", "restricting_api_keys_url": "https://developers.google.com/maps/api-security-best-practices#restricting-api-keys", } if user_input is not None: api_key = user_input[CONF_API_KEY] referrer = user_input.get(SECTION_API_KEY_OPTIONS, {}).get(CONF_REFERRER) self._async_abort_entries_match({CONF_API_KEY: api_key}) if _is_location_already_configured(self.hass, user_input[CONF_LOCATION]): return self.async_abort(reason="already_configured") api = GoogleWeatherApi( session=async_get_clientsession(self.hass), api_key=api_key, referrer=referrer, language_code=self.hass.config.language, ) if await _validate_input(user_input, api, errors, description_placeholders): return self.async_create_entry( title="Google Weather", data={ CONF_API_KEY: api_key, CONF_REFERRER: referrer, }, subentries=[ { "subentry_type": "location", "data": user_input[CONF_LOCATION], "title": user_input[CONF_NAME], "unique_id": None, }, ], ) else: user_input = {} schema = STEP_USER_DATA_SCHEMA.schema.copy() schema.update(_get_location_schema(self.hass).schema) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( vol.Schema(schema), user_input ), errors=errors, description_placeholders=description_placeholders, ) @classmethod @callback def async_get_supported_subentry_types( cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by this integration.""" return {"location": LocationSubentryFlowHandler} class LocationSubentryFlowHandler(ConfigSubentryFlow): """Handle a subentry flow for location.""" async def async_step_location( self, user_input: dict[str, Any] | None = None, ) -> SubentryFlowResult: """Handle the location step.""" if self._get_entry().state != ConfigEntryState.LOADED: return self.async_abort(reason="entry_not_loaded") errors: dict[str, str] = {} description_placeholders: dict[str, str] = {} if user_input is not None: if _is_location_already_configured(self.hass, user_input[CONF_LOCATION]): return self.async_abort(reason="already_configured") api: GoogleWeatherApi = self._get_entry().runtime_data.api if await _validate_input(user_input, api, errors, description_placeholders): return self.async_create_entry( title=user_input[CONF_NAME], data=user_input[CONF_LOCATION], ) else: user_input = {} return self.async_show_form( step_id="location", data_schema=self.add_suggested_values_to_schema( _get_location_schema(self.hass), user_input ), errors=errors, description_placeholders=description_placeholders, ) async_step_user = async_step_location
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/config_flow.py", "license": "Apache License 2.0", "lines": 175, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/google_weather/const.py
"""Constants for the Google Weather integration.""" from typing import Final DOMAIN = "google_weather" SECTION_API_KEY_OPTIONS: Final = "api_key_options" CONF_REFERRER: Final = "referrer"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/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/google_weather/coordinator.py
"""The Google Weather coordinator.""" from __future__ import annotations from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import timedelta import logging from typing import TypeVar from google_weather_api import ( CurrentConditionsResponse, DailyForecastResponse, GoogleWeatherApi, GoogleWeatherApiError, HourlyForecastResponse, ) from homeassistant.config_entries import ConfigEntry, ConfigSubentry from homeassistant.const import CONF_LATITUDE, CONF_LONGITUDE from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import ( TimestampDataUpdateCoordinator, UpdateFailed, ) _LOGGER = logging.getLogger(__name__) T = TypeVar( "T", bound=( CurrentConditionsResponse | DailyForecastResponse | HourlyForecastResponse | None ), ) @dataclass class GoogleWeatherSubEntryRuntimeData: """Runtime data for a Google Weather sub-entry.""" coordinator_observation: GoogleWeatherCurrentConditionsCoordinator coordinator_daily_forecast: GoogleWeatherDailyForecastCoordinator coordinator_hourly_forecast: GoogleWeatherHourlyForecastCoordinator @dataclass class GoogleWeatherRuntimeData: """Runtime data for the Google Weather integration.""" api: GoogleWeatherApi subentries_runtime_data: dict[str, GoogleWeatherSubEntryRuntimeData] type GoogleWeatherConfigEntry = ConfigEntry[GoogleWeatherRuntimeData] class GoogleWeatherBaseCoordinator(TimestampDataUpdateCoordinator[T]): """Base class for Google Weather coordinators.""" config_entry: GoogleWeatherConfigEntry def __init__( self, hass: HomeAssistant, config_entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, data_type_name: str, update_interval: timedelta, api_method: Callable[..., Awaitable[T]], ) -> None: """Initialize the data updater.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"Google Weather {data_type_name} coordinator for {subentry.title}", update_interval=update_interval, ) self.subentry = subentry self._data_type_name = data_type_name self._api_method = api_method async def _async_update_data(self) -> T: """Fetch data from API and handle errors.""" try: return await self._api_method( self.subentry.data[CONF_LATITUDE], self.subentry.data[CONF_LONGITUDE], ) except GoogleWeatherApiError as err: _LOGGER.error( "Error fetching %s for %s: %s", self._data_type_name, self.subentry.title, err, ) raise UpdateFailed(f"Error fetching {self._data_type_name}") from err class GoogleWeatherCurrentConditionsCoordinator( GoogleWeatherBaseCoordinator[CurrentConditionsResponse] ): """Handle fetching current weather conditions.""" def __init__( self, hass: HomeAssistant, config_entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, api: GoogleWeatherApi, ) -> None: """Initialize the data updater.""" super().__init__( hass, config_entry, subentry, "current weather conditions", timedelta(minutes=15), api.async_get_current_conditions, ) class GoogleWeatherDailyForecastCoordinator( GoogleWeatherBaseCoordinator[DailyForecastResponse] ): """Handle fetching daily weather forecast.""" def __init__( self, hass: HomeAssistant, config_entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, api: GoogleWeatherApi, ) -> None: """Initialize the data updater.""" super().__init__( hass, config_entry, subentry, "daily weather forecast", timedelta(hours=1), api.async_get_daily_forecast, ) class GoogleWeatherHourlyForecastCoordinator( GoogleWeatherBaseCoordinator[HourlyForecastResponse] ): """Handle fetching hourly weather forecast.""" def __init__( self, hass: HomeAssistant, config_entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, api: GoogleWeatherApi, ) -> None: """Initialize the data updater.""" super().__init__( hass, config_entry, subentry, "hourly weather forecast", timedelta(hours=1), api.async_get_hourly_forecast, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/coordinator.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_weather/entity.py
"""Base entity for Google Weather.""" from __future__ import annotations from homeassistant.config_entries import ConfigSubentry from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity import Entity from .const import DOMAIN from .coordinator import GoogleWeatherConfigEntry class GoogleWeatherBaseEntity(Entity): """Base entity for all Google Weather entities.""" _attr_has_entity_name = True def __init__( self, config_entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, unique_id_suffix: str | None = None, ) -> None: """Initialize base entity.""" self._attr_unique_id = subentry.subentry_id if unique_id_suffix is not None: self._attr_unique_id += f"_{unique_id_suffix.lower()}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, subentry.subentry_id)}, name=subentry.title, manufacturer="Google", entry_type=DeviceEntryType.SERVICE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/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/google_weather/sensor.py
"""Support for Google Weather sensors.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from google_weather_api import CurrentConditionsResponse from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.config_entries import ConfigSubentry from homeassistant.const import ( DEGREE, PERCENTAGE, UV_INDEX, UnitOfLength, UnitOfPressure, UnitOfSpeed, UnitOfTemperature, UnitOfVolumetricFlux, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .coordinator import ( GoogleWeatherConfigEntry, GoogleWeatherCurrentConditionsCoordinator, ) from .entity import GoogleWeatherBaseEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class GoogleWeatherSensorDescription(SensorEntityDescription): """Class describing Google Weather sensor entities.""" value_fn: Callable[[CurrentConditionsResponse], str | int | float | None] SENSOR_TYPES: tuple[GoogleWeatherSensorDescription, ...] = ( GoogleWeatherSensorDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, value_fn=lambda data: data.temperature.degrees, ), GoogleWeatherSensorDescription( key="feelsLikeTemperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, value_fn=lambda data: data.feels_like_temperature.degrees, translation_key="apparent_temperature", ), GoogleWeatherSensorDescription( key="dewPoint", device_class=SensorDeviceClass.TEMPERATURE, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, value_fn=lambda data: data.dew_point.degrees, translation_key="dew_point", ), GoogleWeatherSensorDescription( key="heatIndex", device_class=SensorDeviceClass.TEMPERATURE, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, value_fn=lambda data: data.heat_index.degrees, translation_key="heat_index", ), GoogleWeatherSensorDescription( key="windChill", device_class=SensorDeviceClass.TEMPERATURE, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, value_fn=lambda data: data.wind_chill.degrees, translation_key="wind_chill", ), GoogleWeatherSensorDescription( key="relativeHumidity", device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, value_fn=lambda data: data.relative_humidity, ), GoogleWeatherSensorDescription( key="uvIndex", entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UV_INDEX, value_fn=lambda data: data.uv_index, translation_key="uv_index", ), GoogleWeatherSensorDescription( key="precipitation_probability", entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, value_fn=lambda data: data.precipitation.probability.percent, translation_key="precipitation_probability", ), GoogleWeatherSensorDescription( key="precipitation_qpf", device_class=SensorDeviceClass.PRECIPITATION_INTENSITY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfVolumetricFlux.MILLIMETERS_PER_HOUR, value_fn=lambda data: data.precipitation.qpf.quantity, ), GoogleWeatherSensorDescription( key="thunderstormProbability", entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, value_fn=lambda data: data.thunderstorm_probability, translation_key="thunderstorm_probability", ), GoogleWeatherSensorDescription( key="airPressure", device_class=SensorDeviceClass.ATMOSPHERIC_PRESSURE, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, native_unit_of_measurement=UnitOfPressure.HPA, value_fn=lambda data: data.air_pressure.mean_sea_level_millibars, ), GoogleWeatherSensorDescription( key="wind_direction", device_class=SensorDeviceClass.WIND_DIRECTION, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT_ANGLE, native_unit_of_measurement=DEGREE, value_fn=lambda data: data.wind.direction.degrees, ), GoogleWeatherSensorDescription( key="wind_speed", device_class=SensorDeviceClass.WIND_SPEED, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR, value_fn=lambda data: data.wind.speed.value, ), GoogleWeatherSensorDescription( key="wind_gust", device_class=SensorDeviceClass.WIND_SPEED, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR, value_fn=lambda data: data.wind.gust.value, translation_key="wind_gust_speed", ), GoogleWeatherSensorDescription( key="visibility", device_class=SensorDeviceClass.DISTANCE, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfLength.KILOMETERS, value_fn=lambda data: data.visibility.distance, translation_key="visibility", ), GoogleWeatherSensorDescription( key="cloudCover", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, value_fn=lambda data: data.cloud_cover, translation_key="cloud_coverage", ), GoogleWeatherSensorDescription( key="weatherCondition", entity_registry_enabled_default=False, value_fn=lambda data: data.weather_condition.description.text, translation_key="weather_condition", ), ) async def async_setup_entry( hass: HomeAssistant, entry: GoogleWeatherConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Add Google Weather entities from a config_entry.""" for subentry in entry.subentries.values(): subentry_runtime_data = entry.runtime_data.subentries_runtime_data[ subentry.subentry_id ] coordinator = subentry_runtime_data.coordinator_observation async_add_entities( ( GoogleWeatherSensor(coordinator, subentry, description) for description in SENSOR_TYPES if description.value_fn(coordinator.data) is not None ), config_subentry_id=subentry.subentry_id, ) class GoogleWeatherSensor( CoordinatorEntity[GoogleWeatherCurrentConditionsCoordinator], GoogleWeatherBaseEntity, SensorEntity, ): """Define a Google Weather entity.""" entity_description: GoogleWeatherSensorDescription def __init__( self, coordinator: GoogleWeatherCurrentConditionsCoordinator, subentry: ConfigSubentry, description: GoogleWeatherSensorDescription, ) -> None: """Initialize.""" super().__init__(coordinator) GoogleWeatherBaseEntity.__init__( self, coordinator.config_entry, subentry, description.key ) self.entity_description = description @property def native_value(self) -> str | int | float | None: """Return the state.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/sensor.py", "license": "Apache License 2.0", "lines": 215, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/google_weather/weather.py
"""Weather entity.""" from __future__ import annotations from google_weather_api import ( DailyForecastResponse, HourlyForecastResponse, WeatherCondition, ) from homeassistant.components.weather import ( ATTR_CONDITION_CLEAR_NIGHT, ATTR_CONDITION_CLOUDY, ATTR_CONDITION_HAIL, ATTR_CONDITION_LIGHTNING_RAINY, ATTR_CONDITION_PARTLYCLOUDY, ATTR_CONDITION_POURING, ATTR_CONDITION_RAINY, ATTR_CONDITION_SNOWY, ATTR_CONDITION_SNOWY_RAINY, ATTR_CONDITION_SUNNY, ATTR_CONDITION_WINDY, ATTR_FORECAST_CLOUD_COVERAGE, ATTR_FORECAST_CONDITION, ATTR_FORECAST_HUMIDITY, ATTR_FORECAST_IS_DAYTIME, ATTR_FORECAST_NATIVE_APPARENT_TEMP, ATTR_FORECAST_NATIVE_DEW_POINT, ATTR_FORECAST_NATIVE_PRECIPITATION, ATTR_FORECAST_NATIVE_PRESSURE, ATTR_FORECAST_NATIVE_TEMP, ATTR_FORECAST_NATIVE_TEMP_LOW, ATTR_FORECAST_NATIVE_WIND_GUST_SPEED, ATTR_FORECAST_NATIVE_WIND_SPEED, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TIME, ATTR_FORECAST_UV_INDEX, ATTR_FORECAST_WIND_BEARING, CoordinatorWeatherEntity, Forecast, WeatherEntityFeature, ) from homeassistant.config_entries import ConfigSubentry from homeassistant.const import ( UnitOfLength, UnitOfPrecipitationDepth, UnitOfPressure, UnitOfSpeed, UnitOfTemperature, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import ( GoogleWeatherConfigEntry, GoogleWeatherCurrentConditionsCoordinator, GoogleWeatherDailyForecastCoordinator, GoogleWeatherHourlyForecastCoordinator, ) from .entity import GoogleWeatherBaseEntity PARALLEL_UPDATES = 0 # Maps https://developers.google.com/maps/documentation/weather/weather-condition-icons # to https://developers.home-assistant.io/docs/core/entity/weather/#recommended-values-for-state-and-condition _CONDITION_MAP: dict[WeatherCondition.Type, str | None] = { WeatherCondition.Type.TYPE_UNSPECIFIED: None, WeatherCondition.Type.CLEAR: ATTR_CONDITION_SUNNY, WeatherCondition.Type.MOSTLY_CLEAR: ATTR_CONDITION_PARTLYCLOUDY, WeatherCondition.Type.PARTLY_CLOUDY: ATTR_CONDITION_PARTLYCLOUDY, WeatherCondition.Type.MOSTLY_CLOUDY: ATTR_CONDITION_CLOUDY, WeatherCondition.Type.CLOUDY: ATTR_CONDITION_CLOUDY, WeatherCondition.Type.WINDY: ATTR_CONDITION_WINDY, WeatherCondition.Type.WIND_AND_RAIN: ATTR_CONDITION_RAINY, WeatherCondition.Type.LIGHT_RAIN_SHOWERS: ATTR_CONDITION_RAINY, WeatherCondition.Type.CHANCE_OF_SHOWERS: ATTR_CONDITION_RAINY, WeatherCondition.Type.SCATTERED_SHOWERS: ATTR_CONDITION_RAINY, WeatherCondition.Type.RAIN_SHOWERS: ATTR_CONDITION_RAINY, WeatherCondition.Type.HEAVY_RAIN_SHOWERS: ATTR_CONDITION_POURING, WeatherCondition.Type.LIGHT_TO_MODERATE_RAIN: ATTR_CONDITION_RAINY, WeatherCondition.Type.MODERATE_TO_HEAVY_RAIN: ATTR_CONDITION_POURING, WeatherCondition.Type.RAIN: ATTR_CONDITION_RAINY, WeatherCondition.Type.LIGHT_RAIN: ATTR_CONDITION_RAINY, WeatherCondition.Type.HEAVY_RAIN: ATTR_CONDITION_POURING, WeatherCondition.Type.RAIN_PERIODICALLY_HEAVY: ATTR_CONDITION_POURING, WeatherCondition.Type.LIGHT_SNOW_SHOWERS: ATTR_CONDITION_SNOWY, WeatherCondition.Type.CHANCE_OF_SNOW_SHOWERS: ATTR_CONDITION_SNOWY, WeatherCondition.Type.SCATTERED_SNOW_SHOWERS: ATTR_CONDITION_SNOWY, WeatherCondition.Type.SNOW_SHOWERS: ATTR_CONDITION_SNOWY, WeatherCondition.Type.HEAVY_SNOW_SHOWERS: ATTR_CONDITION_SNOWY, WeatherCondition.Type.LIGHT_TO_MODERATE_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.MODERATE_TO_HEAVY_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.LIGHT_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.HEAVY_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.SNOWSTORM: ATTR_CONDITION_SNOWY, WeatherCondition.Type.SNOW_PERIODICALLY_HEAVY: ATTR_CONDITION_SNOWY, WeatherCondition.Type.HEAVY_SNOW_STORM: ATTR_CONDITION_SNOWY, WeatherCondition.Type.BLOWING_SNOW: ATTR_CONDITION_SNOWY, WeatherCondition.Type.RAIN_AND_SNOW: ATTR_CONDITION_SNOWY_RAINY, WeatherCondition.Type.HAIL: ATTR_CONDITION_HAIL, WeatherCondition.Type.HAIL_SHOWERS: ATTR_CONDITION_HAIL, WeatherCondition.Type.THUNDERSTORM: ATTR_CONDITION_LIGHTNING_RAINY, WeatherCondition.Type.THUNDERSHOWER: ATTR_CONDITION_LIGHTNING_RAINY, WeatherCondition.Type.LIGHT_THUNDERSTORM_RAIN: ATTR_CONDITION_LIGHTNING_RAINY, WeatherCondition.Type.SCATTERED_THUNDERSTORMS: ATTR_CONDITION_LIGHTNING_RAINY, WeatherCondition.Type.HEAVY_THUNDERSTORM: ATTR_CONDITION_LIGHTNING_RAINY, } def _get_condition( api_condition: WeatherCondition.Type, is_daytime: bool ) -> str | None: """Map Google Weather condition to Home Assistant condition.""" cond = _CONDITION_MAP[api_condition] if cond == ATTR_CONDITION_SUNNY and not is_daytime: return ATTR_CONDITION_CLEAR_NIGHT return cond async def async_setup_entry( hass: HomeAssistant, entry: GoogleWeatherConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Add a weather entity from a config_entry.""" for subentry in entry.subentries.values(): async_add_entities( [GoogleWeatherEntity(entry, subentry)], config_subentry_id=subentry.subentry_id, ) class GoogleWeatherEntity( CoordinatorWeatherEntity[ GoogleWeatherCurrentConditionsCoordinator, GoogleWeatherDailyForecastCoordinator, GoogleWeatherHourlyForecastCoordinator, GoogleWeatherDailyForecastCoordinator, ], GoogleWeatherBaseEntity, ): """Representation of a Google Weather entity.""" _attr_attribution = "Data from Google Weather" _attr_native_temperature_unit = UnitOfTemperature.CELSIUS _attr_native_pressure_unit = UnitOfPressure.MBAR _attr_native_wind_speed_unit = UnitOfSpeed.KILOMETERS_PER_HOUR _attr_native_visibility_unit = UnitOfLength.KILOMETERS _attr_native_precipitation_unit = UnitOfPrecipitationDepth.MILLIMETERS _attr_name = None _attr_supported_features = ( WeatherEntityFeature.FORECAST_DAILY | WeatherEntityFeature.FORECAST_HOURLY | WeatherEntityFeature.FORECAST_TWICE_DAILY ) def __init__( self, entry: GoogleWeatherConfigEntry, subentry: ConfigSubentry, ) -> None: """Initialize the weather entity.""" subentry_runtime_data = entry.runtime_data.subentries_runtime_data[ subentry.subentry_id ] super().__init__( observation_coordinator=subentry_runtime_data.coordinator_observation, daily_coordinator=subentry_runtime_data.coordinator_daily_forecast, hourly_coordinator=subentry_runtime_data.coordinator_hourly_forecast, twice_daily_coordinator=subentry_runtime_data.coordinator_daily_forecast, ) GoogleWeatherBaseEntity.__init__(self, entry, subentry) @property def condition(self) -> str | None: """Return the current condition.""" return _get_condition( self.coordinator.data.weather_condition.type, self.coordinator.data.is_daytime, ) @property def native_temperature(self) -> float: """Return the temperature.""" return self.coordinator.data.temperature.degrees @property def native_apparent_temperature(self) -> float: """Return the apparent temperature.""" return self.coordinator.data.feels_like_temperature.degrees @property def native_dew_point(self) -> float: """Return the dew point.""" return self.coordinator.data.dew_point.degrees @property def humidity(self) -> int: """Return the humidity.""" return self.coordinator.data.relative_humidity @property def uv_index(self) -> float: """Return the UV index.""" return float(self.coordinator.data.uv_index) @property def native_pressure(self) -> float: """Return the pressure.""" return self.coordinator.data.air_pressure.mean_sea_level_millibars @property def native_wind_gust_speed(self) -> float: """Return the wind gust speed.""" return self.coordinator.data.wind.gust.value @property def native_wind_speed(self) -> float: """Return the wind speed.""" return self.coordinator.data.wind.speed.value @property def wind_bearing(self) -> int: """Return the wind bearing.""" return self.coordinator.data.wind.direction.degrees @property def native_visibility(self) -> float: """Return the visibility.""" return self.coordinator.data.visibility.distance @property def cloud_coverage(self) -> float: """Return the Cloud coverage in %.""" return float(self.coordinator.data.cloud_cover) @callback def _async_forecast_daily(self) -> list[Forecast] | None: """Return the daily forecast in native units.""" coordinator = self.forecast_coordinators["daily"] assert coordinator daily_data = coordinator.data assert isinstance(daily_data, DailyForecastResponse) return [ { ATTR_FORECAST_CONDITION: _get_condition( item.daytime_forecast.weather_condition.type, is_daytime=True ), ATTR_FORECAST_TIME: item.interval.start_time, ATTR_FORECAST_HUMIDITY: item.daytime_forecast.relative_humidity, ATTR_FORECAST_PRECIPITATION_PROBABILITY: max( item.daytime_forecast.precipitation.probability.percent, item.nighttime_forecast.precipitation.probability.percent, ), ATTR_FORECAST_CLOUD_COVERAGE: item.daytime_forecast.cloud_cover, ATTR_FORECAST_NATIVE_PRECIPITATION: ( item.daytime_forecast.precipitation.qpf.quantity + item.nighttime_forecast.precipitation.qpf.quantity ), ATTR_FORECAST_NATIVE_TEMP: item.max_temperature.degrees, ATTR_FORECAST_NATIVE_TEMP_LOW: item.min_temperature.degrees, ATTR_FORECAST_NATIVE_APPARENT_TEMP: ( item.feels_like_max_temperature.degrees ), ATTR_FORECAST_WIND_BEARING: item.daytime_forecast.wind.direction.degrees, ATTR_FORECAST_NATIVE_WIND_GUST_SPEED: max( item.daytime_forecast.wind.gust.value, item.nighttime_forecast.wind.gust.value, ), ATTR_FORECAST_NATIVE_WIND_SPEED: max( item.daytime_forecast.wind.speed.value, item.nighttime_forecast.wind.speed.value, ), ATTR_FORECAST_UV_INDEX: item.daytime_forecast.uv_index, } for item in daily_data.forecast_days ] @callback def _async_forecast_hourly(self) -> list[Forecast] | None: """Return the hourly forecast in native units.""" coordinator = self.forecast_coordinators["hourly"] assert coordinator hourly_data = coordinator.data assert isinstance(hourly_data, HourlyForecastResponse) return [ { ATTR_FORECAST_CONDITION: _get_condition( item.weather_condition.type, item.is_daytime ), ATTR_FORECAST_TIME: item.interval.start_time, ATTR_FORECAST_HUMIDITY: item.relative_humidity, ATTR_FORECAST_PRECIPITATION_PROBABILITY: item.precipitation.probability.percent, ATTR_FORECAST_CLOUD_COVERAGE: item.cloud_cover, ATTR_FORECAST_NATIVE_PRECIPITATION: item.precipitation.qpf.quantity, ATTR_FORECAST_NATIVE_PRESSURE: item.air_pressure.mean_sea_level_millibars, ATTR_FORECAST_NATIVE_TEMP: item.temperature.degrees, ATTR_FORECAST_NATIVE_APPARENT_TEMP: item.feels_like_temperature.degrees, ATTR_FORECAST_WIND_BEARING: item.wind.direction.degrees, ATTR_FORECAST_NATIVE_WIND_GUST_SPEED: item.wind.gust.value, ATTR_FORECAST_NATIVE_WIND_SPEED: item.wind.speed.value, ATTR_FORECAST_NATIVE_DEW_POINT: item.dew_point.degrees, ATTR_FORECAST_UV_INDEX: item.uv_index, ATTR_FORECAST_IS_DAYTIME: item.is_daytime, } for item in hourly_data.forecast_hours ] @callback def _async_forecast_twice_daily(self) -> list[Forecast] | None: """Return the twice daily forecast in native units.""" coordinator = self.forecast_coordinators["twice_daily"] assert coordinator daily_data = coordinator.data assert isinstance(daily_data, DailyForecastResponse) forecasts: list[Forecast] = [] for item in daily_data.forecast_days: # Process daytime forecast day_forecast = item.daytime_forecast forecasts.append( { ATTR_FORECAST_CONDITION: _get_condition( day_forecast.weather_condition.type, is_daytime=True ), ATTR_FORECAST_TIME: day_forecast.interval.start_time, ATTR_FORECAST_HUMIDITY: day_forecast.relative_humidity, ATTR_FORECAST_PRECIPITATION_PROBABILITY: day_forecast.precipitation.probability.percent, ATTR_FORECAST_CLOUD_COVERAGE: day_forecast.cloud_cover, ATTR_FORECAST_NATIVE_PRECIPITATION: day_forecast.precipitation.qpf.quantity, ATTR_FORECAST_NATIVE_TEMP: item.max_temperature.degrees, ATTR_FORECAST_NATIVE_APPARENT_TEMP: item.feels_like_max_temperature.degrees, ATTR_FORECAST_WIND_BEARING: day_forecast.wind.direction.degrees, ATTR_FORECAST_NATIVE_WIND_GUST_SPEED: day_forecast.wind.gust.value, ATTR_FORECAST_NATIVE_WIND_SPEED: day_forecast.wind.speed.value, ATTR_FORECAST_UV_INDEX: day_forecast.uv_index, ATTR_FORECAST_IS_DAYTIME: True, } ) # Process nighttime forecast night_forecast = item.nighttime_forecast forecasts.append( { ATTR_FORECAST_CONDITION: _get_condition( night_forecast.weather_condition.type, is_daytime=False ), ATTR_FORECAST_TIME: night_forecast.interval.start_time, ATTR_FORECAST_HUMIDITY: night_forecast.relative_humidity, ATTR_FORECAST_PRECIPITATION_PROBABILITY: night_forecast.precipitation.probability.percent, ATTR_FORECAST_CLOUD_COVERAGE: night_forecast.cloud_cover, ATTR_FORECAST_NATIVE_PRECIPITATION: night_forecast.precipitation.qpf.quantity, ATTR_FORECAST_NATIVE_TEMP: item.min_temperature.degrees, ATTR_FORECAST_NATIVE_APPARENT_TEMP: item.feels_like_min_temperature.degrees, ATTR_FORECAST_WIND_BEARING: night_forecast.wind.direction.degrees, ATTR_FORECAST_NATIVE_WIND_GUST_SPEED: night_forecast.wind.gust.value, ATTR_FORECAST_NATIVE_WIND_SPEED: night_forecast.wind.speed.value, ATTR_FORECAST_UV_INDEX: night_forecast.uv_index, ATTR_FORECAST_IS_DAYTIME: False, } ) return forecasts
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_weather/weather.py", "license": "Apache License 2.0", "lines": 332, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hanna/config_flow.py
"""Config flow for Hanna Instruments integration.""" from __future__ import annotations import logging from typing import Any from hanna_cloud import AuthenticationError, HannaCloudClient from requests.exceptions import ConnectionError as RequestsConnectionError, Timeout import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from .const import DOMAIN _LOGGER = logging.getLogger(__name__) class HannaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Hanna Instruments.""" VERSION = 1 data_schema = vol.Schema( {vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str} ) async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the setup flow.""" errors: dict[str, str] = {} if user_input is not None: await self.async_set_unique_id(user_input[CONF_EMAIL]) self._abort_if_unique_id_configured() client = HannaCloudClient() try: await self.hass.async_add_executor_job( client.authenticate, user_input[CONF_EMAIL], user_input[CONF_PASSWORD], ) except Timeout, RequestsConnectionError: errors["base"] = "cannot_connect" except AuthenticationError: errors["base"] = "invalid_auth" if not errors: return self.async_create_entry( title=user_input[CONF_EMAIL], data=user_input, ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( self.data_schema, user_input ), errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hanna/config_flow.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/hanna/coordinator.py
"""Hanna Instruments data coordinator for Home Assistant. This module provides the data coordinator for fetching and managing Hanna Instruments sensor data. """ from datetime import timedelta import logging from typing import Any from hanna_cloud import HannaCloudClient from requests.exceptions import RequestException from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN type HannaConfigEntry = ConfigEntry[dict[str, HannaDataCoordinator]] _LOGGER = logging.getLogger(__name__) class HannaDataCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Coordinator for fetching Hanna sensor data.""" def __init__( self, hass: HomeAssistant, config_entry: HannaConfigEntry, device: dict[str, Any], api_client: HannaCloudClient, ) -> None: """Initialize the Hanna data coordinator.""" self.api_client = api_client self.device_data = device super().__init__( hass, _LOGGER, name=f"{DOMAIN}_{self.device_identifier}", config_entry=config_entry, update_interval=timedelta(seconds=30), ) @property def device_identifier(self) -> str: """Return the device identifier.""" return self.device_data["DID"] def get_parameters(self) -> list[dict[str, Any]]: """Get all parameters from the sensor data.""" return self.api_client.parameters def get_parameter_value(self, key: str) -> Any: """Get the value for a specific parameter.""" for parameter in self.get_parameters(): if parameter["name"] == key: return parameter["value"] return None async def _async_update_data(self) -> dict[str, Any]: """Fetch latest sensor data from the Hanna API.""" try: readings = await self.hass.async_add_executor_job( self.api_client.get_last_device_reading, self.device_identifier ) except RequestException as e: raise UpdateFailed(f"Error communicating with Hanna API: {e}") from e except (KeyError, IndexError) as e: raise UpdateFailed(f"Error parsing Hanna API response: {e}") from e return readings
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hanna/coordinator.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hanna/entity.py
"""Hanna Instruments entity base class for Home Assistant. This module provides the base entity class for Hanna Instruments entities. """ from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import HannaDataCoordinator class HannaEntity(CoordinatorEntity[HannaDataCoordinator]): """Base class for Hanna entities.""" _attr_has_entity_name = True def __init__(self, coordinator: HannaDataCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.device_identifier)}, manufacturer=coordinator.device_data.get("manufacturer"), model=coordinator.device_data.get("DM"), name=coordinator.device_data.get("name"), serial_number=coordinator.device_data.get("serial_number"), sw_version=coordinator.device_data.get("sw_version"), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hanna/entity.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hanna/sensor.py
"""Hanna Instruments sensor integration for Home Assistant. This module provides sensor entities for various Hanna Instruments devices, including pH, ORP, temperature, and chemical sensors. It uses the Hanna API to fetch readings and updates them periodically. """ from __future__ import annotations import logging from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfElectricPotential, UnitOfTemperature, UnitOfVolume from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .coordinator import HannaConfigEntry, HannaDataCoordinator from .entity import HannaEntity _LOGGER = logging.getLogger(__name__) SENSOR_DESCRIPTIONS = [ SensorEntityDescription( key="ph", translation_key="ph_value", device_class=SensorDeviceClass.PH, state_class=SensorStateClass.MEASUREMENT, ), SensorEntityDescription( key="orp", translation_key="chlorine_orp_value", device_class=SensorDeviceClass.VOLTAGE, native_unit_of_measurement=UnitOfElectricPotential.MILLIVOLT, state_class=SensorStateClass.MEASUREMENT, ), SensorEntityDescription( key="temp", translation_key="water_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, ), SensorEntityDescription( key="airTemp", translation_key="air_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, ), SensorEntityDescription( key="acidBase", translation_key="ph_acid_base_flow_rate", icon="mdi:chemical-weapon", device_class=SensorDeviceClass.VOLUME, native_unit_of_measurement=UnitOfVolume.MILLILITERS, state_class=SensorStateClass.MEASUREMENT, ), SensorEntityDescription( key="cl", translation_key="chlorine_flow_rate", icon="mdi:chemical-weapon", device_class=SensorDeviceClass.VOLUME, native_unit_of_measurement=UnitOfVolume.MILLILITERS, state_class=SensorStateClass.MEASUREMENT, ), ] async def async_setup_entry( hass: HomeAssistant, entry: HannaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Hanna sensors from a config entry.""" device_coordinators = entry.runtime_data async_add_entities( HannaSensor(coordinator, description) for description in SENSOR_DESCRIPTIONS for coordinator in device_coordinators.values() ) class HannaSensor(HannaEntity, SensorEntity): """Representation of a Hanna sensor.""" def __init__( self, coordinator: HannaDataCoordinator, description: SensorEntityDescription, ) -> None: """Initialize a Hanna sensor.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.device_identifier}_{description.key}" self.entity_description = description @property def native_value(self) -> StateType: """Return the value reported by the sensor.""" return self.coordinator.get_parameter_value(self.entity_description.key)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hanna/sensor.py", "license": "Apache License 2.0", "lines": 92, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hue_ble/config_flow.py
"""Config flow for Hue BLE integration.""" from __future__ import annotations from enum import Enum import logging from typing import Any from bleak.backends.scanner import AdvertisementData from HueBLE import ConnectionError, HueBleError, HueBleLight, PairingError import voluptuous as vol from homeassistant.components import bluetooth from homeassistant.components.bluetooth.api import ( async_ble_device_from_address, async_scanner_count, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_MAC, CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr from .const import DOMAIN, URL_FACTORY_RESET, URL_PAIRING_MODE from .light import get_available_color_modes _LOGGER = logging.getLogger(__name__) SERVICE_UUID = SERVICE_DATA_UUID = "0000fe0f-0000-1000-8000-00805f9b34fb" def device_filter(advertisement_data: AdvertisementData) -> bool: """Return True if the device is supported.""" return ( SERVICE_UUID in advertisement_data.service_uuids and SERVICE_DATA_UUID in advertisement_data.service_data ) async def validate_input(hass: HomeAssistant, address: str) -> Error | None: """Return error if cannot connect and validate.""" ble_device = async_ble_device_from_address(hass, address.upper(), connectable=True) if ble_device is None: count_scanners = async_scanner_count(hass, connectable=True) _LOGGER.debug("Count of BLE scanners in HA bt: %i", count_scanners) if count_scanners < 1: return Error.NO_SCANNERS return Error.NOT_FOUND try: light = HueBleLight(ble_device) await light.connect() get_available_color_modes(light) await light.poll_state() except ConnectionError as e: _LOGGER.exception("Error connecting to light") return ( Error.INVALID_AUTH if type(e.__cause__) is PairingError else Error.CANNOT_CONNECT ) except HueBleError: _LOGGER.exception("Unexpected error validating light connection") return Error.UNKNOWN except HomeAssistantError: return Error.NOT_SUPPORTED else: return None finally: await light.disconnect() class HueBleConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Hue BLE.""" VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._discovered_devices: dict[str, bluetooth.BluetoothServiceInfoBleak] = {} self._discovery_info: bluetooth.BluetoothServiceInfoBleak | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the user step to pick discovered device.""" errors: dict[str, str] = {} if user_input is not None: unique_id = dr.format_mac(user_input[CONF_MAC]) # Don't raise on progress because there may be discovery flows await self.async_set_unique_id(unique_id, raise_on_progress=False) # Guard against the user selecting a device which has been configured by # another flow. self._abort_if_unique_id_configured() self._discovery_info = self._discovered_devices[user_input[CONF_MAC]] return await self.async_step_confirm() current_addresses = self._async_current_ids(include_ignore=False) for discovery in bluetooth.async_discovered_service_info(self.hass): if ( discovery.address in current_addresses or discovery.address in self._discovered_devices or not device_filter(discovery.advertisement) ): continue self._discovered_devices[discovery.address] = discovery if not self._discovered_devices: return self.async_abort(reason="no_devices_found") data_schema = vol.Schema( { vol.Required(CONF_MAC): vol.In( { service_info.address: ( f"{service_info.name} ({service_info.address})" ) for service_info in self._discovered_devices.values() } ), } ) return self.async_show_form( step_id="user", data_schema=data_schema, errors=errors, ) async def async_step_bluetooth( self, discovery_info: bluetooth.BluetoothServiceInfoBleak ) -> ConfigFlowResult: """Handle a flow initialized by the home assistant scanner.""" _LOGGER.debug( "HA found light %s. Use user flow to show in UI and connect", discovery_info.name, ) return self.async_abort(reason="discovery_unsupported") async def async_step_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm a single device.""" assert self._discovery_info is not None errors: dict[str, str] = {} if user_input is not None: unique_id = dr.format_mac(self._discovery_info.address) # Don't raise on progress because there may be discovery flows await self.async_set_unique_id(unique_id, raise_on_progress=False) # Guard against the user selecting a device which has been configured by # another flow. self._abort_if_unique_id_configured() error = await validate_input(self.hass, unique_id) if error: errors["base"] = error.value else: return self.async_create_entry(title=self._discovery_info.name, data={}) return self.async_show_form( step_id="confirm", data_schema=vol.Schema({}), errors=errors, description_placeholders={ CONF_NAME: self._discovery_info.name, CONF_MAC: self._discovery_info.address, "url_pairing_mode": URL_PAIRING_MODE, "url_factory_reset": URL_FACTORY_RESET, }, ) class Error(Enum): """Potential validation errors when attempting to connect.""" CANNOT_CONNECT = "cannot_connect" """Error to indicate we cannot connect.""" INVALID_AUTH = "invalid_auth" """Error to indicate there is invalid auth.""" NO_SCANNERS = "no_scanners" """Error to indicate no bluetooth scanners are available.""" NOT_FOUND = "not_found" """Error to indicate the light could not be found.""" NOT_SUPPORTED = "not_supported" """Error to indicate that the light is not a supported model.""" UNKNOWN = "unknown" """Error to indicate that the issue is unknown."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hue_ble/config_flow.py", "license": "Apache License 2.0", "lines": 159, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/hue_ble/light.py
"""Hue BLE light platform.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from HueBLE import HueBleLight from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, ATTR_XY_COLOR, ColorMode, LightEntity, filter_supported_color_modes, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import color as color_util _LOGGER = logging.getLogger(__name__) if TYPE_CHECKING: from . import HueBLEConfigEntry async def async_setup_entry( hass: HomeAssistant, config_entry: HueBLEConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Add light for passed config_entry in HA.""" light = config_entry.runtime_data async_add_entities([HueBLELight(light)]) def get_available_color_modes(api: HueBleLight) -> set[ColorMode]: """Return a set of available color modes.""" color_modes = set() if api.supports_colour_xy: color_modes.add(ColorMode.XY) if api.supports_colour_temp: color_modes.add(ColorMode.COLOR_TEMP) if api.supports_brightness: color_modes.add(ColorMode.BRIGHTNESS) if api.supports_on_off: color_modes.add(ColorMode.ONOFF) return filter_supported_color_modes(color_modes) class HueBLELight(LightEntity): """Representation of a light.""" _attr_has_entity_name = True _attr_name = None def __init__(self, light: HueBleLight) -> None: """Initialize the light object. Does not connect.""" self._api = light self._attr_unique_id = light.address if light.maximum_mireds: self._attr_min_color_temp_kelvin = ( color_util.color_temperature_mired_to_kelvin(light.maximum_mireds) ) if light.minimum_mireds: self._attr_max_color_temp_kelvin = ( color_util.color_temperature_mired_to_kelvin(light.minimum_mireds) ) self._attr_device_info = DeviceInfo( name=light.name, connections={(CONNECTION_BLUETOOTH, light.address)}, manufacturer=light.manufacturer, model_id=light.model, sw_version=light.firmware, ) self._attr_supported_color_modes = get_available_color_modes(self._api) self._update_updatable_attributes() async def async_added_to_hass(self) -> None: """Run when this Entity has been added to HA.""" self._api.add_callback_on_state_changed(self._state_change_callback) async def async_will_remove_from_hass(self) -> None: """Run when entity will be removed from HA.""" self._api.remove_callback(self._state_change_callback) def _update_updatable_attributes(self) -> None: """Update this entities updatable attrs from the lights state.""" self._attr_available = self._api.available self._attr_is_on = self._api.power_state self._attr_brightness = self._api.brightness self._attr_color_temp_kelvin = ( color_util.color_temperature_mired_to_kelvin(self._api.colour_temp) if self._api.colour_temp is not None and self._api.colour_temp != 0 else None ) self._attr_xy_color = self._api.colour_xy def _state_change_callback(self) -> None: """Run when light informs of state update. Updates local properties.""" _LOGGER.debug("Received state notification from light %s", self.name) self._update_updatable_attributes() self.async_write_ha_state() async def async_update(self) -> None: """Fetch latest state from light and make available via properties.""" await self._api.poll_state() async def async_turn_on(self, **kwargs: Any) -> None: """Set properties then turn the light on.""" _LOGGER.debug("Turning light %s on with args %s", self.name, kwargs) if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] _LOGGER.debug("Setting brightness of %s to %s", self.name, brightness) await self._api.set_brightness(brightness) if ATTR_COLOR_TEMP_KELVIN in kwargs: color_temp_kelvin = kwargs[ATTR_COLOR_TEMP_KELVIN] mireds = color_util.color_temperature_kelvin_to_mired(color_temp_kelvin) _LOGGER.debug("Setting color temp of %s to %s", self.name, mireds) await self._api.set_colour_temp(mireds) if ATTR_XY_COLOR in kwargs: xy_color = kwargs[ATTR_XY_COLOR] _LOGGER.debug("Setting XY color of %s to %s", self.name, xy_color) await self._api.set_colour_xy(xy_color[0], xy_color[1]) await self._api.set_power(True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn light off then set properties.""" _LOGGER.debug("Turning light %s off with args %s", self.name, kwargs) await self._api.set_power(False) @property def color_mode(self) -> ColorMode: """Color mode of the light.""" if self._api.supports_colour_xy and not self._api.colour_temp_mode: return ColorMode.XY if self._api.colour_temp_mode: return ColorMode.COLOR_TEMP if self._api.supports_brightness: return ColorMode.BRIGHTNESS return ColorMode.ONOFF
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hue_ble/light.py", "license": "Apache License 2.0", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/labs/const.py
"""Constants for the Home Assistant Labs integration.""" from __future__ import annotations from homeassistant.util.hass_dict import HassKey from .models import LabsData DOMAIN = "labs" STORAGE_KEY = "core.labs" STORAGE_VERSION = 1 LABS_DATA: HassKey[LabsData] = HassKey(DOMAIN)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/labs/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/labs/models.py
"""Data models for the Home Assistant Labs integration.""" from __future__ import annotations from dataclasses import dataclass, field from typing import TYPE_CHECKING, Self, TypedDict if TYPE_CHECKING: from homeassistant.helpers.storage import Store class EventLabsUpdatedData(TypedDict): """Event data for labs_updated event.""" domain: str preview_feature: str enabled: bool @dataclass(frozen=True, kw_only=True, slots=True) class LabPreviewFeature: """Lab preview feature definition.""" domain: str preview_feature: str is_built_in: bool = True feedback_url: str | None = None learn_more_url: str | None = None report_issue_url: str | None = None @property def full_key(self) -> str: """Return the full key for the preview feature (domain.preview_feature).""" return f"{self.domain}.{self.preview_feature}" def to_dict(self, *, enabled: bool) -> dict[str, str | bool | None]: """Return a serialized version of the preview feature.""" return { "preview_feature": self.preview_feature, "domain": self.domain, "enabled": enabled, "is_built_in": self.is_built_in, "feedback_url": self.feedback_url, "learn_more_url": self.learn_more_url, "report_issue_url": self.report_issue_url, } @dataclass(kw_only=True) class LabsStoreData: """Storage data for Labs.""" preview_feature_status: set[tuple[str, str]] @classmethod def from_store_format(cls, data: NativeLabsStoreData | None) -> Self: """Initialize from storage format.""" if data is None: return cls(preview_feature_status=set()) return cls( preview_feature_status={ (item["domain"], item["preview_feature"]) for item in data["preview_feature_status"] } ) def to_store_format(self) -> NativeLabsStoreData: """Convert to storage format.""" return { "preview_feature_status": [ {"domain": domain, "preview_feature": preview_feature} for domain, preview_feature in self.preview_feature_status ] } class NativeLabsStoreData(TypedDict): """Storage data for Labs.""" preview_feature_status: list[NativeLabsStoredFeature] class NativeLabsStoredFeature(TypedDict): """A single preview feature entry in storage format.""" domain: str preview_feature: str @dataclass class LabsData: """Storage class for Labs global data.""" store: Store[NativeLabsStoreData] data: LabsStoreData preview_features: dict[str, LabPreviewFeature] = field(default_factory=dict)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/labs/models.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/labs/websocket_api.py
"""Websocket API for the Home Assistant Labs integration.""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.components import websocket_api from homeassistant.components.backup import async_get_manager from homeassistant.core import HomeAssistant, callback from .const import LABS_DATA from .helpers import ( async_is_preview_feature_enabled, async_subscribe_preview_feature, async_update_preview_feature, ) from .models import EventLabsUpdatedData @callback def async_setup(hass: HomeAssistant) -> None: """Set up the number websocket API.""" websocket_api.async_register_command(hass, websocket_list_preview_features) websocket_api.async_register_command(hass, websocket_update_preview_feature) websocket_api.async_register_command(hass, websocket_subscribe_feature) @callback @websocket_api.require_admin @websocket_api.websocket_command({vol.Required("type"): "labs/list"}) def websocket_list_preview_features( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """List all lab preview features filtered by loaded integrations.""" labs_data = hass.data[LABS_DATA] loaded_components = hass.config.components preview_features: list[dict[str, Any]] = [ preview_feature.to_dict( enabled=(preview_feature.domain, preview_feature.preview_feature) in labs_data.data.preview_feature_status ) for preview_feature in labs_data.preview_features.values() if preview_feature.domain in loaded_components ] connection.send_result(msg["id"], {"features": preview_features}) @websocket_api.require_admin @websocket_api.websocket_command( { vol.Required("type"): "labs/update", vol.Required("domain"): str, vol.Required("preview_feature"): str, vol.Required("enabled"): bool, vol.Optional("create_backup", default=False): bool, } ) @websocket_api.async_response async def websocket_update_preview_feature( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Update a lab preview feature state.""" domain = msg["domain"] preview_feature = msg["preview_feature"] enabled = msg["enabled"] create_backup = msg["create_backup"] labs_data = hass.data[LABS_DATA] preview_feature_id = f"{domain}.{preview_feature}" if preview_feature_id not in labs_data.preview_features: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, f"Preview feature {preview_feature_id} not found", ) return # Create backup if requested and enabled if create_backup and enabled: try: backup_manager = async_get_manager(hass) await backup_manager.async_create_automatic_backup() except Exception as err: # noqa: BLE001 - websocket handlers can catch broad exceptions connection.send_error( msg["id"], websocket_api.ERR_UNKNOWN_ERROR, f"Error creating backup: {err}", ) return await async_update_preview_feature(hass, domain, preview_feature, enabled) connection.send_result(msg["id"]) @websocket_api.websocket_command( { vol.Required("type"): "labs/subscribe", vol.Required("domain"): str, vol.Required("preview_feature"): str, } ) @websocket_api.async_response async def websocket_subscribe_feature( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any], ) -> None: """Subscribe to a specific lab preview feature updates.""" domain = msg["domain"] preview_feature_key = msg["preview_feature"] labs_data = hass.data[LABS_DATA] preview_feature_id = f"{domain}.{preview_feature_key}" if preview_feature_id not in labs_data.preview_features: connection.send_error( msg["id"], websocket_api.ERR_NOT_FOUND, f"Preview feature {preview_feature_id} not found", ) return preview_feature = labs_data.preview_features[preview_feature_id] async def send_event(event_data: EventLabsUpdatedData | None = None) -> None: """Send feature state to client.""" enabled = ( event_data["enabled"] if event_data is not None else async_is_preview_feature_enabled(hass, domain, preview_feature_key) ) connection.send_message( websocket_api.event_message( msg["id"], preview_feature.to_dict(enabled=enabled), ) ) connection.subscriptions[msg["id"]] = async_subscribe_preview_feature( hass, domain, preview_feature_key, send_event ) connection.send_result(msg["id"]) await send_event()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/labs/websocket_api.py", "license": "Apache License 2.0", "lines": 128, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/lawn_mower/trigger.py
"""Provides triggers for lawn mowers.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN, LawnMowerActivity TRIGGERS: dict[str, type[Trigger]] = { "docked": make_entity_target_state_trigger(DOMAIN, LawnMowerActivity.DOCKED), "errored": make_entity_target_state_trigger(DOMAIN, LawnMowerActivity.ERROR), "paused_mowing": make_entity_target_state_trigger(DOMAIN, LawnMowerActivity.PAUSED), "started_mowing": make_entity_target_state_trigger( DOMAIN, LawnMowerActivity.MOWING ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for lawn mowers.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lawn_mower/trigger.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/light/condition.py
"""Provides conditions for lights.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN CONDITIONS: dict[str, type[Condition]] = { "is_off": make_entity_state_condition(DOMAIN, STATE_OFF), "is_on": make_entity_state_condition(DOMAIN, STATE_ON), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the light conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/light/condition.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/light/trigger.py
"""Provides triggers for lights.""" from typing import Any from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import ( EntityNumericalStateAttributeChangedTriggerBase, EntityNumericalStateAttributeCrossedThresholdTriggerBase, Trigger, make_entity_target_state_trigger, ) from . import ATTR_BRIGHTNESS from .const import DOMAIN def _convert_uint8_to_percentage(value: Any) -> float: """Convert a uint8 value (0-255) to a percentage (0-100).""" return (float(value) / 255.0) * 100.0 class BrightnessChangedTrigger(EntityNumericalStateAttributeChangedTriggerBase): """Trigger for brightness changed.""" _domain = DOMAIN _attribute = ATTR_BRIGHTNESS _converter = staticmethod(_convert_uint8_to_percentage) class BrightnessCrossedThresholdTrigger( EntityNumericalStateAttributeCrossedThresholdTriggerBase ): """Trigger for brightness crossed threshold.""" _domain = DOMAIN _attribute = ATTR_BRIGHTNESS _converter = staticmethod(_convert_uint8_to_percentage) TRIGGERS: dict[str, type[Trigger]] = { "brightness_changed": BrightnessChangedTrigger, "brightness_crossed_threshold": BrightnessCrossedThresholdTrigger, "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 lights.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/light/trigger.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/media_player/trigger.py
"""Provides triggers for media players.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_transition_trigger from . import MediaPlayerState from .const import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "stopped_playing": make_entity_transition_trigger( DOMAIN, from_states={ MediaPlayerState.BUFFERING, MediaPlayerState.PAUSED, MediaPlayerState.PLAYING, }, to_states={ MediaPlayerState.IDLE, MediaPlayerState.OFF, MediaPlayerState.ON, }, ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for media players.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/media_player/trigger.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/miele/select.py
"""Platform for Miele select entity.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from enum import IntEnum import logging from typing import Final from aiohttp import ClientResponseError from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .const import DOMAIN, MieleAppliance from .coordinator import MieleConfigEntry from .entity import MieleDevice, MieleEntity PARALLEL_UPDATES = 1 _LOGGER = logging.getLogger(__name__) class MieleModes(IntEnum): """Modes for fridge/freezer.""" NORMAL = 0 SABBATH = 1 PARTY = 2 HOLIDAY = 3 @dataclass(frozen=True, kw_only=True) class MieleSelectDescription(SelectEntityDescription): """Class describing Miele select entities.""" value_fn: Callable[[MieleDevice], StateType] @dataclass class MieleSelectDefinition: """Class for defining select entities.""" types: tuple[MieleAppliance, ...] description: MieleSelectDescription SELECT_TYPES: Final[tuple[MieleSelectDefinition, ...]] = ( MieleSelectDefinition( types=( MieleAppliance.FREEZER, MieleAppliance.FRIDGE, MieleAppliance.FRIDGE_FREEZER, ), description=MieleSelectDescription( key="fridge_freezer_modes", value_fn=lambda value: 1, translation_key="fridge_freezer_mode", ), ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: MieleConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the select platform.""" coordinator = config_entry.runtime_data.coordinator added_devices: set[str] = set() def _async_add_new_devices() -> None: nonlocal added_devices new_devices_set, current_devices = coordinator.async_add_devices(added_devices) added_devices = current_devices async_add_entities( MieleSelectMode(coordinator, device_id, definition.description) for device_id, device in coordinator.data.devices.items() for definition in SELECT_TYPES if device_id in new_devices_set and device.device_type in definition.types ) config_entry.async_on_unload(coordinator.async_add_listener(_async_add_new_devices)) _async_add_new_devices() class MieleSelectMode(MieleEntity, SelectEntity): """Representation of a Select mode entity.""" entity_description: MieleSelectDescription @property def options(self) -> list[str]: """Return the list of available options.""" return sorted( {MieleModes(x).name.lower() for x in self.action.modes} | {self.current_option} ) @property def current_option(self) -> str: """Retrieve currently selected option.""" # There is no direct mapping from Miele 3rd party API, so we infer the # current mode based on available modes in action.modes action_modes = set(self.action.modes) if action_modes in ({1}, {1, 2}, {1, 3}, {1, 2, 3}): return MieleModes.NORMAL.name.lower() if action_modes in ({0}, {0, 2}, {0, 3}, {0, 2, 3}): return MieleModes.SABBATH.name.lower() if action_modes in ({0, 1}, {0, 1, 3}): return MieleModes.PARTY.name.lower() if action_modes == {0, 1, 2}: return MieleModes.HOLIDAY.name.lower() return MieleModes.NORMAL.name.lower() async def async_select_option(self, option: str) -> None: """Set the selected option.""" new_mode = MieleModes[option.upper()].value if new_mode not in self.action.modes: _LOGGER.debug("Option '%s' is not available for %s", option, self.entity_id) raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_option", translation_placeholders={ "option": option, "entity": self.entity_id, }, ) try: await self.api.send_action( self._device_id, {"modes": new_mode}, ) except ClientResponseError as err: _LOGGER.debug("Error setting select state for %s: %s", self.entity_id, err) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_state_error", translation_placeholders={ "entity": self.entity_id, }, ) from err # Refresh data as API does not push changes for modes updates await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/miele/select.py", "license": "Apache License 2.0", "lines": 121, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nasweb/alarm_control_panel.py
"""Platform for NASweb alarms.""" from __future__ import annotations import logging import time from webio_api import Zone as NASwebZone from webio_api.const import STATE_ZONE_ALARM, STATE_ZONE_ARMED, STATE_ZONE_DISARMED from homeassistant.components.alarm_control_panel import ( DOMAIN as ALARM_CONTROL_PANEL_DOMAIN, AlarmControlPanelEntity, AlarmControlPanelEntityFeature, AlarmControlPanelState, CodeFormat, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback import homeassistant.helpers.entity_registry as er from homeassistant.helpers.typing import DiscoveryInfoType from homeassistant.helpers.update_coordinator import ( BaseCoordinatorEntity, BaseDataUpdateCoordinatorProtocol, ) from . import NASwebConfigEntry from .const import DOMAIN, STATUS_UPDATE_MAX_TIME_INTERVAL _LOGGER = logging.getLogger(__name__) ALARM_CONTROL_PANEL_TRANSLATION_KEY = "zone" NASWEB_STATE_TO_HA_STATE = { STATE_ZONE_ALARM: AlarmControlPanelState.TRIGGERED, STATE_ZONE_ARMED: AlarmControlPanelState.ARMED_AWAY, STATE_ZONE_DISARMED: AlarmControlPanelState.DISARMED, } async def async_setup_entry( hass: HomeAssistant, config: NASwebConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up alarm control panel platform.""" coordinator = config.runtime_data current_zones: set[int] = set() @callback def _check_entities() -> None: received_zones: dict[int, NASwebZone] = { entry.index: entry for entry in coordinator.webio_api.zones } added = {i for i in received_zones if i not in current_zones} removed = {i for i in current_zones if i not in received_zones} entities_to_add: list[ZoneEntity] = [] for index in added: webio_zone = received_zones[index] if not isinstance(webio_zone, NASwebZone): _LOGGER.error("Cannot create ZoneEntity without NASwebZone") continue new_zone = ZoneEntity(coordinator, webio_zone) entities_to_add.append(new_zone) current_zones.add(index) async_add_entities(entities_to_add) entity_registry = er.async_get(hass) for index in removed: unique_id = f"{DOMAIN}.{config.unique_id}.zone.{index}" if entity_id := entity_registry.async_get_entity_id( ALARM_CONTROL_PANEL_DOMAIN, DOMAIN, unique_id ): entity_registry.async_remove(entity_id) current_zones.remove(index) else: _LOGGER.warning("Failed to remove old zone: no entity_id") coordinator.async_add_listener(_check_entities) _check_entities() class ZoneEntity(AlarmControlPanelEntity, BaseCoordinatorEntity): """Entity representing NASweb zone.""" _attr_has_entity_name = True _attr_should_poll = False _attr_translation_key = ALARM_CONTROL_PANEL_TRANSLATION_KEY def __init__( self, coordinator: BaseDataUpdateCoordinatorProtocol, nasweb_zone: NASwebZone ) -> None: """Initialize zone entity.""" super().__init__(coordinator) self._zone = nasweb_zone self._attr_name = nasweb_zone.name self._attr_translation_placeholders = {"index": f"{nasweb_zone.index:2d}"} self._attr_unique_id = ( f"{DOMAIN}.{self._zone.webio_serial}.zone.{self._zone.index}" ) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self._zone.webio_serial)}, ) async def async_added_to_hass(self) -> None: """When entity is added to hass.""" await super().async_added_to_hass() self._handle_coordinator_update() def _set_attr_available( self, entity_last_update: float, available: bool | None ) -> None: if ( self.coordinator.last_update is None or time.time() - entity_last_update >= STATUS_UPDATE_MAX_TIME_INTERVAL ): self._attr_available = False else: self._attr_available = available if available is not None else False @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._attr_alarm_state = NASWEB_STATE_TO_HA_STATE[self._zone.state] if self._zone.pass_type == 0: self._attr_code_format = CodeFormat.TEXT elif self._zone.pass_type == 1: self._attr_code_format = CodeFormat.NUMBER else: self._attr_code_format = None self._attr_code_arm_required = self._attr_code_format is not None self._set_attr_available(self._zone.last_update, self._zone.available) self.async_write_ha_state() async def async_update(self) -> None: """Update the entity. Only used by the generic entity update service. Scheduling updates is not necessary, the coordinator takes care of updates via push notifications. """ @property def supported_features(self) -> AlarmControlPanelEntityFeature: """Return the list of supported features.""" return AlarmControlPanelEntityFeature.ARM_AWAY async def async_alarm_arm_away(self, code: str | None = None) -> None: """Arm away ZoneEntity.""" await self._zone.arm(code) async def async_alarm_disarm(self, code: str | None = None) -> None: """Disarm ZoneEntity.""" await self._zone.disarm(code)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nasweb/alarm_control_panel.py", "license": "Apache License 2.0", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nederlandse_spoorwegen/binary_sensor.py
"""Support for Nederlandse Spoorwegen public transport.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime import logging from ns_api import Trip from homeassistant.components.binary_sensor import ( BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, INTEGRATION_TITLE, ROUTE_MODEL from .coordinator import NSConfigEntry, NSDataUpdateCoordinator _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 # since we use coordinator pattern @dataclass(frozen=True, kw_only=True) class NSBinarySensorEntityDescription(BinarySensorEntityDescription): """Describes Nederlandse Spoorwegen sensor entity.""" value_fn: Callable[[Trip], bool] def get_delay(planned: datetime | None, actual: datetime | None) -> bool: """Return True if delay is present, False otherwise.""" return bool(planned and actual and planned != actual) BINARY_SENSOR_DESCRIPTIONS = [ NSBinarySensorEntityDescription( key="is_departure_delayed", translation_key="is_departure_delayed", entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda trip: get_delay( trip.departure_time_planned, trip.departure_time_actual ), entity_registry_enabled_default=False, ), NSBinarySensorEntityDescription( key="is_arrival_delayed", translation_key="is_arrival_delayed", entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda trip: get_delay( trip.arrival_time_planned, trip.arrival_time_actual ), entity_registry_enabled_default=False, ), NSBinarySensorEntityDescription( key="is_going", translation_key="is_going", entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda trip: trip.going, entity_registry_enabled_default=False, ), ] async def async_setup_entry( hass: HomeAssistant, config_entry: NSConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the departure sensor from a config entry.""" coordinators = config_entry.runtime_data for subentry_id, coordinator in coordinators.items(): async_add_entities( ( NSBinarySensor(coordinator, subentry_id, description) for description in BINARY_SENSOR_DESCRIPTIONS ), config_subentry_id=subentry_id, ) class NSBinarySensor(CoordinatorEntity[NSDataUpdateCoordinator], BinarySensorEntity): """Generic NS binary sensor based on entity description.""" _attr_has_entity_name = True _attr_attribution = "Data provided by NS" entity_description: NSBinarySensorEntityDescription def __init__( self, coordinator: NSDataUpdateCoordinator, subentry_id: str, description: NSBinarySensorEntityDescription, ) -> None: """Initialize the binary sensor.""" super().__init__(coordinator) self.entity_description = description self._subentry_id = subentry_id self._attr_unique_id = f"{subentry_id}-{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, subentry_id)}, name=coordinator.name, manufacturer=INTEGRATION_TITLE, model=ROUTE_MODEL, ) @property def is_on(self) -> bool | None: """Return true if the binary sensor is on.""" if not (trip := self.coordinator.data.first_trip): return None return self.entity_description.value_fn(trip)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nederlandse_spoorwegen/binary_sensor.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/niko_home_control/climate.py
"""Support for Niko Home Control thermostats.""" from typing import Any from nhc.const import THERMOSTAT_MODES, THERMOSTAT_MODES_REVERSE from nhc.thermostat import NHCThermostat from homeassistant.components.climate import ( PRESET_ECO, ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.components.sensor import UnitOfTemperature from homeassistant.const import ATTR_TEMPERATURE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import NikoHomeControlConfigEntry from .const import ( NIKO_HOME_CONTROL_THERMOSTAT_MODES_MAP, NikoHomeControlThermostatModes, ) from .entity import NikoHomeControlEntity async def async_setup_entry( hass: HomeAssistant, entry: NikoHomeControlConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Niko Home Control thermostat entry.""" controller = entry.runtime_data async_add_entities( NikoHomeControlClimate(thermostat, controller, entry.entry_id) for thermostat in controller.thermostats.values() ) class NikoHomeControlClimate(NikoHomeControlEntity, ClimateEntity): """Representation of a Niko Home Control thermostat.""" _attr_supported_features: ClimateEntityFeature = ( ClimateEntityFeature.PRESET_MODE | ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TURN_OFF ) _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_name = None _action: NHCThermostat _attr_translation_key = "nhc_thermostat" _attr_hvac_modes = [HVACMode.OFF, HVACMode.COOL, HVACMode.AUTO] _attr_preset_modes = [ "day", "night", PRESET_ECO, "prog1", "prog2", "prog3", ] def _get_niko_mode(self, mode: str) -> int: """Return the Niko mode.""" return THERMOSTAT_MODES_REVERSE.get(mode, NikoHomeControlThermostatModes.OFF) async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" if ATTR_TEMPERATURE in kwargs: await self._action.set_temperature(kwargs.get(ATTR_TEMPERATURE)) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" await self._action.set_mode(self._get_niko_mode(preset_mode)) async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target hvac mode.""" await self._action.set_mode(NIKO_HOME_CONTROL_THERMOSTAT_MODES_MAP[hvac_mode]) async def async_turn_off(self) -> None: """Turn thermostat off.""" await self._action.set_mode(NikoHomeControlThermostatModes.OFF) def update_state(self) -> None: """Update the state of the entity.""" if self._action.state == NikoHomeControlThermostatModes.OFF: self._attr_hvac_mode = HVACMode.OFF self._attr_preset_mode = None elif self._action.state == NikoHomeControlThermostatModes.COOL: self._attr_hvac_mode = HVACMode.COOL self._attr_preset_mode = None else: self._attr_hvac_mode = HVACMode.AUTO self._attr_preset_mode = THERMOSTAT_MODES[self._action.state] self._attr_target_temperature = self._action.setpoint self._attr_current_temperature = self._action.measured
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/niko_home_control/climate.py", "license": "Apache License 2.0", "lines": 80, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/noaa_tides/const.py
"""Constants for the NOAA Tides integration.""" from datetime import timedelta CONF_STATION_ID = "station_id" DEFAULT_NAME = "NOAA Tides" DEFAULT_PREDICTION_LENGTH = timedelta(days=2) DEFAULT_TIMEZONE = "lst_ldt" ATTRIBUTION = "Data provided by NOAA"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/noaa_tides/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/pooldose/binary_sensor.py
"""Binary sensors for the Seko PoolDose integration.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, cast 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 PooldoseConfigEntry from .entity import PooldoseEntity _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 BINARY_SENSOR_DESCRIPTIONS: tuple[BinarySensorEntityDescription, ...] = ( BinarySensorEntityDescription( key="pump_alarm", translation_key="pump_alarm", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="ph_level_alarm", translation_key="ph_level_alarm", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="orp_level_alarm", translation_key="orp_level_alarm", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="flow_rate_alarm", translation_key="flow_rate_alarm", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="alarm_ofa_ph", translation_key="alarm_ofa_ph", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="alarm_ofa_orp", translation_key="alarm_ofa_orp", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="alarm_ofa_cl", translation_key="alarm_ofa_cl", device_class=BinarySensorDeviceClass.PROBLEM, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="relay_alarm", translation_key="relay_alarm", device_class=BinarySensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, ), BinarySensorEntityDescription( key="relay_aux1", translation_key="relay_aux1", device_class=BinarySensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), BinarySensorEntityDescription( key="relay_aux2", translation_key="relay_aux2", device_class=BinarySensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), BinarySensorEntityDescription( key="relay_aux3", translation_key="relay_aux3", device_class=BinarySensorDeviceClass.POWER, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: PooldoseConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up PoolDose binary sensor entities from a config entry.""" if TYPE_CHECKING: assert config_entry.unique_id is not None coordinator = config_entry.runtime_data binary_sensor_data = coordinator.data["binary_sensor"] serial_number = config_entry.unique_id async_add_entities( PooldoseBinarySensor( coordinator, serial_number, coordinator.device_info, description, "binary_sensor", ) for description in BINARY_SENSOR_DESCRIPTIONS if description.key in binary_sensor_data ) class PooldoseBinarySensor(PooldoseEntity, BinarySensorEntity): """Binary sensor entity for the Seko PoolDose Python API.""" @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" data = cast(dict, self.get_data()) return cast(bool, data["value"])
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/pooldose/binary_sensor.py", "license": "Apache License 2.0", "lines": 116, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/pooldose/switch.py
"""Switches for the Seko PoolDose integration.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any, cast 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 . import PooldoseConfigEntry from .entity import PooldoseEntity if TYPE_CHECKING: from .coordinator import PooldoseCoordinator _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 SWITCH_DESCRIPTIONS: tuple[SwitchEntityDescription, ...] = ( SwitchEntityDescription( key="pause_dosing", translation_key="pause_dosing", entity_category=EntityCategory.CONFIG, ), SwitchEntityDescription( key="pump_monitoring", translation_key="pump_monitoring", entity_category=EntityCategory.CONFIG, ), SwitchEntityDescription( key="frequency_input", translation_key="frequency_input", entity_category=EntityCategory.CONFIG, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: PooldoseConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up PoolDose switch entities from a config entry.""" if TYPE_CHECKING: assert config_entry.unique_id is not None coordinator = config_entry.runtime_data switch_data = coordinator.data["switch"] serial_number = config_entry.unique_id async_add_entities( PooldoseSwitch(coordinator, serial_number, coordinator.device_info, description) for description in SWITCH_DESCRIPTIONS if description.key in switch_data ) class PooldoseSwitch(PooldoseEntity, SwitchEntity): """Switch entity for the Seko PoolDose Python API.""" def __init__( self, coordinator: PooldoseCoordinator, serial_number: str, device_info: Any, description: SwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator, serial_number, device_info, description, "switch") self._async_update_attrs() def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._async_update_attrs() super()._handle_coordinator_update() def _async_update_attrs(self) -> None: """Update switch attributes.""" data = cast(dict, self.get_data()) self._attr_is_on = cast(bool, data["value"]) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self._async_perform_write( self.coordinator.client.set_switch, self.entity_description.key, True ) self._attr_is_on = True self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self._async_perform_write( self.coordinator.client.set_switch, self.entity_description.key, False ) self._attr_is_on = False self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/pooldose/switch.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/satel_integra/entity.py
"""Satel Integra base entity.""" from __future__ import annotations from typing import TYPE_CHECKING from satel_integra.satel_integra import AsyncSatel from homeassistant.config_entries import ConfigSubentry from homeassistant.const import CONF_NAME from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( DOMAIN, SUBENTRY_TYPE_OUTPUT, SUBENTRY_TYPE_PARTITION, SUBENTRY_TYPE_SWITCHABLE_OUTPUT, SUBENTRY_TYPE_ZONE, ) from .coordinator import SatelIntegraBaseCoordinator SubentryTypeToEntityType: dict[str, str] = { SUBENTRY_TYPE_PARTITION: "alarm_panel", SUBENTRY_TYPE_SWITCHABLE_OUTPUT: "switch", SUBENTRY_TYPE_ZONE: "zones", SUBENTRY_TYPE_OUTPUT: "outputs", } class SatelIntegraEntity[_CoordinatorT: SatelIntegraBaseCoordinator]( CoordinatorEntity[_CoordinatorT] ): """Defines a base Satel Integra entity.""" _attr_should_poll = False _attr_has_entity_name = True _attr_name = None _controller: AsyncSatel def __init__( self, coordinator: _CoordinatorT, config_entry_id: str, subentry: ConfigSubentry, device_number: int, ) -> None: """Initialize the Satel Integra entity.""" super().__init__(coordinator) self._controller = coordinator.client.controller self._device_number = device_number entity_type = SubentryTypeToEntityType[subentry.subentry_type] if TYPE_CHECKING: assert entity_type is not None self._attr_unique_id = f"{config_entry_id}_{entity_type}_{device_number}" self._attr_device_info = DeviceInfo( name=subentry.data[CONF_NAME], identifiers={(DOMAIN, self._attr_unique_id)}, via_device=(DOMAIN, config_entry_id), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/satel_integra/entity.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/saunum/climate.py
"""Climate platform for Saunum Leil Sauna Control Unit.""" from __future__ import annotations import asyncio from datetime import timedelta from typing import Any from pysaunum import MAX_TEMPERATURE, MIN_TEMPERATURE, SaunumException from homeassistant.components.climate import ( FAN_HIGH, FAN_LOW, FAN_MEDIUM, FAN_OFF, ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_WHOLE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import LeilSaunaConfigEntry, LeilSaunaCoordinator from .const import ( DEFAULT_PRESET_NAME_TYPE_1, DEFAULT_PRESET_NAME_TYPE_2, DEFAULT_PRESET_NAME_TYPE_3, DELAYED_REFRESH_SECONDS, DOMAIN, OPT_PRESET_NAME_TYPE_1, OPT_PRESET_NAME_TYPE_2, OPT_PRESET_NAME_TYPE_3, ) from .entity import LeilSaunaEntity PARALLEL_UPDATES = 1 # Map Saunum fan speed (0-3) to Home Assistant fan modes FAN_SPEED_TO_MODE = { 0: FAN_OFF, 1: FAN_LOW, 2: FAN_MEDIUM, 3: FAN_HIGH, } FAN_MODE_TO_SPEED = {v: k for k, v in FAN_SPEED_TO_MODE.items()} async def async_setup_entry( hass: HomeAssistant, entry: LeilSaunaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Saunum Leil Sauna climate entity.""" coordinator = entry.runtime_data async_add_entities([LeilSaunaClimate(coordinator)]) class LeilSaunaClimate(LeilSaunaEntity, ClimateEntity): """Representation of a Saunum Leil Sauna climate entity.""" _attr_name = None _attr_translation_key = "saunum_climate" _attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT] _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.FAN_MODE | ClimateEntityFeature.PRESET_MODE ) _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_precision = PRECISION_WHOLE _attr_target_temperature_step = 1.0 _attr_min_temp = MIN_TEMPERATURE _attr_max_temp = MAX_TEMPERATURE _attr_fan_modes = [FAN_OFF, FAN_LOW, FAN_MEDIUM, FAN_HIGH] _preset_name_map: dict[int, str] def __init__(self, coordinator: LeilSaunaCoordinator) -> None: """Initialize the climate entity.""" super().__init__(coordinator) self._update_preset_names() def _update_preset_names(self) -> None: """Update preset names from config entry options.""" options = self.coordinator.config_entry.options self._preset_name_map = { 0: options.get(OPT_PRESET_NAME_TYPE_1, DEFAULT_PRESET_NAME_TYPE_1), 1: options.get(OPT_PRESET_NAME_TYPE_2, DEFAULT_PRESET_NAME_TYPE_2), 2: options.get(OPT_PRESET_NAME_TYPE_3, DEFAULT_PRESET_NAME_TYPE_3), } self._attr_preset_modes = list(self._preset_name_map.values()) async def async_added_to_hass(self) -> None: """Run when entity about to be added to hass.""" await super().async_added_to_hass() self.async_on_remove( self.coordinator.config_entry.add_update_listener( self._async_update_listener ) ) async def _async_update_listener( self, hass: HomeAssistant, entry: LeilSaunaConfigEntry ) -> None: """Handle options update.""" self._update_preset_names() self.async_write_ha_state() @property def current_temperature(self) -> float | None: """Return the current temperature in Celsius.""" return self.coordinator.data.current_temperature @property def target_temperature(self) -> float | None: """Return the target temperature in Celsius.""" return self.coordinator.data.target_temperature @property def fan_mode(self) -> str | None: """Return the current fan mode.""" fan_speed = self.coordinator.data.fan_speed if fan_speed is not None and fan_speed in FAN_SPEED_TO_MODE: return FAN_SPEED_TO_MODE[fan_speed] return None @property def hvac_mode(self) -> HVACMode: """Return current HVAC mode.""" session_active = self.coordinator.data.session_active return HVACMode.HEAT if session_active else HVACMode.OFF @property def hvac_action(self) -> HVACAction | None: """Return current HVAC action.""" if not self.coordinator.data.session_active: return HVACAction.OFF heater_elements_active = self.coordinator.data.heater_elements_active return ( HVACAction.HEATING if heater_elements_active and heater_elements_active > 0 else HVACAction.IDLE ) @property def preset_mode(self) -> str | None: """Return the current preset mode.""" sauna_type = self.coordinator.data.sauna_type if sauna_type is not None and sauna_type in self._preset_name_map: return self._preset_name_map[sauna_type] return self._preset_name_map[0] async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new HVAC mode.""" if hvac_mode == HVACMode.HEAT and self.coordinator.data.door_open: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="door_open", ) try: if hvac_mode == HVACMode.HEAT: await self.coordinator.client.async_start_session() else: await self.coordinator.client.async_stop_session() except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_hvac_mode_failed", translation_placeholders={"hvac_mode": hvac_mode}, ) from err # The device takes 1-2 seconds to turn heater elements on/off and # update heater_elements_active. Wait and refresh again to ensure # the HVAC action state reflects the actual heater status. await asyncio.sleep(DELAYED_REFRESH_SECONDS.total_seconds()) await self.coordinator.async_request_refresh() async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" try: await self.coordinator.client.async_set_target_temperature( int(kwargs[ATTR_TEMPERATURE]) ) except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_temperature_failed", translation_placeholders={"temperature": str(kwargs[ATTR_TEMPERATURE])}, ) from err await self.coordinator.async_request_refresh() async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new fan mode.""" if not self.coordinator.data.session_active: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="session_not_active", ) try: await self.coordinator.client.async_set_fan_speed( FAN_MODE_TO_SPEED[fan_mode] ) except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_fan_mode_failed", ) from err await self.coordinator.async_request_refresh() async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode (sauna type).""" if self.coordinator.data.session_active: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="preset_session_active", ) # Find the sauna type value from the preset name sauna_type_value = 0 # Default to type 1 for type_value, type_name in self._preset_name_map.items(): if type_name == preset_mode: sauna_type_value = type_value break try: await self.coordinator.client.async_set_sauna_type(sauna_type_value) except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_preset_failed", translation_placeholders={"preset_mode": preset_mode}, ) from err await self.coordinator.async_request_refresh() async def async_start_session( self, duration: timedelta = timedelta(minutes=120), target_temperature: int = 80, fan_duration: timedelta = timedelta(minutes=10), ) -> None: """Start a sauna session with custom parameters.""" if self.coordinator.data.door_open: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="door_open", ) try: # Set all parameters before starting the session await self.coordinator.client.async_set_sauna_duration( int(duration.total_seconds() // 60) ) await self.coordinator.client.async_set_target_temperature( target_temperature ) await self.coordinator.client.async_set_fan_duration( int(fan_duration.total_seconds() // 60) ) await self.coordinator.client.async_start_session() except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="start_session_failed", ) from err await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/climate.py", "license": "Apache License 2.0", "lines": 236, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/saunum/config_flow.py
"""Config flow for Saunum Leil Sauna Control Unit integration.""" from __future__ import annotations import logging from typing import Any from pysaunum import SaunumClient, SaunumException import voluptuous as vol from homeassistant.config_entries import ( SOURCE_USER, ConfigFlow, ConfigFlowResult, OptionsFlow, ) from homeassistant.const import CONF_HOST from homeassistant.core import callback from homeassistant.helpers import config_validation as cv from . import LeilSaunaConfigEntry from .const import ( DEFAULT_PRESET_NAME_TYPE_1, DEFAULT_PRESET_NAME_TYPE_2, DEFAULT_PRESET_NAME_TYPE_3, DOMAIN, OPT_PRESET_NAME_TYPE_1, OPT_PRESET_NAME_TYPE_2, OPT_PRESET_NAME_TYPE_3, ) _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, } ) async def validate_input(data: dict[str, Any]) -> None: """Validate the user input allows us to connect. Data has the keys from STEP_USER_DATA_SCHEMA with values provided by the user. """ host = data[CONF_HOST] client = await SaunumClient.create(host) try: # Try to read data to verify communication await client.async_get_data() finally: await client.async_close() class LeilSaunaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Saunum Leil Sauna Control Unit.""" VERSION = 1 MINOR_VERSION = 1 @staticmethod @callback def async_get_options_flow( config_entry: LeilSaunaConfigEntry, ) -> LeilSaunaOptionsFlow: """Get the options flow for this handler.""" return LeilSaunaOptionsFlow() async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" return await self.async_step_user(user_input) 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(user_input) try: await validate_input(user_input) except SaunumException: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: if self.source == SOURCE_USER: return self.async_create_entry( title="Saunum", data=user_input, ) return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates=user_input, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, ) class LeilSaunaOptionsFlow(OptionsFlow): """Handle options flow for Saunum Leil Sauna Control Unit.""" async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Manage the options for preset mode names.""" if user_input is not None: return self.async_create_entry(title="", data=user_input) return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Optional( OPT_PRESET_NAME_TYPE_1, default=self.config_entry.options.get( OPT_PRESET_NAME_TYPE_1, DEFAULT_PRESET_NAME_TYPE_1 ), ): cv.string, vol.Optional( OPT_PRESET_NAME_TYPE_2, default=self.config_entry.options.get( OPT_PRESET_NAME_TYPE_2, DEFAULT_PRESET_NAME_TYPE_2 ), ): cv.string, vol.Optional( OPT_PRESET_NAME_TYPE_3, default=self.config_entry.options.get( OPT_PRESET_NAME_TYPE_3, DEFAULT_PRESET_NAME_TYPE_3 ), ): cv.string, } ), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/config_flow.py", "license": "Apache License 2.0", "lines": 120, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/saunum/const.py
"""Constants for the Saunum Leil Sauna Control Unit integration.""" from datetime import timedelta from typing import Final DOMAIN: Final = "saunum" DEFAULT_SCAN_INTERVAL: Final = timedelta(seconds=60) DELAYED_REFRESH_SECONDS: Final = timedelta(seconds=3) # Option keys for preset names OPT_PRESET_NAME_TYPE_1: Final = "preset_name_type_1" OPT_PRESET_NAME_TYPE_2: Final = "preset_name_type_2" OPT_PRESET_NAME_TYPE_3: Final = "preset_name_type_3" # Default preset names (translation keys) DEFAULT_PRESET_NAME_TYPE_1: Final = "type_1" DEFAULT_PRESET_NAME_TYPE_2: Final = "type_2" DEFAULT_PRESET_NAME_TYPE_3: Final = "type_3"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/const.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/saunum/coordinator.py
"""Coordinator for Saunum Leil Sauna Control Unit integration.""" from __future__ import annotations import logging from typing import TYPE_CHECKING from pysaunum import SaunumClient, SaunumData, SaunumException from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN if TYPE_CHECKING: from . import LeilSaunaConfigEntry _LOGGER = logging.getLogger(__name__) class LeilSaunaCoordinator(DataUpdateCoordinator[SaunumData]): """Coordinator for fetching Saunum Leil Sauna data.""" config_entry: LeilSaunaConfigEntry def __init__( self, hass: HomeAssistant, client: SaunumClient, config_entry: LeilSaunaConfigEntry, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL, config_entry=config_entry, ) self.client = client async def _async_update_data(self) -> SaunumData: """Fetch data from the sauna controller.""" try: return await self.client.async_get_data() except SaunumException as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="communication_error", ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/coordinator.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/saunum/diagnostics.py
"""Diagnostics support for Saunum Leil Sauna Control Unit integration.""" 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 from homeassistant.core import HomeAssistant from . import LeilSaunaConfigEntry REDACT_CONFIG = {CONF_HOST} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: LeilSaunaConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data # Build diagnostics data diagnostics_data: dict[str, Any] = { "config": async_redact_data(entry.data, REDACT_CONFIG), "options": dict(entry.options), "client_info": {"connected": coordinator.client.is_connected}, "coordinator_info": { "last_update_success": coordinator.last_update_success, "update_interval": str(coordinator.update_interval), "last_exception": str(coordinator.last_exception) if coordinator.last_exception else None, }, } # Add coordinator data if available if coordinator.data: data_dict = asdict(coordinator.data) diagnostics_data["coordinator_data"] = data_dict # Add alarm summary alarm_fields = [ key for key, value in data_dict.items() if key.startswith("alarm_") and value is True ] diagnostics_data["active_alarms"] = alarm_fields return diagnostics_data
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/diagnostics.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/saunum/entity.py
"""Base entity for Saunum Leil Sauna Control Unit integration.""" from __future__ import annotations from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import LeilSaunaCoordinator class LeilSaunaEntity(CoordinatorEntity[LeilSaunaCoordinator]): """Base entity for Saunum Leil Sauna.""" _attr_has_entity_name = True def __init__(self, coordinator: LeilSaunaCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) entry_id = coordinator.config_entry.entry_id self._attr_unique_id = entry_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, entry_id)}, name="Saunum Leil", manufacturer="Saunum", model="Leil Touch Panel", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/entity.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/saunum/light.py
"""Light platform for Saunum Leil Sauna Control Unit.""" from __future__ import annotations from typing import TYPE_CHECKING, Any from pysaunum import SaunumException from homeassistant.components.light import ColorMode, LightEntity from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import LeilSaunaConfigEntry from .const import DOMAIN from .entity import LeilSaunaEntity if TYPE_CHECKING: from .coordinator import LeilSaunaCoordinator PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: LeilSaunaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Saunum Leil Sauna light entity.""" coordinator = entry.runtime_data async_add_entities([LeilSaunaLight(coordinator)]) class LeilSaunaLight(LeilSaunaEntity, LightEntity): """Representation of a Saunum Leil Sauna light entity.""" _attr_translation_key = "light" _attr_color_mode = ColorMode.ONOFF _attr_supported_color_modes = {ColorMode.ONOFF} def __init__(self, coordinator: LeilSaunaCoordinator) -> None: """Initialize the light entity.""" super().__init__(coordinator) # Override unique_id to differentiate from climate entity self._attr_unique_id = f"{coordinator.config_entry.entry_id}_light" @property def is_on(self) -> bool | None: """Return True if light is on.""" return self.coordinator.data.light_on async def async_turn_on(self, **kwargs: Any) -> None: """Turn the light on.""" try: await self.coordinator.client.async_set_light_control(True) except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_light_on_failed", ) from err await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the light off.""" try: await self.coordinator.client.async_set_light_control(False) except SaunumException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_light_off_failed", ) from err await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/light.py", "license": "Apache License 2.0", "lines": 56, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/senz/diagnostics.py
"""Diagnostics platform for Senz integration.""" from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.core import HomeAssistant from . import SENZConfigEntry TO_REDACT = [ "access_token", "refresh_token", ] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: SENZConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" raw_data = ([device.raw_data for device in entry.runtime_data.data.values()],) return { "entry_data": async_redact_data(entry.data, TO_REDACT), "thermostats": raw_data, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/senz/diagnostics.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/senz/sensor.py
"""nVent RAYCHEM SENZ sensor platform.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from pysenz import Thermostat from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import SENZConfigEntry, SENZDataUpdateCoordinator from .const import DOMAIN @dataclass(kw_only=True, frozen=True) class SenzSensorDescription(SensorEntityDescription): """Describes SENZ sensor entity.""" value_fn: Callable[[Thermostat], str | int | float | None] SENSORS: tuple[SenzSensorDescription, ...] = ( SenzSensorDescription( key="temperature", device_class=SensorDeviceClass.TEMPERATURE, value_fn=lambda data: data.current_temperatue, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=1, ), ) async def async_setup_entry( hass: HomeAssistant, entry: SENZConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the SENZ sensor entities from a config entry.""" coordinator = entry.runtime_data async_add_entities( SENZSensor(thermostat, coordinator, description) for description in SENSORS for thermostat in coordinator.data.values() ) class SENZSensor(CoordinatorEntity[SENZDataUpdateCoordinator], SensorEntity): """Representation of a SENZ sensor entity.""" entity_description: SenzSensorDescription _attr_has_entity_name = True def __init__( self, thermostat: Thermostat, coordinator: SENZDataUpdateCoordinator, description: SenzSensorDescription, ) -> None: """Init SENZ sensor.""" super().__init__(coordinator) self.entity_description = description self._thermostat = thermostat self._attr_unique_id = f"{thermostat.serial_number}_{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, thermostat.serial_number)}, manufacturer="nVent Raychem", model="SENZ WIFI", name=thermostat.name, serial_number=thermostat.serial_number, ) @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._thermostat = self.coordinator.data[self._thermostat.serial_number] self.async_write_ha_state() @property def available(self) -> bool: """Return True if the thermostat is available.""" return super().available and self._thermostat.online @property def native_value(self) -> str | float | int | None: """Return the state of the sensor.""" return self.entity_description.value_fn(self._thermostat)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/senz/sensor.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/shelly/ble_provisioning.py
"""BLE provisioning helpers for Shelly integration.""" from __future__ import annotations import asyncio from dataclasses import dataclass, field import logging from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import format_mac from homeassistant.util.hass_dict import HassKey _LOGGER = logging.getLogger(__name__) @dataclass class ProvisioningState: """State for tracking zeroconf discovery during BLE provisioning.""" event: asyncio.Event = field(default_factory=asyncio.Event) host: str | None = None port: int | None = None PROVISIONING_FUTURES: HassKey[dict[str, ProvisioningState]] = HassKey( "shelly_provisioning_futures" ) @callback def async_get_provisioning_registry( hass: HomeAssistant, ) -> dict[str, ProvisioningState]: """Get the provisioning registry, creating it if needed. This is a helper function for internal use. It ensures the registry exists without requiring async_setup to run first. """ return hass.data.setdefault(PROVISIONING_FUTURES, {}) @callback def async_register_zeroconf_discovery( hass: HomeAssistant, mac: str, host: str, port: int ) -> None: """Register a zeroconf discovery for a device that was provisioned via BLE. Called by zeroconf discovery when it finds a device that may have been provisioned via BLE. If BLE provisioning is waiting for this device, the host and port will be stored (replacing any previous values). Multiple zeroconf discoveries can happen (Shelly service, HTTP service, etc.) and the last one wins. Args: hass: Home Assistant instance mac: Device MAC address (will be normalized) host: Device IP address/hostname from zeroconf port: Device port from zeroconf """ registry = async_get_provisioning_registry(hass) normalized_mac = format_mac(mac) state = registry.get(normalized_mac) if not state: _LOGGER.debug( "No BLE provisioning state found for %s (host %s, port %s)", normalized_mac, host, port, ) return _LOGGER.debug( "Registering zeroconf discovery for %s at %s:%s (replacing previous)", normalized_mac, host, port, ) # Store host and port (replacing any previous values) and signal the event state.host = host state.port = port state.event.set()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/shelly/ble_provisioning.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/switchbot/climate.py
"""Support for Switchbot Climate devices.""" from __future__ import annotations import logging from typing import Any import switchbot from switchbot import ( ClimateAction as SwitchBotClimateAction, ClimateMode as SwitchBotClimateMode, ) from homeassistant.components.climate import ( ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import SwitchbotConfigEntry from .entity import SwitchbotEntity, exception_handler SWITCHBOT_CLIMATE_TO_HASS_HVAC_MODE = { SwitchBotClimateMode.HEAT: HVACMode.HEAT, SwitchBotClimateMode.OFF: HVACMode.OFF, } HASS_HVAC_MODE_TO_SWITCHBOT_CLIMATE = { HVACMode.HEAT: SwitchBotClimateMode.HEAT, HVACMode.OFF: SwitchBotClimateMode.OFF, } SWITCHBOT_ACTION_TO_HASS_HVAC_ACTION = { SwitchBotClimateAction.HEATING: HVACAction.HEATING, SwitchBotClimateAction.IDLE: HVACAction.IDLE, SwitchBotClimateAction.OFF: HVACAction.OFF, } _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, entry: SwitchbotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Switchbot climate based on a config entry.""" coordinator = entry.runtime_data async_add_entities([SwitchBotClimateEntity(coordinator)]) class SwitchBotClimateEntity(SwitchbotEntity, ClimateEntity): """Representation of a Switchbot Climate device.""" _device: switchbot.SwitchbotDevice _attr_supported_features = ( ClimateEntityFeature.PRESET_MODE | ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TURN_OFF | ClimateEntityFeature.TURN_ON ) _attr_target_temperature_step = 0.5 _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_translation_key = "climate" _attr_name = None @property def min_temp(self) -> float: """Return the minimum temperature.""" return self._device.min_temperature @property def max_temp(self) -> float: """Return the maximum temperature.""" return self._device.max_temperature @property def preset_modes(self) -> list[str] | None: """Return the list of available preset modes.""" return self._device.preset_modes @property def preset_mode(self) -> str | None: """Return the current preset mode.""" return self._device.preset_mode @property def hvac_mode(self) -> HVACMode | None: """Return the current HVAC mode.""" return SWITCHBOT_CLIMATE_TO_HASS_HVAC_MODE.get( self._device.hvac_mode, HVACMode.OFF ) @property def hvac_modes(self) -> list[HVACMode]: """Return the list of available HVAC modes.""" return [ SWITCHBOT_CLIMATE_TO_HASS_HVAC_MODE[mode] for mode in self._device.hvac_modes ] @property def hvac_action(self) -> HVACAction | None: """Return the current HVAC action.""" return SWITCHBOT_ACTION_TO_HASS_HVAC_ACTION.get( self._device.hvac_action, HVACAction.OFF ) @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self._device.current_temperature @property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self._device.target_temperature @exception_handler async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new HVAC mode.""" return await self._device.set_hvac_mode( HASS_HVAC_MODE_TO_SWITCHBOT_CLIMATE[hvac_mode] ) @exception_handler async def async_set_preset_mode(self, preset_mode: str) -> None: """Set new preset mode.""" return await self._device.set_preset_mode(preset_mode) @exception_handler async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) return await self._device.set_target_temperature(temperature)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/switchbot/climate.py", "license": "Apache License 2.0", "lines": 114, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/tesla_fleet/update.py
"""Update platform for Tesla Fleet integration.""" from __future__ import annotations import time from typing import Any from tesla_fleet_api.const import Scope from tesla_fleet_api.tesla.vehicle.fleet import VehicleFleet from homeassistant.components.update import UpdateEntity, UpdateEntityFeature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TeslaFleetConfigEntry from .entity import TeslaFleetVehicleEntity from .helpers import handle_vehicle_command from .models import TeslaFleetVehicleData AVAILABLE = "available" DOWNLOADING = "downloading" INSTALLING = "installing" WIFI_WAIT = "downloading_wifi_wait" SCHEDULED = "scheduled" PARALLEL_UPDATES = 0 # Show scheduled update as installing if within this many seconds SCHEDULED_THRESHOLD_SECONDS = 120 async def async_setup_entry( hass: HomeAssistant, entry: TeslaFleetConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Tesla Fleet update platform from a config entry.""" async_add_entities( TeslaFleetUpdateEntity(vehicle, entry.runtime_data.scopes) for vehicle in entry.runtime_data.vehicles ) class TeslaFleetUpdateEntity(TeslaFleetVehicleEntity, UpdateEntity): """Tesla Fleet Update entity.""" _attr_supported_features = UpdateEntityFeature.PROGRESS api: VehicleFleet def __init__( self, data: TeslaFleetVehicleData, scopes: list[Scope], ) -> None: """Initialize the Update.""" self.scoped = Scope.VEHICLE_CMDS in scopes super().__init__( data, "vehicle_state_software_update_status", ) async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Install an update.""" self.raise_for_read_only(Scope.VEHICLE_CMDS) await handle_vehicle_command(self.api.schedule_software_update(offset_sec=0)) self._attr_in_progress = True self.async_write_ha_state() def _async_update_attrs(self) -> None: """Update the attributes of the entity.""" # Supported Features - only show install button if update is available # but not already scheduled if self.scoped and self._value == AVAILABLE: self._attr_supported_features = ( UpdateEntityFeature.PROGRESS | UpdateEntityFeature.INSTALL ) else: self._attr_supported_features = UpdateEntityFeature.PROGRESS # Installed Version self._attr_installed_version = self.get("vehicle_state_car_version") if self._attr_installed_version is not None: # Remove build from version self._attr_installed_version = self._attr_installed_version.split(" ")[0] # Latest Version - hide update if scheduled far in the future if self._value in (AVAILABLE, INSTALLING, DOWNLOADING, WIFI_WAIT) or ( self._value == SCHEDULED and self._is_scheduled_soon() ): self._attr_latest_version = self.coordinator.data[ "vehicle_state_software_update_version" ] else: self._attr_latest_version = self._attr_installed_version # In Progress - only show as installing if actually installing or # scheduled to start within 2 minutes if self._value == INSTALLING: self._attr_in_progress = True if install_perc := self.get("vehicle_state_software_update_install_perc"): self._attr_update_percentage = install_perc elif self._value == SCHEDULED and self._is_scheduled_soon(): self._attr_in_progress = True self._attr_update_percentage = None else: self._attr_in_progress = False self._attr_update_percentage = None def _is_scheduled_soon(self) -> bool: """Check if a scheduled update is within the threshold to start.""" scheduled_time_ms = self.get("vehicle_state_software_update_scheduled_time_ms") if scheduled_time_ms is None: return False # Convert milliseconds to seconds and compare to current time scheduled_time_sec = scheduled_time_ms / 1000 return scheduled_time_sec - time.time() < SCHEDULED_THRESHOLD_SECONDS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/tesla_fleet/update.py", "license": "Apache License 2.0", "lines": 98, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/text/trigger.py
"""Provides triggers for texts.""" 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 .const import DOMAIN class TextChangedTrigger(EntityTriggerBase): """Trigger for text entity when its content changes.""" _domain = DOMAIN _schema = ENTITY_STATE_TRIGGER_SCHEMA 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]] = { "changed": TextChangedTrigger, } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for texts.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/text/trigger.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/transmission/entity.py
"""Base class for Transmission entities.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import TransmissionDataUpdateCoordinator class TransmissionEntity(CoordinatorEntity[TransmissionDataUpdateCoordinator]): """Defines a base Transmission entity.""" _attr_has_entity_name = True def __init__( self, coordinator: TransmissionDataUpdateCoordinator, entity_description: EntityDescription, ) -> None: """Initialize Transmission entity.""" super().__init__(coordinator) self.entity_description = entity_description self._attr_unique_id = ( f"{coordinator.config_entry.entry_id}-{entity_description.key}" ) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.config_entry.entry_id)}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/transmission/entity.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/transmission/services.py
"""Define services for the Transmission integration.""" from enum import StrEnum from functools import partial import logging from typing import Any from transmission_rpc import Torrent import voluptuous as vol from homeassistant.const import CONF_ID from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, selector, service from .const import ( ATTR_DELETE_DATA, ATTR_DOWNLOAD_PATH, ATTR_LABELS, ATTR_TORRENT, ATTR_TORRENT_FILTER, ATTR_TORRENTS, CONF_ENTRY_ID, DEFAULT_DELETE_DATA, DOMAIN, FILTER_MODES, SERVICE_ADD_TORRENT, SERVICE_GET_TORRENTS, SERVICE_REMOVE_TORRENT, SERVICE_START_TORRENT, SERVICE_STOP_TORRENT, ) from .coordinator import TransmissionConfigEntry, TransmissionDataUpdateCoordinator from .helpers import filter_torrents, format_torrents _LOGGER = logging.getLogger(__name__) class TorrentFilter(StrEnum): """TorrentFilter model.""" ALL = "all" STARTED = "started" COMPLETED = "completed" PAUSED = "paused" ACTIVE = "active" SERVICE_BASE_SCHEMA = vol.Schema( { vol.Required(CONF_ENTRY_ID): selector.ConfigEntrySelector( {"integration": DOMAIN} ), } ) SERVICE_ADD_TORRENT_SCHEMA = vol.All( SERVICE_BASE_SCHEMA.extend( { vol.Required(ATTR_TORRENT): cv.string, vol.Optional(ATTR_DOWNLOAD_PATH): cv.string, vol.Optional(ATTR_LABELS): cv.string, } ), ) SERVICE_GET_TORRENTS_SCHEMA = vol.All( SERVICE_BASE_SCHEMA.extend( { vol.Required(ATTR_TORRENT_FILTER): vol.In( [x.lower() for x in TorrentFilter] ), } ), ) SERVICE_REMOVE_TORRENT_SCHEMA = vol.All( SERVICE_BASE_SCHEMA.extend( { vol.Required(CONF_ID): cv.positive_int, vol.Optional(ATTR_DELETE_DATA, default=DEFAULT_DELETE_DATA): cv.boolean, } ) ) SERVICE_START_TORRENT_SCHEMA = vol.All( SERVICE_BASE_SCHEMA.extend({vol.Required(CONF_ID): cv.positive_int}), ) SERVICE_STOP_TORRENT_SCHEMA = vol.All( SERVICE_BASE_SCHEMA.extend( { vol.Required(CONF_ID): cv.positive_int, } ) ) def _get_coordinator_from_service_data( call: ServiceCall, ) -> TransmissionDataUpdateCoordinator: """Return coordinator for entry id.""" entry: TransmissionConfigEntry = service.async_get_config_entry( call.hass, DOMAIN, call.data[CONF_ENTRY_ID] ) return entry.runtime_data async def _async_add_torrent(call: ServiceCall) -> None: """Add new torrent to download.""" coordinator = _get_coordinator_from_service_data(call) torrent: str = call.data[ATTR_TORRENT] download_path: str | None = call.data.get(ATTR_DOWNLOAD_PATH) labels: list[str] | None = ( call.data[ATTR_LABELS].split(",") if ATTR_LABELS in call.data else None ) if not ( torrent.startswith(("http", "ftp:", "magnet:")) or call.hass.config.is_allowed_path(torrent) ): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="could_not_add_torrent", ) await call.hass.async_add_executor_job( partial( coordinator.api.add_torrent, torrent, labels=labels, download_dir=download_path, ) ) await coordinator.async_request_refresh() async def _async_get_torrents(call: ServiceCall) -> dict[str, Any] | None: """Get torrents.""" coordinator = _get_coordinator_from_service_data(call) torrent_filter: str = call.data[ATTR_TORRENT_FILTER] def get_filtered_torrents() -> list[Torrent]: """Filter torrents based on the filter provided.""" all_torrents = coordinator.api.get_torrents() return filter_torrents(all_torrents, FILTER_MODES[torrent_filter]) torrents = await call.hass.async_add_executor_job(get_filtered_torrents) info = format_torrents(torrents) return { ATTR_TORRENTS: info, } async def _async_start_torrent(call: ServiceCall) -> None: """Start torrent.""" coordinator = _get_coordinator_from_service_data(call) torrent_id = call.data[CONF_ID] await call.hass.async_add_executor_job(coordinator.api.start_torrent, torrent_id) await coordinator.async_request_refresh() async def _async_stop_torrent(call: ServiceCall) -> None: """Stop torrent.""" coordinator = _get_coordinator_from_service_data(call) torrent_id = call.data[CONF_ID] await call.hass.async_add_executor_job(coordinator.api.stop_torrent, torrent_id) await coordinator.async_request_refresh() async def _async_remove_torrent(call: ServiceCall) -> None: """Remove torrent.""" coordinator = _get_coordinator_from_service_data(call) torrent_id = call.data[CONF_ID] delete_data = call.data[ATTR_DELETE_DATA] await call.hass.async_add_executor_job( partial(coordinator.api.remove_torrent, torrent_id, delete_data=delete_data) ) await coordinator.async_request_refresh() @callback def async_setup_services(hass: HomeAssistant) -> None: """Register services for the Transmission integration.""" hass.services.async_register( DOMAIN, SERVICE_ADD_TORRENT, _async_add_torrent, schema=SERVICE_ADD_TORRENT_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_GET_TORRENTS, _async_get_torrents, schema=SERVICE_GET_TORRENTS_SCHEMA, supports_response=SupportsResponse.ONLY, ) hass.services.async_register( DOMAIN, SERVICE_REMOVE_TORRENT, _async_remove_torrent, schema=SERVICE_REMOVE_TORRENT_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_START_TORRENT, _async_start_torrent, schema=SERVICE_START_TORRENT_SCHEMA, ) hass.services.async_register( DOMAIN, SERVICE_STOP_TORRENT, _async_stop_torrent, schema=SERVICE_STOP_TORRENT_SCHEMA, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/transmission/services.py", "license": "Apache License 2.0", "lines": 182, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/vacuum/trigger.py
"""Provides triggers for vacuum cleaners.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import Trigger, make_entity_target_state_trigger from .const import DOMAIN, VacuumActivity TRIGGERS: dict[str, type[Trigger]] = { "docked": make_entity_target_state_trigger(DOMAIN, VacuumActivity.DOCKED), "errored": make_entity_target_state_trigger(DOMAIN, VacuumActivity.ERROR), "paused_cleaning": make_entity_target_state_trigger(DOMAIN, VacuumActivity.PAUSED), "started_cleaning": make_entity_target_state_trigger( DOMAIN, VacuumActivity.CLEANING ), "started_returning": make_entity_target_state_trigger( DOMAIN, VacuumActivity.RETURNING ), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for vacuum cleaners.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vacuum/trigger.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple