sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:tests/components/vesync/test_update.py
"""Tests for the update module.""" import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.update import DOMAIN as UPDATE_DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from .common import ALL_DEVICE_NAMES, mock_devices_response from tests.common import MockConfigEntry from tests.test_util.aiohttp import AiohttpClientMocker @pytest.mark.parametrize("device_name", ALL_DEVICE_NAMES) async def test_update_state( hass: HomeAssistant, snapshot: SnapshotAssertion, config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, aioclient_mock: AiohttpClientMocker, device_name: str, ) -> None: """Test the resulting setup state is as expected for the platform.""" # Configure the API devices call for device_name mock_devices_response(aioclient_mock, device_name) # setup platform - only including the named device await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() # Check device registry devices = dr.async_entries_for_config_entry(device_registry, config_entry.entry_id) assert devices == snapshot(name="devices") # Check entity registry entities = [ entity for entity in er.async_entries_for_config_entry( entity_registry, config_entry.entry_id ) if entity.domain == UPDATE_DOMAIN ] assert entities == snapshot(name="entities") # Check states for entity in entities: assert hass.states.get(entity.entity_id) == snapshot(name=entity.entity_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/vesync/test_update.py", "license": "Apache License 2.0", "lines": 40, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/victron_ble/fixtures.py
"""Fixtures for testing victron_ble.""" from home_assistant_bluetooth import BluetoothServiceInfo NOT_VICTRON_SERVICE_INFO = BluetoothServiceInfo( name="Not it", address="61DE521B-F0BF-9F44-64D4-75BBE1738105", rssi=-63, manufacturer_data={3234: b"\x00\x01"}, service_data={}, service_uuids=[], source="local", ) VICTRON_TEST_WRONG_TOKEN = "00000000000000000000000000000000" # battery monitor VICTRON_BATTERY_MONITOR_SERVICE_INFO = BluetoothServiceInfo( name="Battery Monitor", address="01:02:03:04:05:07", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("100289a302b040af925d09a4d89aa0128bdef48c6298a9") }, service_data={}, service_uuids=[], source="local", ) VICTRON_BATTERY_MONITOR_TOKEN = "aff4d0995b7d1e176c0c33ecb9e70dcd" VICTRON_BATTERY_MONITOR_SENSORS = { "battery_monitor_aux_mode": "disabled", "battery_monitor_consumed_ampere_hours": "-50.0", "battery_monitor_current": "0.0", "battery_monitor_remaining_minutes": "unknown", "battery_monitor_state_of_charge": "50.0", "battery_monitor_voltage": "12.53", "battery_monitor_alarm": "none", "battery_monitor_temperature": "unknown", "battery_monitor_starter_voltage": "unknown", "battery_monitor_midpoint_voltage": "unknown", } # DC/DC converter VICTRON_DC_DC_CONVERTER_SERVICE_INFO = BluetoothServiceInfo( name="DC/DC Converter", address="01:02:03:04:05:08", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("1000c0a304121d64ca8d442b90bbdf6a8cba"), }, service_data={}, service_uuids=[], source="local", ) # DC energy meter VICTRON_DC_ENERGY_METER_SERVICE_INFO = BluetoothServiceInfo( name="DC Energy Meter", address="01:02:03:04:05:09", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("100289a30d787fafde83ccec982199fd815286"), }, service_data={}, service_uuids=[], source="local", ) VICTRON_DC_ENERGY_METER_TOKEN = "aff4d0995b7d1e176c0c33ecb9e70dcd" VICTRON_DC_ENERGY_METER_SENSORS = { "dc_energy_meter_meter_type": "dc_dc_charger", "dc_energy_meter_aux_mode": "starter_voltage", "dc_energy_meter_current": "0.0", "dc_energy_meter_voltage": "12.52", "dc_energy_meter_starter_voltage": "-0.01", "dc_energy_meter_alarm": "none", "dc_energy_meter_temperature": "unknown", } # Inverter VICTRON_INVERTER_SERVICE_INFO = BluetoothServiceInfo( name="Inverter", address="01:02:03:04:05:10", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("1003a2a2031252dad26f0b8eb39162074d140df410"), }, # not a valid advertisement, but model id mangled to match inverter service_data={}, service_uuids=[], source="local", ) # Solar charger VICTRON_SOLAR_CHARGER_SERVICE_INFO = BluetoothServiceInfo( name="Solar Charger", address="01:02:03:04:05:11", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("100242a0016207adceb37b605d7e0ee21b24df5c"), }, service_data={}, service_uuids=[], source="local", ) VICTRON_SOLAR_CHARGER_TOKEN = "adeccb947395801a4dd45a2eaa44bf17" VICTRON_SOLAR_CHARGER_SENSORS = { "solar_charger_charge_state": "absorption", "solar_charger_battery_voltage": "13.88", "solar_charger_battery_current": "1.4", "solar_charger_yield_today": "30", "solar_charger_solar_power": "19", "solar_charger_external_device_load": "0.0", } # ve.bus VICTRON_VEBUS_SERVICE_INFO = BluetoothServiceInfo( name="Inverter Charger", address="01:02:03:04:05:06", rssi=-60, manufacturer_data={ 0x02E1: bytes.fromhex("100380270c1252dad26f0b8eb39162074d140df410") }, service_data={}, service_uuids=[], source="local", ) VICTRON_VEBUS_TOKEN = "da3f5fa2860cb1cf86ba7a6d1d16b9dd" VICTRON_VEBUS_SENSORS = { "inverter_charger_device_state": "float", "inverter_charger_battery_voltage": "14.45", "inverter_charger_battery_current": "23.2", "inverter_charger_ac_in_state": "AC_IN_1", "inverter_charger_ac_in_power": "1459", "inverter_charger_ac_out_power": "1046", "inverter_charger_battery_temperature": "32", "inverter_charger_state_of_charge": "unknown", }
{ "repo_id": "home-assistant/core", "file_path": "tests/components/victron_ble/fixtures.py", "license": "Apache License 2.0", "lines": 127, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/victron_ble/test_config_flow.py
"""Test the Victron Bluetooth Low Energy config flow.""" from unittest.mock import AsyncMock from home_assistant_bluetooth import BluetoothServiceInfo import pytest from homeassistant import config_entries from homeassistant.components.victron_ble.const import DOMAIN from homeassistant.config_entries import SOURCE_BLUETOOTH, SOURCE_USER from homeassistant.const import CONF_ACCESS_TOKEN, CONF_ADDRESS from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .fixtures import ( NOT_VICTRON_SERVICE_INFO, VICTRON_INVERTER_SERVICE_INFO, VICTRON_TEST_WRONG_TOKEN, VICTRON_VEBUS_SERVICE_INFO, VICTRON_VEBUS_TOKEN, ) from tests.common import MockConfigEntry @pytest.fixture(autouse=True) def mock_bluetooth(enable_bluetooth: None) -> None: """Mock bluetooth for all tests in this module.""" async def test_async_step_bluetooth_valid_device( hass: HomeAssistant, mock_setup_entry: AsyncMock ) -> None: """Test discovery via bluetooth with a valid device.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_BLUETOOTH}, data=VICTRON_VEBUS_SERVICE_INFO, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "access_token" # test valid access token result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_ACCESS_TOKEN: VICTRON_VEBUS_TOKEN}, ) assert result.get("type") is FlowResultType.CREATE_ENTRY assert result.get("title") == VICTRON_VEBUS_SERVICE_INFO.name flow_result = result.get("result") assert flow_result is not None assert flow_result.unique_id == VICTRON_VEBUS_SERVICE_INFO.address assert flow_result.data == { CONF_ACCESS_TOKEN: VICTRON_VEBUS_TOKEN, } assert set(flow_result.data.keys()) == {CONF_ACCESS_TOKEN} @pytest.mark.parametrize( ("source", "service_info", "expected_reason"), [ ( SOURCE_BLUETOOTH, NOT_VICTRON_SERVICE_INFO, "not_supported", ), ( SOURCE_BLUETOOTH, VICTRON_INVERTER_SERVICE_INFO, "not_supported", ), ( SOURCE_USER, None, "no_devices_found", ), ], ids=["bluetooth_not_victron", "bluetooth_unsupported_device", "user_no_devices"], ) async def test_abort_scenarios( hass: HomeAssistant, source: str, service_info: BluetoothServiceInfo | None, expected_reason: str, ) -> None: """Test flows that result in abort.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": source}, data=service_info, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == expected_reason async def test_async_step_user_with_devices_found( hass: HomeAssistant, mock_discovered_service_info: AsyncMock ) -> None: """Test setup from service info cache with devices found.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_ADDRESS: VICTRON_VEBUS_SERVICE_INFO.address}, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "access_token" # test invalid access token (valid already tested above) result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={CONF_ACCESS_TOKEN: VICTRON_TEST_WRONG_TOKEN} ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "invalid_access_token" async def test_async_step_user_device_added_between_steps( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_discovered_service_info: AsyncMock, ) -> None: """Test abort when the device gets added via another flow between steps.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "user" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"address": VICTRON_VEBUS_SERVICE_INFO.address}, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" async def test_async_step_user_with_found_devices_already_setup( hass: HomeAssistant, mock_config_entry_added_to_hass: MockConfigEntry, mock_discovered_service_info: AsyncMock, ) -> None: """Test setup from service info cache with devices found.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER}, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "no_devices_found" async def test_async_step_bluetooth_devices_already_setup( hass: HomeAssistant, mock_config_entry_added_to_hass: MockConfigEntry ) -> None: """Test we can't start a flow if there is already a config entry.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_BLUETOOTH}, data=VICTRON_VEBUS_SERVICE_INFO, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" async def test_async_step_bluetooth_already_in_progress(hass: HomeAssistant) -> None: """Test we can't start a flow for the same device twice.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_BLUETOOTH}, data=VICTRON_VEBUS_SERVICE_INFO, ) assert result.get("type") is FlowResultType.FORM assert result.get("step_id") == "access_token" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_BLUETOOTH}, data=VICTRON_VEBUS_SERVICE_INFO, ) assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_in_progress"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/victron_ble/test_config_flow.py", "license": "Apache License 2.0", "lines": 161, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/victron_ble/test_sensor.py
"""Test updating sensors in the victron_ble integration.""" from home_assistant_bluetooth import BluetoothServiceInfo import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .fixtures import ( VICTRON_BATTERY_MONITOR_SERVICE_INFO, VICTRON_BATTERY_MONITOR_TOKEN, VICTRON_DC_ENERGY_METER_SERVICE_INFO, VICTRON_DC_ENERGY_METER_TOKEN, VICTRON_SOLAR_CHARGER_SERVICE_INFO, VICTRON_SOLAR_CHARGER_TOKEN, VICTRON_VEBUS_SERVICE_INFO, VICTRON_VEBUS_TOKEN, ) from tests.common import MockConfigEntry, snapshot_platform from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.usefixtures("enable_bluetooth") @pytest.mark.parametrize( ( "service_info", "access_token", ), [ (VICTRON_BATTERY_MONITOR_SERVICE_INFO, VICTRON_BATTERY_MONITOR_TOKEN), (VICTRON_DC_ENERGY_METER_SERVICE_INFO, VICTRON_DC_ENERGY_METER_TOKEN), (VICTRON_SOLAR_CHARGER_SERVICE_INFO, VICTRON_SOLAR_CHARGER_TOKEN), (VICTRON_VEBUS_SERVICE_INFO, VICTRON_VEBUS_TOKEN), ], ids=["battery_monitor", "dc_energy_meter", "solar_charger", "vebus"], ) async def test_sensors( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry_added_to_hass: MockConfigEntry, service_info: BluetoothServiceInfo, access_token: str, ) -> None: """Test sensor entities.""" entry = mock_config_entry_added_to_hass assert await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() # Initially no entities should be created until bluetooth data is received assert len(hass.states.async_all()) == 0 # Inject bluetooth service info to trigger entity creation inject_bluetooth_service_info(hass, service_info) await hass.async_block_till_done() # Use snapshot testing to verify all entity states and registry entries await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/victron_ble/test_sensor.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/volvo/test_lock.py
"""Test Volvo locks.""" from collections.abc import Awaitable, Callable from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from volvocarsapi.api import VolvoCarsApi from volvocarsapi.models import VolvoApiException, VolvoCarsCommandResult from homeassistant.components.lock import ( DOMAIN as LOCK_DOMAIN, SERVICE_LOCK, SERVICE_UNLOCK, LockState, ) 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 configure_mock from .const import DEFAULT_VIN from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.usefixtures("mock_api", "full_model") @pytest.mark.parametrize( "full_model", ["ex30_2024", "s90_diesel_2018", "xc40_electric_2024", "xc90_petrol_2019"], ) async def test_lock( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test lock.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.LOCK]): assert await setup_integration() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("full_model") @pytest.mark.parametrize( "action", [SERVICE_UNLOCK, SERVICE_LOCK], ) async def test_unlock_lock( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], mock_api: VolvoCarsApi, action: str, ) -> None: """Test unlock/lock.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.LOCK]): assert await setup_integration() await hass.services.async_call( LOCK_DOMAIN, action, {ATTR_ENTITY_ID: "lock.volvo_xc40_lock"}, blocking=True, ) await hass.async_block_till_done() mock_api.async_execute_command.assert_called_once_with(action) @pytest.mark.usefixtures("full_model") @pytest.mark.parametrize( "action", [SERVICE_UNLOCK, SERVICE_LOCK], ) async def test_unlock_lock_error( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], mock_api: VolvoCarsApi, action: str, ) -> None: """Test unlock/lock with error response.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.LOCK]): assert await setup_integration() configure_mock(mock_api.async_execute_command, side_effect=VolvoApiException) entity_id = "lock.volvo_xc40_lock" assert hass.states.get(entity_id).state == LockState.LOCKED with pytest.raises(HomeAssistantError): await hass.services.async_call( LOCK_DOMAIN, action, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() assert hass.states.get(entity_id).state == LockState.LOCKED @pytest.mark.usefixtures("full_model") async def test_unlock_failure( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], mock_api: VolvoCarsApi, ) -> None: """Test unlock/lock with error response.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.LOCK]): assert await setup_integration() configure_mock( mock_api.async_execute_command, return_value=VolvoCarsCommandResult( vin=DEFAULT_VIN, invoke_status="CONNECTION_FAILURE", message="" ), ) entity_id = "lock.volvo_xc40_lock" assert hass.states.get(entity_id).state == LockState.LOCKED with pytest.raises(HomeAssistantError): await hass.services.async_call( LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: entity_id}, blocking=True, ) await hass.async_block_till_done() assert hass.states.get(entity_id).state == LockState.LOCKED
{ "repo_id": "home-assistant/core", "file_path": "tests/components/volvo/test_lock.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/waqi/test_diagnostics.py
"""Tests for the diagnostics data provided by the WAQI integration.""" from unittest.mock import AsyncMock from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from . import setup_integration from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_waqi: AsyncMock, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test diagnostics.""" await setup_integration(hass, mock_config_entry) assert ( await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/waqi/test_diagnostics.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/xbox/test_diagnostics.py
"""Test for diagnostics platform of the Xbox integration.""" import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator @pytest.mark.usefixtures("xbox_live_client") async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test diagnostics.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert ( await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/xbox/test_diagnostics.py", "license": "Apache License 2.0", "lines": 24, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/xbox/test_media_source.py
"""Tests for the Xbox media source platform.""" from httpx import HTTPStatusError, RequestError, Response, TimeoutException import pytest from pythonxbox.api.provider.people.models import PeopleResponse from syrupy.assertion import SnapshotAssertion from homeassistant.components.media_player import BrowseError from homeassistant.components.media_source import ( URI_SCHEME, Unresolvable, async_browse_media, async_resolve_media, ) from homeassistant.components.xbox.const import DOMAIN from homeassistant.config_entries import ConfigEntryDisabler, ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.common import AsyncMock, MockConfigEntry, async_load_json_object_fixture from tests.typing import MagicMock @pytest.fixture(autouse=True) async def setup_media_source(hass: HomeAssistant) -> None: """Setup media source component.""" await async_setup_component(hass, "media_source", {}) @pytest.mark.usefixtures("xbox_live_client") @pytest.mark.freeze_time("2025-11-06T17:12:27") async def test_browse_media( hass: HomeAssistant, config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test browsing media.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert ( await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}") ).as_dict() == snapshot(name="games_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135" ) ).as_dict() == snapshot(name="category_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/gameclips" ) ).as_dict() == snapshot(name="gameclips_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/screenshots" ) ).as_dict() == snapshot(name="screenshots_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/game_media" ) ).as_dict() == snapshot(name="game_media_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/community_gameclips" ) ).as_dict() == snapshot(name="community_gameclips_view") assert ( await async_browse_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/community_screenshots", ) ).as_dict() == snapshot(name="community_screenshots_view") async def test_browse_media_accounts( hass: HomeAssistant, xbox_live_client: AsyncMock, snapshot: SnapshotAssertion, ) -> None: """Test browsing media we get account view if more than 1 account is configured.""" config_entry = MockConfigEntry( domain=DOMAIN, title="GSR Ae", data={ "auth_implementation": "cloud", "token": { "access_token": "1234567890", "expires_at": 1760697327.7298331, "expires_in": 3600, "refresh_token": "0987654321", "scope": "XboxLive.signin XboxLive.offline_access", "service": "xbox", "token_type": "bearer", "user_id": "AAAAAAAAAAAAAAAAAAAAA", }, }, unique_id="271958441785640", minor_version=3, ) config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED xbox_live_client.people.get_friends_by_xuid.return_value = PeopleResponse( **(await async_load_json_object_fixture(hass, "people_batch2.json", DOMAIN)) # type: ignore[reportArgumentType] ) config_entry2 = MockConfigEntry( domain=DOMAIN, title="Iqnavs", data={ "auth_implementation": "cloud", "token": { "access_token": "1234567890", "expires_at": 1760697327.7298331, "expires_in": 3600, "refresh_token": "0987654321", "scope": "XboxLive.signin XboxLive.offline_access", "service": "xbox", "token_type": "bearer", "user_id": "AAAAAAAAAAAAAAAAAAAAA", }, }, unique_id="277923030577271", minor_version=3, ) config_entry2.add_to_hass(hass) await hass.config_entries.async_setup(config_entry2.entry_id) await hass.async_block_till_done() assert config_entry2.state is ConfigEntryState.LOADED assert len(hass.config_entries.async_loaded_entries(DOMAIN)) == 2 assert ( await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}") ).as_dict() == snapshot @pytest.mark.parametrize( ("media_content_id", "provider", "method"), [ ("", "titlehub", "get_title_history"), ("/271958441785640", "titlehub", "get_title_history"), ("/271958441785640/1297287135", "titlehub", "get_title_info"), ( "/271958441785640/1297287135/gameclips", "gameclips", "get_recent_clips_by_xuid", ), ( "/271958441785640/1297287135/screenshots", "screenshots", "get_recent_screenshots_by_xuid", ), ( "/271958441785640/1297287135/game_media", "titlehub", "get_title_info", ), ( "/271958441785640/1297287135/community_gameclips", "gameclips", "get_recent_community_clips_by_title_id", ), ( "/271958441785640/1297287135/community_screenshots", "screenshots", "get_recent_community_screenshots_by_title_id", ), ], ) @pytest.mark.parametrize( ("exception", "translation_key"), [ ( HTTPStatusError("", request=MagicMock(), response=Response(500)), "request_exception", ), ( RequestError(""), "request_exception", ), (TimeoutException(""), "timeout_exception"), ], ) async def test_browse_media_exceptions( hass: HomeAssistant, config_entry: MockConfigEntry, xbox_live_client: AsyncMock, media_content_id: str, provider: str, method: str, exception: Exception, translation_key: str, ) -> None: """Test browsing media exceptions.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED provider = getattr(xbox_live_client, provider) getattr(provider, method).side_effect = exception with pytest.raises(BrowseError) as e: await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}{media_content_id}") assert e.value.translation_key == translation_key @pytest.mark.usefixtures("xbox_live_client") async def test_browse_media_not_configured_exception( hass: HomeAssistant, ) -> None: """Test browsing media integration not configured exception.""" config_entry = MockConfigEntry( domain=DOMAIN, title="Mock title", data={ "auth_implementation": "cloud", "token": { "access_token": "1234567890", "expires_at": 1760697327.7298331, "expires_in": 3600, "refresh_token": "0987654321", "scope": "XboxLive.signin XboxLive.offline_access", "service": "xbox", "token_type": "bearer", "user_id": "AAAAAAAAAAAAAAAAAAAAA", }, }, unique_id="2533274838782903", disabled_by=ConfigEntryDisabler.USER, minor_version=3, ) config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.NOT_LOADED with pytest.raises(BrowseError) as e: await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}") assert e.value.translation_key == "xbox_not_configured" @pytest.mark.usefixtures("xbox_live_client") async def test_browse_media_account_not_configured_exception( hass: HomeAssistant, config_entry: MockConfigEntry, ) -> None: """Test browsing media account not configured exception.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED with pytest.raises(BrowseError) as e: await async_browse_media(hass, f"{URI_SCHEME}{DOMAIN}/2533274838782903") assert e.value.translation_key == "account_not_configured" @pytest.mark.parametrize( ("media_content_id", "url", "mime_type"), [ ( "/271958441785640/1297287135/screenshots/41593644-be22-43d6-b224-c7bebe14076e", "https://screenshotscontent-d5001.xboxlive.com/00097bbbbbbbbb23-41593644-be22-43d6-b224-c7bebe14076e/Screenshot-Original.png?sv=2015-12-11&sr=b&si=DefaultAccess&sig=ALKo3DE2HXqBTlpdyynIrH6RPKIECOF7zwotH%2Bb30Ts%3D", "image/png", ), ( "/271958441785640/1297287135/gameclips/f87cc6ac-c291-4998-9124-d8b36c059b6a", "https://gameclipscontent-d2015.xboxlive.com/asset-d5448dbd-f45e-46ab-ae4e-a2e205a70e7c/GameClip-Original.MP4?sv=2015-12-11&sr=b&si=DefaultAccess&sig=ArSoLvy9EnQeBthGW6%2FbasedHHk0Jb6iXjI3EMq8oh8%3D&__gda__=1522241341_69f67a7a3533626ae90b52845664dc0c", "video/mp4", ), ( "/271958441785640/1297287135/game_media/0", "https://store-images.s-microsoft.com/image/apps.35725.65457035095819016.56f55216-1bb9-40aa-8796-068cf3075fc1.c4bf34f8-ad40-4af3-914e-a85e75a76bed", "image/png", ), ( "/271958441785640/1297287135/community_screenshots/504a78e5-be24-4020-a245-77cb528e91ea", "https://screenshotscontent-d5002.media.xboxlive.com/xuid-2535422966774043-private/504a78e5-be24-4020-a245-77cb528e91ea.PNG?skoid=296fcea0-0bf0-4a22-abf7-16b3524eba1b&sktid=68cd85cc-e0b3-43c8-ba3c-67686dbf8a67&skt=2025-11-06T10%3A21%3A06Z&ske=2025-11-07T10%3A21%3A06Z&sks=b&skv=2025-05-05&sv=2025-05-05&st=2025-11-06T10%3A35%3A59Z&se=2125-11-06T10%3A50%3A59Z&sr=b&sp=r&sig=TqUUNeuAzHawaXBTFfSVuUzuXbGOMgrDu0Q2VBTFd5U%3D", "image/png", ), ( "/271958441785640/1297287135/community_gameclips/6fa2731a-8b58-4aa6-848c-4bf15734358b", "https://gameclipscontent-d3021.media.xboxlive.com/xuid-2535458333395495-private/6fa2731a-8b58-4aa6-848c-4bf15734358b.MP4?skoid=2938738c-0e58-4f21-9b82-98081ade42e2&sktid=68cd85cc-e0b3-43c8-ba3c-67686dbf8a67&skt=2025-11-06T08%3A20%3A51Z&ske=2025-11-07T08%3A20%3A51Z&sks=b&skv=2025-05-05&sv=2025-05-05&st=2025-11-06T10%3A05%3A41Z&se=2125-11-06T10%3A20%3A41Z&sr=b&sp=r&sig=s%2FWDtmE2cnAwl9iJJFcch3knbRlkxkALoinHQwCnNP0%3D&__gda__=1762438393_eb8a56c3f482d00099045aa892a2aa05", "video/mp4", ), ], ids=[ "screenshot", "gameclips", "game_media", "community_screenshots", "community_gameclips", ], ) @pytest.mark.usefixtures("xbox_live_client") async def test_resolve_media( hass: HomeAssistant, config_entry: MockConfigEntry, media_content_id: str, url: str, mime_type: str, ) -> None: """Test resolve media.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED media = await async_resolve_media( hass, f"{URI_SCHEME}{DOMAIN}{media_content_id}", None, ) assert media.url == url assert media.mime_type == mime_type @pytest.mark.parametrize( ("media_content_id", "provider", "method"), [ ( "/271958441785640/1297287135/screenshots/41593644-be22-43d6-b224-c7bebe14076e", "screenshots", "get_recent_screenshots_by_xuid", ), ( "/271958441785640/1297287135/gameclips/f87cc6ac-c291-4998-9124-d8b36c059b6a", "gameclips", "get_recent_clips_by_xuid", ), ( "/271958441785640/1297287135/community_screenshots/504a78e5-be24-4020-a245-77cb528e91ea", "screenshots", "get_recent_community_screenshots_by_title_id", ), ( "/271958441785640/1297287135/community_gameclips/6fa2731a-8b58-4aa6-848c-4bf15734358b", "gameclips", "get_recent_community_clips_by_title_id", ), ( "/271958441785640/1297287135/game_media/0", "titlehub", "get_title_info", ), ], ) @pytest.mark.parametrize( ("exception", "translation_key"), [ ( HTTPStatusError("", request=MagicMock(), response=Response(500)), "request_exception", ), (RequestError(""), "request_exception"), (TimeoutException(""), "timeout_exception"), ], ) async def test_resolve_media_exceptions( hass: HomeAssistant, config_entry: MockConfigEntry, xbox_live_client: AsyncMock, media_content_id: str, provider: str, method: str, exception: Exception, translation_key: str, ) -> None: """Test resolve media exceptions.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED provider = getattr(xbox_live_client, provider) getattr(provider, method).side_effect = exception with pytest.raises(Unresolvable) as e: await async_resolve_media( hass, f"{URI_SCHEME}{DOMAIN}{media_content_id}", None, ) assert e.value.translation_key == translation_key @pytest.mark.parametrize(("media_type"), ["screenshots", "gameclips", "game_media"]) @pytest.mark.usefixtures("xbox_live_client") async def test_resolve_media_not_found_exceptions( hass: HomeAssistant, config_entry: MockConfigEntry, media_type: str, ) -> None: """Test resolve media not found exceptions.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED with pytest.raises(Unresolvable) as e: await async_resolve_media( hass, f"{URI_SCHEME}{DOMAIN}/271958441785640/1297287135/{media_type}/12345", None, ) assert e.value.translation_key == "media_not_found" @pytest.mark.usefixtures("xbox_live_client") async def test_resolve_media_not_configured( hass: HomeAssistant, ) -> None: """Test resolve media integration not configured exception.""" config_entry = MockConfigEntry( domain=DOMAIN, title="Mock title", data={ "auth_implementation": "cloud", "token": { "access_token": "1234567890", "expires_at": 1760697327.7298331, "expires_in": 3600, "refresh_token": "0987654321", "scope": "XboxLive.signin XboxLive.offline_access", "service": "xbox", "token_type": "bearer", "user_id": "AAAAAAAAAAAAAAAAAAAAA", }, }, unique_id="2533274838782903", disabled_by=ConfigEntryDisabler.USER, ) config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.NOT_LOADED with pytest.raises(Unresolvable) as e: await async_resolve_media( hass, f"{URI_SCHEME}{DOMAIN}/2533274838782903", None, ) assert e.value.translation_key == "xbox_not_configured" @pytest.mark.usefixtures("xbox_live_client") async def test_resolve_media_account_not_configured( hass: HomeAssistant, config_entry: MockConfigEntry, ) -> None: """Test resolve media account not configured exception.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED with pytest.raises(Unresolvable) as e: await async_resolve_media( hass, f"{URI_SCHEME}{DOMAIN}/2533274838782903", None, ) assert e.value.translation_key == "account_not_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/xbox/test_media_source.py", "license": "Apache License 2.0", "lines": 432, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_areas.py
"""Test area template functions.""" from __future__ import annotations from homeassistant.core import HomeAssistant from homeassistant.helpers import ( area_registry as ar, device_registry as dr, entity_registry as er, ) from tests.common import MockConfigEntry from tests.helpers.template.helpers import assert_result_info, render_to_info async def test_areas(hass: HomeAssistant, area_registry: ar.AreaRegistry) -> None: """Test areas function.""" # Test no areas info = render_to_info(hass, "{{ areas() }}") assert_result_info(info, []) assert info.rate_limit is None # Test one area area1 = area_registry.async_get_or_create("area1") info = render_to_info(hass, "{{ areas() }}") assert_result_info(info, [area1.id]) assert info.rate_limit is None # Test multiple areas area2 = area_registry.async_get_or_create("area2") info = render_to_info(hass, "{{ areas() }}") assert_result_info(info, [area1.id, area2.id]) assert info.rate_limit is None async def test_area_id( hass: HomeAssistant, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test area_id function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing entity id info = render_to_info(hass, "{{ area_id('sensor.fake') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing device id (hex value) info = render_to_info(hass, "{{ area_id('123abc') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing area name info = render_to_info(hass, "{{ area_id('fake area name') }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ area_id(56) }}") assert_result_info(info, None) assert info.rate_limit is None area_registry.async_get_or_create("sensor.fake") # Test device with single entity, which has no area device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(hass, f"{{{{ area_id('{device_entry.id}') }}}}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_id('{entity_entry.entity_id}') }}}}") assert_result_info(info, None) assert info.rate_limit is None # Test device ID, entity ID and area name as input with area name that looks like # a device ID. Try a filter too area_entry_hex = area_registry.async_get_or_create("123abc") device_entry = device_registry.async_update_device( device_entry.id, area_id=area_entry_hex.id ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry_hex.id ) info = render_to_info(hass, f"{{{{ '{device_entry.id}' | area_id }}}}") assert_result_info(info, area_entry_hex.id) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_id('{entity_entry.entity_id}') }}}}") assert_result_info(info, area_entry_hex.id) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_id('{area_entry_hex.name}') }}}}") assert_result_info(info, area_entry_hex.id) assert info.rate_limit is None # Test device ID, entity ID and area name as input with area name that looks like an # entity ID area_entry_entity_id = area_registry.async_get_or_create("sensor.fake") device_entry = device_registry.async_update_device( device_entry.id, area_id=area_entry_entity_id.id ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry_entity_id.id ) info = render_to_info(hass, f"{{{{ area_id('{device_entry.id}') }}}}") assert_result_info(info, area_entry_entity_id.id) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_id('{entity_entry.entity_id}') }}}}") assert_result_info(info, area_entry_entity_id.id) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_id('{area_entry_entity_id.name}') }}}}") assert_result_info(info, area_entry_entity_id.id) assert info.rate_limit is None # Make sure that when entity doesn't have an area but its device does, that's what # gets returned entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry_entity_id.id ) info = render_to_info(hass, f"{{{{ area_id('{entity_entry.entity_id}') }}}}") assert_result_info(info, area_entry_entity_id.id) assert info.rate_limit is None async def test_area_name( hass: HomeAssistant, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test area_name function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing entity id info = render_to_info(hass, "{{ area_name('sensor.fake') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing device id (hex value) info = render_to_info(hass, "{{ area_name('123abc') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing area id info = render_to_info(hass, "{{ area_name('1234567890') }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ area_name(56) }}") assert_result_info(info, None) assert info.rate_limit is None # Test device with single entity, which has no area device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(hass, f"{{{{ area_name('{device_entry.id}') }}}}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_name('{entity_entry.entity_id}') }}}}") assert_result_info(info, None) assert info.rate_limit is None # Test device ID, entity ID and area id as input. Try a filter too area_entry = area_registry.async_get_or_create("123abc") device_entry = device_registry.async_update_device( device_entry.id, area_id=area_entry.id ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry.id ) info = render_to_info(hass, f"{{{{ '{device_entry.id}' | area_name }}}}") assert_result_info(info, area_entry.name) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_name('{entity_entry.entity_id}') }}}}") assert_result_info(info, area_entry.name) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ area_name('{area_entry.id}') }}}}") assert_result_info(info, area_entry.name) assert info.rate_limit is None # Make sure that when entity doesn't have an area but its device does, that's what # gets returned entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=None ) info = render_to_info(hass, f"{{{{ area_name('{entity_entry.entity_id}') }}}}") assert_result_info(info, area_entry.name) assert info.rate_limit is None async def test_area_entities( hass: HomeAssistant, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test area_entities function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing device id info = render_to_info(hass, "{{ area_entities('deadbeef') }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ area_entities(56) }}") assert_result_info(info, []) assert info.rate_limit is None area_entry = area_registry.async_get_or_create("sensor.fake") entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, ) entity_registry.async_update_entity(entity_entry.entity_id, area_id=area_entry.id) info = render_to_info(hass, f"{{{{ area_entities('{area_entry.id}') }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{area_entry.name}' | area_entities }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None # Test for entities that inherit area from device device_entry = device_registry.async_get_or_create( connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, config_entry_id=config_entry.entry_id, suggested_area="sensor.fake", ) entity_registry.async_get_or_create( "light", "hue_light", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(hass, f"{{{{ '{area_entry.name}' | area_entities }}}}") assert_result_info(info, ["light.hue_5678", "light.hue_light_5678"]) assert info.rate_limit is None async def test_area_devices( hass: HomeAssistant, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, ) -> None: """Test area_devices function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing device id info = render_to_info(hass, "{{ area_devices('deadbeef') }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ area_devices(56) }}") assert_result_info(info, []) assert info.rate_limit is None area_entry = area_registry.async_get_or_create("sensor.fake") device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, suggested_area=area_entry.name, ) info = render_to_info(hass, f"{{{{ area_devices('{area_entry.id}') }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{area_entry.name}' | area_devices }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_areas.py", "license": "Apache License 2.0", "lines": 257, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_base.py
"""Test base template extension.""" from __future__ import annotations import pytest from homeassistant.exceptions import TemplateError from homeassistant.helpers.template import TemplateEnvironment from homeassistant.helpers.template.extensions.base import ( BaseTemplateExtension, TemplateFunction, ) def test_hass_property_raises_when_hass_is_none() -> None: """Test that accessing hass property raises RuntimeError when hass is None.""" # Create an environment without hass env = TemplateEnvironment(None) # Create a simple extension extension = BaseTemplateExtension(env) # Accessing hass property should raise RuntimeError with pytest.raises( RuntimeError, match=( "Home Assistant instance is not available. " "This property should only be used in extensions with " "functions marked requires_hass=True." ), ): _ = extension.hass def test_requires_hass_functions_not_registered_without_hass() -> None: """Test that functions requiring hass are not registered when hass is None.""" # Create an environment without hass env = TemplateEnvironment(None) # Create a test function def test_func() -> str: return "test" # Create extension with a function that requires hass extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_func", test_func, as_global=True, requires_hass=True, ), ], ) # Function should not be registered assert "test_func" not in env.globals assert extension is not None # Extension is created but function not registered def test_requires_hass_false_functions_registered_without_hass() -> None: """Test that functions not requiring hass are registered even when hass is None.""" # Create an environment without hass env = TemplateEnvironment(None) # Create a test function def test_func() -> str: return "test" # Create extension with a function that does not require hass extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_func", test_func, as_global=True, requires_hass=False, # Explicitly False (default) ), ], ) # Function should be registered assert "test_func" in env.globals assert extension is not None def test_limited_ok_functions_not_registered_in_limited_env() -> None: """Test that functions with limited_ok=False raise error in limited env.""" # Create a limited environment without hass env = TemplateEnvironment(None, limited=True) # Create test functions def allowed_func() -> str: return "allowed" def restricted_func() -> str: return "restricted" # Create extension with both types of functions extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "allowed_func", allowed_func, as_global=True, limited_ok=True, # Allowed in limited environments ), TemplateFunction( "restricted_func", restricted_func, as_global=True, limited_ok=False, # Not allowed in limited environments ), ], ) # The allowed function should be registered and work assert "allowed_func" in env.globals assert env.globals["allowed_func"]() == "allowed" # The restricted function should be registered but raise TemplateError assert "restricted_func" in env.globals with pytest.raises( TemplateError, match="Use of 'restricted_func' is not supported in limited templates", ): env.globals["restricted_func"]() assert extension is not None def test_limited_ok_true_functions_registered_in_limited_env() -> None: """Test that functions with limited_ok=True are registered in limited env.""" # Create a limited environment without hass env = TemplateEnvironment(None, limited=True) # Create a test function def test_func() -> str: return "test" # Create extension with a function allowed in limited environments extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_func", test_func, as_global=True, limited_ok=True, # Default is True ), ], ) # Function should be registered assert "test_func" in env.globals assert extension is not None def test_function_registered_as_global() -> None: """Test that functions can be registered as globals.""" env = TemplateEnvironment(None) def test_func() -> str: return "global" extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_func", test_func, as_global=True, ), ], ) # Function should be registered as a global assert "test_func" in env.globals assert env.globals["test_func"] is test_func assert extension is not None def test_function_registered_as_filter() -> None: """Test that functions can be registered as filters.""" env = TemplateEnvironment(None) def test_filter(value: str) -> str: return f"filtered_{value}" extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_filter", test_filter, as_filter=True, ), ], ) # Function should be registered as a filter assert "test_filter" in env.filters assert env.filters["test_filter"] is test_filter # Should not be in globals since as_global=False assert "test_filter" not in env.globals assert extension is not None def test_function_registered_as_test() -> None: """Test that functions can be registered as tests.""" env = TemplateEnvironment(None) def test_check(value: str) -> bool: return value == "test" extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "test_check", test_check, as_test=True, ), ], ) # Function should be registered as a test assert "test_check" in env.tests assert env.tests["test_check"] is test_check # Should not be in globals or filters assert "test_check" not in env.globals assert "test_check" not in env.filters assert extension is not None def test_function_registered_as_multiple_types() -> None: """Test that functions can be registered as multiple types simultaneously.""" env = TemplateEnvironment(None) def multi_func(value: str = "default") -> str: return f"multi_{value}" extension = BaseTemplateExtension( env, functions=[ TemplateFunction( "multi_func", multi_func, as_global=True, as_filter=True, as_test=True, ), ], ) # Function should be registered in all three places assert "multi_func" in env.globals assert env.globals["multi_func"] is multi_func assert "multi_func" in env.filters assert env.filters["multi_func"] is multi_func assert "multi_func" in env.tests assert env.tests["multi_func"] is multi_func assert extension is not None def test_multiple_functions_registered() -> None: """Test that multiple functions can be registered at once.""" env = TemplateEnvironment(None) def func1() -> str: return "one" def func2() -> str: return "two" def func3() -> str: return "three" extension = BaseTemplateExtension( env, functions=[ TemplateFunction("func1", func1, as_global=True), TemplateFunction("func2", func2, as_filter=True), TemplateFunction("func3", func3, as_test=True), ], ) # All functions should be registered in their respective places assert "func1" in env.globals assert "func2" in env.filters assert "func3" in env.tests assert extension is not None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_base.py", "license": "Apache License 2.0", "lines": 238, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_datetime.py
"""Test datetime template functions.""" from __future__ import annotations from datetime import datetime from types import MappingProxyType from typing import Any from unittest.mock import patch from freezegun import freeze_time import pytest from homeassistant.core import HomeAssistant from homeassistant.exceptions import TemplateError from homeassistant.util import dt as dt_util from homeassistant.util.read_only_dict import ReadOnlyDict from tests.helpers.template.helpers import render, render_to_info @pytest.mark.parametrize( ("value", "expected"), [ ([1, 2], False), ({1, 2}, False), ({"a": 1, "b": 2}, False), (ReadOnlyDict({"a": 1, "b": 2}), False), (MappingProxyType({"a": 1, "b": 2}), False), ("abc", False), (b"abc", False), ((1, 2), False), (datetime(2024, 1, 1, 0, 0, 0), True), ], ) def test_is_datetime(hass: HomeAssistant, value, expected) -> None: """Test is datetime.""" assert render(hass, "{{ value is datetime }}", {"value": value}) == expected def test_strptime(hass: HomeAssistant) -> None: """Test the parse timestamp method.""" tests = [ ("2016-10-19 15:22:05.588122 UTC", "%Y-%m-%d %H:%M:%S.%f %Z", None), ("2016-10-19 15:22:05.588122+0100", "%Y-%m-%d %H:%M:%S.%f%z", None), ("2016-10-19 15:22:05.588122", "%Y-%m-%d %H:%M:%S.%f", None), ("2016-10-19", "%Y-%m-%d", None), ("2016", "%Y", None), ("15:22:05", "%H:%M:%S", None), ] for inp, fmt, expected in tests: if expected is None: expected = str(datetime.strptime(inp, fmt)) temp = f"{{{{ strptime('{inp}', '{fmt}') }}}}" assert render(hass, temp) == expected # Test handling of invalid input invalid_tests = [ ("1469119144", "%Y"), ("invalid", "%Y"), ] for inp, fmt in invalid_tests: temp = f"{{{{ strptime('{inp}', '{fmt}') }}}}" with pytest.raises(TemplateError): render(hass, temp) # Test handling of default return value assert render(hass, "{{ strptime('invalid', '%Y', 1) }}") == 1 assert render(hass, "{{ strptime('invalid', '%Y', default=1) }}") == 1 async def test_timestamp_custom(hass: HomeAssistant) -> None: """Test the timestamps to custom filter.""" await hass.config.async_set_time_zone("UTC") now = dt_util.utcnow() tests = [ (1469119144, None, True, "2016-07-21 16:39:04"), (1469119144, "%Y", True, 2016), (1469119144, "invalid", True, "invalid"), (dt_util.as_timestamp(now), None, False, now.strftime("%Y-%m-%d %H:%M:%S")), ] for inp, fmt, local, out in tests: if fmt: fil = f"timestamp_custom('{fmt}')" elif fmt and local: fil = f"timestamp_custom('{fmt}', {local})" else: fil = "timestamp_custom" assert render(hass, f"{{{{ {inp} | {fil} }}}}") == out # Test handling of invalid input invalid_tests = [ (None, None, None), ] for inp, fmt, local in invalid_tests: if fmt: fil = f"timestamp_custom('{fmt}')" elif fmt and local: fil = f"timestamp_custom('{fmt}', {local})" else: fil = "timestamp_custom" with pytest.raises(TemplateError): render(hass, f"{{{{ {inp} | {fil} }}}}") # Test handling of default return value assert render(hass, "{{ None | timestamp_custom('invalid', True, 1) }}") == 1 assert render(hass, "{{ None | timestamp_custom(default=1) }}") == 1 async def test_timestamp_local(hass: HomeAssistant) -> None: """Test the timestamps to local filter.""" await hass.config.async_set_time_zone("UTC") tests = [ (1469119144, "2016-07-21T16:39:04+00:00"), ] for inp, out in tests: assert render(hass, f"{{{{ {inp} | timestamp_local }}}}") == out # Test handling of invalid input invalid_tests = [ None, ] for inp in invalid_tests: with pytest.raises(TemplateError): render(hass, f"{{{{ {inp} | timestamp_local }}}}") # Test handling of default return value assert render(hass, "{{ None | timestamp_local(1) }}") == 1 assert render(hass, "{{ None | timestamp_local(default=1) }}") == 1 @pytest.mark.parametrize( "input", [ "2021-06-03 13:00:00.000000+00:00", "1986-07-09T12:00:00Z", "2016-10-19 15:22:05.588122+0100", "2016-10-19", "2021-01-01 00:00:01", "invalid", ], ) def test_as_datetime(hass: HomeAssistant, input) -> None: """Test converting a timestamp string to a date object.""" expected = dt_util.parse_datetime(input) if expected is not None: expected = str(expected) assert render(hass, f"{{{{ as_datetime('{input}') }}}}") == expected assert render(hass, f"{{{{ '{input}' | as_datetime }}}}") == expected @pytest.mark.parametrize( ("input", "output"), [ (1469119144, "2016-07-21 16:39:04+00:00"), (1469119144.0, "2016-07-21 16:39:04+00:00"), (-1, "1969-12-31 23:59:59+00:00"), ], ) def test_as_datetime_from_timestamp( hass: HomeAssistant, input: float, output: str, ) -> None: """Test converting a UNIX timestamp to a date object.""" assert render(hass, f"{{{{ as_datetime({input}) }}}}") == output assert render(hass, f"{{{{ {input} | as_datetime }}}}") == output assert render(hass, f"{{{{ as_datetime('{input}') }}}}") == output assert render(hass, f"{{{{ '{input}' | as_datetime }}}}") == output @pytest.mark.parametrize( ("input", "output"), [ ( "{% set dt = as_datetime('2024-01-01 16:00:00-08:00') %}", "2024-01-01 16:00:00-08:00", ), ( "{% set dt = as_datetime('2024-01-29').date() %}", "2024-01-29 00:00:00", ), ], ) def test_as_datetime_from_datetime( hass: HomeAssistant, input: str, output: str ) -> None: """Test using datetime.datetime or datetime.date objects as input.""" assert render(hass, f"{input}{{{{ dt | as_datetime }}}}") == output assert render(hass, f"{input}{{{{ as_datetime(dt) }}}}") == output @pytest.mark.parametrize( ("input", "default", "output"), [ (1469119144, 123, "2016-07-21 16:39:04+00:00"), ('"invalid"', ["default output"], ["default output"]), (["a", "list"], 0, 0), ({"a": "dict"}, None, None), ], ) def test_as_datetime_default( hass: HomeAssistant, input: Any, default: Any, output: str ) -> None: """Test invalid input and return default value.""" assert render(hass, f"{{{{ as_datetime({input}, default={default}) }}}}") == output assert render(hass, f"{{{{ {input} | as_datetime({default}) }}}}") == output def test_as_local(hass: HomeAssistant) -> None: """Test converting time to local.""" hass.states.async_set("test.object", "available") last_updated = hass.states.get("test.object").last_updated assert render(hass, "{{ as_local(states.test.object.last_updated) }}") == str( dt_util.as_local(last_updated) ) assert render(hass, "{{ states.test.object.last_updated | as_local }}") == str( dt_util.as_local(last_updated) ) def test_timestamp_utc(hass: HomeAssistant) -> None: """Test the timestamps to local filter.""" now = dt_util.utcnow() tests = [ (1469119144, "2016-07-21T16:39:04+00:00"), (dt_util.as_timestamp(now), now.isoformat()), ] for inp, out in tests: assert render(hass, f"{{{{ {inp} | timestamp_utc }}}}") == out # Test handling of invalid input invalid_tests = [ None, ] for inp in invalid_tests: with pytest.raises(TemplateError): render(hass, f"{{{{ {inp} | timestamp_utc }}}}") # Test handling of default return value assert render(hass, "{{ None | timestamp_utc(1) }}") == 1 assert render(hass, "{{ None | timestamp_utc(default=1) }}") == 1 def test_as_timestamp(hass: HomeAssistant) -> None: """Test the as_timestamp function.""" with pytest.raises(TemplateError): render(hass, '{{ as_timestamp("invalid") }}') hass.states.async_set("test.object", None) with pytest.raises(TemplateError): render(hass, "{{ as_timestamp(states.test.object) }}") tpl = ( '{{ as_timestamp(strptime("2024-02-03T09:10:24+0000", ' '"%Y-%m-%dT%H:%M:%S%z")) }}' ) assert render(hass, tpl) == 1706951424.0 # Test handling of default return value assert render(hass, "{{ 'invalid' | as_timestamp(1) }}") == 1 assert render(hass, "{{ 'invalid' | as_timestamp(default=1) }}") == 1 assert render(hass, "{{ as_timestamp('invalid', 1) }}") == 1 assert render(hass, "{{ as_timestamp('invalid', default=1) }}") == 1 def test_as_timedelta(hass: HomeAssistant) -> None: """Test the as_timedelta function/filter.""" result = render(hass, "{{ as_timedelta('PT10M') }}") assert result == "0:10:00" result = render(hass, "{{ 'PT10M' | as_timedelta }}") assert result == "0:10:00" result = render(hass, "{{ 'T10M' | as_timedelta }}") assert result is None @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_now(mock_is_safe, hass: HomeAssistant) -> None: """Test now method.""" now = dt_util.now() with freeze_time(now): info = render_to_info(hass, "{{ now().isoformat() }}") assert now.isoformat() == info.result() assert info.has_time is True @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) def test_utcnow(mock_is_safe, hass: HomeAssistant) -> None: """Test now method.""" utcnow = dt_util.utcnow() with freeze_time(utcnow): info = render_to_info(hass, "{{ utcnow().isoformat() }}") assert utcnow.isoformat() == info.result() assert info.has_time is True @pytest.mark.parametrize( ("now", "expected", "expected_midnight", "timezone_str"), [ # Host clock in UTC ( "2021-11-24 03:00:00+00:00", "2021-11-23T10:00:00-08:00", "2021-11-23T00:00:00-08:00", "America/Los_Angeles", ), # Host clock in local time ( "2021-11-23 19:00:00-08:00", "2021-11-23T10:00:00-08:00", "2021-11-23T00:00:00-08:00", "America/Los_Angeles", ), ], ) @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) async def test_today_at( mock_is_safe, hass: HomeAssistant, now, expected, expected_midnight, timezone_str ) -> None: """Test today_at method.""" freezer = freeze_time(now) freezer.start() await hass.config.async_set_time_zone(timezone_str) result = render(hass, "{{ today_at('10:00').isoformat() }}") assert result == expected result = render(hass, "{{ today_at('10:00:00').isoformat() }}") assert result == expected result = render(hass, "{{ ('10:00:00' | today_at).isoformat() }}") assert result == expected result = render(hass, "{{ today_at().isoformat() }}") assert result == expected_midnight with pytest.raises(TemplateError): render(hass, "{{ today_at('bad') }}") info = render_to_info(hass, "{{ today_at('10:00').isoformat() }}") assert info.has_time is True freezer.stop() @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) async def test_relative_time(mock_is_safe, hass: HomeAssistant) -> None: """Test relative_time method.""" await hass.config.async_set_time_zone("UTC") now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") relative_time_template = ( '{{relative_time(strptime("2000-01-01 09:00:00", "%Y-%m-%d %H:%M:%S"))}}' ) with freeze_time(now): result = render(hass, relative_time_template) assert result == "1 hour" result = render( hass, ( "{{" " relative_time(" " strptime(" ' "2000-01-01 09:00:00 +01:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "2 hours" result = render( hass, ( "{{" " relative_time(" " strptime(" ' "2000-01-01 03:00:00 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "1 hour" result1 = str( datetime.strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = render( hass, ( "{{" " relative_time(" " strptime(" ' "2000-01-01 11:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result1 == result2 result = render(hass, '{{relative_time("string")}}') assert result == "string" # Test behavior when current time is same as the input time result = render( hass, ( "{{" " relative_time(" " strptime(" ' "2000-01-01 10:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "0 seconds" # Test behavior when the input time is in the future result = render( hass, ( "{{" " relative_time(" " strptime(" ' "2000-01-01 11:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "2000-01-01 11:00:00+00:00" info = render_to_info(hass, relative_time_template) assert info.has_time is True @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) async def test_time_since(mock_is_safe, hass: HomeAssistant) -> None: """Test time_since method.""" await hass.config.async_set_time_zone("UTC") now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") time_since_template = ( '{{time_since(strptime("2000-01-01 09:00:00", "%Y-%m-%d %H:%M:%S"))}}' ) with freeze_time(now): result = render(hass, time_since_template) assert result == "1 hour" result = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 09:00:00 +01:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "2 hours" result = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 03:00:00 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "1 hour" result1 = str( datetime.strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 11:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 2" " )" "}}" ), ) assert result1 == result2 result = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 09:05:00 +01:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision=2" " )" "}}" ), ) assert result == "1 hour 55 minutes" result = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 02:05:27 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 3" " )" "}}" ), ) assert result == "1 hour 54 minutes 33 seconds" result = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 02:05:27 -06:00",' ' "%Y-%m-%d %H:%M:%S %z")' " )" "}}" ), ) assert result == "2 hours" result = render( hass, ( "{{" " time_since(" " strptime(" ' "1999-02-01 02:05:27 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 0" " )" "}}" ), ) assert result == "11 months 4 days 1 hour 54 minutes 33 seconds" result = render( hass, ( "{{" " time_since(" " strptime(" ' "1999-02-01 02:05:27 -06:00",' ' "%Y-%m-%d %H:%M:%S %z")' " )" "}}" ), ) assert result == "11 months" result1 = str( datetime.strptime("2000-01-01 11:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = render( hass, ( "{{" " time_since(" " strptime(" ' "2000-01-01 11:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision=3" " )" "}}" ), ) assert result1 == result2 result = render(hass, '{{time_since("string")}}') assert result == "string" info = render_to_info(hass, time_since_template) assert info.has_time is True @patch( "homeassistant.helpers.template.TemplateEnvironment.is_safe_callable", return_value=True, ) async def test_time_until(mock_is_safe, hass: HomeAssistant) -> None: """Test time_until method.""" await hass.config.async_set_time_zone("UTC") now = datetime.strptime("2000-01-01 10:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") time_until_template = ( '{{time_until(strptime("2000-01-01 11:00:00", "%Y-%m-%d %H:%M:%S"))}}' ) with freeze_time(now): result = render(hass, time_until_template) assert result == "1 hour" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 13:00:00 +01:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "2 hours" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 05:00:00 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"' " )" " )" "}}" ), ) assert result == "1 hour" result1 = str( datetime.strptime("2000-01-01 09:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 09:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 2" " )" "}}" ), ) assert result1 == result2 result = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 12:05:00 +01:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision=2" " )" "}}" ), ) assert result == "1 hour 5 minutes" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 05:54:33 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 3" " )" "}}" ), ) assert result == "1 hour 54 minutes 33 seconds" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 05:54:33 -06:00",' ' "%Y-%m-%d %H:%M:%S %z")' " )" "}}" ), ) assert result == "2 hours" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2001-02-01 05:54:33 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 0" " )" "}}" ), ) assert result == "1 year 1 month 2 days 1 hour 54 minutes 33 seconds" result = render( hass, ( "{{" " time_until(" " strptime(" ' "2001-02-01 05:54:33 -06:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision = 4" " )" "}}" ), ) assert result == "1 year 1 month 2 days 2 hours" result1 = str( datetime.strptime("2000-01-01 09:00:00 +00:00", "%Y-%m-%d %H:%M:%S %z") ) result2 = render( hass, ( "{{" " time_until(" " strptime(" ' "2000-01-01 09:00:00 +00:00",' ' "%Y-%m-%d %H:%M:%S %z"),' " precision=3" " )" "}}" ), ) assert result1 == result2 result = render(hass, '{{time_until("string")}}') assert result == "string" info = render_to_info(hass, time_until_template) assert info.has_time is True
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_datetime.py", "license": "Apache License 2.0", "lines": 688, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_devices.py
"""Test device template functions.""" from __future__ import annotations import pytest from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.template import TemplateError from tests.common import MockConfigEntry from tests.helpers.template.helpers import assert_result_info, render_to_info async def test_device_entities( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test device_entities function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing device ids info = render_to_info(hass, "{{ device_entities('abc123') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ device_entities(56) }}") assert_result_info(info, []) assert info.rate_limit is None # Test device without entities device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) info = render_to_info(hass, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, []) assert info.rate_limit is None # Test device with single entity, which has no state entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(hass, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, ["light.hue_5678"], []) assert info.rate_limit is None info = render_to_info( hass, ( f"{{{{ device_entities('{device_entry.id}') | expand " "| sort(attribute='entity_id') | map(attribute='entity_id') | join(', ') }}" ), ) assert_result_info(info, "", ["light.hue_5678"]) assert info.rate_limit is None # Test device with single entity, with state hass.states.async_set("light.hue_5678", "happy") info = render_to_info( hass, ( f"{{{{ device_entities('{device_entry.id}') | expand " "| sort(attribute='entity_id') | map(attribute='entity_id') | join(', ') }}" ), ) assert_result_info(info, "light.hue_5678", ["light.hue_5678"]) assert info.rate_limit is None # Test device with multiple entities, which have a state entity_registry.async_get_or_create( "light", "hue", "ABCD", config_entry=config_entry, device_id=device_entry.id, ) hass.states.async_set("light.hue_abcd", "camper") info = render_to_info(hass, f"{{{{ device_entities('{device_entry.id}') }}}}") assert_result_info(info, ["light.hue_5678", "light.hue_abcd"], []) assert info.rate_limit is None info = render_to_info( hass, ( f"{{{{ device_entities('{device_entry.id}') | expand " "| sort(attribute='entity_id') | map(attribute='entity_id') | join(', ') }}" ), ) assert_result_info( info, "light.hue_5678, light.hue_abcd", ["light.hue_5678", "light.hue_abcd"] ) assert info.rate_limit is None async def test_device_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test device_id function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, model="test", name="test", ) entity_entry = entity_registry.async_get_or_create( "sensor", "test", "test", suggested_object_id="test", device_id=device_entry.id ) entity_entry_no_device = entity_registry.async_get_or_create( "sensor", "test", "test_no_device", suggested_object_id="test" ) info = render_to_info(hass, "{{ 'sensor.fail' | device_id }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 56 | device_id }}") assert_result_info(info, None) info = render_to_info(hass, "{{ 'not_a_real_entity_id' | device_id }}") assert_result_info(info, None) info = render_to_info( hass, f"{{{{ device_id('{entity_entry_no_device.entity_id}') }}}}" ) assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ device_id('{entity_entry.entity_id}') }}}}") assert_result_info(info, device_entry.id) assert info.rate_limit is None info = render_to_info(hass, "{{ device_id('test') }}") assert_result_info(info, device_entry.id) assert info.rate_limit is None async def test_device_name( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test device_name function.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing entity id info = render_to_info(hass, "{{ device_name('sensor.fake') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing device id info = render_to_info(hass, "{{ device_name('1234567890') }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ device_name(56) }}") assert_result_info(info, None) assert info.rate_limit is None # Test device with single entity device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, name="A light", ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) info = render_to_info(hass, f"{{{{ device_name('{device_entry.id}') }}}}") assert_result_info(info, device_entry.name) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ device_name('{entity_entry.entity_id}') }}}}") assert_result_info(info, device_entry.name) assert info.rate_limit is None # Test device after renaming device_entry = device_registry.async_update_device( device_entry.id, name_by_user="My light", ) info = render_to_info(hass, f"{{{{ device_name('{device_entry.id}') }}}}") assert_result_info(info, device_entry.name_by_user) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ device_name('{entity_entry.entity_id}') }}}}") assert_result_info(info, device_entry.name_by_user) assert info.rate_limit is None async def test_device_attr( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test device_attr and is_device_attr functions.""" config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) # Test non existing device ids (device_attr) info = render_to_info(hass, "{{ device_attr('abc123', 'id') }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ device_attr(56, 'id') }}") with pytest.raises(TemplateError): assert_result_info(info, None) # Test non existing device ids (is_device_attr) info = render_to_info(hass, "{{ is_device_attr('abc123', 'id', 'test') }}") assert_result_info(info, False) assert info.rate_limit is None info = render_to_info(hass, "{{ is_device_attr(56, 'id', 'test') }}") with pytest.raises(TemplateError): assert_result_info(info, False) # Test non existing entity id (device_attr) info = render_to_info(hass, "{{ device_attr('entity.test', 'id') }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing entity id (is_device_attr) info = render_to_info(hass, "{{ is_device_attr('entity.test', 'id', 'test') }}") assert_result_info(info, False) assert info.rate_limit is None device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, model="test", ) entity_entry = entity_registry.async_get_or_create( "sensor", "test", "test", suggested_object_id="test", device_id=device_entry.id ) # Test non existent device attribute (device_attr) info = render_to_info( hass, f"{{{{ device_attr('{device_entry.id}', 'invalid_attr') }}}}" ) assert_result_info(info, None) assert info.rate_limit is None # Test non existent device attribute (is_device_attr) info = render_to_info( hass, f"{{{{ is_device_attr('{device_entry.id}', 'invalid_attr', 'test') }}}}" ) assert_result_info(info, False) assert info.rate_limit is None # Test None device attribute (device_attr) info = render_to_info( hass, f"{{{{ device_attr('{device_entry.id}', 'manufacturer') }}}}" ) assert_result_info(info, None) assert info.rate_limit is None # Test None device attribute mismatch (is_device_attr) info = render_to_info( hass, f"{{{{ is_device_attr('{device_entry.id}', 'manufacturer', 'test') }}}}" ) assert_result_info(info, False) assert info.rate_limit is None # Test None device attribute match (is_device_attr) info = render_to_info( hass, f"{{{{ is_device_attr('{device_entry.id}', 'manufacturer', None) }}}}" ) assert_result_info(info, True) assert info.rate_limit is None # Test valid device attribute match (device_attr) info = render_to_info(hass, f"{{{{ device_attr('{device_entry.id}', 'model') }}}}") assert_result_info(info, "test") assert info.rate_limit is None # Test valid device attribute match (device_attr) info = render_to_info( hass, f"{{{{ device_attr('{entity_entry.entity_id}', 'model') }}}}" ) assert_result_info(info, "test") assert info.rate_limit is None # Test valid device attribute mismatch (is_device_attr) info = render_to_info( hass, f"{{{{ is_device_attr('{device_entry.id}', 'model', 'fail') }}}}" ) assert_result_info(info, False) assert info.rate_limit is None # Test valid device attribute match (is_device_attr) info = render_to_info( hass, f"{{{{ is_device_attr('{device_entry.id}', 'model', 'test') }}}}" ) assert_result_info(info, True) assert info.rate_limit is None # Test filter syntax (device_attr) info = render_to_info( hass, f"{{{{ '{entity_entry.entity_id}' | device_attr('model') }}}}" ) assert_result_info(info, "test") assert info.rate_limit is None # Test test syntax (is_device_attr) info = render_to_info( hass, ( f"{{{{ ['{device_entry.id}'] | select('is_device_attr', 'model', 'test') " "| list }}" ), ) assert_result_info(info, [device_entry.id]) assert info.rate_limit is None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_devices.py", "license": "Apache License 2.0", "lines": 279, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_floors.py
"""Test floor template functions.""" from __future__ import annotations from homeassistant.core import HomeAssistant from homeassistant.helpers import ( area_registry as ar, device_registry as dr, entity_registry as er, floor_registry as fr, ) from tests.common import MockConfigEntry from tests.helpers.template.helpers import assert_result_info, render_to_info async def test_floors( hass: HomeAssistant, floor_registry: fr.FloorRegistry, ) -> None: """Test floors function.""" # Test no floors info = render_to_info(hass, "{{ floors() }}") assert_result_info(info, []) assert info.rate_limit is None # Test one floor floor1 = floor_registry.async_create("First floor") info = render_to_info(hass, "{{ floors() }}") assert_result_info(info, [floor1.floor_id]) assert info.rate_limit is None # Test multiple floors floor2 = floor_registry.async_create("Second floor") info = render_to_info(hass, "{{ floors() }}") assert_result_info(info, [floor1.floor_id, floor2.floor_id]) assert info.rate_limit is None async def test_floor_id( hass: HomeAssistant, floor_registry: fr.FloorRegistry, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test floor_id function.""" def test(value: str, expected: str | None) -> None: info = render_to_info(hass, f"{{{{ floor_id('{value}') }}}}") assert_result_info(info, expected) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{value}' | floor_id }}}}") assert_result_info(info, expected) assert info.rate_limit is None # Test non existing floor name test("Third floor", None) # Test wrong value type info = render_to_info(hass, "{{ floor_id(42) }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | floor_id }}") assert_result_info(info, None) assert info.rate_limit is None # Test with an actual floor floor = floor_registry.async_create("First floor") test("First floor", floor.floor_id) config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) area_entry_hex = area_registry.async_get_or_create("123abc") # Create area, device, entity and assign area to device and entity device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) device_entry = device_registry.async_update_device( device_entry.id, area_id=area_entry_hex.id ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry_hex.id ) test(area_entry_hex.id, None) test(device_entry.id, None) test(entity_entry.entity_id, None) # Add floor to area area_entry_hex = area_registry.async_update( area_entry_hex.id, floor_id=floor.floor_id ) test(area_entry_hex.id, floor.floor_id) test(device_entry.id, floor.floor_id) test(entity_entry.entity_id, floor.floor_id) async def test_floor_name( hass: HomeAssistant, floor_registry: fr.FloorRegistry, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test floor_name function.""" def test(value: str, expected: str | None) -> None: info = render_to_info(hass, f"{{{{ floor_name('{value}') }}}}") assert_result_info(info, expected) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{value}' | floor_name }}}}") assert_result_info(info, expected) assert info.rate_limit is None # Test non existing floor name test("Third floor", None) # Test wrong value type info = render_to_info(hass, "{{ floor_name(42) }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | floor_name }}") assert_result_info(info, None) assert info.rate_limit is None # Test existing floor ID floor = floor_registry.async_create("First floor") test(floor.floor_id, floor.name) config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) area_entry_hex = area_registry.async_get_or_create("123abc") # Create area, device, entity and assign area to device and entity device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) device_entry = device_registry.async_update_device( device_entry.id, area_id=area_entry_hex.id ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, area_id=area_entry_hex.id ) test(area_entry_hex.id, None) test(device_entry.id, None) test(entity_entry.entity_id, None) # Add floor to area area_entry_hex = area_registry.async_update( area_entry_hex.id, floor_id=floor.floor_id ) test(area_entry_hex.id, floor.name) test(device_entry.id, floor.name) test(entity_entry.entity_id, floor.name) async def test_floor_areas( hass: HomeAssistant, floor_registry: fr.FloorRegistry, area_registry: ar.AreaRegistry, ) -> None: """Test floor_areas function.""" # Test non existing floor ID info = render_to_info(hass, "{{ floor_areas('skyring') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'skyring' | floor_areas }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ floor_areas(42) }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | floor_areas }}") assert_result_info(info, []) assert info.rate_limit is None floor = floor_registry.async_create("First floor") area = area_registry.async_create("Living room") area_registry.async_update(area.id, floor_id=floor.floor_id) # Get areas by floor ID info = render_to_info(hass, f"{{{{ floor_areas('{floor.floor_id}') }}}}") assert_result_info(info, [area.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{floor.floor_id}' | floor_areas }}}}") assert_result_info(info, [area.id]) assert info.rate_limit is None # Get areas by floor name info = render_to_info(hass, f"{{{{ floor_areas('{floor.name}') }}}}") assert_result_info(info, [area.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{floor.name}' | floor_areas }}}}") assert_result_info(info, [area.id]) assert info.rate_limit is None async def test_floor_entities( hass: HomeAssistant, floor_registry: fr.FloorRegistry, area_registry: ar.AreaRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test floor_entities function.""" # Test non existing floor ID info = render_to_info(hass, "{{ floor_entities('skyring') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'skyring' | floor_entities }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ floor_entities(42) }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | floor_entities }}") assert_result_info(info, []) assert info.rate_limit is None floor = floor_registry.async_create("First floor") area1 = area_registry.async_create("Living room") area2 = area_registry.async_create("Dining room") area_registry.async_update(area1.id, floor_id=floor.floor_id) area_registry.async_update(area2.id, floor_id=floor.floor_id) config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) entity_entry = entity_registry.async_get_or_create( "light", "hue", "living_room", config_entry=config_entry, ) entity_registry.async_update_entity(entity_entry.entity_id, area_id=area1.id) entity_entry = entity_registry.async_get_or_create( "light", "hue", "dining_room", config_entry=config_entry, ) entity_registry.async_update_entity(entity_entry.entity_id, area_id=area2.id) # Get entities by floor ID expected = ["light.hue_living_room", "light.hue_dining_room"] info = render_to_info(hass, f"{{{{ floor_entities('{floor.floor_id}') }}}}") assert_result_info(info, expected) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{floor.floor_id}' | floor_entities }}}}") assert_result_info(info, expected) assert info.rate_limit is None # Get entities by floor name info = render_to_info(hass, f"{{{{ floor_entities('{floor.name}') }}}}") assert_result_info(info, expected) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{floor.name}' | floor_entities }}}}") assert_result_info(info, expected) assert info.rate_limit is None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_floors.py", "license": "Apache License 2.0", "lines": 240, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_issues.py
"""Test issue template functions.""" from __future__ import annotations from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from homeassistant.util import dt as dt_util from tests.helpers.template.helpers import assert_result_info, render_to_info async def test_issues(hass: HomeAssistant, issue_registry: ir.IssueRegistry) -> None: """Test issues function.""" # Test no issues info = render_to_info(hass, "{{ issues() }}") assert_result_info(info, {}) assert info.rate_limit is None # Test persistent issue ir.async_create_issue( hass, "test", "issue 1", breaks_in_ha_version="2023.7", is_fixable=True, is_persistent=True, learn_more_url="https://theuselessweb.com", severity="error", translation_key="abc_1234", translation_placeholders={"abc": "123"}, ) await hass.async_block_till_done() created_issue = issue_registry.async_get_issue("test", "issue 1") info = render_to_info(hass, "{{ issues()['test', 'issue 1'] }}") assert_result_info(info, created_issue.to_json()) assert info.rate_limit is None # Test fixed issue ir.async_delete_issue(hass, "test", "issue 1") await hass.async_block_till_done() info = render_to_info(hass, "{{ issues() }}") assert_result_info(info, {}) assert info.rate_limit is None issue = ir.IssueEntry( active=False, breaks_in_ha_version="2025.12", created=dt_util.utcnow(), data=None, dismissed_version=None, domain="test", is_fixable=False, is_persistent=False, issue_domain="test", issue_id="issue 2", learn_more_url=None, severity="warning", translation_key="abc_1234", translation_placeholders={"abc": "123"}, ) # Add non active issue issue_registry.issues[("test", "issue 2")] = issue # Test non active issue is omitted issue_entry = issue_registry.async_get_issue("test", "issue 2") assert issue_entry issue_2_created = issue_entry.created assert issue_entry and not issue_entry.active info = render_to_info(hass, "{{ issues() }}") assert_result_info(info, {}) assert info.rate_limit is None # Load and activate the issue ir.async_create_issue( hass=hass, breaks_in_ha_version="2025.12", data=None, domain="test", is_fixable=False, is_persistent=False, issue_domain="test", issue_id="issue 2", learn_more_url=None, severity="warning", translation_key="abc_1234", translation_placeholders={"abc": "123"}, ) activated_issue_entry = issue_registry.async_get_issue("test", "issue 2") assert activated_issue_entry and activated_issue_entry.active assert issue_2_created == activated_issue_entry.created info = render_to_info(hass, "{{ issues()['test', 'issue 2'] }}") assert_result_info(info, activated_issue_entry.to_json()) assert info.rate_limit is None async def test_issue(hass: HomeAssistant, issue_registry: ir.IssueRegistry) -> None: """Test issue function.""" # Test non existent issue info = render_to_info(hass, "{{ issue('non_existent', 'issue') }}") assert_result_info(info, None) assert info.rate_limit is None # Test existing issue ir.async_create_issue( hass, "test", "issue 1", breaks_in_ha_version="2023.7", is_fixable=True, is_persistent=True, learn_more_url="https://theuselessweb.com", severity="error", translation_key="abc_1234", translation_placeholders={"abc": "123"}, ) await hass.async_block_till_done() created_issue = issue_registry.async_get_issue("test", "issue 1") info = render_to_info(hass, "{{ issue('test', 'issue 1') }}") assert_result_info(info, created_issue.to_json()) assert info.rate_limit is None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_issues.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/template/extensions/test_labels.py
"""Test label template functions.""" from __future__ import annotations from homeassistant.core import HomeAssistant from homeassistant.helpers import ( area_registry as ar, device_registry as dr, entity_registry as er, label_registry as lr, ) from tests.common import MockConfigEntry from tests.helpers.template.helpers import assert_result_info, render_to_info async def test_labels( hass: HomeAssistant, label_registry: lr.LabelRegistry, area_registry: ar.AreaRegistry, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test labels function.""" # Test no labels info = render_to_info(hass, "{{ labels() }}") assert_result_info(info, []) assert info.rate_limit is None # Test one label label1 = label_registry.async_create("label1") info = render_to_info(hass, "{{ labels() }}") assert_result_info(info, [label1.label_id]) assert info.rate_limit is None # Test multiple label label2 = label_registry.async_create("label2") info = render_to_info(hass, "{{ labels() }}") assert_result_info(info, [label1.label_id, label2.label_id]) assert info.rate_limit is None # Test non-existing entity ID info = render_to_info(hass, "{{ labels('sensor.fake') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'sensor.fake' | labels }}") assert_result_info(info, []) assert info.rate_limit is None # Test non existing device ID (hex value) info = render_to_info(hass, "{{ labels('123abc') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ '123abc' | labels }}") assert_result_info(info, []) assert info.rate_limit is None # Create a device & entity for testing config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, device_id=device_entry.id, ) # Test entity, which has no labels info = render_to_info(hass, f"{{{{ labels('{entity_entry.entity_id}') }}}}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{entity_entry.entity_id}' | labels }}}}") assert_result_info(info, []) assert info.rate_limit is None # Test device, which has no labels info = render_to_info(hass, f"{{{{ labels('{device_entry.id}') }}}}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{device_entry.id}' | labels }}}}") assert_result_info(info, []) assert info.rate_limit is None # Add labels to the entity & device device_entry = device_registry.async_update_device( device_entry.id, labels=[label1.label_id] ) entity_entry = entity_registry.async_update_entity( entity_entry.entity_id, labels=[label2.label_id] ) # Test entity, which now has a label info = render_to_info(hass, f"{{{{ '{entity_entry.entity_id}' | labels }}}}") assert_result_info(info, [label2.label_id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ labels('{entity_entry.entity_id}') }}}}") assert_result_info(info, [label2.label_id]) assert info.rate_limit is None # Test device, which now has a label info = render_to_info(hass, f"{{{{ '{device_entry.id}' | labels }}}}") assert_result_info(info, [label1.label_id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ labels('{device_entry.id}') }}}}") assert_result_info(info, [label1.label_id]) assert info.rate_limit is None # Create area for testing area = area_registry.async_create("living room") # Test area, which has no labels info = render_to_info(hass, f"{{{{ '{area.id}' | labels }}}}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ labels('{area.id}') }}}}") assert_result_info(info, []) assert info.rate_limit is None # Add label to the area area_registry.async_update(area.id, labels=[label1.label_id, label2.label_id]) # Test area, which now has labels info = render_to_info(hass, f"{{{{ '{area.id}' | labels }}}}") assert_result_info(info, [label1.label_id, label2.label_id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ labels('{area.id}') }}}}") assert_result_info(info, [label1.label_id, label2.label_id]) assert info.rate_limit is None async def test_label_id( hass: HomeAssistant, label_registry: lr.LabelRegistry, ) -> None: """Test label_id function.""" # Test non existing label name info = render_to_info(hass, "{{ label_id('non-existing label') }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 'non-existing label' | label_id }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_id(42) }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_id }}") assert_result_info(info, None) assert info.rate_limit is None # Test with an actual label label = label_registry.async_create("existing label") info = render_to_info(hass, "{{ label_id('existing label') }}") assert_result_info(info, label.label_id) assert info.rate_limit is None info = render_to_info(hass, "{{ 'existing label' | label_id }}") assert_result_info(info, label.label_id) assert info.rate_limit is None async def test_label_name( hass: HomeAssistant, label_registry: lr.LabelRegistry, ) -> None: """Test label_name function.""" # Test non existing label ID info = render_to_info(hass, "{{ label_name('1234567890') }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ '1234567890' | label_name }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_name(42) }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_name }}") assert_result_info(info, None) assert info.rate_limit is None # Test non existing label ID label = label_registry.async_create("choo choo") info = render_to_info(hass, f"{{{{ label_name('{label.label_id}') }}}}") assert_result_info(info, label.name) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.label_id}' | label_name }}}}") assert_result_info(info, label.name) assert info.rate_limit is None async def test_label_description( hass: HomeAssistant, label_registry: lr.LabelRegistry, ) -> None: """Test label_description function.""" # Test non existing label ID info = render_to_info(hass, "{{ label_description('1234567890') }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ '1234567890' | label_description }}") assert_result_info(info, None) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_description(42) }}") assert_result_info(info, None) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_description }}") assert_result_info(info, None) assert info.rate_limit is None # Test valid label ID label = label_registry.async_create("choo choo", description="chugga chugga") info = render_to_info(hass, f"{{{{ label_description('{label.label_id}') }}}}") assert_result_info(info, label.description) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.label_id}' | label_description }}}}") assert_result_info(info, label.description) assert info.rate_limit is None async def test_label_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, label_registry: lr.LabelRegistry, ) -> None: """Test label_entities function.""" # Test non existing device ID info = render_to_info(hass, "{{ label_entities('deadbeef') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'deadbeef' | label_entities }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_entities(42) }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_entities }}") assert_result_info(info, []) assert info.rate_limit is None # Create a fake config entry with a entity config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) entity_entry = entity_registry.async_get_or_create( "light", "hue", "5678", config_entry=config_entry, ) # Add a label to the entity label = label_registry.async_create("Romantic Lights") entity_registry.async_update_entity(entity_entry.entity_id, labels={label.label_id}) # Get entities by label ID info = render_to_info(hass, f"{{{{ label_entities('{label.label_id}') }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.label_id}' | label_entities }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None # Get entities by label name info = render_to_info(hass, f"{{{{ label_entities('{label.name}') }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.name}' | label_entities }}}}") assert_result_info(info, ["light.hue_5678"]) assert info.rate_limit is None async def test_label_devices( hass: HomeAssistant, device_registry: dr.DeviceRegistry, label_registry: lr.LabelRegistry, ) -> None: """Test label_devices function.""" # Test non existing device ID info = render_to_info(hass, "{{ label_devices('deadbeef') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'deadbeef' | label_devices }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_devices(42) }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_devices }}") assert_result_info(info, []) assert info.rate_limit is None # Create a fake config entry with a device config_entry = MockConfigEntry(domain="light") config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) # Add a label to it label = label_registry.async_create("Romantic Lights") device_registry.async_update_device(device_entry.id, labels=[label.label_id]) # Get the devices from a label by its ID info = render_to_info(hass, f"{{{{ label_devices('{label.label_id}') }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.label_id}' | label_devices }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None # Get the devices from a label by its name info = render_to_info(hass, f"{{{{ label_devices('{label.name}') }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.name}' | label_devices }}}}") assert_result_info(info, [device_entry.id]) assert info.rate_limit is None async def test_label_areas( hass: HomeAssistant, area_registry: ar.AreaRegistry, label_registry: lr.LabelRegistry, ) -> None: """Test label_areas function.""" # Test non existing area ID info = render_to_info(hass, "{{ label_areas('deadbeef') }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 'deadbeef' | label_areas }}") assert_result_info(info, []) assert info.rate_limit is None # Test wrong value type info = render_to_info(hass, "{{ label_areas(42) }}") assert_result_info(info, []) assert info.rate_limit is None info = render_to_info(hass, "{{ 42 | label_areas }}") assert_result_info(info, []) assert info.rate_limit is None # Create an area with an label label = label_registry.async_create("Upstairs") master_bedroom = area_registry.async_create( "Master Bedroom", labels=[label.label_id] ) # Get areas by label ID info = render_to_info(hass, f"{{{{ label_areas('{label.label_id}') }}}}") assert_result_info(info, [master_bedroom.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.label_id}' | label_areas }}}}") assert_result_info(info, [master_bedroom.id]) assert info.rate_limit is None # Get areas by label name info = render_to_info(hass, f"{{{{ label_areas('{label.name}') }}}}") assert_result_info(info, [master_bedroom.id]) assert info.rate_limit is None info = render_to_info(hass, f"{{{{ '{label.name}' | label_areas }}}}") assert_result_info(info, [master_bedroom.id]) assert info.rate_limit is None
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/template/extensions/test_labels.py", "license": "Apache License 2.0", "lines": 324, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/icloud/test_account.py
"""Tests for the iCloud account.""" from unittest.mock import MagicMock, Mock, patch import pytest from homeassistant.components.icloud.account import IcloudAccount from homeassistant.components.icloud.const import ( CONF_GPS_ACCURACY_THRESHOLD, CONF_MAX_INTERVAL, CONF_WITH_FAMILY, DOMAIN, ) from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.storage import Store from .const import DEVICE, MOCK_CONFIG, USER_INFO, USERNAME from tests.common import MockConfigEntry @pytest.fixture(name="mock_store") def mock_store_fixture(): """Mock the storage.""" with patch("homeassistant.components.icloud.account.Store") as store_mock: store_instance = Mock(spec=Store) store_instance.path = "/mock/path" store_mock.return_value = store_instance yield store_instance @pytest.fixture(name="mock_icloud_service_no_userinfo") def mock_icloud_service_no_userinfo_fixture(): """Mock PyiCloudService with devices as dict but no userInfo.""" with patch( "homeassistant.components.icloud.account.PyiCloudService" ) as service_mock: service_instance = MagicMock() service_instance.requires_2fa = False mock_device = MagicMock() mock_device.status = iter(DEVICE) mock_device.user_info = None service_instance.devices = mock_device service_mock.return_value = service_instance yield service_instance async def test_setup_fails_when_userinfo_missing( hass: HomeAssistant, mock_store: Mock, mock_icloud_service_no_userinfo: MagicMock, ) -> None: """Test setup fails when userInfo is missing from devices dict.""" assert mock_icloud_service_no_userinfo is not None config_entry = MockConfigEntry( domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME ) config_entry.add_to_hass(hass) account = IcloudAccount( hass, MOCK_CONFIG[CONF_USERNAME], MOCK_CONFIG[CONF_PASSWORD], mock_store, MOCK_CONFIG[CONF_WITH_FAMILY], MOCK_CONFIG[CONF_MAX_INTERVAL], MOCK_CONFIG[CONF_GPS_ACCURACY_THRESHOLD], config_entry, ) with pytest.raises(ConfigEntryNotReady, match="No user info found"): account.setup() class MockAppleDevice: """Mock "Apple device" which implements the .status(...) method used by the account.""" def __init__(self, status_dict) -> None: """Set status.""" self._status = status_dict def status(self, key): """Return current status.""" return self._status def __getitem__(self, key): """Allow indexing the device itself (device[KEY]) to proxy into the raw status dict.""" return self._status.get(key) class MockDevicesContainer: """Mock devices container which is iterable and indexable returning device status dicts.""" def __init__(self, userinfo, devices) -> None: """Initialize with userinfo and list of device objects.""" self.user_info = userinfo self._devices = devices def __iter__(self): """Iterate returns device objects (each must have .status(...)).""" return iter(self._devices) def __len__(self): """Return number of devices.""" return len(self._devices) def __getitem__(self, idx): """Indexing returns device object (which must have .status(...)).""" dev = self._devices[idx] if hasattr(dev, "status"): return dev.status(None) return dev @pytest.fixture(name="mock_icloud_service") def mock_icloud_service_fixture(): """Mock PyiCloudService with devices container that is iterable and indexable returning status dict.""" with patch( "homeassistant.components.icloud.account.PyiCloudService", ) as service_mock: service_instance = MagicMock() device_obj = MockAppleDevice(DEVICE) devices_container = MockDevicesContainer(USER_INFO, [device_obj]) service_instance.devices = devices_container service_instance.requires_2fa = False service_mock.return_value = service_instance yield service_instance async def test_setup_success_with_devices( hass: HomeAssistant, mock_store: Mock, mock_icloud_service: MagicMock, ) -> None: """Test successful setup with devices.""" assert mock_icloud_service is not None config_entry = MockConfigEntry( domain=DOMAIN, data=MOCK_CONFIG, entry_id="test", unique_id=USERNAME ) config_entry.add_to_hass(hass) account = IcloudAccount( hass, MOCK_CONFIG[CONF_USERNAME], MOCK_CONFIG[CONF_PASSWORD], mock_store, MOCK_CONFIG[CONF_WITH_FAMILY], MOCK_CONFIG[CONF_MAX_INTERVAL], MOCK_CONFIG[CONF_GPS_ACCURACY_THRESHOLD], config_entry, ) with patch.object(account, "_schedule_next_fetch"): account.setup() assert account.api is not None assert account.owner_fullname == "user name" assert "johntravolta" in account.family_members_fullname assert account.family_members_fullname["johntravolta"] == "John TRAVOLTA"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/icloud/test_account.py", "license": "Apache License 2.0", "lines": 130, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/recorder/db_schema_51.py
"""Models for SQLAlchemy. This file contains the model definitions for schema version 51. It is used to test the schema migration logic. """ from __future__ import annotations from collections.abc import Callable from datetime import datetime, timedelta import logging import time from typing import Any, Final, Protocol, Self import ciso8601 from fnv_hash_fast import fnv1a_32 from sqlalchemy import ( CHAR, JSON, BigInteger, Boolean, ColumnElement, DateTime, Float, ForeignKey, Identity, Index, Integer, LargeBinary, SmallInteger, String, Text, case, type_coerce, ) from sqlalchemy.dialects import mysql, oracle, postgresql, sqlite from sqlalchemy.engine.interfaces import Dialect from sqlalchemy.ext.compiler import compiles from sqlalchemy.orm import DeclarativeBase, Mapped, aliased, mapped_column, relationship from sqlalchemy.types import TypeDecorator from homeassistant.components.recorder.const import ( ALL_DOMAIN_EXCLUDE_ATTRS, SupportedDialect, ) from homeassistant.components.recorder.models import ( StatisticData, StatisticDataTimestamp, StatisticMeanType, StatisticMetaData, datetime_to_timestamp_or_none, process_timestamp, ulid_to_bytes_or_none, uuid_hex_to_bytes_or_none, ) from homeassistant.components.sensor import ATTR_STATE_CLASS from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_FRIENDLY_NAME, ATTR_UNIT_OF_MEASUREMENT, MATCH_ALL, MAX_LENGTH_EVENT_EVENT_TYPE, MAX_LENGTH_STATE_ENTITY_ID, MAX_LENGTH_STATE_STATE, ) from homeassistant.core import Event, EventStateChangedData from homeassistant.helpers.json import JSON_DUMP, json_bytes, json_bytes_strip_null from homeassistant.util import dt as dt_util # SQLAlchemy Schema class Base(DeclarativeBase): """Base class for tables.""" class LegacyBase(DeclarativeBase): """Base class for tables, used for schema migration.""" SCHEMA_VERSION = 51 _LOGGER = logging.getLogger(__name__) TABLE_EVENTS = "events" TABLE_EVENT_DATA = "event_data" TABLE_EVENT_TYPES = "event_types" TABLE_STATES = "states" TABLE_STATE_ATTRIBUTES = "state_attributes" TABLE_STATES_META = "states_meta" TABLE_RECORDER_RUNS = "recorder_runs" TABLE_SCHEMA_CHANGES = "schema_changes" TABLE_STATISTICS = "statistics" TABLE_STATISTICS_META = "statistics_meta" TABLE_STATISTICS_RUNS = "statistics_runs" TABLE_STATISTICS_SHORT_TERM = "statistics_short_term" TABLE_MIGRATION_CHANGES = "migration_changes" STATISTICS_TABLES = ("statistics", "statistics_short_term") MAX_STATE_ATTRS_BYTES = 16384 MAX_EVENT_DATA_BYTES = 32768 PSQL_DIALECT = SupportedDialect.POSTGRESQL ALL_TABLES = [ TABLE_STATES, TABLE_STATE_ATTRIBUTES, TABLE_EVENTS, TABLE_EVENT_DATA, TABLE_EVENT_TYPES, TABLE_RECORDER_RUNS, TABLE_SCHEMA_CHANGES, TABLE_MIGRATION_CHANGES, TABLE_STATES_META, TABLE_STATISTICS, TABLE_STATISTICS_META, TABLE_STATISTICS_RUNS, TABLE_STATISTICS_SHORT_TERM, ] TABLES_TO_CHECK = [ TABLE_STATES, TABLE_EVENTS, TABLE_RECORDER_RUNS, TABLE_SCHEMA_CHANGES, ] LAST_UPDATED_INDEX_TS = "ix_states_last_updated_ts" METADATA_ID_LAST_UPDATED_INDEX_TS = "ix_states_metadata_id_last_updated_ts" EVENTS_CONTEXT_ID_BIN_INDEX = "ix_events_context_id_bin" STATES_CONTEXT_ID_BIN_INDEX = "ix_states_context_id_bin" LEGACY_STATES_EVENT_ID_INDEX = "ix_states_event_id" LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX = "ix_states_entity_id_last_updated_ts" LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID: Final = 36 CONTEXT_ID_BIN_MAX_LENGTH = 16 MYSQL_COLLATE = "utf8mb4_unicode_ci" MYSQL_DEFAULT_CHARSET = "utf8mb4" MYSQL_ENGINE = "InnoDB" _DEFAULT_TABLE_ARGS = { "mysql_default_charset": MYSQL_DEFAULT_CHARSET, "mysql_collate": MYSQL_COLLATE, "mysql_engine": MYSQL_ENGINE, "mariadb_default_charset": MYSQL_DEFAULT_CHARSET, "mariadb_collate": MYSQL_COLLATE, "mariadb_engine": MYSQL_ENGINE, } _MATCH_ALL_KEEP = { ATTR_DEVICE_CLASS, ATTR_STATE_CLASS, ATTR_UNIT_OF_MEASUREMENT, ATTR_FRIENDLY_NAME, } class UnusedDateTime(DateTime): """An unused column type that behaves like a datetime.""" class Unused(CHAR): """An unused column type that behaves like a string.""" @compiles(UnusedDateTime, "mysql", "mariadb", "sqlite") @compiles(Unused, "mysql", "mariadb", "sqlite") def compile_char_zero(type_: TypeDecorator, compiler: Any, **kw: Any) -> str: """Compile UnusedDateTime and Unused as CHAR(0) on mysql, mariadb, and sqlite.""" return "CHAR(0)" # Uses 1 byte on MySQL (no change on sqlite) @compiles(Unused, "postgresql") def compile_char_one(type_: TypeDecorator, compiler: Any, **kw: Any) -> str: """Compile Unused as CHAR(1) on postgresql.""" return "CHAR(1)" # Uses 1 byte class FAST_PYSQLITE_DATETIME(sqlite.DATETIME): """Use ciso8601 to parse datetimes instead of sqlalchemy built-in regex.""" def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None: """Offload the datetime parsing to ciso8601.""" return lambda value: None if value is None else ciso8601.parse_datetime(value) class NativeLargeBinary(LargeBinary): """A faster version of LargeBinary for engines that support python bytes natively.""" def result_processor(self, dialect: Dialect, coltype: Any) -> Callable | None: """No conversion needed for engines that support native bytes.""" return None # Although all integers are same in SQLite, it does not allow an identity column to be BIGINT # https://sqlite.org/forum/info/2dfa968a702e1506e885cb06d92157d492108b22bf39459506ab9f7125bca7fd ID_TYPE = BigInteger().with_variant(sqlite.INTEGER, "sqlite") # For MariaDB and MySQL we can use an unsigned integer type since it will fit 2**32 # for sqlite and postgresql we use a bigint UINT_32_TYPE = BigInteger().with_variant( mysql.INTEGER(unsigned=True), # type: ignore[no-untyped-call] "mysql", "mariadb", ) JSON_VARIANT_CAST = Text().with_variant( postgresql.JSON(none_as_null=True), "postgresql", ) JSONB_VARIANT_CAST = Text().with_variant( postgresql.JSONB(none_as_null=True), "postgresql", ) DATETIME_TYPE = ( DateTime(timezone=True) .with_variant(mysql.DATETIME(timezone=True, fsp=6), "mysql", "mariadb") # type: ignore[no-untyped-call] .with_variant(FAST_PYSQLITE_DATETIME(), "sqlite") # type: ignore[no-untyped-call] ) DOUBLE_TYPE = ( Float() .with_variant(mysql.DOUBLE(asdecimal=False), "mysql", "mariadb") # type: ignore[no-untyped-call] .with_variant(oracle.DOUBLE_PRECISION(), "oracle") .with_variant(postgresql.DOUBLE_PRECISION(), "postgresql") ) UNUSED_LEGACY_COLUMN = Unused(0) UNUSED_LEGACY_DATETIME_COLUMN = UnusedDateTime(timezone=True) UNUSED_LEGACY_INTEGER_COLUMN = SmallInteger() DOUBLE_PRECISION_TYPE_SQL = "DOUBLE PRECISION" BIG_INTEGER_SQL = "BIGINT" CONTEXT_BINARY_TYPE = LargeBinary(CONTEXT_ID_BIN_MAX_LENGTH).with_variant( NativeLargeBinary(CONTEXT_ID_BIN_MAX_LENGTH), "mysql", "mariadb", "sqlite" ) TIMESTAMP_TYPE = DOUBLE_TYPE class _LiteralProcessorType(Protocol): def __call__(self, value: Any) -> str: ... class JSONLiteral(JSON): """Teach SA how to literalize json.""" def literal_processor(self, dialect: Dialect) -> _LiteralProcessorType: """Processor to convert a value to JSON.""" def process(value: Any) -> str: """Dump json.""" return JSON_DUMP(value) return process class Events(Base): """Event history data.""" __table_args__ = ( # Used for fetching events at a specific time # see logbook Index( "ix_events_event_type_id_time_fired_ts", "event_type_id", "time_fired_ts" ), Index( EVENTS_CONTEXT_ID_BIN_INDEX, "context_id_bin", mysql_length=CONTEXT_ID_BIN_MAX_LENGTH, mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH, ), _DEFAULT_TABLE_ARGS, ) __tablename__ = TABLE_EVENTS event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) event_type: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) event_data: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) origin: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) origin_idx: Mapped[int | None] = mapped_column(SmallInteger) time_fired: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) time_fired_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True) context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) data_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey("event_data.data_id"), index=True ) context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) event_type_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey("event_types.event_type_id") ) event_data_rel: Mapped[EventData | None] = relationship("EventData") event_type_rel: Mapped[EventTypes | None] = relationship("EventTypes") def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( "<recorder.Events(" f"id={self.event_id}, event_type_id='{self.event_type_id}', " f"origin_idx='{self.origin_idx}', time_fired='{self._time_fired_isotime}'" f", data_id={self.data_id})>" ) @property def _time_fired_isotime(self) -> str | None: """Return time_fired as an isotime string.""" date_time: datetime | None if self.time_fired_ts is not None: date_time = dt_util.utc_from_timestamp(self.time_fired_ts) else: date_time = process_timestamp(self.time_fired) if date_time is None: return None return date_time.isoformat(sep=" ", timespec="seconds") @staticmethod def from_event(event: Event) -> Events: """Create an event database object from a native event.""" context = event.context return Events( event_type=None, event_data=None, origin_idx=event.origin.idx, time_fired=None, time_fired_ts=event.time_fired_timestamp, context_id=None, context_id_bin=ulid_to_bytes_or_none(context.id), context_user_id=None, context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id), context_parent_id=None, context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id), ) class LegacyEvents(LegacyBase): """Event history data with event_id, used for schema migration.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_EVENTS event_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) context_id: Mapped[str | None] = mapped_column( String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True ) class EventData(Base): """Event data history.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_EVENT_DATA data_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True) # Note that this is not named attributes to avoid confusion with the states table shared_data: Mapped[str | None] = mapped_column( Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb") ) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( "<recorder.EventData(" f"id={self.data_id}, hash='{self.hash}', data='{self.shared_data}'" ")>" ) @staticmethod def shared_data_bytes_from_event( event: Event, dialect: SupportedDialect | None ) -> bytes: """Create shared_data from an event.""" encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes bytes_result = encoder(event.data) if len(bytes_result) > MAX_EVENT_DATA_BYTES: _LOGGER.warning( "Event data for %s exceed maximum size of %s bytes. " "This can cause database performance issues; Event data " "will not be stored", event.event_type, MAX_EVENT_DATA_BYTES, ) return b"{}" return bytes_result @staticmethod def hash_shared_data_bytes(shared_data_bytes: bytes) -> int: """Return the hash of json encoded shared data.""" return fnv1a_32(shared_data_bytes) class EventTypes(Base): """Event type history.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_EVENT_TYPES event_type_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) event_type: Mapped[str | None] = mapped_column( String(MAX_LENGTH_EVENT_EVENT_TYPE), index=True, unique=True ) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( "<recorder.EventTypes(" f"id={self.event_type_id}, event_type='{self.event_type}'" ")>" ) class States(Base): """State change history.""" __table_args__ = ( # Used for fetching the state of entities at a specific time # (get_states in history.py) Index(METADATA_ID_LAST_UPDATED_INDEX_TS, "metadata_id", "last_updated_ts"), Index( STATES_CONTEXT_ID_BIN_INDEX, "context_id_bin", mysql_length=CONTEXT_ID_BIN_MAX_LENGTH, mariadb_length=CONTEXT_ID_BIN_MAX_LENGTH, ), _DEFAULT_TABLE_ARGS, ) __tablename__ = TABLE_STATES state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) state: Mapped[str | None] = mapped_column(String(MAX_LENGTH_STATE_STATE)) attributes: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) event_id: Mapped[int | None] = mapped_column(UNUSED_LEGACY_INTEGER_COLUMN) last_changed: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) last_changed_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE) last_reported_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE) last_updated: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) last_updated_ts: Mapped[float | None] = mapped_column( TIMESTAMP_TYPE, default=time.time, index=True ) old_state_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey("states.state_id"), index=True ) attributes_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey("state_attributes.attributes_id"), index=True ) context_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) context_user_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) context_parent_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) origin_idx: Mapped[int | None] = mapped_column( SmallInteger ) # 0 is local, 1 is remote old_state: Mapped[States | None] = relationship("States", remote_side=[state_id]) state_attributes: Mapped[StateAttributes | None] = relationship("StateAttributes") context_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) context_user_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) context_parent_id_bin: Mapped[bytes | None] = mapped_column(CONTEXT_BINARY_TYPE) metadata_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey("states_meta.metadata_id") ) states_meta_rel: Mapped[StatesMeta | None] = relationship("StatesMeta") def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( f"<recorder.States(id={self.state_id}, entity_id='{self.entity_id}'" f" metadata_id={self.metadata_id}," f" state='{self.state}', event_id='{self.event_id}'," f" last_updated='{self._last_updated_isotime}'," f" old_state_id={self.old_state_id}, attributes_id={self.attributes_id})>" ) @property def _last_updated_isotime(self) -> str | None: """Return last_updated as an isotime string.""" date_time: datetime | None if self.last_updated_ts is not None: date_time = dt_util.utc_from_timestamp(self.last_updated_ts) else: date_time = process_timestamp(self.last_updated) if date_time is None: return None return date_time.isoformat(sep=" ", timespec="seconds") @staticmethod def from_event(event: Event[EventStateChangedData]) -> States: """Create object from a state_changed event.""" state = event.data["new_state"] # None state means the state was removed from the state machine if state is None: state_value = "" last_updated_ts = event.time_fired_timestamp last_changed_ts = None last_reported_ts = None else: state_value = state.state last_updated_ts = state.last_updated_timestamp if state.last_updated == state.last_changed: last_changed_ts = None else: last_changed_ts = state.last_changed_timestamp if state.last_updated == state.last_reported: last_reported_ts = None else: last_reported_ts = state.last_reported_timestamp context = event.context return States( state=state_value, entity_id=None, attributes=None, context_id=None, context_id_bin=ulid_to_bytes_or_none(context.id), context_user_id=None, context_user_id_bin=uuid_hex_to_bytes_or_none(context.user_id), context_parent_id=None, context_parent_id_bin=ulid_to_bytes_or_none(context.parent_id), origin_idx=event.origin.idx, last_updated=None, last_changed=None, last_updated_ts=last_updated_ts, last_changed_ts=last_changed_ts, last_reported_ts=last_reported_ts, ) class LegacyStates(LegacyBase): """State change history with entity_id, used for schema migration.""" __table_args__ = ( Index( LEGACY_STATES_ENTITY_ID_LAST_UPDATED_TS_INDEX, "entity_id", "last_updated_ts", ), _DEFAULT_TABLE_ARGS, ) __tablename__ = TABLE_STATES state_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) entity_id: Mapped[str | None] = mapped_column(UNUSED_LEGACY_COLUMN) last_updated_ts: Mapped[float | None] = mapped_column( TIMESTAMP_TYPE, default=time.time, index=True ) context_id: Mapped[str | None] = mapped_column( String(LEGACY_MAX_LENGTH_EVENT_CONTEXT_ID), index=True ) class StateAttributes(Base): """State attribute change history.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_STATE_ATTRIBUTES attributes_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) hash: Mapped[int | None] = mapped_column(UINT_32_TYPE, index=True) # Note that this is not named attributes to avoid confusion with the states table shared_attrs: Mapped[str | None] = mapped_column( Text().with_variant(mysql.LONGTEXT, "mysql", "mariadb") ) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( f"<recorder.StateAttributes(id={self.attributes_id}, hash='{self.hash}'," f" attributes='{self.shared_attrs}')>" ) @staticmethod def shared_attrs_bytes_from_event( event: Event[EventStateChangedData], dialect: SupportedDialect | None, ) -> bytes: """Create shared_attrs from a state_changed event.""" # None state means the state was removed from the state machine if (state := event.data["new_state"]) is None: return b"{}" if state_info := state.state_info: unrecorded_attributes = state_info["unrecorded_attributes"] exclude_attrs = { *ALL_DOMAIN_EXCLUDE_ATTRS, *unrecorded_attributes, } if MATCH_ALL in unrecorded_attributes: # Don't exclude device class, state class, unit of measurement # or friendly name when using the MATCH_ALL exclude constant exclude_attrs.update(state.attributes) exclude_attrs -= _MATCH_ALL_KEEP else: exclude_attrs = ALL_DOMAIN_EXCLUDE_ATTRS encoder = json_bytes_strip_null if dialect == PSQL_DIALECT else json_bytes bytes_result = encoder( {k: v for k, v in state.attributes.items() if k not in exclude_attrs} ) if len(bytes_result) > MAX_STATE_ATTRS_BYTES: _LOGGER.warning( "State attributes for %s exceed maximum size of %s bytes. " "This can cause database performance issues; Attributes " "will not be stored", state.entity_id, MAX_STATE_ATTRS_BYTES, ) return b"{}" return bytes_result @staticmethod def hash_shared_attrs_bytes(shared_attrs_bytes: bytes) -> int: """Return the hash of json encoded shared attributes.""" return fnv1a_32(shared_attrs_bytes) class StatesMeta(Base): """Metadata for states.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_STATES_META metadata_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) entity_id: Mapped[str | None] = mapped_column( String(MAX_LENGTH_STATE_ENTITY_ID), index=True, unique=True ) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( "<recorder.StatesMeta(" f"id={self.metadata_id}, entity_id='{self.entity_id}'" ")>" ) class StatisticsBase: """Statistics base class.""" id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) created: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) created_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, default=time.time) metadata_id: Mapped[int | None] = mapped_column( ID_TYPE, ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"), ) start: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) start_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE, index=True) mean: Mapped[float | None] = mapped_column(DOUBLE_TYPE) mean_weight: Mapped[float | None] = mapped_column(DOUBLE_TYPE) min: Mapped[float | None] = mapped_column(DOUBLE_TYPE) max: Mapped[float | None] = mapped_column(DOUBLE_TYPE) last_reset: Mapped[datetime | None] = mapped_column(UNUSED_LEGACY_DATETIME_COLUMN) last_reset_ts: Mapped[float | None] = mapped_column(TIMESTAMP_TYPE) state: Mapped[float | None] = mapped_column(DOUBLE_TYPE) sum: Mapped[float | None] = mapped_column(DOUBLE_TYPE) duration: timedelta @classmethod def from_stats( cls, metadata_id: int, stats: StatisticData, now_timestamp: float | None = None ) -> Self: """Create object from a statistics with datetime objects.""" return cls( # type: ignore[call-arg] metadata_id=metadata_id, created=None, created_ts=now_timestamp or time.time(), start=None, start_ts=stats["start"].timestamp(), mean=stats.get("mean"), mean_weight=stats.get("mean_weight"), min=stats.get("min"), max=stats.get("max"), last_reset=None, last_reset_ts=datetime_to_timestamp_or_none(stats.get("last_reset")), state=stats.get("state"), sum=stats.get("sum"), ) @classmethod def from_stats_ts( cls, metadata_id: int, stats: StatisticDataTimestamp, now_timestamp: float | None = None, ) -> Self: """Create object from a statistics with timestamps.""" return cls( # type: ignore[call-arg] metadata_id=metadata_id, created=None, created_ts=now_timestamp or time.time(), start=None, start_ts=stats["start_ts"], mean=stats.get("mean"), mean_weight=stats.get("mean_weight"), min=stats.get("min"), max=stats.get("max"), last_reset=None, last_reset_ts=stats.get("last_reset_ts"), state=stats.get("state"), sum=stats.get("sum"), ) class Statistics(Base, StatisticsBase): """Long term statistics.""" duration = timedelta(hours=1) __table_args__ = ( # Used for fetching statistics for a certain entity at a specific time Index( "ix_statistics_statistic_id_start_ts", "metadata_id", "start_ts", unique=True, ), _DEFAULT_TABLE_ARGS, ) __tablename__ = TABLE_STATISTICS class _StatisticsShortTerm(StatisticsBase): """Short term statistics.""" duration = timedelta(minutes=5) __tablename__ = TABLE_STATISTICS_SHORT_TERM class StatisticsShortTerm(Base, _StatisticsShortTerm): """Short term statistics.""" __table_args__ = ( # Used for fetching statistics for a certain entity at a specific time Index( "ix_statistics_short_term_statistic_id_start_ts", "metadata_id", "start_ts", unique=True, ), _DEFAULT_TABLE_ARGS, ) class LegacyStatisticsShortTerm(LegacyBase, _StatisticsShortTerm): """Short term statistics with 32-bit index, used for schema migration.""" __table_args__ = ( # Used for fetching statistics for a certain entity at a specific time Index( "ix_statistics_short_term_statistic_id_start_ts", "metadata_id", "start_ts", unique=True, ), _DEFAULT_TABLE_ARGS, ) metadata_id: Mapped[int | None] = mapped_column( Integer, ForeignKey(f"{TABLE_STATISTICS_META}.id", ondelete="CASCADE"), use_existing_column=True, ) class _StatisticsMeta: """Statistics meta data.""" __table_args__ = (_DEFAULT_TABLE_ARGS,) __tablename__ = TABLE_STATISTICS_META id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) statistic_id: Mapped[str | None] = mapped_column( String(255), index=True, unique=True ) source: Mapped[str | None] = mapped_column(String(32)) unit_of_measurement: Mapped[str | None] = mapped_column(String(255)) unit_class: Mapped[str | None] = mapped_column(String(255)) has_mean: Mapped[bool | None] = mapped_column(Boolean) has_sum: Mapped[bool | None] = mapped_column(Boolean) name: Mapped[str | None] = mapped_column(String(255)) mean_type: Mapped[StatisticMeanType] = mapped_column( SmallInteger, nullable=False, default=StatisticMeanType.NONE.value ) # See StatisticMeanType @staticmethod def from_meta(meta: StatisticMetaData) -> StatisticsMeta: """Create object from meta data.""" return StatisticsMeta(**meta) class StatisticsMeta(Base, _StatisticsMeta): """Statistics meta data.""" class LegacyStatisticsMeta(LegacyBase, _StatisticsMeta): """Statistics meta data with 32-bit index, used for schema migration.""" id: Mapped[int] = mapped_column( Integer, Identity(), primary_key=True, use_existing_column=True, ) class RecorderRuns(Base): """Representation of recorder run.""" __table_args__ = ( Index("ix_recorder_runs_start_end", "start", "end"), _DEFAULT_TABLE_ARGS, ) __tablename__ = TABLE_RECORDER_RUNS run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) start: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow) end: Mapped[datetime | None] = mapped_column(DATETIME_TYPE) closed_incorrect: Mapped[bool] = mapped_column(Boolean, default=False) created: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow) def __repr__(self) -> str: """Return string representation of instance for debugging.""" end = ( f"'{self.end.isoformat(sep=' ', timespec='seconds')}'" if self.end else None ) return ( f"<recorder.RecorderRuns(id={self.run_id}," f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', end={end}," f" closed_incorrect={self.closed_incorrect}," f" created='{self.created.isoformat(sep=' ', timespec='seconds')}')>" ) class MigrationChanges(Base): """Representation of migration changes.""" __tablename__ = TABLE_MIGRATION_CHANGES __table_args__ = (_DEFAULT_TABLE_ARGS,) migration_id: Mapped[str] = mapped_column(String(255), primary_key=True) version: Mapped[int] = mapped_column(SmallInteger) class SchemaChanges(Base): """Representation of schema version changes.""" __tablename__ = TABLE_SCHEMA_CHANGES __table_args__ = (_DEFAULT_TABLE_ARGS,) change_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) schema_version: Mapped[int | None] = mapped_column(Integer) changed: Mapped[datetime] = mapped_column(DATETIME_TYPE, default=dt_util.utcnow) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( "<recorder.SchemaChanges(" f"id={self.change_id}, schema_version={self.schema_version}, " f"changed='{self.changed.isoformat(sep=' ', timespec='seconds')}'" ")>" ) class StatisticsRuns(Base): """Representation of statistics run.""" __tablename__ = TABLE_STATISTICS_RUNS __table_args__ = (_DEFAULT_TABLE_ARGS,) run_id: Mapped[int] = mapped_column(ID_TYPE, Identity(), primary_key=True) start: Mapped[datetime] = mapped_column(DATETIME_TYPE, index=True) def __repr__(self) -> str: """Return string representation of instance for debugging.""" return ( f"<recorder.StatisticsRuns(id={self.run_id}," f" start='{self.start.isoformat(sep=' ', timespec='seconds')}', )>" ) EVENT_DATA_JSON = type_coerce( EventData.shared_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True) ) OLD_FORMAT_EVENT_DATA_JSON = type_coerce( Events.event_data.cast(JSONB_VARIANT_CAST), JSONLiteral(none_as_null=True) ) SHARED_ATTRS_JSON = type_coerce( StateAttributes.shared_attrs.cast(JSON_VARIANT_CAST), JSON(none_as_null=True) ) OLD_FORMAT_ATTRS_JSON = type_coerce( States.attributes.cast(JSON_VARIANT_CAST), JSON(none_as_null=True) ) ENTITY_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["entity_id"] OLD_ENTITY_ID_IN_EVENT: ColumnElement = OLD_FORMAT_EVENT_DATA_JSON["entity_id"] DEVICE_ID_IN_EVENT: ColumnElement = EVENT_DATA_JSON["device_id"] OLD_STATE = aliased(States, name="old_state") SHARED_ATTR_OR_LEGACY_ATTRIBUTES = case( (StateAttributes.shared_attrs.is_(None), States.attributes), else_=StateAttributes.shared_attrs, ).label("attributes") SHARED_DATA_OR_LEGACY_EVENT_DATA = case( (EventData.shared_data.is_(None), Events.event_data), else_=EventData.shared_data ).label("event_data")
{ "repo_id": "home-assistant/core", "file_path": "tests/components/recorder/db_schema_51.py", "license": "Apache License 2.0", "lines": 756, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/recorder/test_migration_from_schema_51.py
"""Test for migration from DB schema version 51.""" import importlib import sys import threading from unittest.mock import patch import pytest from pytest_unordered import unordered from sqlalchemy import create_engine, inspect from sqlalchemy.orm import Session from homeassistant.components import recorder from homeassistant.components.recorder import core, migration, statistics from homeassistant.components.recorder.const import UNIT_CLASS_SCHEMA_VERSION from homeassistant.components.recorder.db_schema import StatisticsMeta from homeassistant.components.recorder.models import StatisticMeanType from homeassistant.components.recorder.util import session_scope from homeassistant.core import HomeAssistant from .common import ( async_recorder_block_till_done, async_wait_recording_done, get_patched_live_version, ) from .conftest import instrument_migration from tests.common import async_test_home_assistant from tests.typing import RecorderInstanceContextManager CREATE_ENGINE_TARGET = "homeassistant.components.recorder.core.create_engine" SCHEMA_MODULE_51 = "tests.components.recorder.db_schema_51" @pytest.fixture async def mock_recorder_before_hass( async_test_recorder: RecorderInstanceContextManager, ) -> None: """Set up recorder.""" async def _async_wait_migration_done(hass: HomeAssistant) -> None: """Wait for the migration to be done.""" await recorder.get_instance(hass).async_block_till_done() await async_recorder_block_till_done(hass) def _create_engine_test(*args, **kwargs): """Test version of create_engine that initializes with old schema. This simulates an existing db with the old schema. """ importlib.import_module(SCHEMA_MODULE_51) old_db_schema = sys.modules[SCHEMA_MODULE_51] engine = create_engine(*args, **kwargs) old_db_schema.Base.metadata.create_all(engine) with Session(engine) as session: session.add( recorder.db_schema.StatisticsRuns(start=statistics.get_start_time()) ) session.add( recorder.db_schema.SchemaChanges( schema_version=old_db_schema.SCHEMA_VERSION ) ) session.commit() return engine @pytest.fixture def db_schema_51(): """Fixture to initialize the db with the old schema.""" importlib.import_module(SCHEMA_MODULE_51) old_db_schema = sys.modules[SCHEMA_MODULE_51] with ( patch.object(recorder, "db_schema", old_db_schema), patch.object(migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION), patch.object( migration, "LIVE_MIGRATION_MIN_SCHEMA_VERSION", get_patched_live_version(old_db_schema), ), patch.object(migration, "non_live_data_migration_needed", return_value=False), patch.object(core, "StatesMeta", old_db_schema.StatesMeta), patch.object(core, "EventTypes", old_db_schema.EventTypes), patch.object(core, "EventData", old_db_schema.EventData), patch.object(core, "States", old_db_schema.States), patch.object(core, "Events", old_db_schema.Events), patch.object(core, "StateAttributes", old_db_schema.StateAttributes), patch(CREATE_ENGINE_TARGET, new=_create_engine_test), ): yield @pytest.mark.parametrize( ("persistent_database", "expected_unit_class"), [ ( True, { # MariaDB/MySQL should correct unit class of sensor.test4 + sensor.test5 "mysql": { "sensor.test1": "energy", "sensor.test2": "power", "sensor.test3": "unitless", "sensor.test4": None, "sensor.test5": None, }, # PostgreSQL is not modified by the migration "postgresql": { "sensor.test1": "energy", "sensor.test2": "power", "sensor.test3": "unitless", "sensor.test4": "volume_flow_rate", "sensor.test5": "area", }, # SQLite is not modified by the migration "sqlite": { "sensor.test1": "energy", "sensor.test2": "power", "sensor.test3": "unitless", "sensor.test4": "volume_flow_rate", "sensor.test5": "area", }, }, ), ], ) @pytest.mark.usefixtures("hass_storage") # Prevent test hass from writing to storage async def test_migrate_statistics_meta( async_test_recorder: RecorderInstanceContextManager, caplog: pytest.LogCaptureFixture, expected_unit_class: dict[str, dict[str, str | None]], ) -> None: """Test we can fix bad migration to version 51.""" importlib.import_module(SCHEMA_MODULE_51) old_db_schema = sys.modules[SCHEMA_MODULE_51] def _insert_metadata(): with session_scope(hass=hass) as session: session.add_all( ( old_db_schema.StatisticsMeta( statistic_id="sensor.test1", source="recorder", unit_of_measurement="kWh", has_mean=None, has_sum=True, name="Test 1", mean_type=StatisticMeanType.NONE, unit_class="energy", ), # Unexpected, but will not be changed by migration old_db_schema.StatisticsMeta( statistic_id="sensor.test2", source="recorder", unit_of_measurement="cats", has_mean=None, has_sum=True, name="Test 2", mean_type=StatisticMeanType.NONE, unit_class="power", ), # This will be updated to "unitless" when migration runs again old_db_schema.StatisticsMeta( statistic_id="sensor.test3", source="recorder", unit_of_measurement="ppm", has_mean=None, has_sum=True, name="Test 3", mean_type=StatisticMeanType.NONE, unit_class=None, ), # Wrong case old_db_schema.StatisticsMeta( statistic_id="sensor.test4", source="recorder", unit_of_measurement="l/min", has_mean=None, has_sum=True, name="Test 4", mean_type=StatisticMeanType.NONE, unit_class="volume_flow_rate", ), # Wrong encoding old_db_schema.StatisticsMeta( statistic_id="sensor.test5", source="recorder", unit_of_measurement="㎡", has_mean=None, has_sum=True, name="Test 5", mean_type=StatisticMeanType.NONE, unit_class="area", ), ) ) # Create database with old schema with ( patch.object(recorder, "db_schema", old_db_schema), patch.object(migration, "SCHEMA_VERSION", old_db_schema.SCHEMA_VERSION), patch.object( migration, "LIVE_MIGRATION_MIN_SCHEMA_VERSION", get_patched_live_version(old_db_schema), ), patch.object(migration.EventsContextIDMigration, "migrate_data"), patch(CREATE_ENGINE_TARGET, new=_create_engine_test), ): async with ( async_test_home_assistant() as hass, async_test_recorder(hass) as instance, ): await instance.async_add_executor_job(_insert_metadata) await async_wait_recording_done(hass) await _async_wait_migration_done(hass) await hass.async_stop() await hass.async_block_till_done() def _object_as_dict(obj): return {c.key: getattr(obj, c.key) for c in inspect(obj).mapper.column_attrs} def _fetch_metadata(): with session_scope(hass=hass) as session: metadatas = session.query(StatisticsMeta).all() return { metadata.statistic_id: _object_as_dict(metadata) for metadata in metadatas } # Run again with new schema, let migration run async with async_test_home_assistant() as hass: with ( instrument_migration(hass) as instrumented_migration, ): # Stall migration when the last non-live schema migration is done instrumented_migration.stall_on_schema_version = UNIT_CLASS_SCHEMA_VERSION async with async_test_recorder( hass, wait_recorder=False, wait_recorder_setup=False ) as instance: engine_name = instance.engine.dialect.name # Wait for migration to reach migration of unit class await hass.async_add_executor_job( instrumented_migration.apply_update_stalled.wait ) # Check that it's possible to read metadata via the API, this will # stop working when version 50 is migrated off line pre_migration_metadata_api = await instance.async_add_executor_job( statistics.list_statistic_ids, hass, None, None, ) instrumented_migration.migration_stall.set() instance.recorder_and_worker_thread_ids.add(threading.get_ident()) await hass.async_block_till_done() await async_wait_recording_done(hass) await async_wait_recording_done(hass) post_migration_metadata_db = await instance.async_add_executor_job( _fetch_metadata ) post_migration_metadata_api = await instance.async_add_executor_job( statistics.list_statistic_ids, hass, None, None, ) await hass.async_stop() await hass.async_block_till_done() assert pre_migration_metadata_api == unordered( [ { "display_unit_of_measurement": "kWh", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 1", "source": "recorder", "statistic_id": "sensor.test1", "statistics_unit_of_measurement": "kWh", "unit_class": "energy", }, { "display_unit_of_measurement": "cats", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 2", "source": "recorder", "statistic_id": "sensor.test2", "statistics_unit_of_measurement": "cats", "unit_class": None, }, { "display_unit_of_measurement": "ppm", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 3", "source": "recorder", "statistic_id": "sensor.test3", "statistics_unit_of_measurement": "ppm", "unit_class": "unitless", }, { "display_unit_of_measurement": "l/min", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 4", "source": "recorder", "statistic_id": "sensor.test4", "statistics_unit_of_measurement": "l/min", "unit_class": None, }, { "display_unit_of_measurement": "㎡", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 5", "source": "recorder", "statistic_id": "sensor.test5", "statistics_unit_of_measurement": "㎡", "unit_class": None, }, ] ) assert post_migration_metadata_db == { "sensor.test1": { "has_mean": None, "has_sum": True, "id": 1, "mean_type": 0, "name": "Test 1", "source": "recorder", "statistic_id": "sensor.test1", "unit_class": expected_unit_class[engine_name]["sensor.test1"], "unit_of_measurement": "kWh", }, "sensor.test2": { "has_mean": None, "has_sum": True, "id": 2, "mean_type": 0, "name": "Test 2", "source": "recorder", "statistic_id": "sensor.test2", "unit_class": expected_unit_class[engine_name]["sensor.test2"], "unit_of_measurement": "cats", }, "sensor.test3": { "has_mean": None, "has_sum": True, "id": 3, "mean_type": 0, "name": "Test 3", "source": "recorder", "statistic_id": "sensor.test3", "unit_class": expected_unit_class[engine_name]["sensor.test3"], "unit_of_measurement": "ppm", }, "sensor.test4": { "has_mean": None, "has_sum": True, "id": 4, "mean_type": 0, "name": "Test 4", "source": "recorder", "statistic_id": "sensor.test4", "unit_class": expected_unit_class[engine_name]["sensor.test4"], "unit_of_measurement": "l/min", }, "sensor.test5": { "has_mean": None, "has_sum": True, "id": 5, "mean_type": 0, "name": "Test 5", "source": "recorder", "statistic_id": "sensor.test5", "unit_class": expected_unit_class[engine_name]["sensor.test5"], "unit_of_measurement": "㎡", }, } assert post_migration_metadata_api == unordered( [ { "display_unit_of_measurement": "kWh", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 1", "source": "recorder", "statistic_id": "sensor.test1", "statistics_unit_of_measurement": "kWh", "unit_class": expected_unit_class[engine_name]["sensor.test1"], }, { "display_unit_of_measurement": "cats", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 2", "source": "recorder", "statistic_id": "sensor.test2", "statistics_unit_of_measurement": "cats", "unit_class": expected_unit_class[engine_name]["sensor.test2"], }, { "display_unit_of_measurement": "ppm", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 3", "source": "recorder", "statistic_id": "sensor.test3", "statistics_unit_of_measurement": "ppm", "unit_class": expected_unit_class[engine_name]["sensor.test3"], }, { "display_unit_of_measurement": "l/min", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 4", "source": "recorder", "statistic_id": "sensor.test4", "statistics_unit_of_measurement": "l/min", "unit_class": expected_unit_class[engine_name]["sensor.test4"], }, { "display_unit_of_measurement": "㎡", "has_mean": False, "has_sum": True, "mean_type": StatisticMeanType.NONE, "name": "Test 5", "source": "recorder", "statistic_id": "sensor.test5", "statistics_unit_of_measurement": "㎡", "unit_class": expected_unit_class[engine_name]["sensor.test5"], }, ] )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/recorder/test_migration_from_schema_51.py", "license": "Apache License 2.0", "lines": 424, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/ukraine_alarm/test_init.py
"""Test the Ukraine Alarm integration initialization.""" from unittest.mock import patch from homeassistant.components.ukraine_alarm.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from . import REGIONS from tests.common import MockConfigEntry async def test_migration_v1_to_v2_state_without_districts( hass: HomeAssistant, issue_registry: ir.IssueRegistry, ) -> None: """Test migration allows states without districts.""" entry = MockConfigEntry( domain=DOMAIN, version=1, data={"region": "1", "name": "State 1"}, unique_id="1", ) entry.add_to_hass(hass) with ( patch( "homeassistant.components.ukraine_alarm.Client.get_regions", return_value=REGIONS, ), patch( "homeassistant.components.ukraine_alarm.Client.get_alerts", return_value=[{"activeAlerts": []}], ), ): result = await hass.config_entries.async_setup(entry.entry_id) assert result is True assert entry.version == 2 assert ( DOMAIN, f"deprecated_state_region_{entry.entry_id}", ) not in issue_registry.issues async def test_migration_v1_to_v2_state_with_districts_fails( hass: HomeAssistant, issue_registry: ir.IssueRegistry, ) -> None: """Test migration rejects states with districts.""" entry = MockConfigEntry( domain=DOMAIN, version=1, data={"region": "2", "name": "State 2"}, unique_id="2", ) entry.add_to_hass(hass) with patch( "homeassistant.components.ukraine_alarm.Client.get_regions", return_value=REGIONS, ): result = await hass.config_entries.async_setup(entry.entry_id) assert result is False assert ( DOMAIN, f"deprecated_state_region_{entry.entry_id}", ) in issue_registry.issues
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ukraine_alarm/test_init.py", "license": "Apache License 2.0", "lines": 58, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airthings_ble/test_init.py
"""Test the Airthings BLE integration init.""" from copy import deepcopy from airthings_ble import AirthingsDeviceType from freezegun.api import FrozenDateTimeFactory import pytest from homeassistant.components.airthings_ble.const import ( DEFAULT_SCAN_INTERVAL, DEVICE_MODEL, DEVICE_SPECIFIC_SCAN_INTERVAL, DOMAIN, ) from homeassistant.core import HomeAssistant from . import ( CORENTIUM_HOME_2_DEVICE_INFO, CORENTIUM_HOME_2_SERVICE_INFO, WAVE_DEVICE_INFO, WAVE_ENHANCE_DEVICE_INFO, WAVE_ENHANCE_SERVICE_INFO, WAVE_SERVICE_INFO, patch_airthings_ble, patch_async_ble_device_from_address, ) from tests.common import MockConfigEntry, async_fire_time_changed from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.parametrize( ("service_info", "device_info"), [ (WAVE_SERVICE_INFO, WAVE_DEVICE_INFO), (WAVE_ENHANCE_SERVICE_INFO, WAVE_ENHANCE_DEVICE_INFO), (CORENTIUM_HOME_2_SERVICE_INFO, CORENTIUM_HOME_2_DEVICE_INFO), ], ) async def test_migration_existing_entries( hass: HomeAssistant, service_info, device_info, ) -> None: """Test migration of existing config entry without device model.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=service_info.address, data={}, ) entry.add_to_hass(hass) inject_bluetooth_service_info(hass, service_info) assert DEVICE_MODEL not in entry.data with ( patch_async_ble_device_from_address(service_info.device), patch_airthings_ble(device_info), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() # Migration should have added device_model to entry data assert DEVICE_MODEL in entry.data assert entry.data[DEVICE_MODEL] == device_info.model.value async def test_no_migration_when_device_model_exists( hass: HomeAssistant, ) -> None: """Test that migration does not run when device_model already exists.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=WAVE_SERVICE_INFO.address, data={DEVICE_MODEL: WAVE_DEVICE_INFO.model.value}, ) entry.add_to_hass(hass) inject_bluetooth_service_info(hass, WAVE_SERVICE_INFO) with ( patch_async_ble_device_from_address(WAVE_SERVICE_INFO.device), patch_airthings_ble(WAVE_DEVICE_INFO) as mock_update, ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() # Should have only 1 call for initial refresh (no migration call) assert mock_update.call_count == 1 assert entry.data[DEVICE_MODEL] == WAVE_DEVICE_INFO.model.value async def test_scan_interval_corentium_home_2( hass: HomeAssistant, freezer: FrozenDateTimeFactory ) -> None: """Test that coordinator uses radon scan interval for Corentium Home 2.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=WAVE_SERVICE_INFO.address, data={DEVICE_MODEL: CORENTIUM_HOME_2_DEVICE_INFO.model.value}, ) entry.add_to_hass(hass) inject_bluetooth_service_info(hass, WAVE_SERVICE_INFO) with ( patch_async_ble_device_from_address(WAVE_SERVICE_INFO.device), patch_airthings_ble(CORENTIUM_HOME_2_DEVICE_INFO), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() assert ( hass.states.get("sensor.airthings_corentium_home_2_123456_battery").state == "90" ) changed_info = deepcopy(CORENTIUM_HOME_2_DEVICE_INFO) changed_info.sensors["battery"] = 89 with patch_airthings_ble(changed_info): freezer.tick(DEFAULT_SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() assert ( hass.states.get("sensor.airthings_corentium_home_2_123456_battery").state == "90" ) freezer.tick( DEVICE_SPECIFIC_SCAN_INTERVAL.get( AirthingsDeviceType.CORENTIUM_HOME_2.value ) - DEFAULT_SCAN_INTERVAL ) async_fire_time_changed(hass) await hass.async_block_till_done() assert ( hass.states.get("sensor.airthings_corentium_home_2_123456_battery").state == "89" ) @pytest.mark.parametrize( ("service_info", "device_info", "battery_entity_id"), [ (WAVE_SERVICE_INFO, WAVE_DEVICE_INFO, "sensor.airthings_wave_123456_battery"), ( WAVE_ENHANCE_SERVICE_INFO, WAVE_ENHANCE_DEVICE_INFO, "sensor.airthings_wave_enhance_123456_battery", ), ], ) async def test_coordinator_default_scan_interval( hass: HomeAssistant, service_info, device_info, freezer: FrozenDateTimeFactory, battery_entity_id: str, ) -> None: """Test that coordinator uses default scan interval.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=service_info.address, data={DEVICE_MODEL: device_info.model.value}, ) entry.add_to_hass(hass) inject_bluetooth_service_info(hass, service_info) with ( patch_async_ble_device_from_address(service_info.device), patch_airthings_ble(device_info), ): await hass.config_entries.async_setup(entry.entry_id) await hass.async_block_till_done() assert hass.states.get(battery_entity_id).state == "85" changed_info = deepcopy(device_info) changed_info.sensors["battery"] = 84 with patch_airthings_ble(changed_info): freezer.tick(DEFAULT_SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() assert hass.states.get(battery_entity_id).state == "84"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airthings_ble/test_init.py", "license": "Apache License 2.0", "lines": 158, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/actron_air/climate.py
"""Climate platform for Actron Air integration.""" from typing import Any from actron_neo_api import ActronAirStatus, ActronAirZone from homeassistant.components.climate import ( FAN_AUTO, FAN_HIGH, FAN_LOW, FAN_MEDIUM, ClimateEntity, ClimateEntityFeature, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import ActronAirConfigEntry, ActronAirSystemCoordinator from .entity import ActronAirAcEntity, ActronAirZoneEntity, handle_actron_api_errors PARALLEL_UPDATES = 0 FAN_MODE_MAPPING_ACTRONAIR_TO_HA = { "AUTO": FAN_AUTO, "LOW": FAN_LOW, "MED": FAN_MEDIUM, "HIGH": FAN_HIGH, } FAN_MODE_MAPPING_HA_TO_ACTRONAIR = { v: k for k, v in FAN_MODE_MAPPING_ACTRONAIR_TO_HA.items() } HVAC_MODE_MAPPING_ACTRONAIR_TO_HA = { "COOL": HVACMode.COOL, "HEAT": HVACMode.HEAT, "FAN": HVACMode.FAN_ONLY, "AUTO": HVACMode.AUTO, "OFF": HVACMode.OFF, } HVAC_MODE_MAPPING_HA_TO_ACTRONAIR = { v: k for k, v in HVAC_MODE_MAPPING_ACTRONAIR_TO_HA.items() } async def async_setup_entry( hass: HomeAssistant, entry: ActronAirConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Actron Air climate entities.""" system_coordinators = entry.runtime_data.system_coordinators entities: list[ClimateEntity] = [] for coordinator in system_coordinators.values(): status = coordinator.data entities.append(ActronSystemClimate(coordinator)) entities.extend( ActronZoneClimate(coordinator, zone) for zone in status.remote_zone_info if zone.exists ) async_add_entities(entities) class ActronAirClimateEntity(ClimateEntity): """Base class for Actron Air climate entities.""" _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.FAN_MODE | ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF ) _attr_name = None _attr_fan_modes = list(FAN_MODE_MAPPING_ACTRONAIR_TO_HA.values()) _attr_hvac_modes = list(HVAC_MODE_MAPPING_ACTRONAIR_TO_HA.values()) class ActronSystemClimate(ActronAirAcEntity, ActronAirClimateEntity): """Representation of the Actron Air system.""" def __init__( self, coordinator: ActronAirSystemCoordinator, ) -> None: """Initialize an Actron Air unit.""" super().__init__(coordinator) self._attr_unique_id = self._serial_number @property def min_temp(self) -> float: """Return the minimum temperature that can be set.""" return self._status.min_temp @property def max_temp(self) -> float: """Return the maximum temperature that can be set.""" return self._status.max_temp @property def _status(self) -> ActronAirStatus: """Get the current status from the coordinator.""" return self.coordinator.data @property def hvac_mode(self) -> HVACMode | None: """Return the current HVAC mode.""" if not self._status.user_aircon_settings.is_on: return HVACMode.OFF mode = self._status.user_aircon_settings.mode return HVAC_MODE_MAPPING_ACTRONAIR_TO_HA.get(mode) @property def fan_mode(self) -> str | None: """Return the current fan mode.""" fan_mode = self._status.user_aircon_settings.base_fan_mode return FAN_MODE_MAPPING_ACTRONAIR_TO_HA.get(fan_mode) @property def current_humidity(self) -> float: """Return the current humidity.""" return self._status.master_info.live_humidity_pc @property def current_temperature(self) -> float: """Return the current temperature.""" return self._status.master_info.live_temp_c @property def target_temperature(self) -> float: """Return the target temperature.""" return self._status.user_aircon_settings.temperature_setpoint_cool_c @handle_actron_api_errors async def async_set_fan_mode(self, fan_mode: str) -> None: """Set a new fan mode.""" api_fan_mode = FAN_MODE_MAPPING_HA_TO_ACTRONAIR.get(fan_mode) await self._status.user_aircon_settings.set_fan_mode(api_fan_mode) @handle_actron_api_errors async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set the HVAC mode.""" ac_mode = HVAC_MODE_MAPPING_HA_TO_ACTRONAIR.get(hvac_mode) await self._status.ac_system.set_system_mode(ac_mode) @handle_actron_api_errors async def async_set_temperature(self, **kwargs: Any) -> None: """Set the temperature.""" temp = kwargs.get(ATTR_TEMPERATURE) await self._status.user_aircon_settings.set_temperature(temperature=temp) class ActronZoneClimate(ActronAirZoneEntity, ActronAirClimateEntity): """Representation of a zone within the Actron Air system.""" _attr_supported_features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF ) def __init__( self, coordinator: ActronAirSystemCoordinator, zone: ActronAirZone, ) -> None: """Initialize an Actron Air unit.""" super().__init__(coordinator, zone) self._attr_unique_id: str = self._zone_identifier @property def min_temp(self) -> float: """Return the minimum temperature that can be set.""" return self._zone.min_temp @property def max_temp(self) -> float: """Return the maximum temperature that can be set.""" return self._zone.max_temp @property def _zone(self) -> ActronAirZone: """Get the current zone data from the coordinator.""" status = self.coordinator.data return status.zones[self._zone_id] @property def hvac_mode(self) -> HVACMode | None: """Return the current HVAC mode.""" if self._zone.is_active: mode = self._zone.hvac_mode return HVAC_MODE_MAPPING_ACTRONAIR_TO_HA.get(mode) return HVACMode.OFF @property def current_humidity(self) -> float | None: """Return the current humidity.""" return self._zone.humidity @property def current_temperature(self) -> float | None: """Return the current temperature.""" return self._zone.live_temp_c @property def target_temperature(self) -> float | None: """Return the target temperature.""" return self._zone.temperature_setpoint_cool_c @handle_actron_api_errors async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set the HVAC mode.""" is_enabled = hvac_mode != HVACMode.OFF await self._zone.enable(is_enabled) @handle_actron_api_errors async def async_set_temperature(self, **kwargs: Any) -> None: """Set the temperature.""" await self._zone.set_temperature(temperature=kwargs.get(ATTR_TEMPERATURE))
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/actron_air/climate.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/actron_air/config_flow.py
"""Setup config flow for Actron Air integration.""" import asyncio from collections.abc import Mapping from typing import Any from actron_neo_api import ActronAirAPI, ActronAirAuthError from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_TOKEN from homeassistant.exceptions import HomeAssistantError from .const import _LOGGER, DOMAIN class ActronAirConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Actron Air.""" def __init__(self) -> None: """Initialize the config flow.""" self._api: ActronAirAPI | None = None self._device_code: str | None = None self._user_code: str = "" self._verification_uri: str = "" self._expires_minutes: str = "30" self.login_task: asyncio.Task | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" if self._api is None: _LOGGER.debug("Initiating device authorization") self._api = ActronAirAPI() try: device_code_response = await self._api.request_device_code() except ActronAirAuthError as err: _LOGGER.error("OAuth2 flow failed: %s", err) return self.async_abort(reason="oauth2_error") self._device_code = device_code_response["device_code"] self._user_code = device_code_response["user_code"] self._verification_uri = device_code_response["verification_uri_complete"] self._expires_minutes = str(device_code_response["expires_in"] // 60) async def _wait_for_authorization() -> None: """Wait for the user to authorize the device.""" assert self._api is not None assert self._device_code is not None _LOGGER.debug("Waiting for device authorization") try: await self._api.poll_for_token(self._device_code) _LOGGER.debug("Authorization successful") except ActronAirAuthError as ex: _LOGGER.exception("Error while waiting for device authorization") raise CannotConnect from ex _LOGGER.debug("Checking login task") if self.login_task is None: _LOGGER.debug("Creating task for device authorization") self.login_task = self.hass.async_create_task(_wait_for_authorization()) if self.login_task.done(): _LOGGER.debug("Login task is done, checking results") if exception := self.login_task.exception(): if isinstance(exception, CannotConnect): return self.async_show_progress_done( next_step_id="connection_error" ) return self.async_show_progress_done(next_step_id="timeout") return self.async_show_progress_done(next_step_id="finish_login") return self.async_show_progress( step_id="user", progress_action="wait_for_authorization", description_placeholders={ "user_code": self._user_code, "verification_uri": self._verification_uri, "expires_minutes": self._expires_minutes, }, progress_task=self.login_task, ) async def async_step_finish_login( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the finalization of login.""" _LOGGER.debug("Finalizing authorization") assert self._api is not None try: user_data = await self._api.get_user_info() except ActronAirAuthError as err: _LOGGER.error("Error getting user info: %s", err) return self.async_abort(reason="oauth2_error") unique_id = str(user_data["id"]) await self.async_set_unique_id(unique_id) # Check if this is a reauth flow if self.source == SOURCE_REAUTH: self._abort_if_unique_id_mismatch(reason="wrong_account") return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates={CONF_API_TOKEN: self._api.refresh_token_value}, ) self._abort_if_unique_id_configured() return self.async_create_entry( title=user_data["email"], data={CONF_API_TOKEN: self._api.refresh_token_value}, ) async def async_step_timeout( self, user_input: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Handle issues that need transition await from progress step.""" if user_input is None: return self.async_show_form( step_id="timeout", ) del self.login_task return await self.async_step_user() async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle reauthentication request.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauth dialog.""" if user_input is not None: return await self.async_step_user() return self.async_show_form(step_id="reauth_confirm") async def async_step_connection_error( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle connection error from progress step.""" if user_input is None: return self.async_show_form(step_id="connection_error") # Reset state and try again self._api = None self._device_code = None self.login_task = None return await self.async_step_user() class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/actron_air/config_flow.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/actron_air/coordinator.py
"""Coordinator for Actron Air integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta from actron_neo_api import ( ActronAirACSystem, ActronAirAPI, ActronAirAPIError, ActronAirAuthError, ActronAirStatus, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import _LOGGER, DOMAIN SCAN_INTERVAL = timedelta(seconds=30) STALE_DEVICE_TIMEOUT = timedelta(minutes=5) ERROR_NO_SYSTEMS_FOUND = "no_systems_found" ERROR_UNKNOWN = "unknown_error" @dataclass class ActronAirRuntimeData: """Runtime data for the Actron Air integration.""" api: ActronAirAPI system_coordinators: dict[str, ActronAirSystemCoordinator] type ActronAirConfigEntry = ConfigEntry[ActronAirRuntimeData] class ActronAirSystemCoordinator(DataUpdateCoordinator[ActronAirACSystem]): """System coordinator for Actron Air integration.""" def __init__( self, hass: HomeAssistant, entry: ActronAirConfigEntry, api: ActronAirAPI, system: ActronAirACSystem, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name="Actron Air Status", update_interval=SCAN_INTERVAL, config_entry=entry, ) self.system = system self.serial_number = system["serial"] self.api = api self.status = self.api.state_manager.get_status(self.serial_number) self.last_seen = dt_util.utcnow() async def _async_update_data(self) -> ActronAirStatus: """Fetch updates and merge incremental changes into the full state.""" try: await self.api.update_status() except ActronAirAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="auth_error", ) from err except ActronAirAPIError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_error", translation_placeholders={"error": repr(err)}, ) from err self.status = self.api.state_manager.get_status(self.serial_number) self.last_seen = dt_util.utcnow() return self.status def is_device_stale(self) -> bool: """Check if a device is stale (not seen for a while).""" return (dt_util.utcnow() - self.last_seen) > STALE_DEVICE_TIMEOUT
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/actron_air/coordinator.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/control4/climate.py
"""Platform for Control4 Climate/Thermostat.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from pyControl4.climate import C4Climate from pyControl4.error_handling import C4Exception from homeassistant.components.climate import ( ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.const import ATTR_TEMPERATURE, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from . import Control4ConfigEntry, Control4RuntimeData, get_items_of_category from .const import CONTROL4_ENTITY_TYPE from .director_utils import update_variables_for_config_entry from .entity import Control4Entity _LOGGER = logging.getLogger(__name__) CONTROL4_CATEGORY = "comfort" # Control4 variable names CONTROL4_HVAC_STATE = "HVAC_STATE" CONTROL4_HVAC_MODE = "HVAC_MODE" CONTROL4_HUMIDITY = "HUMIDITY" CONTROL4_SCALE = "SCALE" # "FAHRENHEIT" or "CELSIUS" # Temperature variables - Fahrenheit CONTROL4_CURRENT_TEMPERATURE_F = "TEMPERATURE_F" CONTROL4_COOL_SETPOINT_F = "COOL_SETPOINT_F" CONTROL4_HEAT_SETPOINT_F = "HEAT_SETPOINT_F" # Temperature variables - Celsius CONTROL4_CURRENT_TEMPERATURE_C = "TEMPERATURE_C" CONTROL4_COOL_SETPOINT_C = "COOL_SETPOINT_C" CONTROL4_HEAT_SETPOINT_C = "HEAT_SETPOINT_C" CONTROL4_FAN_MODE = "FAN_MODE" CONTROL4_FAN_MODES_LIST = "FAN_MODES_LIST" VARIABLES_OF_INTEREST = { CONTROL4_HVAC_STATE, CONTROL4_HVAC_MODE, CONTROL4_HUMIDITY, CONTROL4_CURRENT_TEMPERATURE_F, CONTROL4_CURRENT_TEMPERATURE_C, CONTROL4_COOL_SETPOINT_F, CONTROL4_HEAT_SETPOINT_F, CONTROL4_COOL_SETPOINT_C, CONTROL4_HEAT_SETPOINT_C, CONTROL4_SCALE, CONTROL4_FAN_MODE, CONTROL4_FAN_MODES_LIST, } # Map Control4 HVAC modes to Home Assistant C4_TO_HA_HVAC_MODE = { "Off": HVACMode.OFF, "Cool": HVACMode.COOL, "Heat": HVACMode.HEAT, "Auto": HVACMode.HEAT_COOL, } HA_TO_C4_HVAC_MODE = {v: k for k, v in C4_TO_HA_HVAC_MODE.items()} # Map Control4 HVAC states to Home Assistant HVAC actions C4_TO_HA_HVAC_ACTION = { "off": HVACAction.OFF, "heat": HVACAction.HEATING, "cool": HVACAction.COOLING, "idle": HVACAction.IDLE, "dry": HVACAction.DRYING, "fan": HVACAction.FAN, } async def async_setup_entry( hass: HomeAssistant, entry: Control4ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Control4 thermostats from a config entry.""" runtime_data = entry.runtime_data async def async_update_data() -> dict[int, dict[str, Any]]: """Fetch data from Control4 director for thermostats.""" try: return await update_variables_for_config_entry( hass, entry, VARIABLES_OF_INTEREST ) except C4Exception as err: raise UpdateFailed(f"Error communicating with API: {err}") from err coordinator = DataUpdateCoordinator[dict[int, dict[str, Any]]]( hass, _LOGGER, name="climate", update_method=async_update_data, update_interval=timedelta(seconds=runtime_data.scan_interval), config_entry=entry, ) # Fetch initial data so we have data when entities subscribe await coordinator.async_refresh() items_of_category = await get_items_of_category(hass, entry, CONTROL4_CATEGORY) entity_list = [] for item in items_of_category: try: if item["type"] == CONTROL4_ENTITY_TYPE: item_name = item["name"] item_id = item["id"] item_parent_id = item["parentId"] item_manufacturer = None item_device_name = None item_model = None for parent_item in items_of_category: if parent_item["id"] == item_parent_id: item_manufacturer = parent_item.get("manufacturer") item_device_name = parent_item.get("roomName") item_model = parent_item.get("model") else: continue except KeyError: _LOGGER.exception( "Unknown device properties received from Control4: %s", item, ) continue # Skip if we don't have data for this thermostat if item_id not in coordinator.data: _LOGGER.warning( "Couldn't get climate state data for %s (ID: %s), skipping setup", item_name, item_id, ) continue entity_list.append( Control4Climate( runtime_data, coordinator, item_name, item_id, item_device_name, item_manufacturer, item_model, item_parent_id, ) ) async_add_entities(entity_list) class Control4Climate(Control4Entity, ClimateEntity): """Control4 climate entity.""" _attr_has_entity_name = True _attr_translation_key = "thermostat" _attr_hvac_modes = [HVACMode.OFF, HVACMode.HEAT, HVACMode.COOL, HVACMode.HEAT_COOL] def __init__( self, runtime_data: Control4RuntimeData, coordinator: DataUpdateCoordinator[dict[int, dict[str, Any]]], name: str, idx: int, device_name: str | None, device_manufacturer: str | None, device_model: str | None, device_id: int, ) -> None: """Initialize Control4 climate entity.""" super().__init__( runtime_data, coordinator, name, idx, device_name, device_manufacturer, device_model, device_id, ) @property def available(self) -> bool: """Return if entity is available.""" return super().available and self._thermostat_data is not None def _create_api_object(self) -> C4Climate: """Create a pyControl4 device object. This exists so the director token used is always the latest one, without needing to re-init the entire entity. """ return C4Climate(self.runtime_data.director, self._idx) @property def _thermostat_data(self) -> dict[str, Any] | None: """Return the thermostat data from the coordinator.""" return self.coordinator.data.get(self._idx) @property def supported_features(self) -> ClimateEntityFeature: """Return the list of supported features.""" features = ( ClimateEntityFeature.TARGET_TEMPERATURE | ClimateEntityFeature.TARGET_TEMPERATURE_RANGE | ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF ) if self.fan_modes: features |= ClimateEntityFeature.FAN_MODE return features @property def temperature_unit(self) -> str: """Return the temperature unit based on the thermostat's SCALE setting.""" data = self._thermostat_data if data is None: return UnitOfTemperature.CELSIUS # Default per HA conventions if data.get(CONTROL4_SCALE) == "FAHRENHEIT": return UnitOfTemperature.FAHRENHEIT return UnitOfTemperature.CELSIUS @property def _cool_setpoint(self) -> float | None: """Return the cooling setpoint from the appropriate variable.""" data = self._thermostat_data if data is None: return None if self.temperature_unit == UnitOfTemperature.CELSIUS: return data.get(CONTROL4_COOL_SETPOINT_C) return data.get(CONTROL4_COOL_SETPOINT_F) @property def _heat_setpoint(self) -> float | None: """Return the heating setpoint from the appropriate variable.""" data = self._thermostat_data if data is None: return None if self.temperature_unit == UnitOfTemperature.CELSIUS: return data.get(CONTROL4_HEAT_SETPOINT_C) return data.get(CONTROL4_HEAT_SETPOINT_F) @property def current_temperature(self) -> float | None: """Return the current temperature.""" data = self._thermostat_data if data is None: return None if self.temperature_unit == UnitOfTemperature.CELSIUS: return data.get(CONTROL4_CURRENT_TEMPERATURE_C) return data.get(CONTROL4_CURRENT_TEMPERATURE_F) @property def current_humidity(self) -> int | None: """Return the current humidity.""" data = self._thermostat_data if data is None: return None humidity = data.get(CONTROL4_HUMIDITY) return int(humidity) if humidity is not None else None @property def hvac_mode(self) -> HVACMode: """Return current HVAC mode.""" data = self._thermostat_data if data is None: return HVACMode.OFF c4_mode = data.get(CONTROL4_HVAC_MODE) or "" return C4_TO_HA_HVAC_MODE.get(c4_mode, HVACMode.OFF) @property def hvac_action(self) -> HVACAction | None: """Return current HVAC action.""" data = self._thermostat_data if data is None: return None c4_state = data.get(CONTROL4_HVAC_STATE) if c4_state is None: return None action = C4_TO_HA_HVAC_ACTION.get(str(c4_state).lower()) # Substring match for multi-stage systems that report # e.g. "Stage 1 Heat", "Stage 2 Cool" if action is None: if "heat" in str(c4_state).lower(): action = HVACAction.HEATING elif "cool" in str(c4_state).lower(): action = HVACAction.COOLING if action is None: _LOGGER.debug("Unknown HVAC state received from Control4: %s", c4_state) return action @property def target_temperature(self) -> float | None: """Return the target temperature.""" hvac_mode = self.hvac_mode if hvac_mode == HVACMode.COOL: return self._cool_setpoint if hvac_mode == HVACMode.HEAT: return self._heat_setpoint return None @property def target_temperature_high(self) -> float | None: """Return the high target temperature for auto mode.""" if self.hvac_mode == HVACMode.HEAT_COOL: return self._cool_setpoint return None @property def target_temperature_low(self) -> float | None: """Return the low target temperature for auto mode.""" if self.hvac_mode == HVACMode.HEAT_COOL: return self._heat_setpoint return None @property def fan_mode(self) -> str | None: """Return the current fan mode.""" data = self._thermostat_data if data is None: return None c4_fan_mode = data.get(CONTROL4_FAN_MODE) if c4_fan_mode is None: return None return c4_fan_mode.lower() @property def fan_modes(self) -> list[str] | None: """Return the list of available fan modes.""" data = self._thermostat_data if data is None: return None modes = data.get(CONTROL4_FAN_MODES_LIST) if not modes: return None return [m.strip().lower() for m in modes.split(",") if m.strip()] async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target HVAC mode.""" c4_hvac_mode = HA_TO_C4_HVAC_MODE[hvac_mode] c4_climate = self._create_api_object() await c4_climate.setHvacMode(c4_hvac_mode) await self.coordinator.async_request_refresh() async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" c4_climate = self._create_api_object() low_temp = kwargs.get(ATTR_TARGET_TEMP_LOW) high_temp = kwargs.get(ATTR_TARGET_TEMP_HIGH) temp = kwargs.get(ATTR_TEMPERATURE) # Handle temperature range for auto mode if self.hvac_mode == HVACMode.HEAT_COOL: if low_temp is not None: if self.temperature_unit == UnitOfTemperature.CELSIUS: await c4_climate.setHeatSetpointC(low_temp) else: await c4_climate.setHeatSetpointF(low_temp) if high_temp is not None: if self.temperature_unit == UnitOfTemperature.CELSIUS: await c4_climate.setCoolSetpointC(high_temp) else: await c4_climate.setCoolSetpointF(high_temp) # Handle single temperature setpoint elif temp is not None: if self.hvac_mode == HVACMode.COOL: if self.temperature_unit == UnitOfTemperature.CELSIUS: await c4_climate.setCoolSetpointC(temp) else: await c4_climate.setCoolSetpointF(temp) elif self.hvac_mode == HVACMode.HEAT: if self.temperature_unit == UnitOfTemperature.CELSIUS: await c4_climate.setHeatSetpointC(temp) else: await c4_climate.setHeatSetpointF(temp) await self.coordinator.async_request_refresh() async def async_set_fan_mode(self, fan_mode: str) -> None: """Set new target fan mode.""" c4_climate = self._create_api_object() await c4_climate.setFanMode(fan_mode.title()) await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/control4/climate.py", "license": "Apache License 2.0", "lines": 348, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/elevenlabs/stt.py
"""Support for the ElevenLabs speech-to-text service.""" from __future__ import annotations from collections.abc import AsyncIterable from io import BytesIO import logging from typing import Any from elevenlabs import AsyncElevenLabs from elevenlabs.core import ApiError from elevenlabs.types import Model from homeassistant.components import stt from homeassistant.components.stt import ( AudioBitRates, AudioChannels, AudioCodecs, AudioFormats, AudioSampleRates, SpeechMetadata, SpeechResultState, SpeechToTextEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import ElevenLabsConfigEntry from .const import ( CONF_STT_AUTO_LANGUAGE, DEFAULT_STT_AUTO_LANGUAGE, DOMAIN, STT_LANGUAGES, ) _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 10 async def async_setup_entry( hass: HomeAssistant, config_entry: ElevenLabsConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up ElevenLabs stt platform via config entry.""" client = config_entry.runtime_data.client auto_detect = config_entry.options.get( CONF_STT_AUTO_LANGUAGE, DEFAULT_STT_AUTO_LANGUAGE ) async_add_entities( [ ElevenLabsSTTEntity( client, config_entry.runtime_data.model, config_entry.runtime_data.stt_model, config_entry.entry_id, auto_detect_language=auto_detect, ) ] ) class ElevenLabsSTTEntity(SpeechToTextEntity): """The ElevenLabs STT API entity.""" _attr_has_entity_name = True _attr_translation_key = "elevenlabs_stt" def __init__( self, client: AsyncElevenLabs, model: Model, stt_model: str, entry_id: str, auto_detect_language: bool = False, ) -> None: """Init ElevenLabs TTS service.""" self._client = client self._auto_detect_language = auto_detect_language self._stt_model = stt_model # Entity attributes self._attr_unique_id = entry_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, entry_id)}, manufacturer="ElevenLabs", model=model.name, name="ElevenLabs", entry_type=DeviceEntryType.SERVICE, ) @property def supported_languages(self) -> list[str]: """Return a list of supported languages.""" return STT_LANGUAGES @property def supported_formats(self) -> list[AudioFormats]: """Return a list of supported formats.""" return [AudioFormats.WAV, AudioFormats.OGG] @property def supported_codecs(self) -> list[AudioCodecs]: """Return a list of supported codecs.""" return [AudioCodecs.PCM, AudioCodecs.OPUS] @property def supported_bit_rates(self) -> list[AudioBitRates]: """Return a list of supported bit rates.""" return [AudioBitRates.BITRATE_16] @property def supported_sample_rates(self) -> list[AudioSampleRates]: """Return a list of supported sample rates.""" return [AudioSampleRates.SAMPLERATE_16000] @property def supported_channels(self) -> list[AudioChannels]: """Return a list of supported channels.""" return [ AudioChannels.CHANNEL_MONO, AudioChannels.CHANNEL_STEREO, ] async def async_process_audio_stream( self, metadata: SpeechMetadata, stream: AsyncIterable[bytes] ) -> stt.SpeechResult: """Process an audio stream to STT service.""" _LOGGER.debug( "Processing audio stream for STT: model=%s, language=%s, format=%s, codec=%s, sample_rate=%s, channels=%s, bit_rate=%s", self._stt_model, metadata.language, metadata.format, metadata.codec, metadata.sample_rate, metadata.channel, metadata.bit_rate, ) if self._auto_detect_language: lang_code = None else: language = metadata.language if language.lower() not in [lang.lower() for lang in STT_LANGUAGES]: _LOGGER.warning("Unsupported language: %s", language) return stt.SpeechResult(None, SpeechResultState.ERROR) lang_code = language.split("-")[0] raw_pcm_compatible = ( metadata.codec == AudioCodecs.PCM and metadata.sample_rate == AudioSampleRates.SAMPLERATE_16000 and metadata.channel == AudioChannels.CHANNEL_MONO and metadata.bit_rate == AudioBitRates.BITRATE_16 ) if raw_pcm_compatible: file_format = "pcm_s16le_16" elif metadata.codec == AudioCodecs.PCM: _LOGGER.warning("PCM input does not meet expected raw format requirements") return stt.SpeechResult(None, SpeechResultState.ERROR) else: file_format = "other" audio = b"" async for chunk in stream: audio += chunk _LOGGER.debug("Finished reading audio stream, total size: %d bytes", len(audio)) if not audio: _LOGGER.warning("No audio received in stream") return stt.SpeechResult(None, SpeechResultState.ERROR) lang_display = lang_code or "auto-detected" _LOGGER.debug( "Transcribing audio (%s), format: %s, size: %d bytes", lang_display, file_format, len(audio), ) try: kwargs: dict[str, Any] = { "file": BytesIO(audio), "file_format": file_format, "model_id": self._stt_model, "tag_audio_events": False, "num_speakers": 1, "diarize": False, } if lang_code is not None: kwargs["language_code"] = lang_code response = await self._client.speech_to_text.convert(**kwargs) except ApiError as exc: _LOGGER.error("Error during processing of STT request: %s", exc) return stt.SpeechResult(None, SpeechResultState.ERROR) text = response.text or "" detected_lang_code = response.language_code or "?" detected_lang_prob = response.language_probability or "?" _LOGGER.debug( "Transcribed text is in language %s (probability %s): %s", detected_lang_code, detected_lang_prob, text, ) return stt.SpeechResult(text, SpeechResultState.SUCCESS)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/elevenlabs/stt.py", "license": "Apache License 2.0", "lines": 179, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fing/config_flow.py
"""Config flow file.""" from contextlib import suppress import logging from typing import Any from fing_agent_api import FingAgent import httpx import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_KEY, CONF_IP_ADDRESS, CONF_PORT from .const import DOMAIN, UPNP_AVAILABLE _LOGGER = logging.getLogger(__name__) class FingConfigFlow(ConfigFlow, domain=DOMAIN): """Fing config flow.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Set up user step.""" errors: dict[str, str] = {} description_placeholders: dict[str, str] = {} if user_input is not None: devices_response = None agent_info_response = None self._async_abort_entries_match( {CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS]} ) fing_api = FingAgent( ip=user_input[CONF_IP_ADDRESS], port=int(user_input[CONF_PORT]), key=user_input[CONF_API_KEY], ) try: devices_response = await fing_api.get_devices() with suppress(httpx.ConnectError): # The suppression is needed because the get_agent_info method isn't available for desktop agents agent_info_response = await fing_api.get_agent_info() except httpx.NetworkError as _: errors["base"] = "cannot_connect" except httpx.TimeoutException as _: errors["base"] = "timeout_connect" except httpx.HTTPStatusError as exception: description_placeholders["message"] = ( f"{exception.response.status_code} - {exception.response.reason_phrase}" ) if exception.response.status_code == 401: errors["base"] = "invalid_api_key" else: errors["base"] = "http_status_error" except httpx.InvalidURL as _: errors["base"] = "url_error" except ( httpx.HTTPError, httpx.CookieConflict, httpx.StreamError, ) as ex: _LOGGER.error("Unexpected exception: %s", ex) errors["base"] = "unknown" else: if ( devices_response.network_id is not None and len(devices_response.network_id) > 0 ): agent_name = user_input.get(CONF_IP_ADDRESS) upnp_available = False if agent_info_response is not None: upnp_available = True agent_name = agent_info_response.agent_id await self.async_set_unique_id(agent_info_response.agent_id) self._abort_if_unique_id_configured() data = { CONF_IP_ADDRESS: user_input[CONF_IP_ADDRESS], CONF_PORT: user_input[CONF_PORT], CONF_API_KEY: user_input[CONF_API_KEY], UPNP_AVAILABLE: upnp_available, } return self.async_create_entry( title=f"Fing Agent {agent_name}", data=data, ) return self.async_abort(reason="api_version_error") return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( vol.Schema( { vol.Required(CONF_IP_ADDRESS): str, vol.Required(CONF_PORT, default="49090"): str, vol.Required(CONF_API_KEY): str, } ), user_input, ), errors=errors, description_placeholders=description_placeholders, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fing/config_flow.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fing/coordinator.py
"""DataUpdateCoordinator for Fing integration.""" from dataclasses import dataclass, field from datetime import timedelta import logging from fing_agent_api import FingAgent from fing_agent_api.models import AgentInfoResponse, Device import httpx from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_IP_ADDRESS, CONF_PORT from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, UPNP_AVAILABLE _LOGGER = logging.getLogger(__name__) type FingConfigEntry = ConfigEntry[FingDataUpdateCoordinator] @dataclass class FingDataObject: """Fing Data Object.""" network_id: str | None = None agent_info: AgentInfoResponse | None = None devices: dict[str, Device] = field(default_factory=dict) class FingDataUpdateCoordinator(DataUpdateCoordinator[FingDataObject]): """Class to manage fetching data from Fing Agent.""" def __init__(self, hass: HomeAssistant, config_entry: FingConfigEntry) -> None: """Initialize global Fing updater.""" self._fing = FingAgent( ip=config_entry.data[CONF_IP_ADDRESS], port=int(config_entry.data[CONF_PORT]), key=config_entry.data[CONF_API_KEY], ) self._upnp_available = config_entry.data[UPNP_AVAILABLE] update_interval = timedelta(seconds=30) super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=update_interval, config_entry=config_entry, ) async def _async_update_data(self) -> FingDataObject: """Fetch data from Fing Agent.""" device_response = None agent_info_response = None try: device_response = await self._fing.get_devices() if self._upnp_available: agent_info_response = await self._fing.get_agent_info() except httpx.NetworkError as err: raise UpdateFailed("Failed to connect") from err except httpx.TimeoutException as err: raise UpdateFailed("Timeout establishing connection") from err except httpx.HTTPStatusError as err: if err.response.status_code == 401: raise UpdateFailed("Invalid API key") from err raise UpdateFailed( f"Http request failed -> {err.response.status_code} - {err.response.reason_phrase}" ) from err except httpx.InvalidURL as err: raise UpdateFailed("Invalid hostname or IP address") from err except ( httpx.HTTPError, httpx.CookieConflict, httpx.StreamError, ) as err: raise UpdateFailed("Unexpected error from HTTP request") from err else: return FingDataObject( device_response.network_id, agent_info_response, {device.mac: device for device in device_response.devices}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fing/coordinator.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fing/device_tracker.py
"""Platform for Device tracker integration.""" from fing_agent_api.models import Device from homeassistant.components.device_tracker import ScannerEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import FingConfigEntry from .coordinator import FingDataUpdateCoordinator from .utils import get_icon_from_type async def async_setup_entry( hass: HomeAssistant, config_entry: FingConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Add sensors for passed config_entry in HA.""" coordinator = config_entry.runtime_data entity_registry = er.async_get(hass) tracked_devices: set[str] = set() @callback def add_entities() -> None: latest_devices = set(coordinator.data.devices.keys()) devices_to_remove = tracked_devices - set(latest_devices) devices_to_add = set(latest_devices) - tracked_devices entities_to_remove = [] for entity_entry in entity_registry.entities.values(): if entity_entry.config_entry_id != config_entry.entry_id: continue try: _, mac = entity_entry.unique_id.rsplit("-", 1) if mac in devices_to_remove: entities_to_remove.append(entity_entry.entity_id) except ValueError: continue for entity_id in entities_to_remove: entity_registry.async_remove(entity_id) entities_to_add = [] for mac_addr in devices_to_add: device = coordinator.data.devices[mac_addr] entities_to_add.append(FingTrackedDevice(coordinator, device)) tracked_devices.clear() tracked_devices.update(latest_devices) async_add_entities(entities_to_add) add_entities() config_entry.async_on_unload(coordinator.async_add_listener(add_entities)) class FingTrackedDevice(CoordinatorEntity[FingDataUpdateCoordinator], ScannerEntity): """Represent a tracked device.""" _attr_has_entity_name = True def __init__(self, coordinator: FingDataUpdateCoordinator, device: Device) -> None: """Set up FingDevice entity.""" super().__init__(coordinator) self._device = device agent_id = coordinator.data.network_id if coordinator.data.agent_info is not None: agent_id = coordinator.data.agent_info.agent_id self._attr_mac_address = self._device.mac self._attr_unique_id = f"{agent_id}-{self._attr_mac_address}" self._attr_name = self._device.name self._attr_icon = get_icon_from_type(self._device.type) @property def is_connected(self) -> bool: """Return true if the device is connected to the network.""" return self._device.active @property def ip_address(self) -> str | None: """Return the primary ip address of the device.""" return self._device.ip[0] if self._device.ip else None @property def entity_registry_enabled_default(self) -> bool: """Enable entity by default.""" return True @property def unique_id(self) -> str | None: """Return the unique ID of the entity.""" return self._attr_unique_id def check_for_updates(self, new_device: Device) -> bool: """Return true if the device has updates.""" new_device_ip = new_device.ip[0] if new_device.ip else None current_device_ip = self._device.ip[0] if self._device.ip else None return ( current_device_ip != new_device_ip or self._device.active != new_device.active or self._device.type != new_device.type or self._attr_name != new_device.name or self._attr_icon != get_icon_from_type(new_device.type) ) @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" updated_device_data = self.coordinator.data.devices.get(self._device.mac) if updated_device_data is not None and self.check_for_updates( updated_device_data ): self._device = updated_device_data self._attr_name = updated_device_data.name self._attr_icon = get_icon_from_type(updated_device_data.type) er.async_get(self.hass).async_update_entity( entity_id=self.entity_id, original_name=self._attr_name, original_icon=self._attr_icon, ) self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fing/device_tracker.py", "license": "Apache License 2.0", "lines": 102, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/fing/utils.py
"""Utils functions.""" from enum import Enum class DeviceType(Enum): """Device types enum.""" GENERIC = "mdi:lan-connect" MOBILE = PHONE = "mdi:cellphone" TABLET = IPOD = EREADER = "mdi:tablet" WATCH = WEARABLE = "mdi:watch" CAR = AUTOMOTIVE = "mdi:car-back" MEDIA_PLAYER = "mdi:volume-high" TELEVISION = "mdi:television" GAME_CONSOLE = "mdi:nintendo-game-boy" STREAMING_DONGLE = "mdi:cast" LOUDSPEAKER = SOUND_SYSTEM = STB = SATELLITE = MUSIC = "mdi:speaker" DISC_PLAYER = "mdi:disk-player" REMOTE_CONTROL = "mdi:remote-tv" RADIO = "mdi:radio" PHOTO_CAMERA = PHOTOS = "mdi:camera" MICROPHONE = VOICE_CONTROL = "mdi:microphone" PROJECTOR = "mdi:projector" COMPUTER = DESKTOP = "mdi:desktop-tower" LAPTOP = "mdi:laptop" PRINTER = "mdi:printer" SCANNER = "mdi:scanner" POS = "mdi:printer-pos" CLOCK = "mdi:clock" BARCODE = "mdi:barcode" SURVEILLANCE_CAMERA = BABY_MONITOR = PET_MONITOR = "mdi:cctv" POE_PLUG = HEALTH_MONITOR = SMART_HOME = SMART_METER = APPLIANCE = SLEEP = ( "mdi:home-automation" ) SMART_PLUG = "mdi:power-plug" LIGHT = "mdi:lightbulb" THERMOSTAT = HEATING = "mdi:home-thermometer" POWER_SYSTEM = ENERGY = "mdi:lightning-bolt" SOLAR_PANEL = "mdi:solar-power" WASHER = "mdi:washing-machine" FRIDGE = "mdi:fridge" CLEANER = "mdi:vacuum" GARAGE = "mdi:garage" SPRINKLER = "mdi:sprinkler" BELL = "mdi:doorbell" KEY_LOCK = "mdi:lock-smart" CONTROL_PANEL = SMART_CONTROLLER = "mdi:alarm-panel" SCALE = "mdi:scale-bathroom" TOY = "mdi:teddy-bear" ROBOT = "mdi:robot" WEATHER = "mdi:weather-cloudy" ALARM = "mdi:alarm-light" MOTION_DETECTOR = "mdi:motion-sensor" SMOKE = HUMIDITY = SENSOR = DOMOTZ_BOX = FINGBOX = "mdi:smoke-detector" ROUTER = MODEM = GATEWAY = FIREWALL = VPN = SMALL_CELL = "mdi:router-network" WIFI = WIFI_EXTENDER = "mdi:wifi" NAS_STORAGE = "mdi:nas" SWITCH = "mdi:switch" USB = "mdi:usb" CLOUD = "mdi:cloud" BATTERY = "mdi:battery" NETWORK_APPLIANCE = "mdi:network" VIRTUAL_MACHINE = MAIL_SERVER = FILE_SERVER = PROXY_SERVER = WEB_SERVER = ( DOMAIN_SERVER ) = COMMUNICATION = "mdi:monitor" SERVER = "mdi:server" TERMINAL = "mdi:console" DATABASE = "mdi:database" RASPBERRY = ARDUINO = "mdi:raspberry-pi" PROCESSOR = CIRCUIT_CARD = RFID = "mdi:chip" INDUSTRIAL = "mdi:factory" MEDICAL = "mdi:medical-bag" VOIP = CONFERENCING = "mdi:phone-voip" FITNESS = "mdi:dumbbell" POOL = "mdi:pool" SECURITY_SYSTEM = "mdi:security" def get_icon_from_type(type: str) -> str: """Return the right icon based on the type.""" try: return DeviceType[type].value except ValueError, KeyError: return "mdi:lan-connect"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fing/utils.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/firefly_iii/config_flow.py
"""Config flow for the Firefly III integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from pyfirefly import ( Firefly, FireflyAuthenticationError, FireflyConnectionError, FireflyTimeoutError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_URL): str, vol.Optional(CONF_VERIFY_SSL, default=True): bool, vol.Required(CONF_API_KEY): str, } ) async def _validate_input(hass: HomeAssistant, data: dict[str, Any]) -> bool: """Validate the user input allows us to connect.""" try: client = Firefly( api_url=data[CONF_URL], api_key=data[CONF_API_KEY], session=async_get_clientsession( hass=hass, verify_ssl=data[CONF_VERIFY_SSL] ), ) await client.get_about() except FireflyAuthenticationError: raise InvalidAuth from None except FireflyConnectionError as err: raise CannotConnect from err except FireflyTimeoutError as err: raise FireflyClientTimeout from err return True class FireflyConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Firefly III.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: self._async_abort_entries_match({CONF_URL: user_input[CONF_URL]}) try: await _validate_input(self.hass, user_input) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except FireflyClientTimeout: errors["base"] = "timeout_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_create_entry( title=user_input[CONF_URL], data=user_input ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauth when Firefly III API authentication fails.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauth: ask for a new API key and validate.""" errors: dict[str, str] = {} reauth_entry = self._get_reauth_entry() if user_input is not None: try: await _validate_input( self.hass, data={ **reauth_entry.data, CONF_API_KEY: user_input[CONF_API_KEY], }, ) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except FireflyClientTimeout: errors["base"] = "timeout_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_update_reload_and_abort( reauth_entry, data_updates={CONF_API_KEY: user_input[CONF_API_KEY]}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema({vol.Required(CONF_API_KEY): str}), 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] = {} reconf_entry = self._get_reconfigure_entry() if user_input: try: await _validate_input( self.hass, data={ **reconf_entry.data, **user_input, }, ) except CannotConnect: errors["base"] = "cannot_connect" except InvalidAuth: errors["base"] = "invalid_auth" except FireflyClientTimeout: errors["base"] = "timeout_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: self._async_abort_entries_match({CONF_URL: user_input[CONF_URL]}) return self.async_update_reload_and_abort( reconf_entry, data_updates={ CONF_URL: user_input[CONF_URL], CONF_API_KEY: user_input[CONF_API_KEY], CONF_VERIFY_SSL: user_input[CONF_VERIFY_SSL], }, ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input or reconf_entry.data.copy(), ), errors=errors, ) class CannotConnect(HomeAssistantError): """Error to indicate we cannot connect.""" class InvalidAuth(HomeAssistantError): """Error to indicate there is invalid auth.""" class FireflyClientTimeout(HomeAssistantError): """Error to indicate a timeout occurred."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/firefly_iii/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/firefly_iii/coordinator.py
"""Data Update Coordinator for Firefly III integration.""" from __future__ import annotations import asyncio from dataclasses import dataclass from datetime import datetime, timedelta import logging from aiohttp import CookieJar from pyfirefly import ( Firefly, FireflyAuthenticationError, FireflyConnectionError, FireflyTimeoutError, ) from pyfirefly.models import Account, Bill, Budget, Category, Currency from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_API_KEY, CONF_URL, CONF_VERIFY_SSL from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) type FireflyConfigEntry = ConfigEntry[FireflyDataUpdateCoordinator] DEFAULT_SCAN_INTERVAL = timedelta(minutes=5) @dataclass class FireflyCoordinatorData: """Data structure for Firefly III coordinator data.""" accounts: list[Account] categories: list[Category] category_details: list[Category] budgets: list[Budget] bills: list[Bill] primary_currency: Currency class FireflyDataUpdateCoordinator(DataUpdateCoordinator[FireflyCoordinatorData]): """Coordinator to manage data updates for Firefly III integration.""" config_entry: FireflyConfigEntry def __init__(self, hass: HomeAssistant, config_entry: FireflyConfigEntry) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL, ) self.firefly = Firefly( api_url=self.config_entry.data[CONF_URL], api_key=self.config_entry.data[CONF_API_KEY], session=async_create_clientsession( self.hass, self.config_entry.data[CONF_VERIFY_SSL], cookie_jar=CookieJar(unsafe=True), ), ) async def _async_setup(self) -> None: """Set up the coordinator.""" try: await self.firefly.get_about() except FireflyAuthenticationError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", translation_placeholders={"error": repr(err)}, ) from err except FireflyConnectionError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"error": repr(err)}, ) from err except FireflyTimeoutError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="timeout_connect", translation_placeholders={"error": repr(err)}, ) from err async def _async_update_data(self) -> FireflyCoordinatorData: """Fetch data from Firefly III API.""" now = datetime.now() start_date = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) end_date = now try: ( accounts, categories, primary_currency, budgets, bills, ) = await asyncio.gather( self.firefly.get_accounts(), self.firefly.get_categories(), self.firefly.get_currency_primary(), self.firefly.get_budgets(start=start_date, end=end_date), self.firefly.get_bills(), ) category_details = await asyncio.gather( *( self.firefly.get_category( category_id=int(category.id), start=start_date, end=end_date, ) for category in categories ) ) except FireflyAuthenticationError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", translation_placeholders={"error": repr(err)}, ) from err except FireflyConnectionError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"error": repr(err)}, ) from err except FireflyTimeoutError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="timeout_connect", translation_placeholders={"error": repr(err)}, ) from err return FireflyCoordinatorData( accounts=accounts, categories=categories, category_details=category_details, budgets=budgets, bills=bills, primary_currency=primary_currency, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/firefly_iii/coordinator.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/firefly_iii/diagnostics.py
"""Diagnostics for the Firefly III integration.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_API_KEY, CONF_URL from homeassistant.core import HomeAssistant from . import FireflyConfigEntry from .coordinator import FireflyDataUpdateCoordinator TO_REDACT = [CONF_API_KEY, CONF_URL] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: FireflyConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator: FireflyDataUpdateCoordinator = entry.runtime_data return { "config_entry": async_redact_data(entry.as_dict(), TO_REDACT), "data": {"primary_currency": coordinator.data.primary_currency.to_dict()}, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/firefly_iii/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/firefly_iii/entity.py
"""Base entity for Firefly III integration.""" from __future__ import annotations from pyfirefly.models import Account, Budget, Category from yarl import URL from homeassistant.const import CONF_URL from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER, NAME from .coordinator import FireflyDataUpdateCoordinator class FireflyBaseEntity(CoordinatorEntity[FireflyDataUpdateCoordinator]): """Base class for Firefly III entity.""" _attr_has_entity_name = True def __init__( self, coordinator: FireflyDataUpdateCoordinator, ) -> None: """Initialize a Firefly entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, manufacturer=MANUFACTURER, name=NAME, configuration_url=URL(coordinator.config_entry.data[CONF_URL]), identifiers={(DOMAIN, f"{coordinator.config_entry.entry_id}_service")}, ) class FireflyAccountBaseEntity(FireflyBaseEntity): """Base class for Firefly III account entity.""" def __init__( self, coordinator: FireflyDataUpdateCoordinator, account: Account, key: str, ) -> None: """Initialize a Firefly account entity.""" super().__init__(coordinator) self._account = account self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, manufacturer=MANUFACTURER, name=account.attributes.name, configuration_url=f"{URL(coordinator.config_entry.data[CONF_URL])}/accounts/show/{account.id}", identifiers={ (DOMAIN, f"{coordinator.config_entry.entry_id}_account_{account.id}") }, ) self._attr_unique_id = ( f"{coordinator.config_entry.unique_id}_account_{account.id}_{key}" ) class FireflyCategoryBaseEntity(FireflyBaseEntity): """Base class for Firefly III category entity.""" def __init__( self, coordinator: FireflyDataUpdateCoordinator, category: Category, key: str, ) -> None: """Initialize a Firefly category entity.""" super().__init__(coordinator) self._category = category self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, manufacturer=MANUFACTURER, name=category.attributes.name, configuration_url=f"{URL(coordinator.config_entry.data[CONF_URL])}/categories/show/{category.id}", identifiers={ (DOMAIN, f"{coordinator.config_entry.entry_id}_category_{category.id}") }, ) self._attr_unique_id = ( f"{coordinator.config_entry.unique_id}_category_{category.id}_{key}" ) class FireflyBudgetBaseEntity(FireflyBaseEntity): """Base class for Firefly III budget entity.""" def __init__( self, coordinator: FireflyDataUpdateCoordinator, budget: Budget, key: str, ) -> None: """Initialize a Firefly budget entity.""" super().__init__(coordinator) self._budget = budget self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, manufacturer=MANUFACTURER, name=budget.attributes.name, configuration_url=f"{URL(coordinator.config_entry.data[CONF_URL])}/budgets/show/{budget.id}", identifiers={ (DOMAIN, f"{coordinator.config_entry.entry_id}_budget_{budget.id}") }, ) self._attr_unique_id = ( f"{coordinator.config_entry.unique_id}_budget_{budget.id}_{key}" )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/firefly_iii/entity.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/firefly_iii/sensor.py
"""Sensor platform for Firefly III integration.""" from __future__ import annotations from pyfirefly.models import Account, Budget, Category from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, StateType, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import FireflyConfigEntry, FireflyDataUpdateCoordinator from .entity import ( FireflyAccountBaseEntity, FireflyBudgetBaseEntity, FireflyCategoryBaseEntity, ) ACCOUNT_ROLE_MAPPING = { "defaultAsset": "default_asset", "sharedAsset": "shared_asset", "savingAsset": "saving_asset", "ccAsset": "cc_asset", "cashWalletAsset": "cash_wallet_asset", } ACCOUNT_TYPE_ICONS = { "expense": "mdi:cash-minus", "asset": "mdi:account-cash", "revenue": "mdi:cash-plus", "liability": "mdi:hand-coin", } ACCOUNT_BALANCE = "account_balance" ACCOUNT_ROLE = "account_role" ACCOUNT_TYPE = "account_type" CATEGORY = "category" BUDGET = "budget" async def async_setup_entry( hass: HomeAssistant, entry: FireflyConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Firefly III sensors.""" coordinator = entry.runtime_data entities: list[SensorEntity] = [] for account in coordinator.data.accounts: entities.append( FireflyAccountBalanceSensor(coordinator, account, ACCOUNT_BALANCE) ) entities.append(FireflyAccountRoleSensor(coordinator, account, ACCOUNT_ROLE)) entities.append(FireflyAccountTypeSensor(coordinator, account, ACCOUNT_TYPE)) entities.extend( [ FireflyCategorySensor(coordinator, category, CATEGORY) for category in coordinator.data.category_details ] ) entities.extend( [ FireflyBudgetSensor(coordinator, budget, BUDGET) for budget in coordinator.data.budgets ] ) async_add_entities(entities) class FireflyAccountBalanceSensor(FireflyAccountBaseEntity, SensorEntity): """Account balance sensor.""" _attr_translation_key = "account_balance" _attr_device_class = SensorDeviceClass.MONETARY _attr_state_class = SensorStateClass.TOTAL def __init__( self, coordinator: FireflyDataUpdateCoordinator, account: Account, key: str, ) -> None: """Initialize the account balance sensor.""" super().__init__(coordinator, account, key) self._account = account self._attr_native_unit_of_measurement = ( coordinator.data.primary_currency.attributes.code ) @property def native_value(self) -> StateType: """Return current account balance.""" return self._account.attributes.current_balance class FireflyAccountRoleSensor(FireflyAccountBaseEntity, SensorEntity): """Account role diagnostic sensor.""" _attr_translation_key = "account_role" _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_entity_registry_enabled_default = True def __init__( self, coordinator: FireflyDataUpdateCoordinator, account: Account, key: str, ) -> None: """Initialize the account role sensor.""" super().__init__(coordinator, account, key) self._account = account @property def native_value(self) -> StateType: """Return account role.""" # An account can be empty and then should resort to Unknown account_role: str | None = self._account.attributes.account_role if account_role is None: return None return ACCOUNT_ROLE_MAPPING.get(account_role, account_role) class FireflyAccountTypeSensor(FireflyAccountBaseEntity, SensorEntity): """Account type diagnostic sensor.""" _attr_translation_key = "account_type" _attr_entity_category = EntityCategory.DIAGNOSTIC _attr_entity_registry_enabled_default = True def __init__( self, coordinator: FireflyDataUpdateCoordinator, account: Account, key: str, ) -> None: """Initialize the account type sensor.""" super().__init__(coordinator, account, key) acc_type = account.attributes.type self._attr_icon = ( ACCOUNT_TYPE_ICONS.get(acc_type, "mdi:bank") if acc_type is not None else "mdi:bank" ) @property def native_value(self) -> StateType: """Return account type.""" return self._account.attributes.type class FireflyCategorySensor(FireflyCategoryBaseEntity, SensorEntity): """Category sensor.""" _attr_translation_key = "category" _attr_device_class = SensorDeviceClass.MONETARY _attr_state_class = SensorStateClass.TOTAL def __init__( self, coordinator: FireflyDataUpdateCoordinator, category: Category, key: str, ) -> None: """Initialize the category sensor.""" super().__init__(coordinator, category, key) self._category = category self._attr_native_unit_of_measurement = ( coordinator.data.primary_currency.attributes.code ) @property def native_value(self) -> StateType: """Return net spent+earned value for this category in the period.""" spent_items = self._category.attributes.spent or [] earned_items = self._category.attributes.earned or [] spent = sum(float(item.sum) for item in spent_items if item.sum is not None) earned = sum(float(item.sum) for item in earned_items if item.sum is not None) if spent == 0 and earned == 0: return None return spent + earned class FireflyBudgetSensor(FireflyBudgetBaseEntity, SensorEntity): """Budget sensor.""" _attr_translation_key = "budget" _attr_device_class = SensorDeviceClass.MONETARY _attr_state_class = SensorStateClass.TOTAL def __init__( self, coordinator: FireflyDataUpdateCoordinator, budget: Budget, key: str, ) -> None: """Initialize the budget sensor.""" super().__init__(coordinator, budget, key) self._budget = budget self._attr_native_unit_of_measurement = ( coordinator.data.primary_currency.attributes.code ) @property def native_value(self) -> StateType: """Return spent value for this budget in the period.""" spent_items = self._budget.attributes.spent or [] return sum(float(item.sum) for item in spent_items if item.sum is not None)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/firefly_iii/sensor.py", "license": "Apache License 2.0", "lines": 178, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/group/valve.py
"""Platform allowing several valves to be grouped into one valve.""" from __future__ import annotations from typing import Any import voluptuous as vol from homeassistant.components.valve import ( ATTR_CURRENT_POSITION, ATTR_POSITION, DOMAIN as VALVE_DOMAIN, PLATFORM_SCHEMA as VALVE_PLATFORM_SCHEMA, ValveEntity, ValveEntityFeature, ValveState, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, CONF_ENTITIES, CONF_NAME, CONF_UNIQUE_ID, SERVICE_CLOSE_VALVE, SERVICE_OPEN_VALVE, SERVICE_SET_VALVE_POSITION, SERVICE_STOP_VALVE, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, State, callback from homeassistant.helpers import config_validation as cv, entity_registry as er from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, ) from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from .entity import GroupEntity from .util import reduce_attribute KEY_OPEN_CLOSE = "open_close" KEY_STOP = "stop" KEY_SET_POSITION = "set_position" DEFAULT_NAME = "Valve Group" # No limit on parallel updates to enable a group calling another group PARALLEL_UPDATES = 0 PLATFORM_SCHEMA = VALVE_PLATFORM_SCHEMA.extend( { vol.Required(CONF_ENTITIES): cv.entities_domain(VALVE_DOMAIN), vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string, vol.Optional(CONF_UNIQUE_ID): cv.string, } ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Valve Group platform.""" async_add_entities( [ ValveGroup( config.get(CONF_UNIQUE_ID), config[CONF_NAME], config[CONF_ENTITIES] ) ] ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Initialize Valve Group config entry.""" registry = er.async_get(hass) entities = er.async_validate_entity_ids( registry, config_entry.options[CONF_ENTITIES] ) async_add_entities( [ValveGroup(config_entry.entry_id, config_entry.title, entities)] ) @callback def async_create_preview_valve( hass: HomeAssistant, name: str, validated_config: dict[str, Any] ) -> ValveGroup: """Create a preview valve.""" return ValveGroup( None, name, validated_config[CONF_ENTITIES], ) class ValveGroup(GroupEntity, ValveEntity): """Representation of a ValveGroup.""" _attr_available: bool = False _attr_current_valve_position: int | None = None _attr_is_closed: bool | None = None _attr_is_closing: bool | None = False _attr_is_opening: bool | None = False _attr_reports_position: bool = False def __init__(self, unique_id: str | None, name: str, entities: list[str]) -> None: """Initialize a ValveGroup entity.""" self._entity_ids = entities self._valves: dict[str, set[str]] = { KEY_OPEN_CLOSE: set(), KEY_STOP: set(), KEY_SET_POSITION: set(), } self._attr_name = name self._attr_extra_state_attributes = {ATTR_ENTITY_ID: entities} self._attr_unique_id = unique_id @callback def async_update_supported_features( self, entity_id: str, new_state: State | None, ) -> None: """Update dictionaries with supported features.""" if not new_state: for values in self._valves.values(): values.discard(entity_id) return features = new_state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if features & (ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE): self._valves[KEY_OPEN_CLOSE].add(entity_id) else: self._valves[KEY_OPEN_CLOSE].discard(entity_id) if features & (ValveEntityFeature.STOP): self._valves[KEY_STOP].add(entity_id) else: self._valves[KEY_STOP].discard(entity_id) if features & (ValveEntityFeature.SET_POSITION): self._valves[KEY_SET_POSITION].add(entity_id) else: self._valves[KEY_SET_POSITION].discard(entity_id) async def async_open_valve(self) -> None: """Open the valves.""" data = {ATTR_ENTITY_ID: self._valves[KEY_OPEN_CLOSE]} await self.hass.services.async_call( VALVE_DOMAIN, SERVICE_OPEN_VALVE, data, blocking=True, context=self._context ) async def async_handle_open_valve(self) -> None: # type: ignore[misc] """Open the valves. Override the base class to avoid calling the set position service for all valves. Transfer the service call to the base class and let it decide if the valve uses set position or open service. """ await self.async_open_valve() async def async_close_valve(self) -> None: """Close valves.""" data = {ATTR_ENTITY_ID: self._valves[KEY_OPEN_CLOSE]} await self.hass.services.async_call( VALVE_DOMAIN, SERVICE_CLOSE_VALVE, data, blocking=True, context=self._context, ) async def async_handle_close_valve(self) -> None: # type: ignore[misc] """Close the valves. Override the base class to avoid calling the set position service for all valves. Transfer the service call to the base class and let it decide if the valve uses set position or close service. """ await self.async_close_valve() async def async_set_valve_position(self, position: int) -> None: """Move the valves to a specific position.""" data = { ATTR_ENTITY_ID: self._valves[KEY_SET_POSITION], ATTR_POSITION: position, } await self.hass.services.async_call( VALVE_DOMAIN, SERVICE_SET_VALVE_POSITION, data, blocking=True, context=self._context, ) async def async_stop_valve(self) -> None: """Stop the valves.""" data = {ATTR_ENTITY_ID: self._valves[KEY_STOP]} await self.hass.services.async_call( VALVE_DOMAIN, SERVICE_STOP_VALVE, data, blocking=True, context=self._context ) @callback def async_update_group_state(self) -> None: """Update state and attributes.""" states = [ state for entity_id in self._entity_ids if (state := self.hass.states.get(entity_id)) is not None ] # Set group as unavailable if all members are unavailable or missing self._attr_available = any(state.state != STATE_UNAVAILABLE for state in states) self._attr_is_closed = True self._attr_is_closing = False self._attr_is_opening = False self._attr_reports_position = False self._update_assumed_state_from_members() for state in states: if state.attributes.get(ATTR_CURRENT_POSITION) is not None: self._attr_reports_position = True if state.state == ValveState.OPEN: self._attr_is_closed = False continue if state.state == ValveState.CLOSED: continue if state.state == ValveState.CLOSING: self._attr_is_closing = True continue if state.state == ValveState.OPENING: self._attr_is_opening = True continue valid_state = any( state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) for state in states ) if not valid_state: # Set as unknown if all members are unknown or unavailable self._attr_is_closed = None self._attr_current_valve_position = reduce_attribute( states, ATTR_CURRENT_POSITION ) supported_features = ValveEntityFeature(0) if self._valves[KEY_OPEN_CLOSE]: supported_features |= ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE if self._valves[KEY_STOP]: supported_features |= ValveEntityFeature.STOP if self._valves[KEY_SET_POSITION]: supported_features |= ValveEntityFeature.SET_POSITION self._attr_supported_features = supported_features
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/group/valve.py", "license": "Apache License 2.0", "lines": 224, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/growatt_server/number.py
"""Number platform for Growatt.""" from __future__ import annotations from dataclasses import dataclass import logging from growattServer import GrowattV1ApiError from homeassistant.components.number import NumberEntity, NumberEntityDescription from homeassistant.const import PERCENTAGE, EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError 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 from .coordinator import GrowattConfigEntry, GrowattCoordinator from .sensor.sensor_entity_description import GrowattRequiredKeysMixin _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = ( 1 # Serialize updates as inverter does not handle concurrent requests ) @dataclass(frozen=True, kw_only=True) class GrowattNumberEntityDescription(NumberEntityDescription, GrowattRequiredKeysMixin): """Describes Growatt number entity.""" write_key: str | None = None # Parameter ID for writing (if different from api_key) # Note that the Growatt V1 API uses different keys for reading and writing parameters. # Reading values returns camelCase keys, while writing requires snake_case keys. MIN_NUMBER_TYPES: tuple[GrowattNumberEntityDescription, ...] = ( GrowattNumberEntityDescription( key="battery_charge_power_limit", translation_key="battery_charge_power_limit", api_key="chargePowerCommand", # Key returned by V1 API write_key="charge_power", # Key used to write parameter native_step=1, native_min_value=0, native_max_value=100, native_unit_of_measurement=PERCENTAGE, ), GrowattNumberEntityDescription( key="battery_charge_soc_limit", translation_key="battery_charge_soc_limit", api_key="wchargeSOCLowLimit", # Key returned by V1 API write_key="charge_stop_soc", # Key used to write parameter native_step=1, native_min_value=0, native_max_value=100, native_unit_of_measurement=PERCENTAGE, ), GrowattNumberEntityDescription( key="battery_discharge_power_limit", translation_key="battery_discharge_power_limit", api_key="disChargePowerCommand", # Key returned by V1 API write_key="discharge_power", # Key used to write parameter native_step=1, native_min_value=0, native_max_value=100, native_unit_of_measurement=PERCENTAGE, ), GrowattNumberEntityDescription( key="battery_discharge_soc_limit", # Keep original key to preserve unique_id translation_key="battery_discharge_soc_limit_off_grid", api_key="wdisChargeSOCLowLimit", # Key returned by V1 API (off-grid) write_key="discharge_stop_soc", # Key used to write parameter native_step=1, native_min_value=0, native_max_value=100, native_unit_of_measurement=PERCENTAGE, ), GrowattNumberEntityDescription( key="battery_discharge_soc_limit_on_grid", translation_key="battery_discharge_soc_limit_on_grid", api_key="onGridDischargeStopSOC", # Key returned by V1 API (on-grid) write_key="on_grid_discharge_stop_soc", # Key used to write parameter native_step=1, native_min_value=0, native_max_value=100, native_unit_of_measurement=PERCENTAGE, ), ) async def async_setup_entry( hass: HomeAssistant, entry: GrowattConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Growatt number entities.""" runtime_data = entry.runtime_data # Add number entities for each MIN device (only supported with V1 API) async_add_entities( GrowattNumber(device_coordinator, description) for device_coordinator in runtime_data.devices.values() if ( device_coordinator.device_type == "min" and device_coordinator.api_version == "v1" ) for description in MIN_NUMBER_TYPES ) class GrowattNumber(CoordinatorEntity[GrowattCoordinator], NumberEntity): """Representation of a Growatt number.""" _attr_has_entity_name = True _attr_entity_category = EntityCategory.CONFIG entity_description: GrowattNumberEntityDescription def __init__( self, coordinator: GrowattCoordinator, description: GrowattNumberEntityDescription, ) -> None: """Initialize the number.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.device_id}_{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.device_id)}, manufacturer="Growatt", name=coordinator.device_id, ) @property def native_value(self) -> int | None: """Return the current value of the number.""" value = self.coordinator.data.get(self.entity_description.api_key) if value is None: return None return int(value) async def async_set_native_value(self, value: float) -> None: """Set the value of the number.""" # Use write_key if specified, otherwise fall back to api_key parameter_id = ( self.entity_description.write_key or self.entity_description.api_key ) int_value = int(value) try: # Use V1 API to write parameter await self.hass.async_add_executor_job( self.coordinator.api.min_write_parameter, self.coordinator.device_id, parameter_id, int_value, ) except GrowattV1ApiError as e: raise HomeAssistantError(f"Error while setting parameter: {e}") from e # If no exception was raised, the write was successful _LOGGER.debug( "Set parameter %s to %s", parameter_id, value, ) # Update the value in coordinator data to avoid triggering an immediate # refresh that would hit the API rate limit (5-minute polling interval) self.coordinator.data[self.entity_description.api_key] = int_value self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/growatt_server/number.py", "license": "Apache License 2.0", "lines": 147, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/growatt_server/switch.py
"""Switch platform for Growatt.""" from __future__ import annotations from dataclasses import dataclass import logging from typing import Any from growattServer import GrowattV1ApiError from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError 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 from .coordinator import GrowattConfigEntry, GrowattCoordinator from .sensor.sensor_entity_description import GrowattRequiredKeysMixin _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = ( 1 # Serialize updates as inverter does not handle concurrent requests ) @dataclass(frozen=True, kw_only=True) class GrowattSwitchEntityDescription(SwitchEntityDescription, GrowattRequiredKeysMixin): """Describes Growatt switch entity.""" write_key: str | None = None # Parameter ID for writing (if different from api_key) # Note that the Growatt V1 API uses different keys for reading and writing parameters. # Reading values returns camelCase keys, while writing requires snake_case keys. MIN_SWITCH_TYPES: tuple[GrowattSwitchEntityDescription, ...] = ( GrowattSwitchEntityDescription( key="ac_charge", translation_key="ac_charge", api_key="acChargeEnable", # Key returned by V1 API write_key="ac_charge", # Key used to write parameter ), ) async def async_setup_entry( hass: HomeAssistant, entry: GrowattConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Growatt switch entities.""" runtime_data = entry.runtime_data # Add switch entities for each MIN device (only supported with V1 API) async_add_entities( GrowattSwitch(device_coordinator, description) for device_coordinator in runtime_data.devices.values() if ( device_coordinator.device_type == "min" and device_coordinator.api_version == "v1" ) for description in MIN_SWITCH_TYPES ) class GrowattSwitch(CoordinatorEntity[GrowattCoordinator], SwitchEntity): """Representation of a Growatt switch.""" _attr_has_entity_name = True _attr_entity_category = EntityCategory.CONFIG entity_description: GrowattSwitchEntityDescription def __init__( self, coordinator: GrowattCoordinator, description: GrowattSwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.device_id}_{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.device_id)}, manufacturer="Growatt", name=coordinator.device_id, ) @property def is_on(self) -> bool | None: """Return true if the switch is on.""" value = self.coordinator.data.get(self.entity_description.api_key) if value is None: return None # API returns integer 1 for enabled, 0 for disabled return bool(value) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self._async_set_state(True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self._async_set_state(False) async def _async_set_state(self, state: bool) -> None: """Set the switch state.""" # Use write_key if specified, otherwise fall back to api_key parameter_id = ( self.entity_description.write_key or self.entity_description.api_key ) api_value = int(state) try: # Use V1 API to write parameter await self.hass.async_add_executor_job( self.coordinator.api.min_write_parameter, self.coordinator.device_id, parameter_id, api_value, ) except GrowattV1ApiError as e: raise HomeAssistantError(f"Error while setting switch state: {e}") from e # If no exception was raised, the write was successful _LOGGER.debug( "Set switch %s to %s", parameter_id, api_value, ) # Update the value in coordinator data (keep as integer like API returns) self.coordinator.data[self.entity_description.api_key] = api_value self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/growatt_server/switch.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/habitica/notify.py
"""Notify platform for the Habitica integration.""" from __future__ import annotations from abc import abstractmethod from enum import StrEnum from typing import TYPE_CHECKING from uuid import UUID from aiohttp import ClientError from habiticalib import ( GroupData, HabiticaException, NotAuthorizedError, NotFoundError, TooManyRequestsError, UserData, ) from homeassistant.components.notify import ( DOMAIN as NOTIFY_DOMAIN, NotifyEntity, NotifyEntityDescription, ) from homeassistant.const import CONF_NAME from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HABITICA_KEY from .const import DOMAIN from .coordinator import HabiticaConfigEntry, HabiticaDataUpdateCoordinator from .entity import HabiticaBase PARALLEL_UPDATES = 10 class HabiticaNotify(StrEnum): """Habitica Notifier.""" PARTY_CHAT = "party_chat" PRIVATE_MESSAGE = "private_message" async def async_setup_entry( hass: HomeAssistant, config_entry: HabiticaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the notify entity platform.""" members_added: set[UUID] = set() entity_registry = er.async_get(hass) coordinator = config_entry.runtime_data if party := coordinator.data.user.party.id: party_coordinator = hass.data[HABITICA_KEY][party] async_add_entities( [HabiticaPartyChatNotifyEntity(coordinator, party_coordinator.data.party)] ) @callback def add_entities() -> None: nonlocal members_added new_members = set(party_coordinator.data.members.keys()) - members_added if TYPE_CHECKING: assert coordinator.data.user.id new_members.discard(coordinator.data.user.id) if new_members: async_add_entities( HabiticaPrivateMessageNotifyEntity( coordinator, party_coordinator.data.members[member] ) for member in new_members ) members_added |= new_members delete_members = members_added - set(party_coordinator.data.members.keys()) for member in delete_members: if entity_id := entity_registry.async_get_entity_id( NOTIFY_DOMAIN, DOMAIN, f"{coordinator.config_entry.unique_id}_{member!s}_{HabiticaNotify.PRIVATE_MESSAGE}", ): entity_registry.async_remove(entity_id) members_added.discard(member) party_coordinator.async_add_listener(add_entities) add_entities() class HabiticaBaseNotifyEntity(HabiticaBase, NotifyEntity): """Habitica base notify entity.""" def __init__( self, coordinator: HabiticaDataUpdateCoordinator, ) -> None: """Initialize a Habitica entity.""" super().__init__(coordinator, self.entity_description) @abstractmethod async def _send_message(self, message: str) -> None: """Send a Habitica message.""" async def async_send_message(self, message: str, title: str | None = None) -> None: """Send a message.""" try: await self._send_message(message) except NotAuthorizedError as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="send_message_forbidden", translation_placeholders={ **self.translation_placeholders, "reason": e.error.message, }, ) from e except NotFoundError as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="send_message_not_found", translation_placeholders={ **self.translation_placeholders, "reason": e.error.message, }, ) from e except TooManyRequestsError as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="setup_rate_limit_exception", translation_placeholders={"retry_after": str(e.retry_after)}, ) from e except HabiticaException as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="service_call_exception", translation_placeholders={"reason": e.error.message}, ) from e except ClientError as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="service_call_exception", translation_placeholders={"reason": str(e)}, ) from e class HabiticaPartyChatNotifyEntity(HabiticaBaseNotifyEntity): """Representation of a Habitica party chat notify entity.""" def __init__( self, coordinator: HabiticaDataUpdateCoordinator, party: GroupData, ) -> None: """Initialize a Habitica entity.""" self._attr_translation_placeholders = {CONF_NAME: party.name} self.entity_description = NotifyEntityDescription( key=HabiticaNotify.PARTY_CHAT, translation_key=HabiticaNotify.PARTY_CHAT, ) self.party = party super().__init__(coordinator) async def _send_message(self, message: str) -> None: """Send a Habitica party chat message.""" await self.coordinator.habitica.send_group_message( message=message, group_id=self.party.id, ) class HabiticaPrivateMessageNotifyEntity(HabiticaBaseNotifyEntity): """Representation of a Habitica private message notify entity.""" def __init__( self, coordinator: HabiticaDataUpdateCoordinator, member: UserData, ) -> None: """Initialize a Habitica entity.""" self._attr_translation_placeholders = {CONF_NAME: member.profile.name or ""} self.entity_description = NotifyEntityDescription( key=f"{member.id!s}_{HabiticaNotify.PRIVATE_MESSAGE}", translation_key=HabiticaNotify.PRIVATE_MESSAGE, ) self.member = member super().__init__(coordinator) async def _send_message(self, message: str) -> None: """Send a Habitica private message.""" if TYPE_CHECKING: assert self.member.id await self.coordinator.habitica.send_private_message( message=message, to_user_id=self.member.id, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/habitica/notify.py", "license": "Apache License 2.0", "lines": 169, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/hassio/jobs.py
"""Track Supervisor job data and allow subscription to updates.""" from collections.abc import Callable from dataclasses import dataclass, replace from functools import partial import logging from typing import Any from uuid import UUID from aiohasupervisor.models import Job from homeassistant.core import ( CALLBACK_TYPE, HomeAssistant, callback, is_callback_check_partial, ) from homeassistant.helpers.dispatcher import async_dispatcher_connect from .const import ( ATTR_DATA, ATTR_STARTUP, ATTR_UPDATE_KEY, ATTR_WS_EVENT, EVENT_JOB, EVENT_SUPERVISOR_EVENT, EVENT_SUPERVISOR_UPDATE, STARTUP_COMPLETE, UPDATE_KEY_SUPERVISOR, ) from .handler import get_supervisor_client _LOGGER = logging.getLogger(__name__) @dataclass(slots=True, frozen=True) class JobSubscription: """Subscribe for updates on jobs which match filters. UUID is preferred match but only available in cases of a background API that returns the UUID before taking the action. Others are used to match jobs only if UUID is omitted. Either name or UUID is required to be able to match. event_callback must be safe annotated as a homeassistant.core.callback and safe to call in the event loop. """ event_callback: Callable[[Job], Any] uuid: str | None = None name: str | None = None reference: str | None = None def __post_init__(self) -> None: """Validate at least one filter option is present.""" if not self.name and not self.uuid: raise ValueError("Either name or uuid must be provided!") if not is_callback_check_partial(self.event_callback): raise ValueError("event_callback must be a homeassistant.core.callback!") def matches(self, job: Job) -> bool: """Return true if job matches subscription filters.""" if self.uuid: return job.uuid == self.uuid return job.name == self.name and self.reference in (None, job.reference) class SupervisorJobs: """Manage access to Supervisor jobs.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize object.""" self._hass = hass self._supervisor_client = get_supervisor_client(hass) self._jobs: dict[UUID, Job] = {} self._subscriptions: set[JobSubscription] = set() self._dispatcher_disconnect: Callable[[], None] | None = None @property def current_jobs(self) -> list[Job]: """Return current jobs.""" return list(self._jobs.values()) def subscribe(self, subscription: JobSubscription) -> CALLBACK_TYPE: """Subscribe to updates for job. Return callback is used to unsubscribe. If any jobs match the subscription at the time this is called, runs the callback on them. """ self._subscriptions.add(subscription) # Run the callback on each existing match # We catch all errors to prevent an error in one from stopping the others for match in [job for job in self._jobs.values() if subscription.matches(job)]: try: return subscription.event_callback(match) except Exception as err: # noqa: BLE001 _LOGGER.error( "Error encountered processing Supervisor Job (%s %s %s) - %s", match.name, match.reference, match.uuid, err, ) return partial(self._subscriptions.discard, subscription) async def refresh_data(self, first_update: bool = False) -> None: """Refresh job data.""" job_data = await self._supervisor_client.jobs.info() job_queue: list[Job] = job_data.jobs.copy() new_jobs: dict[UUID, Job] = {} changed_jobs: list[Job] = [] # Rebuild our job cache from new info and compare to find changes while job_queue: job = job_queue.pop(0) job_queue.extend(job.child_jobs) job = replace(job, child_jobs=[]) if job.uuid not in self._jobs or job != self._jobs[job.uuid]: changed_jobs.append(job) new_jobs[job.uuid] = replace(job, child_jobs=[]) # For any jobs that disappeared which weren't done, tell subscribers they # changed to done. We don't know what else happened to them so leave the # rest of their state as is rather then guessing changed_jobs.extend( [ replace(job, done=True) for uuid, job in self._jobs.items() if uuid not in new_jobs and job.done is False ] ) # Replace our cache and inform subscribers of all changes self._jobs = new_jobs for job in changed_jobs: self._process_job_change(job) # If this is the first update register to receive Supervisor events if first_update: self._dispatcher_disconnect = async_dispatcher_connect( self._hass, EVENT_SUPERVISOR_EVENT, self._supervisor_events_to_jobs ) @callback def _supervisor_events_to_jobs(self, event: dict[str, Any]) -> None: """Update job data cache from supervisor events.""" if ATTR_WS_EVENT not in event: return if ( event[ATTR_WS_EVENT] == EVENT_SUPERVISOR_UPDATE and event.get(ATTR_UPDATE_KEY) == UPDATE_KEY_SUPERVISOR and event.get(ATTR_DATA, {}).get(ATTR_STARTUP) == STARTUP_COMPLETE ): self._hass.async_create_task(self.refresh_data()) elif event[ATTR_WS_EVENT] == EVENT_JOB: job = Job.from_dict(event[ATTR_DATA] | {"child_jobs": []}) self._jobs[job.uuid] = job self._process_job_change(job) def _process_job_change(self, job: Job) -> None: """Process a job change by triggering callbacks on subscribers.""" for sub in self._subscriptions: if sub.matches(job): sub.event_callback(job) # If the job is done, pop it from our cache if present after processing is done if job.done and job.uuid in self._jobs: del self._jobs[job.uuid] @callback def unload(self) -> None: """Unregister with dispatcher on config entry unload.""" if self._dispatcher_disconnect: self._dispatcher_disconnect() self._dispatcher_disconnect = None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hassio/jobs.py", "license": "Apache License 2.0", "lines": 147, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/homeassistant_connect_zbt2/switch.py
"""Home Assistant Connect ZBT-2 switch entities.""" from __future__ import annotations import logging from homeassistant.components.homeassistant_hardware.coordinator import ( FirmwareUpdateCoordinator, ) from homeassistant.components.homeassistant_hardware.switch import ( BaseBetaFirmwareSwitch, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HomeAssistantConnectZBT2ConfigEntry from .const import DOMAIN, HARDWARE_NAME, SERIAL_NUMBER _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: HomeAssistantConnectZBT2ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform for Home Assistant Connect ZBT-2.""" async_add_entities( [BetaFirmwareSwitch(config_entry.runtime_data.coordinator, config_entry)] ) class BetaFirmwareSwitch(BaseBetaFirmwareSwitch): """Home Assistant Connect ZBT-2 beta firmware switch.""" def __init__( self, coordinator: FirmwareUpdateCoordinator, config_entry: HomeAssistantConnectZBT2ConfigEntry, ) -> None: """Initialize the beta firmware switch.""" super().__init__(coordinator, config_entry) serial_number = self._config_entry.data[SERIAL_NUMBER] self._attr_unique_id = f"{serial_number}_beta_firmware" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, serial_number)}, name=f"{HARDWARE_NAME} ({serial_number})", model=HARDWARE_NAME, manufacturer="Nabu Casa", serial_number=serial_number, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homeassistant_connect_zbt2/switch.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/homeassistant_hardware/switch.py
"""Home Assistant Hardware base beta firmware switch entity.""" from __future__ import annotations import logging from typing import Any from homeassistant.components.switch import SwitchEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory from homeassistant.helpers.restore_state import RestoreEntity from .coordinator import FirmwareUpdateCoordinator _LOGGER = logging.getLogger(__name__) class BaseBetaFirmwareSwitch(SwitchEntity, RestoreEntity): """Base switch to enable beta firmware updates.""" _attr_has_entity_name = True _attr_entity_category = EntityCategory.CONFIG _attr_entity_registry_enabled_default = False _attr_translation_key = "beta_firmware" def __init__( self, coordinator: FirmwareUpdateCoordinator, config_entry: ConfigEntry, ) -> None: """Initialize the beta firmware switch.""" self._coordinator = coordinator self._config_entry = config_entry async def async_added_to_hass(self) -> None: """Handle entity which will be added to hass.""" await super().async_added_to_hass() # Restore the last state last_state = await self.async_get_last_state() if last_state is not None: self._attr_is_on = last_state.state == "on" else: self._attr_is_on = False # Apply the restored state to the coordinator await self._update_coordinator_prerelease() async def async_turn_on(self, **kwargs: Any) -> None: """Turn on beta firmware updates.""" self._attr_is_on = True self.async_write_ha_state() await self._update_coordinator_prerelease() async def async_turn_off(self, **kwargs: Any) -> None: """Turn off beta firmware updates.""" self._attr_is_on = False self.async_write_ha_state() await self._update_coordinator_prerelease() async def _update_coordinator_prerelease(self) -> None: """Update the coordinator with the current prerelease setting.""" self._coordinator.client.update_prerelease(bool(self._attr_is_on)) await self._coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homeassistant_hardware/switch.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/homeassistant_sky_connect/switch.py
"""Home Assistant SkyConnect switch entities.""" from __future__ import annotations import logging from homeassistant.components.homeassistant_hardware.coordinator import ( FirmwareUpdateCoordinator, ) from homeassistant.components.homeassistant_hardware.switch import ( BaseBetaFirmwareSwitch, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HomeAssistantSkyConnectConfigEntry from .const import DOMAIN, PRODUCT, SERIAL_NUMBER, HardwareVariant _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: HomeAssistantSkyConnectConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform for Home Assistant SkyConnect.""" async_add_entities( [BetaFirmwareSwitch(config_entry.runtime_data.coordinator, config_entry)] ) class BetaFirmwareSwitch(BaseBetaFirmwareSwitch): """Home Assistant SkyConnect beta firmware switch.""" def __init__( self, coordinator: FirmwareUpdateCoordinator, config_entry: HomeAssistantSkyConnectConfigEntry, ) -> None: """Initialize the beta firmware switch.""" super().__init__(coordinator, config_entry) variant = HardwareVariant.from_usb_product_name( self._config_entry.data[PRODUCT] ) serial_number = self._config_entry.data[SERIAL_NUMBER] self._attr_unique_id = f"{serial_number}_beta_firmware" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, serial_number)}, name=f"{variant.full_name} ({serial_number[:8]})", model=variant.full_name, manufacturer="Nabu Casa", serial_number=serial_number, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homeassistant_sky_connect/switch.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/homeassistant_yellow/switch.py
"""Home Assistant Yellow switch entities.""" from __future__ import annotations import logging from homeassistant.components.homeassistant_hardware.coordinator import ( FirmwareUpdateCoordinator, ) from homeassistant.components.homeassistant_hardware.switch import ( BaseBetaFirmwareSwitch, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HomeAssistantYellowConfigEntry from .const import DOMAIN, MANUFACTURER, MODEL _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: HomeAssistantYellowConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform for Home Assistant Yellow.""" async_add_entities( [BetaFirmwareSwitch(config_entry.runtime_data.coordinator, config_entry)] ) class BetaFirmwareSwitch(BaseBetaFirmwareSwitch): """Home Assistant Yellow beta firmware switch.""" def __init__( self, coordinator: FirmwareUpdateCoordinator, config_entry: HomeAssistantYellowConfigEntry, ) -> None: """Initialize the beta firmware switch.""" super().__init__(coordinator, config_entry) self._attr_unique_id = "beta_firmware" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, "yellow")}, name=MODEL, model=MODEL, manufacturer=MANUFACTURER, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homeassistant_yellow/switch.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/inels/config_flow.py
"""Config flow for iNELS.""" from __future__ import annotations from typing import Any from homeassistant.components import mqtt from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers.service_info.mqtt import MqttServiceInfo from .const import DOMAIN, TITLE class INelsConfigFlow(ConfigFlow, domain=DOMAIN): """Handle of iNELS config flow.""" VERSION = 1 async def async_step_mqtt( self, discovery_info: MqttServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by MQTT discovery.""" if self._async_in_progress(): return self.async_abort(reason="already_in_progress") # Validate the message, abort if it fails. if not discovery_info.topic.endswith("/gw"): # Not an iNELS discovery message. return self.async_abort(reason="invalid_discovery_info") if not discovery_info.payload: # Empty payload, unexpected payload. return self.async_abort(reason="invalid_discovery_info") return await self.async_step_confirm_from_mqtt() async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow initialized by the user.""" try: if not mqtt.is_connected(self.hass): return self.async_abort(reason="mqtt_not_connected") except KeyError: return self.async_abort(reason="mqtt_not_configured") return await self.async_step_confirm_from_user() async def step_confirm( self, step_id: str, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm the setup.""" if user_input is not None: await self.async_set_unique_id(DOMAIN) return self.async_create_entry(title=TITLE, data={}) return self.async_show_form(step_id=step_id) async def async_step_confirm_from_mqtt( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm the setup from MQTT discovered.""" return await self.step_confirm( step_id="confirm_from_mqtt", user_input=user_input ) async def async_step_confirm_from_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm the setup from user add integration.""" return await self.step_confirm( step_id="confirm_from_user", user_input=user_input )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/inels/config_flow.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/inels/const.py
"""Constants for the iNELS integration.""" import logging from homeassistant.const import Platform DOMAIN = "inels" TITLE = "iNELS" PLATFORMS: list[Platform] = [ Platform.SWITCH, ] LOGGER = logging.getLogger(__package__)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/inels/const.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/inels/entity.py
"""Base class for iNELS components.""" from __future__ import annotations from inelsmqtt.devices import Device from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import Entity from .const import DOMAIN class InelsBaseEntity(Entity): """Base iNELS entity.""" _attr_should_poll = False _attr_has_entity_name = True def __init__( self, device: Device, key: str, index: int, ) -> None: """Init base entity.""" self._device = device self._device_id = device.unique_id self._attr_unique_id = self._device_id # The referenced variable to read from self._key = key # The index of the variable list to read from. '-1' for no index self._index = index info = device.info() self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.unique_id)}, manufacturer=info.manufacturer, model=info.model_number, name=device.title, sw_version=info.sw_version, ) async def async_added_to_hass(self) -> None: """Add subscription of the data listener.""" # Register the HA callback self._device.add_ha_callback(self._key, self._index, self._callback) # Subscribe to MQTT updates self._device.mqtt.subscribe_listener( self._device.state_topic, self._device.unique_id, self._device.callback ) def _callback(self) -> None: """Get data from broker into the HA.""" if hasattr(self, "hass"): self.schedule_update_ha_state() @property def available(self) -> bool: """Return if entity is available.""" return self._device.is_available
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/inels/entity.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/inels/switch.py
"""iNELS switch entity.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Any from inelsmqtt.devices import Device from inelsmqtt.utils.common import Bit, Relay, SimpleRelay from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import InelsConfigEntry from .entity import InelsBaseEntity @dataclass(frozen=True, kw_only=True) class InelsSwitchEntityDescription(SwitchEntityDescription): """Class describing iNELS switch entities.""" get_state_fn: Callable[[Device, int], Bit | SimpleRelay | Relay] alerts: list[str] | None = None placeholder_fn: Callable[[Device, int, bool], dict[str, str]] SWITCH_TYPES = [ InelsSwitchEntityDescription( key="bit", translation_key="bit", get_state_fn=lambda device, index: device.state.bit[index], placeholder_fn=lambda device, index, indexed: { "addr": f" {device.state.bit[index].addr}" }, ), InelsSwitchEntityDescription( key="simple_relay", translation_key="simple_relay", get_state_fn=lambda device, index: device.state.simple_relay[index], placeholder_fn=lambda device, index, indexed: { "index": f" {index + 1}" if indexed else "" }, ), InelsSwitchEntityDescription( key="relay", translation_key="relay", get_state_fn=lambda device, index: device.state.relay[index], alerts=["overflow"], placeholder_fn=lambda device, index, indexed: { "index": f" {index + 1}" if indexed else "" }, ), ] async def async_setup_entry( hass: HomeAssistant, entry: InelsConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Load iNELS switch.""" entities: list[InelsSwitch] = [] for device in entry.runtime_data.devices: for description in SWITCH_TYPES: if hasattr(device.state, description.key): switch_count = len(getattr(device.state, description.key)) entities.extend( InelsSwitch( device=device, description=description, index=idx, switch_count=switch_count, ) for idx in range(switch_count) ) async_add_entities(entities, False) class InelsSwitch(InelsBaseEntity, SwitchEntity): """The platform class required by Home Assistant.""" entity_description: InelsSwitchEntityDescription def __init__( self, device: Device, description: InelsSwitchEntityDescription, index: int = 0, switch_count: int = 1, ) -> None: """Initialize the switch.""" super().__init__(device=device, key=description.key, index=index) self.entity_description = description self._switch_count = switch_count # Include index in unique_id for devices with multiple switches unique_key = f"{description.key}{index}" if index else description.key self._attr_unique_id = f"{self._attr_unique_id}_{unique_key}".lower() # Set translation placeholders self._attr_translation_placeholders = self.entity_description.placeholder_fn( self._device, self._index, self._switch_count > 1 ) def _check_alerts(self, current_state: Bit | SimpleRelay | Relay) -> None: """Check if there are active alerts and raise ServiceValidationError if found.""" if self.entity_description.alerts and any( getattr(current_state, alert_key, None) for alert_key in self.entity_description.alerts ): raise ServiceValidationError("Cannot operate switch with active alerts") @property def is_on(self) -> bool | None: """Return if switch is on.""" current_state = self.entity_description.get_state_fn(self._device, self._index) return current_state.is_on async def async_turn_off(self, **kwargs: Any) -> None: """Instruct the switch to turn off.""" current_state = self.entity_description.get_state_fn(self._device, self._index) self._check_alerts(current_state) current_state.is_on = False await self._device.set_ha_value(self._device.state) async def async_turn_on(self, **kwargs: Any) -> None: """Instruct the switch to turn on.""" current_state = self.entity_description.get_state_fn(self._device, self._index) self._check_alerts(current_state) current_state.is_on = True await self._device.set_ha_value(self._device.state)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/inels/switch.py", "license": "Apache License 2.0", "lines": 112, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/london_underground/config_flow.py
"""Config flow for London Underground integration.""" from __future__ import annotations import asyncio import logging from typing import Any from london_tube_status import TubeData import voluptuous as vol from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlowWithReload, ) from homeassistant.core import callback from homeassistant.helpers import selector from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.typing import ConfigType from .const import CONF_LINE, DEFAULT_LINES, DOMAIN, TUBE_LINES _LOGGER = logging.getLogger(__name__) class LondonUndergroundConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for London Underground.""" VERSION = 1 MINOR_VERSION = 1 @staticmethod @callback def async_get_options_flow( _: ConfigEntry, ) -> LondonUndergroundOptionsFlow: """Get the options flow for this handler.""" return LondonUndergroundOptionsFlow() 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: session = async_get_clientsession(self.hass) data = TubeData(session) try: async with asyncio.timeout(10): await data.update() except TimeoutError: errors["base"] = "timeout_connect" except Exception: _LOGGER.exception("Unexpected error") errors["base"] = "cannot_connect" else: return self.async_create_entry( title="London Underground", data={}, options={CONF_LINE: user_input.get(CONF_LINE, DEFAULT_LINES)}, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Optional( CONF_LINE, default=DEFAULT_LINES, ): selector.SelectSelector( selector.SelectSelectorConfig( options=TUBE_LINES, multiple=True, mode=selector.SelectSelectorMode.DROPDOWN, ) ), } ), errors=errors, ) async def async_step_import(self, import_data: ConfigType) -> ConfigFlowResult: """Handle import from configuration.yaml.""" session = async_get_clientsession(self.hass) data = TubeData(session) try: async with asyncio.timeout(10): await data.update() except Exception: _LOGGER.exception( "Unexpected error trying to connect before importing config, aborting import " ) return self.async_abort(reason="cannot_connect") _LOGGER.warning( "Importing London Underground config from configuration.yaml: %s", import_data, ) # Extract lines from the sensor platform config lines = import_data.get(CONF_LINE, DEFAULT_LINES) if "London Overground" in lines: _LOGGER.warning( "London Overground was removed from the configuration as the line has been divided and renamed" ) lines.remove("London Overground") return self.async_create_entry( title="London Underground", data={}, options={CONF_LINE: import_data.get(CONF_LINE, DEFAULT_LINES)}, ) class LondonUndergroundOptionsFlow(OptionsFlowWithReload): """Handle options.""" async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Manage the options.""" if user_input is not None: _LOGGER.debug( "Updating london underground with options flow user_input: %s", user_input, ) return self.async_create_entry( title="", data={CONF_LINE: user_input[CONF_LINE]}, ) return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Optional( CONF_LINE, default=self.config_entry.options.get( CONF_LINE, self.config_entry.data.get(CONF_LINE, DEFAULT_LINES), ), ): selector.SelectSelector( selector.SelectSelectorConfig( options=TUBE_LINES, multiple=True, mode=selector.SelectSelectorMode.DROPDOWN, ) ), } ), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/london_underground/config_flow.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/lunatone/config_flow.py
"""Config flow for Lunatone.""" from typing import Any, Final import aiohttp from lunatone_rest_api_client import Auth, Info import voluptuous as vol from homeassistant.config_entries import ( SOURCE_RECONFIGURE, ConfigFlow, ConfigFlowResult, ) from homeassistant.const import CONF_URL from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN DATA_SCHEMA: Final[vol.Schema] = vol.Schema( {vol.Required(CONF_URL, default="http://"): cv.string}, ) class LunatoneConfigFlow(ConfigFlow, domain=DOMAIN): """Lunatone config flow.""" VERSION = 1 MINOR_VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow initialized by the user.""" errors: dict[str, str] = {} if user_input is not None: url = user_input[CONF_URL] data = {CONF_URL: url} self._async_abort_entries_match(data) auth_api = Auth( session=async_get_clientsession(self.hass), base_url=url, ) info_api = Info(auth_api) try: await info_api.async_update() except aiohttp.InvalidUrlClientError: errors["base"] = "invalid_url" except aiohttp.ClientConnectionError: errors["base"] = "cannot_connect" else: if info_api.serial_number is None: errors["base"] = "missing_device_info" else: await self.async_set_unique_id(str(info_api.serial_number)) if self.source == SOURCE_RECONFIGURE: self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates=data, title=url ) self._abort_if_unique_id_configured() return self.async_create_entry(title=url, data={CONF_URL: url}) return self.async_show_form( step_id="user", data_schema=DATA_SCHEMA, errors=errors, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a reconfiguration flow initialized by the user.""" return await self.async_step_user(user_input)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lunatone/config_flow.py", "license": "Apache License 2.0", "lines": 63, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/lunatone/coordinator.py
"""Coordinator for handling data fetching and updates.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta import logging import aiohttp from lunatone_rest_api_client import DALIBroadcast, Device, Devices, Info from lunatone_rest_api_client.models import InfoData from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) DEFAULT_INFO_SCAN_INTERVAL = timedelta(seconds=60) DEFAULT_DEVICES_SCAN_INTERVAL = timedelta(seconds=10) @dataclass class LunatoneData: """Data for Lunatone integration.""" coordinator_info: LunatoneInfoDataUpdateCoordinator coordinator_devices: LunatoneDevicesDataUpdateCoordinator dali_line_broadcasts: list[DALIBroadcast] type LunatoneConfigEntry = ConfigEntry[LunatoneData] class LunatoneInfoDataUpdateCoordinator(DataUpdateCoordinator[InfoData]): """Data update coordinator for Lunatone info.""" config_entry: LunatoneConfigEntry def __init__( self, hass: HomeAssistant, config_entry: LunatoneConfigEntry, info_api: Info ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"{DOMAIN}-info", always_update=False, update_interval=DEFAULT_INFO_SCAN_INTERVAL, ) self.info_api = info_api async def _async_update_data(self) -> InfoData: """Update info data.""" try: await self.info_api.async_update() except aiohttp.ClientConnectionError as ex: raise UpdateFailed( "Unable to retrieve info data from Lunatone REST API" ) from ex if self.info_api.data is None: raise UpdateFailed("Did not receive info data from Lunatone REST API") return self.info_api.data class LunatoneDevicesDataUpdateCoordinator(DataUpdateCoordinator[dict[int, Device]]): """Data update coordinator for Lunatone devices.""" config_entry: LunatoneConfigEntry def __init__( self, hass: HomeAssistant, config_entry: LunatoneConfigEntry, devices_api: Devices, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"{DOMAIN}-devices", always_update=False, update_interval=DEFAULT_DEVICES_SCAN_INTERVAL, ) self.devices_api = devices_api async def _async_update_data(self) -> dict[int, Device]: """Update devices data.""" try: await self.devices_api.async_update() except aiohttp.ClientConnectionError as ex: raise UpdateFailed( "Unable to retrieve devices data from Lunatone REST API" ) from ex if self.devices_api.data is None: raise UpdateFailed("Did not receive devices data from Lunatone REST API") return {device.id: device for device in self.devices_api.devices}
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lunatone/coordinator.py", "license": "Apache License 2.0", "lines": 79, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/lunatone/light.py
"""Platform for Lunatone light integration.""" from __future__ import annotations import asyncio from typing import Any from lunatone_rest_api_client import DALIBroadcast from lunatone_rest_api_client.models import LineStatus from homeassistant.components.light import ( ATTR_BRIGHTNESS, ColorMode, LightEntity, brightness_supported, ) 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 homeassistant.util.color import brightness_to_value, value_to_brightness from .const import DOMAIN from .coordinator import ( LunatoneConfigEntry, LunatoneDevicesDataUpdateCoordinator, LunatoneInfoDataUpdateCoordinator, ) PARALLEL_UPDATES = 0 STATUS_UPDATE_DELAY = 0.04 async def async_setup_entry( hass: HomeAssistant, config_entry: LunatoneConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Lunatone Light platform.""" coordinator_info = config_entry.runtime_data.coordinator_info coordinator_devices = config_entry.runtime_data.coordinator_devices dali_line_broadcasts = config_entry.runtime_data.dali_line_broadcasts entities: list[LightEntity] = [ LunatoneLineBroadcastLight( coordinator_info, coordinator_devices, dali_line_broadcast ) for dali_line_broadcast in dali_line_broadcasts ] entities.extend( [ LunatoneLight( coordinator_devices, device_id, coordinator_info.data.device.serial ) for device_id in coordinator_devices.data ] ) async_add_entities(entities) class LunatoneLight( CoordinatorEntity[LunatoneDevicesDataUpdateCoordinator], LightEntity ): """Representation of a Lunatone light.""" BRIGHTNESS_SCALE = (1, 100) _last_brightness = 255 _attr_has_entity_name = True _attr_name = None _attr_should_poll = False def __init__( self, coordinator: LunatoneDevicesDataUpdateCoordinator, device_id: int, interface_serial_number: int, ) -> None: """Initialize a Lunatone light.""" super().__init__(coordinator) self._device_id = device_id self._interface_serial_number = interface_serial_number self._device = self.coordinator.data[self._device_id] self._attr_unique_id = f"{interface_serial_number}-device{device_id}" @property def device_info(self) -> DeviceInfo: """Return the device info.""" assert self.unique_id return DeviceInfo( identifiers={(DOMAIN, self.unique_id)}, name=self._device.name, via_device=( DOMAIN, f"{self._interface_serial_number}-line{self._device.data.line}", ), ) @property def available(self) -> bool: """Return True if entity is available.""" return super().available and self._device is not None @property def is_on(self) -> bool: """Return True if light is on.""" return self._device is not None and self._device.is_on @property def brightness(self) -> int | None: """Return the brightness of this light between 0..255.""" return ( value_to_brightness(self.BRIGHTNESS_SCALE, self._device.brightness) if self._device.brightness is not None else None ) @property def color_mode(self) -> ColorMode: """Return the color mode of the light.""" if self._device is not None and self._device.brightness is not None: return ColorMode.BRIGHTNESS return ColorMode.ONOFF @property def supported_color_modes(self) -> set[ColorMode]: """Return the supported color modes.""" return {self.color_mode} @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._device = self.coordinator.data[self._device_id] self.async_write_ha_state() async def async_turn_on(self, **kwargs: Any) -> None: """Instruct the light to turn on.""" if brightness_supported(self.supported_color_modes): await self._device.fade_to_brightness( brightness_to_value( self.BRIGHTNESS_SCALE, kwargs.get(ATTR_BRIGHTNESS, self._last_brightness), ) ) else: await self._device.switch_on() await asyncio.sleep(STATUS_UPDATE_DELAY) await self.coordinator.async_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Instruct the light to turn off.""" if brightness_supported(self.supported_color_modes): if self.brightness: self._last_brightness = self.brightness await self._device.fade_to_brightness(0) else: await self._device.switch_off() await asyncio.sleep(STATUS_UPDATE_DELAY) await self.coordinator.async_refresh() class LunatoneLineBroadcastLight( CoordinatorEntity[LunatoneInfoDataUpdateCoordinator], LightEntity ): """Representation of a Lunatone line broadcast light.""" BRIGHTNESS_SCALE = (1, 100) _attr_assumed_state = True _attr_color_mode = ColorMode.BRIGHTNESS _attr_supported_color_modes = {ColorMode.BRIGHTNESS} def __init__( self, coordinator_info: LunatoneInfoDataUpdateCoordinator, coordinator_devices: LunatoneDevicesDataUpdateCoordinator, broadcast: DALIBroadcast, ) -> None: """Initialize a Lunatone line broadcast light.""" super().__init__(coordinator_info) self._coordinator_devices = coordinator_devices self._broadcast = broadcast line = broadcast.line self._attr_unique_id = f"{coordinator_info.data.device.serial}-line{line}" line_device = self.coordinator.data.lines[str(line)].device extra_info: dict = {} if line_device.serial != coordinator_info.data.device.serial: extra_info.update( serial_number=str(line_device.serial), hw_version=line_device.pcb, model_id=f"{line_device.article_number}{line_device.article_info}", ) assert self.unique_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self.unique_id)}, name=f"DALI Line {line}", via_device=(DOMAIN, str(coordinator_info.data.device.serial)), **extra_info, ) @property def available(self) -> bool: """Return True if entity is available.""" line_status = self.coordinator.data.lines[str(self._broadcast.line)].line_status return super().available and line_status == LineStatus.OK async def async_turn_on(self, **kwargs: Any) -> None: """Instruct the line to turn on.""" await self._broadcast.fade_to_brightness( brightness_to_value(self.BRIGHTNESS_SCALE, kwargs.get(ATTR_BRIGHTNESS, 255)) ) await asyncio.sleep(STATUS_UPDATE_DELAY) await self._coordinator_devices.async_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Instruct the line to turn off.""" await self._broadcast.fade_to_brightness(0) await asyncio.sleep(STATUS_UPDATE_DELAY) await self._coordinator_devices.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lunatone/light.py", "license": "Apache License 2.0", "lines": 188, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/matter/services.py
"""Services for Matter devices.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN from homeassistant.components.water_heater import DOMAIN as WATER_HEATER_DOMAIN from homeassistant.core import HomeAssistant, SupportsResponse, callback from homeassistant.helpers import config_validation as cv, service from .const import ( ATTR_CREDENTIAL_DATA, ATTR_CREDENTIAL_INDEX, ATTR_CREDENTIAL_RULE, ATTR_CREDENTIAL_TYPE, ATTR_USER_INDEX, ATTR_USER_NAME, ATTR_USER_STATUS, ATTR_USER_TYPE, CLEAR_ALL_INDEX, CREDENTIAL_RULE_REVERSE_MAP, CREDENTIAL_TYPE_REVERSE_MAP, DOMAIN, SERVICE_CREDENTIAL_TYPES, USER_TYPE_REVERSE_MAP, ) ATTR_DURATION = "duration" ATTR_EMERGENCY_BOOST = "emergency_boost" ATTR_TEMPORARY_SETPOINT = "temporary_setpoint" SERVICE_WATER_HEATER_BOOST = "water_heater_boost" @callback def async_setup_services(hass: HomeAssistant) -> None: """Register the Matter services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_WATER_HEATER_BOOST, entity_domain=WATER_HEATER_DOMAIN, schema={ # duration >=1 vol.Required(ATTR_DURATION): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(ATTR_EMERGENCY_BOOST): cv.boolean, vol.Optional(ATTR_TEMPORARY_SETPOINT): vol.All( vol.Coerce(int), vol.Range(min=30, max=65) ), }, func="async_set_boost", ) # Lock services - Full user CRUD service.async_register_platform_entity_service( hass, DOMAIN, "set_lock_user", entity_domain=LOCK_DOMAIN, schema={ vol.Optional(ATTR_USER_INDEX): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(ATTR_USER_NAME): vol.Any(str, None), vol.Optional(ATTR_USER_TYPE): vol.In(USER_TYPE_REVERSE_MAP.keys()), vol.Optional(ATTR_CREDENTIAL_RULE): vol.In( CREDENTIAL_RULE_REVERSE_MAP.keys() ), }, func="async_set_lock_user", ) service.async_register_platform_entity_service( hass, DOMAIN, "clear_lock_user", entity_domain=LOCK_DOMAIN, schema={ vol.Required(ATTR_USER_INDEX): vol.All( vol.Coerce(int), vol.Any(vol.Range(min=1), CLEAR_ALL_INDEX), ), }, func="async_clear_lock_user", ) # Lock services - Query operations service.async_register_platform_entity_service( hass, DOMAIN, "get_lock_info", entity_domain=LOCK_DOMAIN, schema={}, func="async_get_lock_info", supports_response=SupportsResponse.ONLY, ) service.async_register_platform_entity_service( hass, DOMAIN, "get_lock_users", entity_domain=LOCK_DOMAIN, schema={}, func="async_get_lock_users", supports_response=SupportsResponse.ONLY, ) # Lock services - Credential management service.async_register_platform_entity_service( hass, DOMAIN, "set_lock_credential", entity_domain=LOCK_DOMAIN, schema={ vol.Required(ATTR_CREDENTIAL_TYPE): vol.In(SERVICE_CREDENTIAL_TYPES), vol.Required(ATTR_CREDENTIAL_DATA): str, vol.Optional(ATTR_CREDENTIAL_INDEX): vol.All( vol.Coerce(int), vol.Range(min=0) ), vol.Optional(ATTR_USER_INDEX): vol.All(vol.Coerce(int), vol.Range(min=1)), vol.Optional(ATTR_USER_STATUS): vol.In( ["occupied_enabled", "occupied_disabled"] ), vol.Optional(ATTR_USER_TYPE): vol.In(USER_TYPE_REVERSE_MAP.keys()), }, func="async_set_lock_credential", supports_response=SupportsResponse.ONLY, ) service.async_register_platform_entity_service( hass, DOMAIN, "clear_lock_credential", entity_domain=LOCK_DOMAIN, schema={ vol.Required(ATTR_CREDENTIAL_TYPE): vol.In(SERVICE_CREDENTIAL_TYPES), vol.Required(ATTR_CREDENTIAL_INDEX): vol.All( vol.Coerce(int), vol.Range(min=0) ), }, func="async_clear_lock_credential", ) service.async_register_platform_entity_service( hass, DOMAIN, "get_lock_credential_status", entity_domain=LOCK_DOMAIN, schema={ vol.Required(ATTR_CREDENTIAL_TYPE): vol.In( CREDENTIAL_TYPE_REVERSE_MAP.keys() ), vol.Required(ATTR_CREDENTIAL_INDEX): vol.All( vol.Coerce(int), vol.Range(min=0) ), }, func="async_get_lock_credential_status", supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/matter/services.py", "license": "Apache License 2.0", "lines": 143, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/meteo_lt/config_flow.py
"""Config flow for Meteo.lt integration.""" from __future__ import annotations import logging from typing import Any import aiohttp from meteo_lt import MeteoLtAPI, Place import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from .const import CONF_PLACE_CODE, DOMAIN _LOGGER = logging.getLogger(__name__) class MeteoLtConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Meteo.lt.""" def __init__(self) -> None: """Initialize the config flow.""" self._api = MeteoLtAPI() self._places: list[Place] = [] self._selected_place: Place | 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: place_code = user_input[CONF_PLACE_CODE] self._selected_place = next( (place for place in self._places if place.code == place_code), None, ) if self._selected_place: await self.async_set_unique_id(self._selected_place.code) self._abort_if_unique_id_configured() return self.async_create_entry( title=self._selected_place.name, data={ CONF_PLACE_CODE: self._selected_place.code, }, ) errors["base"] = "invalid_location" if not self._places: try: await self._api.fetch_places() self._places = self._api.places except (aiohttp.ClientError, TimeoutError) as err: _LOGGER.error("Error fetching places: %s", err) return self.async_abort(reason="cannot_connect") if not self._places: return self.async_abort(reason="no_places_found") places_options = { place.code: f"{place.name} ({place.administrative_division})" for place in self._places } data_schema = vol.Schema( { vol.Required(CONF_PLACE_CODE): vol.In(places_options), } ) return self.async_show_form( step_id="user", data_schema=data_schema, errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/meteo_lt/config_flow.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/meteo_lt/const.py
"""Constants for the Meteo.lt integration.""" from datetime import timedelta from homeassistant.const import Platform DOMAIN = "meteo_lt" PLATFORMS = [Platform.WEATHER] MANUFACTURER = "Lithuanian Hydrometeorological Service" MODEL = "Weather Station" DEFAULT_UPDATE_INTERVAL = timedelta(minutes=30) CONF_PLACE_CODE = "place_code" ATTRIBUTION = "Data provided by Lithuanian Hydrometeorological Service (LHMT)"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/meteo_lt/const.py", "license": "Apache License 2.0", "lines": 10, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/meteo_lt/coordinator.py
"""DataUpdateCoordinator for Meteo.lt integration.""" from __future__ import annotations import logging import aiohttp from meteo_lt import Forecast as MeteoLtForecast, MeteoLtAPI from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_UPDATE_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) type MeteoLtConfigEntry = ConfigEntry[MeteoLtUpdateCoordinator] class MeteoLtUpdateCoordinator(DataUpdateCoordinator[MeteoLtForecast]): """Class to manage fetching Meteo.lt data.""" def __init__( self, hass: HomeAssistant, place_code: str, config_entry: MeteoLtConfigEntry, ) -> None: """Initialize the coordinator.""" self.client = MeteoLtAPI() self.place_code = place_code super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=DEFAULT_UPDATE_INTERVAL, config_entry=config_entry, ) async def _async_update_data(self) -> MeteoLtForecast: """Fetch data from Meteo.lt API.""" try: forecast = await self.client.get_forecast(self.place_code) except aiohttp.ClientResponseError as err: raise UpdateFailed( f"API returned error status {err.status}: {err.message}" ) from err except aiohttp.ClientConnectionError as err: raise UpdateFailed(f"Cannot connect to API: {err}") from err except (aiohttp.ClientError, TimeoutError) as err: raise UpdateFailed(f"Error communicating with API: {err}") from err # Check if forecast data is available if not forecast.forecast_timestamps: raise UpdateFailed( f"No forecast data available for {self.place_code} - API returned empty timestamps" ) return forecast
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/meteo_lt/coordinator.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/meteo_lt/weather.py
"""Weather platform for Meteo.lt integration.""" from __future__ import annotations from collections import defaultdict from datetime import datetime from typing import Any from homeassistant.components.weather import ( Forecast, WeatherEntity, WeatherEntityFeature, ) from homeassistant.const import ( UnitOfPrecipitationDepth, UnitOfPressure, UnitOfSpeed, UnitOfTemperature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ATTRIBUTION, DOMAIN, MANUFACTURER, MODEL from .coordinator import MeteoLtConfigEntry, MeteoLtUpdateCoordinator async def async_setup_entry( hass: HomeAssistant, entry: MeteoLtConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the weather platform.""" coordinator = entry.runtime_data async_add_entities([MeteoLtWeatherEntity(coordinator)]) class MeteoLtWeatherEntity(CoordinatorEntity[MeteoLtUpdateCoordinator], WeatherEntity): """Weather entity for Meteo.lt.""" _attr_has_entity_name = True _attr_name = None _attr_attribution = ATTRIBUTION _attr_native_temperature_unit = UnitOfTemperature.CELSIUS _attr_native_precipitation_unit = UnitOfPrecipitationDepth.MILLIMETERS _attr_native_pressure_unit = UnitOfPressure.HPA _attr_native_wind_speed_unit = UnitOfSpeed.METERS_PER_SECOND _attr_supported_features = ( WeatherEntityFeature.FORECAST_DAILY | WeatherEntityFeature.FORECAST_HOURLY ) def __init__(self, coordinator: MeteoLtUpdateCoordinator) -> None: """Initialize the weather entity.""" super().__init__(coordinator) self._place_code = coordinator.place_code self._attr_unique_id = str(self._place_code) self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, self._place_code)}, manufacturer=MANUFACTURER, model=MODEL, ) @property def native_temperature(self) -> float | None: """Return the temperature.""" return self.coordinator.data.current_conditions.temperature @property def native_apparent_temperature(self) -> float | None: """Return the apparent temperature.""" return self.coordinator.data.current_conditions.apparent_temperature @property def humidity(self) -> int | None: """Return the humidity.""" return self.coordinator.data.current_conditions.humidity @property def native_pressure(self) -> float | None: """Return the pressure.""" return self.coordinator.data.current_conditions.pressure @property def native_wind_speed(self) -> float | None: """Return the wind speed.""" return self.coordinator.data.current_conditions.wind_speed @property def wind_bearing(self) -> int | None: """Return the wind bearing.""" return self.coordinator.data.current_conditions.wind_bearing @property def native_wind_gust_speed(self) -> float | None: """Return the wind gust speed.""" return self.coordinator.data.current_conditions.wind_gust_speed @property def cloud_coverage(self) -> int | None: """Return the cloud coverage.""" return self.coordinator.data.current_conditions.cloud_coverage @property def condition(self) -> str | None: """Return the current condition.""" return self.coordinator.data.current_conditions.condition def _convert_forecast_data( self, forecast_data: Any, include_templow: bool = False ) -> Forecast: """Convert forecast timestamp data to Forecast object.""" return Forecast( datetime=forecast_data.datetime, native_temperature=forecast_data.temperature, native_templow=forecast_data.temperature_low if include_templow else None, native_apparent_temperature=forecast_data.apparent_temperature, condition=forecast_data.condition, native_precipitation=forecast_data.precipitation, precipitation_probability=None, # Not provided by API native_wind_speed=forecast_data.wind_speed, wind_bearing=forecast_data.wind_bearing, cloud_coverage=forecast_data.cloud_coverage, ) async def async_forecast_daily(self) -> list[Forecast] | None: """Return the daily forecast.""" # Using hourly data to create daily summaries, since daily data is not provided directly if not self.coordinator.data: return None forecasts_by_date = defaultdict(list) for timestamp in self.coordinator.data.forecast_timestamps: date = datetime.fromisoformat(timestamp.datetime).date() forecasts_by_date[date].append(timestamp) daily_forecasts = [] for date in sorted(forecasts_by_date.keys()): day_forecasts = forecasts_by_date[date] if not day_forecasts: continue temps = [ ts.temperature for ts in day_forecasts if ts.temperature is not None ] max_temp = max(temps) if temps else None min_temp = min(temps) if temps else None midday_forecast = min( day_forecasts, key=lambda ts: abs(datetime.fromisoformat(ts.datetime).hour - 12), ) daily_forecast = Forecast( datetime=day_forecasts[0].datetime, native_temperature=max_temp, native_templow=min_temp, native_apparent_temperature=midday_forecast.apparent_temperature, condition=midday_forecast.condition, # Calculate precipitation: sum if any values, else None native_precipitation=( sum( ts.precipitation for ts in day_forecasts if ts.precipitation is not None ) if any(ts.precipitation is not None for ts in day_forecasts) else None ), precipitation_probability=None, native_wind_speed=midday_forecast.wind_speed, wind_bearing=midday_forecast.wind_bearing, cloud_coverage=midday_forecast.cloud_coverage, ) daily_forecasts.append(daily_forecast) return daily_forecasts async def async_forecast_hourly(self) -> list[Forecast] | None: """Return the hourly forecast.""" if not self.coordinator.data: return None return [ self._convert_forecast_data(forecast_data) for forecast_data in self.coordinator.data.forecast_timestamps ]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/meteo_lt/weather.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/nederlandse_spoorwegen/coordinator.py
"""DataUpdateCoordinator for Nederlandse Spoorwegen.""" from __future__ import annotations from dataclasses import dataclass from datetime import datetime, timedelta import logging from ns_api import NSAPI, Trip from requests.exceptions import ConnectionError, HTTPError, Timeout from homeassistant.config_entries import ConfigEntry, ConfigSubentry from homeassistant.const import CONF_API_KEY, CONF_NAME from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import ( AMS_TZ, CONF_FROM, CONF_TIME, CONF_TO, CONF_VIA, DOMAIN, SCAN_INTERVAL, ) _LOGGER = logging.getLogger(__name__) def _current_time_nl(tomorrow: bool = False) -> datetime: """Return current time for today or tomorrow in Europe/Amsterdam timezone.""" now = dt_util.now(AMS_TZ) if tomorrow: now = now + timedelta(days=1) return now def _format_time(dt: datetime) -> str: """Format datetime to NS API format (DD-MM-YYYY HH:MM).""" return dt.strftime("%d-%m-%Y %H:%M") type NSConfigEntry = ConfigEntry[dict[str, NSDataUpdateCoordinator]] @dataclass class NSRouteResult: """Data class for Nederlandse Spoorwegen API results.""" trips: list[Trip] first_trip: Trip | None = None next_trip: Trip | None = None class NSDataUpdateCoordinator(DataUpdateCoordinator[NSRouteResult]): """Class to manage fetching Nederlandse Spoorwegen data from the API for a single route.""" def __init__( self, hass: HomeAssistant, config_entry: NSConfigEntry, route_id: str, subentry: ConfigSubentry, ) -> None: """Initialize the coordinator for a specific route.""" super().__init__( hass, _LOGGER, name=f"{DOMAIN}_{route_id}", update_interval=SCAN_INTERVAL, config_entry=config_entry, ) self.id = route_id self.nsapi = NSAPI(config_entry.data[CONF_API_KEY]) self.name = subentry.data[CONF_NAME] self.departure = subentry.data[CONF_FROM] self.destination = subentry.data[CONF_TO] self.via = subentry.data.get(CONF_VIA) self.departure_time = subentry.data.get(CONF_TIME) # str | None async def _async_update_data(self) -> NSRouteResult: """Fetch data from NS API for this specific route.""" trips: list[Trip] = [] first_trip: Trip | None = None next_trip: Trip | None = None try: trips = await self._get_trips( self.departure, self.destination, self.via, departure_time=self.departure_time, ) except (ConnectionError, Timeout, HTTPError, ValueError) as err: # Surface API failures to Home Assistant so the entities become unavailable raise UpdateFailed(f"API communication error: {err}") from err # Filter out trips that have already departed (trips are already sorted) future_trips = self._remove_trips_in_the_past(trips) # If a specific time is configured, filter to only show trips at or after that time if self.departure_time: reference_time = self._get_time_from_route(self.departure_time) future_trips = self._filter_trips_at_or_after_time( future_trips, reference_time ) # Process trips to find current and next departure first_trip, next_trip = self._get_first_and_next_trips(future_trips) return NSRouteResult( trips=trips, first_trip=first_trip, next_trip=next_trip, ) def _get_time_from_route(self, time_str: str | None) -> datetime: """Convert time string to datetime with automatic rollover to tomorrow if needed.""" if not time_str: return _current_time_nl() if ( isinstance(time_str, str) and len(time_str.split(":")) in (2, 3) and " " not in time_str ): # Parse time-only string (HH:MM or HH:MM:SS) time_only = time_str[:5] # Take HH:MM only hours, minutes = map(int, time_only.split(":")) # Create datetime with today's date and the specified time now = _current_time_nl() result_dt = now.replace(hour=hours, minute=minutes, second=0, microsecond=0) # If the time is more than 1 hour in the past, assume user meant tomorrow if (now - result_dt).total_seconds() > 3600: result_dt = _current_time_nl(tomorrow=True).replace( hour=hours, minute=minutes, second=0, microsecond=0 ) return result_dt # Fallback: use current date and time return _current_time_nl() async def _get_trips( self, departure: str, destination: str, via: str | None = None, departure_time: str | None = None, ) -> list[Trip]: """Get trips from NS API, sorted by departure time.""" # Convert time to datetime with rollover logic, then format for API reference_time = self._get_time_from_route(departure_time) time_str = _format_time(reference_time) trips = await self.hass.async_add_executor_job( self.nsapi.get_trips, time_str, # trip_time departure, # departure via, # via destination, # destination True, # exclude_high_speed 0, # year_card 2, # max_number_of_transfers ) if not trips: return [] return self._sort_trips_by_departure(trips) def _sort_trips_by_departure(self, trips: list[Trip]) -> list[Trip]: """Sort trips by departure time (actual or planned).""" return sorted( trips, key=lambda trip: ( trip.departure_time_actual if trip.departure_time_actual is not None else trip.departure_time_planned if trip.departure_time_planned is not None else _current_time_nl() ), ) def _get_first_and_next_trips( self, trips: list[Trip] ) -> tuple[Trip | None, Trip | None]: """Process trips to find the first and next departure.""" if not trips: return None, None # First trip is the earliest future trip first_trip = trips[0] # Find next trip with different departure time next_trip = self._find_next_trip(trips, first_trip) return first_trip, next_trip def _remove_trips_in_the_past(self, trips: list[Trip]) -> list[Trip]: """Filter out trips that have already departed.""" # Compare against Dutch local time to align with ns_api timezone handling now = _current_time_nl() future_trips = [] for trip in trips: departure_time = ( trip.departure_time_actual if trip.departure_time_actual is not None else trip.departure_time_planned ) if departure_time is not None and ( departure_time.tzinfo is None or departure_time.tzinfo.utcoffset(departure_time) is None ): # Make naive datetimes timezone-aware using current reference tz departure_time = departure_time.replace(tzinfo=now.tzinfo) if departure_time and departure_time > now: future_trips.append(trip) return future_trips def _filter_trips_at_or_after_time( self, trips: list[Trip], reference_time: datetime ) -> list[Trip]: """Filter trips to only those at or after the reference time (ignoring date). The API returns trips spanning multiple days, so we simply filter by time component to show only trips at or after the configured time. """ filtered_trips = [] ref_time_only = reference_time.time() for trip in trips: departure_time = ( trip.departure_time_actual if trip.departure_time_actual is not None else trip.departure_time_planned ) if departure_time is None: continue # Make naive datetimes timezone-aware if needed if ( departure_time.tzinfo is None or departure_time.tzinfo.utcoffset(departure_time) is None ): departure_time = departure_time.replace(tzinfo=reference_time.tzinfo) # Compare only the time component, ignoring the date trip_time_only = departure_time.time() if trip_time_only >= ref_time_only: filtered_trips.append(trip) return filtered_trips def _find_next_trip( self, future_trips: list[Trip], first_trip: Trip ) -> Trip | None: """Find the next trip with a different departure time than the first trip.""" next_trip = None if len(future_trips) > 1: first_time = ( first_trip.departure_time_actual if first_trip.departure_time_actual is not None else first_trip.departure_time_planned ) for trip in future_trips[1:]: trip_time = ( trip.departure_time_actual if trip.departure_time_actual is not None else trip.departure_time_planned ) if trip_time and first_time and trip_time > first_time: next_trip = trip break return next_trip
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nederlandse_spoorwegen/coordinator.py", "license": "Apache License 2.0", "lines": 231, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/niko_home_control/scene.py
"""Scene Platform for Niko Home Control.""" from __future__ import annotations from typing import Any from homeassistant.components.scene import BaseScene from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import NikoHomeControlConfigEntry from .entity import NikoHomeControlEntity async def async_setup_entry( hass: HomeAssistant, entry: NikoHomeControlConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Niko Home Control scene entry.""" controller = entry.runtime_data async_add_entities( NikoHomeControlScene(scene, controller, entry.entry_id) for scene in controller.scenes ) class NikoHomeControlScene(NikoHomeControlEntity, BaseScene): """Representation of a Niko Home Control Scene.""" _attr_name = None async def _async_activate(self, **kwargs: Any) -> None: """Activate scene. Try to get entities into requested state.""" await self._action.activate() def update_state(self) -> None: """Update HA state.""" self._async_record_activation()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/niko_home_control/scene.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/nintendo_parental_controls/config_flow.py
"""Config flow for the Nintendo Switch parental controls integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import TYPE_CHECKING, Any from pynintendoauth.exceptions import HttpException, InvalidSessionTokenException from pynintendoparental import Authenticator from pynintendoparental.api import Api import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_TOKEN from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import APP_SETUP_URL, CONF_SESSION_TOKEN, DOMAIN _LOGGER = logging.getLogger(__name__) class NintendoConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Nintendo Switch parental controls.""" def __init__(self) -> None: """Initialize a new config flow instance.""" self.auth: Authenticator | None = None async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors = {} if self.auth is None: self.auth = Authenticator(client_session=async_get_clientsession(self.hass)) if user_input is not None: nintendo_api = Api( self.auth, self.hass.config.time_zone, self.hass.config.language ) try: await self.auth.async_complete_login(user_input[CONF_API_TOKEN]) except ValueError, InvalidSessionTokenException, HttpException: errors["base"] = "invalid_auth" else: if TYPE_CHECKING: assert self.auth.account_id await self.async_set_unique_id(self.auth.account_id) self._abort_if_unique_id_configured() try: if "base" not in errors: await nintendo_api.async_get_account_devices() except HttpException as err: if err.status_code == 404: return self.async_abort( reason="no_devices_found", description_placeholders={"more_info_url": APP_SETUP_URL}, ) errors["base"] = "cannot_connect" else: if "base" not in errors: return self.async_create_entry( title=self.auth.account_id, data={ CONF_SESSION_TOKEN: self.auth.session_token, }, ) return self.async_show_form( step_id="user", description_placeholders={"link": self.auth.login_url}, data_schema=vol.Schema({vol.Required(CONF_API_TOKEN): str}), errors=errors, ) async def async_step_reauth( self, user_input: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauthentication on an API error.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauth dialog.""" errors: dict[str, str] = {} reauth_entry = self._get_reauth_entry() if self.auth is None: self.auth = Authenticator(client_session=async_get_clientsession(self.hass)) if user_input is not None: try: await self.auth.async_complete_login(user_input[CONF_API_TOKEN]) except ValueError, InvalidSessionTokenException, HttpException: errors["base"] = "invalid_auth" else: return self.async_update_reload_and_abort( reauth_entry, data={ **reauth_entry.data, CONF_SESSION_TOKEN: self.auth.session_token, }, ) return self.async_show_form( step_id="reauth_confirm", description_placeholders={"link": self.auth.login_url}, data_schema=vol.Schema({vol.Required(CONF_API_TOKEN): str}), errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/config_flow.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nintendo_parental_controls/const.py
"""Constants for the Nintendo Switch parental controls integration.""" DOMAIN = "nintendo_parental_controls" CONF_UPDATE_INTERVAL = "update_interval" CONF_SESSION_TOKEN = "session_token" BEDTIME_ALARM_MIN = "16:00" BEDTIME_ALARM_MAX = "23:00" BEDTIME_ALARM_DISABLE = "00:00" BEDTIME_END_TIME_MIN = "05:00" BEDTIME_END_TIME_MAX = "09:00" APP_SETUP_URL = ( "https://www.nintendo.com/my/support/switch/parentalcontrols/app/setup.html" ) ATTR_BONUS_TIME = "bonus_time"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/const.py", "license": "Apache License 2.0", "lines": 13, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nintendo_parental_controls/coordinator.py
"""Nintendo parental controls data coordinator.""" from __future__ import annotations from datetime import timedelta import logging from pynintendoauth.exceptions import ( HttpException, InvalidOAuthConfigurationException, InvalidSessionTokenException, ) from pynintendoparental import Authenticator, NintendoParental from pynintendoparental.exceptions import NoDevicesFoundException from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN type NintendoParentalControlsConfigEntry = ConfigEntry[NintendoUpdateCoordinator] _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(seconds=60) class NintendoUpdateCoordinator(DataUpdateCoordinator[None]): """Nintendo data update coordinator.""" config_entry: NintendoParentalControlsConfigEntry def __init__( self, hass: HomeAssistant, authenticator: Authenticator, config_entry: NintendoParentalControlsConfigEntry, ) -> None: """Initialize update coordinator.""" super().__init__( hass=hass, logger=_LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, config_entry=config_entry, ) self.api = NintendoParental( authenticator, hass.config.time_zone, hass.config.language ) async def _async_update_data(self) -> None: """Update data from Nintendo's API.""" try: return await self.api.update() except InvalidOAuthConfigurationException as err: raise ConfigEntryError( err, translation_domain=DOMAIN, translation_key="invalid_auth" ) from err except NoDevicesFoundException as err: raise ConfigEntryError( translation_domain=DOMAIN, translation_key="no_devices_found", ) from err except InvalidSessionTokenException as err: _LOGGER.debug("Session token invalid, will renew on next update") raise UpdateFailed from err except HttpException as err: if err.error_code == "update_required": raise ConfigEntryError( translation_domain=DOMAIN, translation_key="update_required", ) from err raise UpdateFailed(retry_after=900) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/coordinator.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nintendo_parental_controls/entity.py
"""Base entity definition for Nintendo parental controls.""" from __future__ import annotations from pynintendoparental.device import Device from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import NintendoUpdateCoordinator class NintendoDevice(CoordinatorEntity[NintendoUpdateCoordinator]): """Represent a Nintendo Switch.""" _attr_has_entity_name = True def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, key: str ) -> None: """Initialize.""" super().__init__(coordinator) self._device = device self._attr_unique_id = f"{device.device_id}_{key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.device_id)}, manufacturer="Nintendo", name=device.name, sw_version=device.extra["firmwareVersion"]["displayedVersion"], model=device.model, model_id=device.generation, serial_number=device.extra["serialNumber"], ) async def async_added_to_hass(self) -> None: """When entity is loaded.""" await super().async_added_to_hass() self._device.add_device_callback(self.async_write_ha_state) async def async_will_remove_from_hass(self) -> None: """When will be removed from HASS.""" self._device.remove_device_callback(self.async_write_ha_state) await super().async_will_remove_from_hass()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/entity.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/nintendo_parental_controls/number.py
"""Number platform for Nintendo Parental controls.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from enum import StrEnum from typing import Any from homeassistant.components.number import ( NumberEntity, NumberEntityDescription, NumberMode, ) from homeassistant.const import UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import NintendoParentalControlsConfigEntry, NintendoUpdateCoordinator from .entity import Device, NintendoDevice PARALLEL_UPDATES = 1 class NintendoParentalNumber(StrEnum): """Store keys for Nintendo Parental numbers.""" TODAY_MAX_SCREENTIME = "today_max_screentime" @dataclass(kw_only=True, frozen=True) class NintendoParentalControlsNumberEntityDescription(NumberEntityDescription): """Description for Nintendo Parental number entities.""" value_fn: Callable[[Device], int | float | None] set_native_value_fn: Callable[[Device, float], Coroutine[Any, Any, None]] NUMBER_DESCRIPTIONS: tuple[NintendoParentalControlsNumberEntityDescription, ...] = ( NintendoParentalControlsNumberEntityDescription( key=NintendoParentalNumber.TODAY_MAX_SCREENTIME, translation_key=NintendoParentalNumber.TODAY_MAX_SCREENTIME, native_min_value=-1, native_step=1, native_max_value=360, native_unit_of_measurement=UnitOfTime.MINUTES, mode=NumberMode.BOX, set_native_value_fn=lambda device, value: device.update_max_daily_playtime( minutes=value ), value_fn=lambda device: device.limit_time, ), ) async def async_setup_entry( hass: HomeAssistant, entry: NintendoParentalControlsConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up number platform.""" async_add_devices( NintendoParentalControlsNumberEntity(entry.runtime_data, device, entity) for device in entry.runtime_data.api.devices.values() for entity in NUMBER_DESCRIPTIONS ) class NintendoParentalControlsNumberEntity(NintendoDevice, NumberEntity): """Represent a Nintendo Parental number entity.""" entity_description: NintendoParentalControlsNumberEntityDescription def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, description: NintendoParentalControlsNumberEntityDescription, ) -> None: """Initialize the time entity.""" super().__init__(coordinator=coordinator, device=device, key=description.key) self.entity_description = description @property def native_value(self) -> float | None: """Return the state of the entity.""" return self.entity_description.value_fn(self._device) async def async_set_native_value(self, value: float) -> None: """Update entity state.""" await self.entity_description.set_native_value_fn(self._device, value)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/number.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nintendo_parental_controls/sensor.py
"""Sensor platform for Nintendo parental controls.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime from enum import StrEnum from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import NintendoParentalControlsConfigEntry, NintendoUpdateCoordinator from .entity import Device, NintendoDevice # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 class NintendoParentalControlsSensor(StrEnum): """Store keys for Nintendo parental controls sensors.""" PLAYING_TIME = "playing_time" TIME_REMAINING = "time_remaining" TIME_EXTENDED = "time_extended" @dataclass(kw_only=True, frozen=True) class NintendoParentalControlsSensorEntityDescription(SensorEntityDescription): """Description for Nintendo parental controls sensor entities.""" value_fn: Callable[[Device], datetime | int | float | None] available_fn: Callable[[Device], bool] = lambda device: True SENSOR_DESCRIPTIONS: tuple[NintendoParentalControlsSensorEntityDescription, ...] = ( NintendoParentalControlsSensorEntityDescription( key=NintendoParentalControlsSensor.PLAYING_TIME, translation_key=NintendoParentalControlsSensor.PLAYING_TIME, native_unit_of_measurement=UnitOfTime.MINUTES, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda device: device.today_playing_time, ), NintendoParentalControlsSensorEntityDescription( key=NintendoParentalControlsSensor.TIME_REMAINING, translation_key=NintendoParentalControlsSensor.TIME_REMAINING, native_unit_of_measurement=UnitOfTime.MINUTES, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda device: device.today_time_remaining, ), NintendoParentalControlsSensorEntityDescription( key=NintendoParentalControlsSensor.TIME_EXTENDED, translation_key=NintendoParentalControlsSensor.TIME_EXTENDED, native_unit_of_measurement=UnitOfTime.MINUTES, device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda device: device.extra_playing_time, available_fn=lambda device: device.extra_playing_time is not None, ), ) async def async_setup_entry( hass: HomeAssistant, entry: NintendoParentalControlsConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up the sensor platform.""" async_add_devices( NintendoParentalControlsSensorEntity(entry.runtime_data, device, sensor) for device in entry.runtime_data.api.devices.values() for sensor in SENSOR_DESCRIPTIONS ) class NintendoParentalControlsSensorEntity(NintendoDevice, SensorEntity): """Represent a single sensor.""" entity_description: NintendoParentalControlsSensorEntityDescription def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, description: NintendoParentalControlsSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator=coordinator, device=device, key=description.key) self.entity_description = description @property def native_value(self) -> datetime | int | float | None: """Return the native value.""" return self.entity_description.value_fn(self._device) @property def available(self) -> bool: """Return if the sensor is available.""" return super().available and self.entity_description.available_fn(self._device)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/sensor.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nintendo_parental_controls/services.py
"""Services for Nintendo Parental integration.""" from enum import StrEnum import logging import voluptuous as vol from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from .const import ATTR_BONUS_TIME, DOMAIN from .coordinator import NintendoParentalControlsConfigEntry _LOGGER = logging.getLogger(__name__) class NintendoParentalServices(StrEnum): """Store keys for Nintendo Parental services.""" ADD_BONUS_TIME = "add_bonus_time" @callback def async_setup_services( hass: HomeAssistant, ): """Set up the Nintendo Parental services.""" hass.services.async_register( domain=DOMAIN, service=NintendoParentalServices.ADD_BONUS_TIME, service_func=async_add_bonus_time, schema=vol.Schema( { vol.Required(ATTR_DEVICE_ID): cv.string, vol.Required(ATTR_BONUS_TIME): vol.All(int, vol.Range(min=5, max=30)), } ), ) def _get_nintendo_device_id(dev: dr.DeviceEntry) -> str | None: """Get the Nintendo device ID from a device entry.""" for identifier in dev.identifiers: if identifier[0] == DOMAIN: return identifier[1].split("_")[-1] return None async def async_add_bonus_time(call: ServiceCall) -> None: """Add bonus time to a device.""" config_entry: NintendoParentalControlsConfigEntry | None data = call.data device_id: str = data[ATTR_DEVICE_ID] bonus_time: int = data[ATTR_BONUS_TIME] device = dr.async_get(call.hass).async_get(device_id) if device is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="device_not_found", ) for entry_id in device.config_entries: config_entry = call.hass.config_entries.async_get_entry(entry_id) if config_entry is not None and config_entry.domain == DOMAIN: break nintendo_device_id = _get_nintendo_device_id(device) if config_entry and nintendo_device_id: return await config_entry.runtime_data.api.devices[ nintendo_device_id ].add_extra_time(bonus_time) raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/services.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nintendo_parental_controls/switch.py
"""Switch platform for Nintendo Parental.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from enum import StrEnum from typing import Any from pynintendoparental.enum import RestrictionMode from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, SwitchEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import NintendoParentalControlsConfigEntry, NintendoUpdateCoordinator from .entity import Device, NintendoDevice PARALLEL_UPDATES = 1 class NintendoParentalSwitch(StrEnum): """Store keys for Nintendo Parental Controls switches.""" SUSPEND_SOFTWARE = "suspend_software" @dataclass(kw_only=True, frozen=True) class NintendoParentalControlsSwitchEntityDescription(SwitchEntityDescription): """Description for Nintendo Parental Controls switch entities.""" is_on: Callable[[Device], bool | None] turn_on_fn: Callable[[Device], Coroutine[Any, Any, None]] turn_off_fn: Callable[[Device], Coroutine[Any, Any, None]] SWITCH_DESCRIPTIONS: tuple[NintendoParentalControlsSwitchEntityDescription, ...] = ( NintendoParentalControlsSwitchEntityDescription( key=NintendoParentalSwitch.SUSPEND_SOFTWARE, translation_key=NintendoParentalSwitch.SUSPEND_SOFTWARE, device_class=SwitchDeviceClass.SWITCH, is_on=lambda device: device.forced_termination_mode, turn_off_fn=lambda device: device.set_restriction_mode(RestrictionMode.ALARM), turn_on_fn=lambda device: device.set_restriction_mode( RestrictionMode.FORCED_TERMINATION ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: NintendoParentalControlsConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform.""" async_add_devices( NintendoParentalControlsSwitchEntity(entry.runtime_data, device, switch) for device in entry.runtime_data.api.devices.values() for switch in SWITCH_DESCRIPTIONS ) class NintendoParentalControlsSwitchEntity(NintendoDevice, SwitchEntity): """Represent a single switch.""" entity_description: NintendoParentalControlsSwitchEntityDescription def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, description: NintendoParentalControlsSwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator=coordinator, device=device, key=description.key) self.entity_description = description @property def is_on(self) -> bool | None: """Return entity state.""" return self.entity_description.is_on(self._device) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.entity_description.turn_on_fn(self._device) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.entity_description.turn_off_fn(self._device)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/switch.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/nintendo_parental_controls/time.py
"""Time platform for Nintendo parental controls.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from datetime import time from enum import StrEnum import logging from typing import Any from pynintendoparental.exceptions import BedtimeOutOfRangeError from homeassistant.components.time import TimeEntity, TimeEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import ( BEDTIME_ALARM_DISABLE, BEDTIME_ALARM_MAX, BEDTIME_ALARM_MIN, BEDTIME_END_TIME_MAX, BEDTIME_END_TIME_MIN, DOMAIN, ) from .coordinator import NintendoParentalControlsConfigEntry, NintendoUpdateCoordinator from .entity import Device, NintendoDevice _LOGGER = logging.getLogger(__name__) # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 1 class NintendoParentalControlsTime(StrEnum): """Store keys for Nintendo Parental time.""" BEDTIME_ALARM = "bedtime_alarm" BEDTIME_END_TIME = "bedtime_end_time" @dataclass(kw_only=True, frozen=True) class NintendoParentalControlsTimeEntityDescription(TimeEntityDescription): """Description for Nintendo Parental time entities.""" value_fn: Callable[[Device], time | None] set_value_fn: Callable[[Device, time], Coroutine[Any, Any, None]] TIME_DESCRIPTIONS: tuple[NintendoParentalControlsTimeEntityDescription, ...] = ( NintendoParentalControlsTimeEntityDescription( key=NintendoParentalControlsTime.BEDTIME_ALARM, translation_key=NintendoParentalControlsTime.BEDTIME_ALARM, value_fn=lambda device: device.bedtime_alarm, set_value_fn=lambda device, value: device.set_bedtime_alarm(value=value), ), NintendoParentalControlsTimeEntityDescription( key=NintendoParentalControlsTime.BEDTIME_END_TIME, translation_key=NintendoParentalControlsTime.BEDTIME_END_TIME, value_fn=lambda device: device.bedtime_end, set_value_fn=lambda device, value: device.set_bedtime_end_time(value=value), ), ) async def async_setup_entry( hass: HomeAssistant, entry: NintendoParentalControlsConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up the time platform.""" async_add_devices( NintendoParentalControlsTimeEntity(entry.runtime_data, device, entity) for device in entry.runtime_data.api.devices.values() for entity in TIME_DESCRIPTIONS ) class NintendoParentalControlsTimeEntity(NintendoDevice, TimeEntity): """Represent a single time entity.""" entity_description: NintendoParentalControlsTimeEntityDescription def __init__( self, coordinator: NintendoUpdateCoordinator, device: Device, description: NintendoParentalControlsTimeEntityDescription, ) -> None: """Initialize the time entity.""" super().__init__(coordinator=coordinator, device=device, key=description.key) self.entity_description = description @property def native_value(self) -> time | None: """Return the time.""" return self.entity_description.value_fn(self._device) async def async_set_value(self, value: time) -> None: """Update the value.""" try: await self.entity_description.set_value_fn(self._device, value) except BedtimeOutOfRangeError as exc: if ( self.entity_description.key == NintendoParentalControlsTime.BEDTIME_END_TIME ): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="bedtime_end_time_out_of_range", translation_placeholders={ "value": value.strftime("%H:%M"), "bedtime_end_time_max": BEDTIME_END_TIME_MAX, "bedtime_end_time_min": BEDTIME_END_TIME_MIN, "bedtime_alarm_disable": BEDTIME_ALARM_DISABLE, }, ) from exc raise ServiceValidationError( translation_domain=DOMAIN, translation_key="bedtime_alarm_out_of_range", translation_placeholders={ "value": value.strftime("%H:%M"), "bedtime_alarm_max": BEDTIME_ALARM_MAX, "bedtime_alarm_min": BEDTIME_ALARM_MIN, "bedtime_alarm_disable": BEDTIME_ALARM_DISABLE, }, ) from exc
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nintendo_parental_controls/time.py", "license": "Apache License 2.0", "lines": 105, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/octoprint/number.py
"""Support for OctoPrint number entities.""" from __future__ import annotations import logging from pyoctoprintapi import OctoprintClient from homeassistant.components.number import NumberDeviceClass, NumberEntity, NumberMode from homeassistant.config_entries import ConfigEntry from homeassistant.const import UnitOfTemperature from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import OctoprintDataUpdateCoordinator from .const import DOMAIN _LOGGER = logging.getLogger(__name__) def is_bed(tool_name: str) -> bool: """Return True if the tool name indicates a bed.""" return tool_name == "bed" def is_extruder(tool_name: str) -> bool: """Return True if the tool name indicates an extruder.""" return tool_name.startswith("tool") and tool_name[4:].isdigit() def is_first_extruder(tool_name: str) -> bool: """Return True if the tool name indicates the first extruder.""" return tool_name == "tool0" async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the OctoPrint number entities.""" coordinator: OctoprintDataUpdateCoordinator = hass.data[DOMAIN][ config_entry.entry_id ]["coordinator"] client: OctoprintClient = hass.data[DOMAIN][config_entry.entry_id]["client"] device_id = config_entry.unique_id assert device_id is not None known_tools = set() @callback def async_add_tool_numbers() -> None: if not coordinator.data["printer"]: return new_numbers: list[OctoPrintTemperatureNumber] = [] for tool in coordinator.data["printer"].temperatures: if ( is_extruder(tool.name) or is_bed(tool.name) ) and tool.name not in known_tools: assert device_id is not None known_tools.add(tool.name) new_numbers.append( OctoPrintTemperatureNumber( coordinator, client, tool.name, device_id, ) ) async_add_entities(new_numbers) config_entry.async_on_unload(coordinator.async_add_listener(async_add_tool_numbers)) if coordinator.data["printer"]: async_add_tool_numbers() class OctoPrintTemperatureNumber( CoordinatorEntity[OctoprintDataUpdateCoordinator], NumberEntity ): """Representation of an OctoPrint temperature setter entity.""" _attr_has_entity_name = True _attr_native_unit_of_measurement = UnitOfTemperature.CELSIUS _attr_native_min_value = 0 _attr_native_max_value = 300 _attr_native_step = 1 _attr_mode = NumberMode.BOX _attr_device_class = NumberDeviceClass.TEMPERATURE def __init__( self, coordinator: OctoprintDataUpdateCoordinator, client: OctoprintClient, tool: str, device_id: str, ) -> None: """Initialize a new OctoPrint temperature number entity.""" super().__init__(coordinator) self._api_tool = tool self._attr_device_info = coordinator.device_info self._attr_unique_id = f"{device_id}_{tool}_temperature" self._client = client self._device_id = device_id if is_bed(tool): self._attr_translation_key = "bed_temperature" elif is_first_extruder(tool): self._attr_translation_key = "extruder_temperature" else: self._attr_translation_key = "extruder_n_temperature" self._attr_translation_placeholders = {"n": tool[4:]} @property def native_value(self) -> float | None: """Return the current target temperature.""" if not self.coordinator.data["printer"]: return None for tool in self.coordinator.data["printer"].temperatures: if tool.name == self._api_tool and tool.target_temp is not None: return tool.target_temp return None async def async_set_native_value(self, value: float) -> None: """Set the target temperature.""" try: if is_bed(self._api_tool): await self._client.set_bed_temperature(int(value)) elif is_extruder(self._api_tool): await self._client.set_tool_temperature(self._api_tool, int(value)) except Exception as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="error_setting_temperature", translation_placeholders={ "tool": self._api_tool, }, ) from err # Request coordinator update to reflect the change await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/octoprint/number.py", "license": "Apache License 2.0", "lines": 117, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/openrgb/config_flow.py
"""Config flow for the OpenRGB integration.""" from __future__ import annotations import logging from typing import Any from openrgb import OpenRGBClient import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PORT from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from .const import CONNECTION_ERRORS, DEFAULT_CLIENT_NAME, DEFAULT_PORT, DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_NAME): str, vol.Required(CONF_HOST): str, vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) STEP_RECONFIGURE_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, } ) async def validate_input(hass: HomeAssistant, host: str, port: int) -> None: """Validate the user input allows us to connect.""" def _try_connect(host: str, port: int) -> None: client = OpenRGBClient(host, port, DEFAULT_CLIENT_NAME) client.disconnect() await hass.async_add_executor_job(_try_connect, host, port) class OpenRGBConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for OpenRGB.""" async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the OpenRGB SDK Server.""" reconfigure_entry = self._get_reconfigure_entry() errors: dict[str, str] = {} if user_input is not None: host = user_input[CONF_HOST] port = user_input[CONF_PORT] # Prevent duplicate entries self._async_abort_entries_match({CONF_HOST: host, CONF_PORT: port}) try: await validate_input(self.hass, host, port) except CONNECTION_ERRORS: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception( "Unknown error while connecting to OpenRGB SDK server at %s", f"{host}:{port}", ) errors["base"] = "unknown" else: return self.async_update_reload_and_abort( reconfigure_entry, data_updates={CONF_HOST: host, CONF_PORT: port}, ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( data_schema=STEP_RECONFIGURE_DATA_SCHEMA, suggested_values={ CONF_HOST: reconfigure_entry.data[CONF_HOST], CONF_PORT: reconfigure_entry.data[CONF_PORT], }, ), 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: name = user_input[CONF_NAME] host = user_input[CONF_HOST] port = user_input[CONF_PORT] # Prevent duplicate entries self._async_abort_entries_match({CONF_HOST: host, CONF_PORT: port}) try: await validate_input(self.hass, host, port) except CONNECTION_ERRORS: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception( "Unknown error while connecting to OpenRGB SDK server at %s", f"{host}:{port}", ) errors["base"] = "unknown" else: return self.async_create_entry( title=name, data={ CONF_NAME: name, CONF_HOST: host, CONF_PORT: port, }, ) 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, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openrgb/config_flow.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openrgb/const.py
"""Constants for the OpenRGB integration.""" from datetime import timedelta from enum import StrEnum import socket from openrgb.utils import ( ControllerParsingError, DeviceType, OpenRGBDisconnected, SDKVersionError, ) DOMAIN = "openrgb" UID_SEPARATOR = "||" # Defaults DEFAULT_PORT = 6742 DEFAULT_CLIENT_NAME = "Home Assistant" # Update interval SCAN_INTERVAL = timedelta(seconds=15) DEFAULT_COLOR = (255, 255, 255) DEFAULT_BRIGHTNESS = 255 OFF_COLOR = (0, 0, 0) class OpenRGBMode(StrEnum): """OpenRGB modes.""" OFF = "Off" STATIC = "Static" DIRECT = "Direct" CUSTOM = "Custom" EFFECT_OFF_OPENRGB_MODES = {OpenRGBMode.STATIC, OpenRGBMode.DIRECT, OpenRGBMode.CUSTOM} DEVICE_TYPE_ICONS: dict[DeviceType, str] = { DeviceType.MOTHERBOARD: "mdi:developer-board", DeviceType.DRAM: "mdi:memory", DeviceType.GPU: "mdi:expansion-card", DeviceType.COOLER: "mdi:fan", DeviceType.LEDSTRIP: "mdi:led-variant-on", DeviceType.KEYBOARD: "mdi:keyboard", DeviceType.MOUSE: "mdi:mouse", DeviceType.MOUSEMAT: "mdi:rug", DeviceType.HEADSET: "mdi:headset", DeviceType.HEADSET_STAND: "mdi:headset-dock", DeviceType.GAMEPAD: "mdi:gamepad-variant", DeviceType.SPEAKER: "mdi:speaker", DeviceType.STORAGE: "mdi:harddisk", DeviceType.CASE: "mdi:desktop-tower", DeviceType.MICROPHONE: "mdi:microphone", DeviceType.KEYPAD: "mdi:dialpad", } CONNECTION_ERRORS = ( ConnectionRefusedError, OpenRGBDisconnected, ControllerParsingError, TimeoutError, socket.gaierror, # DNS errors SDKVersionError, # The OpenRGB SDK server version is incompatible with the client )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openrgb/const.py", "license": "Apache License 2.0", "lines": 53, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openrgb/coordinator.py
"""DataUpdateCoordinator for OpenRGB.""" from __future__ import annotations import asyncio import logging from openrgb import OpenRGBClient from openrgb.orgb import Device from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.core import HomeAssistant from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( CONNECTION_ERRORS, DEFAULT_CLIENT_NAME, DOMAIN, SCAN_INTERVAL, UID_SEPARATOR, ) _LOGGER = logging.getLogger(__name__) type OpenRGBConfigEntry = ConfigEntry[OpenRGBCoordinator] class OpenRGBCoordinator(DataUpdateCoordinator[dict[str, Device]]): """Class to manage fetching OpenRGB data.""" client: OpenRGBClient def __init__( self, hass: HomeAssistant, config_entry: OpenRGBConfigEntry, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=SCAN_INTERVAL, config_entry=config_entry, request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=0.5, immediate=False ), ) self.host = config_entry.data[CONF_HOST] self.port = config_entry.data[CONF_PORT] self.entry_id = config_entry.entry_id self.server_address = f"{self.host}:{self.port}" self.client_lock = asyncio.Lock() config_entry.async_on_unload(self.async_client_disconnect) async def _async_setup(self) -> None: """Set up the coordinator by connecting to the OpenRGB SDK server.""" try: self.client = await self.hass.async_add_executor_job( OpenRGBClient, self.host, self.port, DEFAULT_CLIENT_NAME, ) except CONNECTION_ERRORS as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={ "server_address": self.server_address, "error": str(err), }, ) from err async def _async_update_data(self) -> dict[str, Device]: """Fetch data from OpenRGB.""" async with self.client_lock: try: await self.hass.async_add_executor_job(self._client_update) except CONNECTION_ERRORS as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={ "server_address": self.server_address, "error": str(err), }, ) from err # Return devices indexed by their key return {self._get_device_key(device): device for device in self.client.devices} def _client_update(self) -> None: try: self.client.update() except CONNECTION_ERRORS: # Try to reconnect once self.client.disconnect() self.client.connect() self.client.update() def _get_device_key(self, device: Device) -> str: """Build a stable device key. Note: the OpenRGB device.id is intentionally not used because it is just a positional index that can change when devices are added or removed. """ parts = ( self.entry_id, device.type.name, device.metadata.vendor or "none", device.metadata.description or "none", device.metadata.serial or "none", device.metadata.location or "none", ) # Double pipe is readable and is unlikely to appear in metadata return UID_SEPARATOR.join(parts) async def async_client_disconnect(self, *args) -> None: """Disconnect the OpenRGB client.""" if not hasattr(self, "client"): # If async_config_entry_first_refresh failed, client will not exist return async with self.client_lock: await self.hass.async_add_executor_job(self.client.disconnect) def get_client_protocol_version(self) -> str: """Get the OpenRGB client protocol version.""" return f"{self.client.protocol_version} (Protocol)" def get_device_name(self, device_key: str) -> str: """Get device name with suffix if there are duplicates.""" device = self.data[device_key] device_name = device.name devices_with_same_name = [ (key, dev) for key, dev in self.data.items() if dev.name == device_name ] if len(devices_with_same_name) == 1: return device_name # Sort duplicates by device.id devices_with_same_name.sort(key=lambda x: x[1].id) # Return name with numeric suffix based on the sorted order for idx, (key, _) in enumerate(devices_with_same_name, start=1): if key == device_key: return f"{device_name} {idx}" # Should never reach here, but just in case return device_name # pragma: no cover
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openrgb/coordinator.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/openrgb/light.py
"""OpenRGB light platform.""" from __future__ import annotations import asyncio from typing import Any from openrgb.orgb import Device from openrgb.utils import ModeColors, ModeData, RGBColor from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_EFFECT, ATTR_RGB_COLOR, EFFECT_OFF, ColorMode, LightEntity, LightEntityFeature, ) from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from homeassistant.util import slugify from homeassistant.util.color import color_hs_to_RGB, color_RGB_to_hsv from .const import ( CONNECTION_ERRORS, DEFAULT_BRIGHTNESS, DEFAULT_COLOR, DEVICE_TYPE_ICONS, DOMAIN, EFFECT_OFF_OPENRGB_MODES, OFF_COLOR, OpenRGBMode, ) from .coordinator import OpenRGBConfigEntry, OpenRGBCoordinator PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: OpenRGBConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the OpenRGB light platform.""" coordinator = config_entry.runtime_data known_device_keys: set[str] = set() def _check_device() -> None: """Add entities for newly discovered OpenRGB devices.""" nonlocal known_device_keys current_keys = set(coordinator.data.keys()) new_keys = current_keys - known_device_keys if new_keys: known_device_keys.update(new_keys) async_add_entities( [OpenRGBLight(coordinator, device_key) for device_key in new_keys] ) _check_device() config_entry.async_on_unload(coordinator.async_add_listener(_check_device)) class OpenRGBLight(CoordinatorEntity[OpenRGBCoordinator], LightEntity): """Representation of an OpenRGB light.""" _attr_has_entity_name = True _attr_name = None # Use the device name _attr_translation_key = "openrgb_light" _mode: str | None = None _supports_color_modes: list[str] _preferred_no_effect_mode: str _supports_off_mode: bool _supports_effects: bool _previous_brightness: int | None = None _previous_rgb_color: tuple[int, int, int] | None = None _previous_mode: str | None = None _update_events: list[asyncio.Event] = [] _effect_to_mode: dict[str, str] def __init__(self, coordinator: OpenRGBCoordinator, device_key: str) -> None: """Initialize the OpenRGB light.""" super().__init__(coordinator) self.device_key = device_key self._attr_unique_id = device_key device_name = coordinator.get_device_name(device_key) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device_key)}, name=device_name, manufacturer=self.device.metadata.vendor, model=f"{self.device.metadata.description} ({self.device.type.name})", sw_version=self.device.metadata.version, serial_number=self.device.metadata.serial, via_device=(DOMAIN, coordinator.entry_id), ) modes = [mode.name for mode in self.device.modes] if self.device.metadata.description == "ASRock Polychrome USB Device": # https://gitlab.com/CalcProgrammer1/OpenRGB/-/issues/5145 self._preferred_no_effect_mode = OpenRGBMode.STATIC else: # https://gitlab.com/CalcProgrammer1/OpenRGB/-/blob/c71cc4f18a54f83d388165ef2ab4c4ad3e980b89/RGBController/RGBController.cpp#L2075-2081 self._preferred_no_effect_mode = ( OpenRGBMode.DIRECT if OpenRGBMode.DIRECT in modes else OpenRGBMode.CUSTOM if OpenRGBMode.CUSTOM in modes else OpenRGBMode.STATIC ) # Determine if the device supports being turned off through modes self._supports_off_mode = OpenRGBMode.OFF in modes # Determine which modes supports color self._supports_color_modes = [ mode.name for mode in self.device.modes if check_if_mode_supports_color(mode) ] # Initialize effects from modes self._effect_to_mode = {} effects = [] for mode in modes: if mode != OpenRGBMode.OFF and mode not in EFFECT_OFF_OPENRGB_MODES: effect_name = slugify(mode) effects.append(effect_name) self._effect_to_mode[effect_name] = mode if len(effects) > 0: self._supports_effects = True self._attr_supported_features = LightEntityFeature.EFFECT self._attr_effect_list = [EFFECT_OFF, *effects] else: self._supports_effects = False self._attr_icon = DEVICE_TYPE_ICONS.get(self.device.type) self._update_attrs() @callback def _update_attrs(self) -> None: """Update the attributes based on the current device state.""" mode_data = self.device.modes[self.device.active_mode] mode = mode_data.name if mode == OpenRGBMode.OFF: mode = None mode_supports_colors = False else: mode_supports_colors = check_if_mode_supports_color(mode_data) color_mode = None rgb_color = None brightness = None on_by_color = True if mode_supports_colors: # Consider the first non-black LED color as the device color openrgb_off_color = RGBColor(*OFF_COLOR) openrgb_color = next( (color for color in self.device.colors if color != openrgb_off_color), openrgb_off_color, ) if openrgb_color == openrgb_off_color: on_by_color = False else: rgb_color = ( openrgb_color.red, openrgb_color.green, openrgb_color.blue, ) # Derive color and brightness from the scaled color hsv_color = color_RGB_to_hsv(*rgb_color) rgb_color = color_hs_to_RGB(hsv_color[0], hsv_color[1]) brightness = round(255.0 * (hsv_color[2] / 100.0)) elif mode is None: # If mode is Off, retain previous color mode to avoid changing the UI color_mode = self._attr_color_mode else: # If the current mode is not Off and does not support color, change to ON/OFF mode color_mode = ColorMode.ONOFF if not on_by_color: # If Off by color, retain previous color mode to avoid changing the UI color_mode = self._attr_color_mode if color_mode is None: # If color mode is still unknown, default to RGB color_mode = ColorMode.RGB if self._attr_brightness is not None and self._attr_brightness != brightness: self._previous_brightness = self._attr_brightness if self._attr_rgb_color is not None and self._attr_rgb_color != rgb_color: self._previous_rgb_color = self._attr_rgb_color if self._mode is not None and self._mode != mode: self._previous_mode = self._mode self._attr_color_mode = color_mode self._attr_supported_color_modes = {color_mode} self._attr_rgb_color = rgb_color self._attr_brightness = brightness if not self._supports_effects or mode is None: self._attr_effect = None elif mode in EFFECT_OFF_OPENRGB_MODES: self._attr_effect = EFFECT_OFF else: self._attr_effect = slugify(mode) self._mode = mode if mode is None: # If the mode is Off, the light is off self._attr_is_on = False else: self._attr_is_on = on_by_color @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" if self.available: self._update_attrs() super()._handle_coordinator_update() # Signal that the update has completed for all waiting events for event in self._update_events: event.set() self._update_events.clear() @property def available(self) -> bool: """Return if the light is available.""" return super().available and self.device_key in self.coordinator.data @property def device(self) -> Device: """Return the OpenRGB device.""" return self.coordinator.data[self.device_key] async def _async_refresh_data(self) -> None: """Request a data refresh from the coordinator and wait for it to complete.""" update_event = asyncio.Event() self._update_events.append(update_event) await self.coordinator.async_request_refresh() await update_event.wait() async def _async_apply_color( self, rgb_color: tuple[int, int, int], brightness: int ) -> None: """Apply the RGB color and brightness to the device.""" brightness_factor = brightness / 255.0 scaled_color = RGBColor( int(rgb_color[0] * brightness_factor), int(rgb_color[1] * brightness_factor), int(rgb_color[2] * brightness_factor), ) async with self.coordinator.client_lock: try: await self.hass.async_add_executor_job( self.device.set_color, scaled_color, True ) except CONNECTION_ERRORS as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={ "server_address": self.coordinator.server_address, "error": str(err), }, ) from err except ValueError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="openrgb_error", translation_placeholders={ "error": str(err), }, ) from err async def _async_apply_mode(self, mode: str) -> None: """Apply the given mode to the device.""" async with self.coordinator.client_lock: try: await self.hass.async_add_executor_job(self.device.set_mode, mode) except CONNECTION_ERRORS as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={ "server_address": self.coordinator.server_address, "error": str(err), }, ) from err except ValueError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="openrgb_error", translation_placeholders={ "error": str(err), }, ) from err async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" mode = None if ATTR_EFFECT in kwargs: effect = kwargs[ATTR_EFFECT] if self._attr_effect_list is None or effect not in self._attr_effect_list: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="unsupported_effect", translation_placeholders={ "effect": effect, "device_name": self.device.name, }, ) if effect == EFFECT_OFF: mode = self._preferred_no_effect_mode else: mode = self._effect_to_mode[effect] elif self._mode is None or ( self._attr_rgb_color is None and self._attr_brightness is None ): # Restore previous mode when turning on from Off mode or black color mode = self._previous_mode or self._preferred_no_effect_mode # Check if current or new mode supports colors if mode is None: # When not applying a new mode, check if the current mode supports color mode_supports_color = self._mode in self._supports_color_modes else: mode_supports_color = mode in self._supports_color_modes color_or_brightness_requested = ( ATTR_RGB_COLOR in kwargs or ATTR_BRIGHTNESS in kwargs ) if color_or_brightness_requested and not mode_supports_color: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="effect_no_color_support", translation_placeholders={ "effect": slugify(mode or self._mode or ""), "device_name": self.device.name, }, ) # Apply color even if switching from Off mode to a color-capable mode # because there is no guarantee that the device won't go back to black need_to_apply_color = color_or_brightness_requested or ( mode_supports_color and (self._attr_brightness is None or self._attr_rgb_color is None) ) # If color/brightness restoration require color support but mode doesn't support it, # switch to a color-capable mode if need_to_apply_color and not mode_supports_color: mode = self._preferred_no_effect_mode if mode is not None: await self._async_apply_mode(mode) if need_to_apply_color: brightness = None if ATTR_BRIGHTNESS in kwargs: brightness = kwargs[ATTR_BRIGHTNESS] elif self._attr_brightness is None: # Restore previous brightness when turning on brightness = self._previous_brightness if brightness is None: # Retain current brightness or use default if still None brightness = self._attr_brightness or DEFAULT_BRIGHTNESS color = None if ATTR_RGB_COLOR in kwargs: color = kwargs[ATTR_RGB_COLOR] elif self._attr_rgb_color is None: # Restore previous color when turning on color = self._previous_rgb_color if color is None: # Retain current color or use default if still None color = self._attr_rgb_color or DEFAULT_COLOR await self._async_apply_color(color, brightness) await self._async_refresh_data() async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" if self._supports_off_mode: await self._async_apply_mode(OpenRGBMode.OFF) else: # If the device does not support Off mode, set color to black await self._async_apply_color(OFF_COLOR, 0) await self._async_refresh_data() def check_if_mode_supports_color(mode: ModeData) -> bool: """Return True if the mode supports colors.""" return mode.color_mode == ModeColors.PER_LED
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openrgb/light.py", "license": "Apache License 2.0", "lines": 351, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/portainer/button.py
"""Support for Portainer buttons.""" from __future__ import annotations from abc import abstractmethod from collections.abc import Callable, Coroutine from dataclasses import dataclass from datetime import timedelta from typing import Any from pyportainer import Portainer from pyportainer.exceptions import ( PortainerAuthenticationError, PortainerConnectionError, PortainerTimeoutError, ) from homeassistant.components.button import ( ButtonDeviceClass, ButtonEntity, ButtonEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PortainerConfigEntry from .const import DOMAIN from .coordinator import ( PortainerContainerData, PortainerCoordinator, PortainerCoordinatorData, ) from .entity import PortainerContainerEntity, PortainerEndpointEntity PARALLEL_UPDATES = 1 @dataclass(frozen=True, kw_only=True) class PortainerButtonDescription(ButtonEntityDescription): """Class to describe a Portainer button entity.""" # Note to reviewer: I am keeping the third argument a str, in order to keep mypy happy :) press_action: Callable[ [Portainer, int, str], Coroutine[Any, Any, None], ] ENDPOINT_BUTTONS: tuple[PortainerButtonDescription, ...] = ( PortainerButtonDescription( key="images_prune", translation_key="images_prune", device_class=ButtonDeviceClass.RESTART, entity_category=EntityCategory.CONFIG, press_action=( lambda portainer, endpoint_id, _: portainer.images_prune( endpoint_id=endpoint_id, dangling=False, until=timedelta(days=0) ) ), ), ) CONTAINER_BUTTONS: tuple[PortainerButtonDescription, ...] = ( PortainerButtonDescription( key="restart", translation_key="restart_container", device_class=ButtonDeviceClass.RESTART, entity_category=EntityCategory.CONFIG, press_action=( lambda portainer, endpoint_id, container_id: portainer.restart_container( endpoint_id, container_id ) ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: PortainerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Portainer buttons.""" coordinator = entry.runtime_data def _async_add_new_endpoints(endpoints: list[PortainerCoordinatorData]) -> None: """Add new endpoint binary sensors.""" async_add_entities( PortainerEndpointButton( coordinator, entity_description, endpoint, ) for entity_description in ENDPOINT_BUTTONS for endpoint in endpoints ) def _async_add_new_containers( containers: list[tuple[PortainerCoordinatorData, PortainerContainerData]], ) -> None: """Add new container button sensors.""" async_add_entities( PortainerContainerButton( coordinator, entity_description, container, endpoint, ) for (endpoint, container) in containers for entity_description in CONTAINER_BUTTONS ) coordinator.new_endpoints_callbacks.append(_async_add_new_endpoints) coordinator.new_containers_callbacks.append(_async_add_new_containers) _async_add_new_endpoints( [ endpoint for endpoint in coordinator.data.values() if endpoint.id in coordinator.known_endpoints ] ) _async_add_new_containers( [ (endpoint, container) for endpoint in coordinator.data.values() for container in endpoint.containers.values() ] ) class PortainerBaseButton(ButtonEntity): """Common base for Portainer buttons. Basically to ensure the async_press logic isn't duplicated.""" entity_description: PortainerButtonDescription coordinator: PortainerCoordinator @abstractmethod async def _async_press_call(self) -> None: """Abstract method used per Portainer button class.""" async def async_press(self) -> None: """Trigger the Portainer button press service.""" try: await self._async_press_call() except PortainerConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect_no_details", ) from err except PortainerAuthenticationError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="invalid_auth_no_details", ) from err except PortainerTimeoutError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="timeout_connect_no_details", ) from err class PortainerEndpointButton(PortainerEndpointEntity, PortainerBaseButton): """Defines a Portainer endpoint button.""" entity_description: PortainerButtonDescription async def _async_press_call(self) -> None: """Call the endpoint button press action.""" await self.entity_description.press_action( self.coordinator.portainer, self.device_id, "" ) class PortainerContainerButton(PortainerContainerEntity, PortainerBaseButton): """Defines a Portainer button.""" entity_description: PortainerButtonDescription async def _async_press_call(self) -> None: """Call the container button press action.""" await self.entity_description.press_action( self.coordinator.portainer, self.endpoint_id, self.container_data.container.id, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/portainer/button.py", "license": "Apache License 2.0", "lines": 157, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/portainer/diagnostics.py
"""Diagnostics for the Portainer integration.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_API_TOKEN, CONF_URL from homeassistant.core import HomeAssistant from . import PortainerConfigEntry from .coordinator import PortainerCoordinator TO_REDACT = [CONF_API_TOKEN, CONF_URL] def _serialize_coordinator(coordinator: PortainerCoordinator) -> dict[str, Any]: """Serialize coordinator data into a JSON-safe structure.""" serialized_endpoints: list[dict[str, Any]] = [] for endpoint_id, endpoint_data in coordinator.data.items(): serialized_endpoints.append( { "id": endpoint_id, "name": endpoint_data.name, "endpoint": { "status": endpoint_data.endpoint.status, "url": endpoint_data.endpoint.url, "public_url": endpoint_data.endpoint.public_url, }, "containers": [ { "id": container.container.id, "names": list(container.container.names or []), "image": container.container.image, "state": container.container.state, "status": container.container.status, } for container in endpoint_data.containers.values() ], } ) return {"endpoints": serialized_endpoints} async def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: PortainerConfigEntry ) -> dict[str, Any]: """Return diagnostics for a Portainer config entry.""" return { "config_entry": async_redact_data(config_entry.as_dict(), TO_REDACT), "coordinator": _serialize_coordinator(config_entry.runtime_data), }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/portainer/diagnostics.py", "license": "Apache License 2.0", "lines": 43, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/portainer/sensor.py
"""Sensor platform for Portainer integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from homeassistant.components.sensor import ( EntityCategory, SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, StateType, ) from homeassistant.const import PERCENTAGE, UnitOfInformation from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import STACK_TYPE_COMPOSE, STACK_TYPE_KUBERNETES, STACK_TYPE_SWARM from .coordinator import ( PortainerConfigEntry, PortainerContainerData, PortainerStackData, ) from .entity import ( PortainerContainerEntity, PortainerCoordinatorData, PortainerEndpointEntity, PortainerStackEntity, ) PARALLEL_UPDATES = 1 @dataclass(frozen=True, kw_only=True) class PortainerContainerSensorEntityDescription(SensorEntityDescription): """Class to hold Portainer container sensor description.""" value_fn: Callable[[PortainerContainerData], StateType] @dataclass(frozen=True, kw_only=True) class PortainerEndpointSensorEntityDescription(SensorEntityDescription): """Class to hold Portainer endpoint sensor description.""" value_fn: Callable[[PortainerCoordinatorData], StateType] @dataclass(frozen=True, kw_only=True) class PortainerStackSensorEntityDescription(SensorEntityDescription): """Class to hold Portainer stack sensor description.""" value_fn: Callable[[PortainerStackData], StateType] CONTAINER_SENSORS: tuple[PortainerContainerSensorEntityDescription, ...] = ( PortainerContainerSensorEntityDescription( key="image", translation_key="image", value_fn=lambda data: data.container.image, ), PortainerContainerSensorEntityDescription( key="container_state", translation_key="container_state", value_fn=lambda data: data.container.state, device_class=SensorDeviceClass.ENUM, options=["running", "exited", "paused", "restarting", "created", "dead"], ), PortainerContainerSensorEntityDescription( key="memory_limit", translation_key="memory_limit", value_fn=lambda data: ( data.stats.memory_stats.limit if data.stats is not None else 0 ), device_class=SensorDeviceClass.DATA_SIZE, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEGABYTES, suggested_display_precision=1, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerContainerSensorEntityDescription( key="memory_usage", translation_key="memory_usage", value_fn=lambda data: ( data.stats.memory_stats.usage if data.stats is not None else 0 ), device_class=SensorDeviceClass.DATA_SIZE, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEGABYTES, suggested_display_precision=1, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerContainerSensorEntityDescription( key="memory_usage_percentage", translation_key="memory_usage_percentage", value_fn=lambda data: ( (data.stats.memory_stats.usage / data.stats.memory_stats.limit) * 100.0 if data.stats is not None and data.stats.memory_stats.limit > 0 and data.stats.memory_stats.usage > 0 else 0.0 ), native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, suggested_display_precision=2, state_class=SensorStateClass.MEASUREMENT, ), PortainerContainerSensorEntityDescription( key="cpu_usage_total", translation_key="cpu_usage_total", value_fn=lambda data: ( (total_delta / system_delta) * data.stats.cpu_stats.online_cpus * 100.0 if data.stats is not None and (prev := data.stats_pre) is not None and ( system_delta := ( data.stats.cpu_stats.system_cpu_usage - prev.cpu_stats.system_cpu_usage ) ) > 0 and ( total_delta := ( data.stats.cpu_stats.cpu_usage.total_usage - prev.cpu_stats.cpu_usage.total_usage ) ) >= 0 and data.stats.cpu_stats.online_cpus > 0 else 0.0 ), native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, suggested_display_precision=2, state_class=SensorStateClass.MEASUREMENT, ), ) ENDPOINT_SENSORS: tuple[PortainerEndpointSensorEntityDescription, ...] = ( PortainerEndpointSensorEntityDescription( key="api_version", translation_key="api_version", value_fn=lambda data: data.docker_version.api_version, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="kernel_version", translation_key="kernel_version", value_fn=lambda data: data.docker_version.kernel_version, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="operating_system", translation_key="operating_system", value_fn=lambda data: data.docker_info.os_type, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="operating_system_version", translation_key="operating_system_version", value_fn=lambda data: data.docker_info.os_version, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="docker_version", translation_key="docker_version", value_fn=lambda data: data.docker_info.server_version, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="architecture", translation_key="architecture", value_fn=lambda data: data.docker_info.architecture, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="containers_count", translation_key="containers_count", value_fn=lambda data: data.docker_info.containers, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="containers_running", translation_key="containers_running", value_fn=lambda data: data.docker_info.containers_running, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="containers_stopped", translation_key="containers_stopped", value_fn=lambda data: data.docker_info.containers_stopped, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="containers_paused", translation_key="containers_paused", value_fn=lambda data: data.docker_info.containers_paused, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="images_count", translation_key="images_count", value_fn=lambda data: data.docker_info.images, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="memory_total", translation_key="memory_total", value_fn=lambda data: data.docker_info.mem_total, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, ), PortainerEndpointSensorEntityDescription( key="cpu_total", translation_key="cpu_total", value_fn=lambda data: data.docker_info.ncpu, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, state_class=SensorStateClass.MEASUREMENT, ), PortainerEndpointSensorEntityDescription( key="container_disk_usage_reclaimable", translation_key="container_disk_usage_reclaimable", value_fn=lambda data: data.docker_system_df.container_disk_usage.reclaimable, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, ), PortainerEndpointSensorEntityDescription( key="container_disk_usage_total_size", translation_key="container_disk_usage_total_size", value_fn=lambda data: data.docker_system_df.container_disk_usage.total_size, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, ), PortainerEndpointSensorEntityDescription( key="image_disk_usage_reclaimable", translation_key="image_disk_usage_reclaimable", value_fn=lambda data: data.docker_system_df.image_disk_usage.reclaimable, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, ), PortainerEndpointSensorEntityDescription( key="image_disk_usage_total_size", translation_key="image_disk_usage_total_size", value_fn=lambda data: data.docker_system_df.image_disk_usage.total_size, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, ), PortainerEndpointSensorEntityDescription( key="volume_disk_usage_total", translation_key="volume_disk_usage_total_size", value_fn=lambda data: data.docker_system_df.volume_disk_usage.total_size, device_class=SensorDeviceClass.DATA_SIZE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfInformation.BYTES, suggested_unit_of_measurement=UnitOfInformation.MEBIBYTES, entity_category=EntityCategory.DIAGNOSTIC, ), ) STACK_SENSORS: tuple[PortainerStackSensorEntityDescription, ...] = ( PortainerStackSensorEntityDescription( key="stack_type", translation_key="stack_type", value_fn=lambda data: ( "swarm" if data.stack.type == STACK_TYPE_SWARM else "compose" if data.stack.type == STACK_TYPE_COMPOSE else "kubernetes" if data.stack.type == STACK_TYPE_KUBERNETES else None ), device_class=SensorDeviceClass.ENUM, options=["swarm", "compose", "kubernetes"], entity_category=EntityCategory.DIAGNOSTIC, ), PortainerStackSensorEntityDescription( key="stack_containers_count", translation_key="stack_containers_count", value_fn=lambda data: data.container_count, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, ), ) async def async_setup_entry( hass: HomeAssistant, entry: PortainerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Portainer sensors based on a config entry.""" coordinator = entry.runtime_data def _async_add_new_endpoints(endpoints: list[PortainerCoordinatorData]) -> None: """Add new endpoint sensor.""" async_add_entities( PortainerEndpointSensor( coordinator, entity_description, endpoint, ) for entity_description in ENDPOINT_SENSORS for endpoint in endpoints if entity_description.value_fn(endpoint) ) def _async_add_new_containers( containers: list[tuple[PortainerCoordinatorData, PortainerContainerData]], ) -> None: """Add new container sensors.""" async_add_entities( PortainerContainerSensor( coordinator, entity_description, container, endpoint, ) for (endpoint, container) in containers for entity_description in CONTAINER_SENSORS ) def _async_add_new_stacks( stacks: list[tuple[PortainerCoordinatorData, PortainerStackData]], ) -> None: """Add new stack sensors.""" async_add_entities( PortainerStackSensor( coordinator, entity_description, stack, endpoint, ) for (endpoint, stack) in stacks for entity_description in STACK_SENSORS ) coordinator.new_endpoints_callbacks.append(_async_add_new_endpoints) coordinator.new_containers_callbacks.append(_async_add_new_containers) coordinator.new_stacks_callbacks.append(_async_add_new_stacks) _async_add_new_endpoints( [ endpoint for endpoint in coordinator.data.values() if endpoint.id in coordinator.known_endpoints ] ) _async_add_new_containers( [ (endpoint, container) for endpoint in coordinator.data.values() for container in endpoint.containers.values() ] ) _async_add_new_stacks( [ (endpoint, stack) for endpoint in coordinator.data.values() for stack in endpoint.stacks.values() ] ) class PortainerContainerSensor(PortainerContainerEntity, SensorEntity): """Representation of a Portainer container sensor.""" entity_description: PortainerContainerSensorEntityDescription @property def native_value(self) -> StateType: """Return the state of the sensor.""" return self.entity_description.value_fn(self.container_data) class PortainerEndpointSensor(PortainerEndpointEntity, SensorEntity): """Representation of a Portainer endpoint sensor.""" entity_description: PortainerEndpointSensorEntityDescription @property def native_value(self) -> StateType: """Return the state of the sensor.""" endpoint_data = self.coordinator.data[self._device_info.endpoint.id] return self.entity_description.value_fn(endpoint_data) class PortainerStackSensor(PortainerStackEntity, SensorEntity): """Representation of a Portainer stack sensor.""" entity_description: PortainerStackSensorEntityDescription @property def native_value(self) -> StateType: """Return the state of the sensor.""" return self.entity_description.value_fn(self.stack_data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/portainer/sensor.py", "license": "Apache License 2.0", "lines": 390, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/portainer/switch.py
"""Switch platform for Portainer containers.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import Any from pyportainer import Portainer from pyportainer.exceptions import ( PortainerAuthenticationError, PortainerConnectionError, PortainerTimeoutError, ) from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, SwitchEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PortainerConfigEntry from .const import DOMAIN, STACK_STATUS_ACTIVE from .coordinator import ( PortainerContainerData, PortainerCoordinator, PortainerStackData, ) from .entity import ( PortainerContainerEntity, PortainerCoordinatorData, PortainerStackEntity, ) @dataclass(frozen=True, kw_only=True) class PortainerSwitchEntityDescription(SwitchEntityDescription): """Class to hold Portainer switch description.""" is_on_fn: Callable[[PortainerContainerData], bool | None] turn_on_fn: Callable[[Portainer], Callable[[int, str], Coroutine[Any, Any, None]]] turn_off_fn: Callable[[Portainer], Callable[[int, str], Coroutine[Any, Any, None]]] @dataclass(frozen=True, kw_only=True) class PortainerStackSwitchEntityDescription(SwitchEntityDescription): """Class to hold Portainer stack switch description.""" is_on_fn: Callable[[PortainerStackData], bool | None] turn_on_fn: Callable[[Portainer], Callable[..., Coroutine[Any, Any, Any]]] turn_off_fn: Callable[[Portainer], Callable[..., Coroutine[Any, Any, Any]]] PARALLEL_UPDATES = 1 async def _perform_action( coordinator: PortainerCoordinator, coroutine: Coroutine[Any, Any, Any], ) -> None: """Perform a Portainer action with error handling and coordinator refresh.""" try: await coroutine except PortainerAuthenticationError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="invalid_auth_no_details", ) from err except PortainerConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="cannot_connect_no_details", ) from err except PortainerTimeoutError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="timeout_connect_no_details", ) from err else: await coordinator.async_request_refresh() CONTAINER_SWITCHES: tuple[PortainerSwitchEntityDescription, ...] = ( PortainerSwitchEntityDescription( key="container", translation_key="container", device_class=SwitchDeviceClass.SWITCH, is_on_fn=lambda data: data.container.state == "running", turn_on_fn=lambda portainer: portainer.start_container, turn_off_fn=lambda portainer: portainer.stop_container, ), ) STACK_SWITCHES: tuple[PortainerStackSwitchEntityDescription, ...] = ( PortainerStackSwitchEntityDescription( key="stack", translation_key="stack", device_class=SwitchDeviceClass.SWITCH, is_on_fn=lambda data: data.stack.status == STACK_STATUS_ACTIVE, turn_on_fn=lambda portainer: portainer.start_stack, turn_off_fn=lambda portainer: portainer.stop_stack, ), ) async def async_setup_entry( hass: HomeAssistant, entry: PortainerConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Portainer switch sensors.""" coordinator = entry.runtime_data def _async_add_new_containers( containers: list[tuple[PortainerCoordinatorData, PortainerContainerData]], ) -> None: """Add new container switch sensors.""" async_add_entities( PortainerContainerSwitch( coordinator, entity_description, container, endpoint, ) for (endpoint, container) in containers for entity_description in CONTAINER_SWITCHES ) def _async_add_new_stacks( stacks: list[tuple[PortainerCoordinatorData, PortainerStackData]], ) -> None: """Add new stack switch sensors.""" async_add_entities( PortainerStackSwitch( coordinator, entity_description, stack, endpoint, ) for (endpoint, stack) in stacks for entity_description in STACK_SWITCHES ) coordinator.new_containers_callbacks.append(_async_add_new_containers) coordinator.new_stacks_callbacks.append(_async_add_new_stacks) _async_add_new_containers( [ (endpoint, container) for endpoint in coordinator.data.values() for container in endpoint.containers.values() ] ) _async_add_new_stacks( [ (endpoint, stack) for endpoint in coordinator.data.values() for stack in endpoint.stacks.values() ] ) class PortainerContainerSwitch(PortainerContainerEntity, SwitchEntity): """Representation of a Portainer container switch.""" entity_description: PortainerSwitchEntityDescription @property def is_on(self) -> bool | None: """Return the state of the device.""" return self.entity_description.is_on_fn(self.container_data) async def async_turn_on(self, **kwargs: Any) -> None: """Start (turn on) the container.""" await _perform_action( self.coordinator, self.entity_description.turn_on_fn(self.coordinator.portainer)( self.endpoint_id, self.container_data.container.id ), ) async def async_turn_off(self, **kwargs: Any) -> None: """Stop (turn off) the container.""" await _perform_action( self.coordinator, self.entity_description.turn_off_fn(self.coordinator.portainer)( self.endpoint_id, self.container_data.container.id ), ) class PortainerStackSwitch(PortainerStackEntity, SwitchEntity): """Representation of a Portainer stack switch.""" entity_description: PortainerStackSwitchEntityDescription @property def is_on(self) -> bool | None: """Return the state of the device.""" return self.entity_description.is_on_fn(self.stack_data) async def async_turn_on(self, **kwargs: Any) -> None: """Start (turn on) the stack.""" await _perform_action( self.coordinator, self.entity_description.turn_on_fn(self.coordinator.portainer)( self.endpoint_id, self.stack_data.stack.id ), ) async def async_turn_off(self, **kwargs: Any) -> None: """Stop (turn off) the stack.""" await _perform_action( self.coordinator, self.entity_description.turn_off_fn(self.coordinator.portainer)( self.endpoint_id, self.stack_data.stack.id ), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/portainer/switch.py", "license": "Apache License 2.0", "lines": 185, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/prowl/config_flow.py
"""The config flow for the Prowl component.""" from __future__ import annotations import logging from typing import Any import prowlpy import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_API_KEY, CONF_NAME from .const import DOMAIN from .helpers import async_verify_key _LOGGER = logging.getLogger(__name__) class ProwlConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for the Prowl component.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle user configuration.""" errors = {} if user_input: api_key = user_input[CONF_API_KEY] self._async_abort_entries_match({CONF_API_KEY: api_key}) errors = await self._validate_api_key(api_key) if not errors: return self.async_create_entry( title=user_input[CONF_NAME], data={ CONF_API_KEY: api_key, }, ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( vol.Schema( { vol.Required(CONF_API_KEY): str, vol.Required(CONF_NAME): str, }, ), user_input or {CONF_NAME: "Prowl"}, ), errors=errors, ) async def _validate_api_key(self, api_key: str) -> dict[str, str]: """Validate the provided API key.""" ret = {} try: if not await async_verify_key(self.hass, api_key): ret = {"base": "invalid_api_key"} except TimeoutError: ret = {"base": "api_timeout"} except prowlpy.APIError: ret = {"base": "bad_api_response"} return ret
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prowl/config_flow.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/prowl/helpers.py
"""Helper functions for Prowl.""" import asyncio import prowlpy from homeassistant.core import HomeAssistant from homeassistant.helpers.httpx_client import get_async_client async def async_verify_key(hass: HomeAssistant, api_key: str) -> bool: """Validate API key.""" prowl = prowlpy.AsyncProwl(api_key, client=get_async_client(hass)) try: async with asyncio.timeout(10): await prowl.verify_key() return True except prowlpy.APIError as ex: if str(ex).startswith("Invalid API key"): return False raise
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prowl/helpers.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/sensibo/services.py
"""Sensibo services.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.climate import ( ATTR_FAN_MODE, ATTR_HVAC_MODE, ATTR_SWING_MODE, DOMAIN as CLIMATE_DOMAIN, HVACMode, ) from homeassistant.const import ATTR_MODE, ATTR_STATE from homeassistant.core import HomeAssistant, SupportsResponse, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN SERVICE_ASSUME_STATE = "assume_state" SERVICE_ENABLE_TIMER = "enable_timer" ATTR_MINUTES = "minutes" SERVICE_ENABLE_PURE_BOOST = "enable_pure_boost" SERVICE_DISABLE_PURE_BOOST = "disable_pure_boost" SERVICE_FULL_STATE = "full_state" SERVICE_ENABLE_CLIMATE_REACT = "enable_climate_react" SERVICE_GET_DEVICE_CAPABILITIES = "get_device_capabilities" ATTR_HIGH_TEMPERATURE_THRESHOLD = "high_temperature_threshold" ATTR_HIGH_TEMPERATURE_STATE = "high_temperature_state" ATTR_LOW_TEMPERATURE_THRESHOLD = "low_temperature_threshold" ATTR_LOW_TEMPERATURE_STATE = "low_temperature_state" ATTR_SMART_TYPE = "smart_type" ATTR_AC_INTEGRATION = "ac_integration" ATTR_GEO_INTEGRATION = "geo_integration" ATTR_INDOOR_INTEGRATION = "indoor_integration" ATTR_OUTDOOR_INTEGRATION = "outdoor_integration" ATTR_SENSITIVITY = "sensitivity" ATTR_TARGET_TEMPERATURE = "target_temperature" ATTR_HORIZONTAL_SWING_MODE = "horizontal_swing_mode" ATTR_LIGHT = "light" BOOST_INCLUSIVE = "boost_inclusive" @callback def async_setup_services(hass: HomeAssistant) -> None: """Register Sensibo services.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_ASSUME_STATE, entity_domain=CLIMATE_DOMAIN, schema={ vol.Required(ATTR_STATE): vol.In(["on", "off"]), }, func="async_assume_state", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_ENABLE_TIMER, entity_domain=CLIMATE_DOMAIN, schema={ vol.Required(ATTR_MINUTES): cv.positive_int, }, func="async_enable_timer", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_ENABLE_PURE_BOOST, entity_domain=CLIMATE_DOMAIN, schema={ vol.Required(ATTR_AC_INTEGRATION): bool, vol.Required(ATTR_GEO_INTEGRATION): bool, vol.Required(ATTR_INDOOR_INTEGRATION): bool, vol.Required(ATTR_OUTDOOR_INTEGRATION): bool, vol.Required(ATTR_SENSITIVITY): vol.In(["normal", "sensitive"]), }, func="async_enable_pure_boost", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_FULL_STATE, entity_domain=CLIMATE_DOMAIN, schema={ vol.Required(ATTR_MODE): vol.In( ["cool", "heat", "fan", "auto", "dry", "off"] ), vol.Optional(ATTR_TARGET_TEMPERATURE): int, vol.Optional(ATTR_FAN_MODE): str, vol.Optional(ATTR_SWING_MODE): str, vol.Optional(ATTR_HORIZONTAL_SWING_MODE): str, vol.Optional(ATTR_LIGHT): vol.In(["on", "off", "dim"]), }, func="async_full_ac_state", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_ENABLE_CLIMATE_REACT, entity_domain=CLIMATE_DOMAIN, schema={ vol.Required(ATTR_HIGH_TEMPERATURE_THRESHOLD): vol.Coerce(float), vol.Required(ATTR_HIGH_TEMPERATURE_STATE): dict, vol.Required(ATTR_LOW_TEMPERATURE_THRESHOLD): vol.Coerce(float), vol.Required(ATTR_LOW_TEMPERATURE_STATE): dict, vol.Required(ATTR_SMART_TYPE): vol.In( ["temperature", "feelslike", "humidity"] ), }, func="async_enable_climate_react", ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_GET_DEVICE_CAPABILITIES, entity_domain=CLIMATE_DOMAIN, schema={vol.Required(ATTR_HVAC_MODE): vol.Coerce(HVACMode)}, func="async_get_device_capabilities", supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sensibo/services.py", "license": "Apache License 2.0", "lines": 115, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/sfr_box/entity.py
"""SFR Box base entity.""" from __future__ import annotations from sfrbox_api.models import SystemInfo from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import Entity, EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import SFRDataUpdateCoordinator class SFREntity(Entity): """SFR Box entity.""" _attr_has_entity_name = True def __init__(self, description: EntityDescription, system_info: SystemInfo) -> None: """Initialize the entity.""" self.entity_description = description self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, system_info.mac_addr)}, ) self._attr_unique_id = f"{system_info.mac_addr}_{description.key}" class SFRCoordinatorEntity[_T]( CoordinatorEntity[SFRDataUpdateCoordinator[_T]], SFREntity ): """SFR Box coordinator entity.""" def __init__( self, coordinator: SFRDataUpdateCoordinator[_T], description: EntityDescription, system_info: SystemInfo, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) SFREntity.__init__(self, description, system_info) self._attr_unique_id = ( f"{system_info.mac_addr}_{coordinator.name}_{description.key}" )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sfr_box/entity.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/sma/coordinator.py
"""Coordinator for the SMA integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta import logging from pysma import ( SmaAuthenticationException, SmaConnectionException, SmaReadException, SMAWebConnect, ) from pysma.helpers import DeviceInfo from pysma.sensor import Sensors from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SCAN_INTERVAL from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) @dataclass(slots=True) class SMACoordinatorData: """Data class for SMA sensors.""" sma_device_info: DeviceInfo sensors: Sensors class SMADataUpdateCoordinator(DataUpdateCoordinator[SMACoordinatorData]): """Data Update Coordinator for SMA.""" config_entry: ConfigEntry def __init__( self, hass: HomeAssistant, config_entry: ConfigEntry, sma: SMAWebConnect, ) -> None: """Initialize the SMA Data Update Coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=timedelta( seconds=config_entry.options.get( CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL ) ), ) self.sma = sma self._sma_device_info = DeviceInfo() self._sensors = Sensors() async def _async_setup(self) -> None: """Setup the SMA Data Update Coordinator.""" try: self._sma_device_info = await self.sma.device_info() self._sensors = await self.sma.get_sensors() except ( SmaReadException, SmaConnectionException, ) as err: await self.async_close_sma_session() raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"error": repr(err)}, ) from err except SmaAuthenticationException as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", translation_placeholders={"error": repr(err)}, ) from err async def _async_update_data(self) -> SMACoordinatorData: """Update the used SMA sensors.""" try: await self.sma.read(self._sensors) except ( SmaReadException, SmaConnectionException, ) as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="cannot_connect", translation_placeholders={"error": repr(err)}, ) from err except SmaAuthenticationException as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", translation_placeholders={"error": repr(err)}, ) from err return SMACoordinatorData( sma_device_info=self._sma_device_info, sensors=self._sensors, ) async def async_close_sma_session(self) -> None: """Close the SMA session.""" await self.sma.close_session() _LOGGER.debug("SMA session closed")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sma/coordinator.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/snoo/button.py
"""Support for Snoo Buttons.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from python_snoo.containers import SnooDevice from python_snoo.exceptions import SnooCommandException from python_snoo.snoo import Snoo from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import SnooConfigEntry from .entity import SnooDescriptionEntity @dataclass(kw_only=True, frozen=True) class SnooButtonEntityDescription(ButtonEntityDescription): """Description for Snoo button entities.""" press_fn: Callable[[Snoo, SnooDevice], Awaitable[None]] BUTTON_DESCRIPTIONS: list[SnooButtonEntityDescription] = [ SnooButtonEntityDescription( key="start_snoo", translation_key="start_snoo", press_fn=lambda snoo, device: snoo.start_snoo( device, ), ), ] async def async_setup_entry( hass: HomeAssistant, entry: SnooConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up buttons for Snoo device.""" coordinators = entry.runtime_data async_add_entities( SnooButton(coordinator, description) for coordinator in coordinators.values() for description in BUTTON_DESCRIPTIONS ) class SnooButton(SnooDescriptionEntity, ButtonEntity): """Representation of a Snoo button.""" entity_description: SnooButtonEntityDescription async def async_press(self) -> None: """Handle the button press.""" try: await self.entity_description.press_fn( self.coordinator.snoo, self.coordinator.device, ) except SnooCommandException as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key=f"{self.entity_description.key}_failed", translation_placeholders={"name": str(self.name)}, ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/snoo/button.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/sql/services.py
"""Services for the SQL integration.""" from __future__ import annotations import logging from sqlalchemy.engine import Result from sqlalchemy.exc import SQLAlchemyError from sqlalchemy.orm import Session import voluptuous as vol from homeassistant.components.recorder import CONF_DB_URL, get_instance from homeassistant.core import ( HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse, callback, ) from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv from homeassistant.helpers.trigger_template_entity import ValueTemplate from homeassistant.util.json import JsonValueType from .const import CONF_QUERY, DOMAIN from .util import ( async_create_sessionmaker, check_and_render_sql_query, convert_value, generate_lambda_stmt, redact_credentials, resolve_db_url, validate_query, validate_sql_select, ) _LOGGER = logging.getLogger(__name__) SERVICE_QUERY = "query" SERVICE_QUERY_SCHEMA = vol.Schema( { vol.Required(CONF_QUERY): vol.All( cv.template, ValueTemplate.from_template, validate_sql_select ), vol.Optional(CONF_DB_URL): cv.string, } ) async def _async_query_service( call: ServiceCall, ) -> ServiceResponse: """Execute a SQL query service and return the result.""" db_url = resolve_db_url(call.hass, call.data.get(CONF_DB_URL)) query_str = call.data[CONF_QUERY] ( sessmaker, uses_recorder_db, use_database_executor, ) = await async_create_sessionmaker(call.hass, db_url) try: validate_query(call.hass, query_str, uses_recorder_db, None) except ValueError as err: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="query_not_allowed", translation_placeholders={"error": str(err)}, ) from err if sessmaker is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="db_connection_failed", translation_placeholders={"db_url": redact_credentials(db_url)}, ) def _execute_and_convert_query() -> list[JsonValueType]: """Execute the query and return the results with converted types.""" sess: Session = sessmaker() rendered_query = check_and_render_sql_query(call.hass, query_str) try: result: Result = sess.execute(generate_lambda_stmt(rendered_query)) except SQLAlchemyError as err: _LOGGER.debug( "Error executing query %s: %s", query_str, redact_credentials(str(err)), ) sess.rollback() raise else: rows: list[JsonValueType] = [] for row in result.mappings(): processed_row: dict[str, JsonValueType] = {} for key, value in row.items(): processed_row[key] = convert_value(value) rows.append(processed_row) return rows finally: sess.close() try: if use_database_executor: result = await get_instance(call.hass).async_add_executor_job( _execute_and_convert_query ) else: result = await call.hass.async_add_executor_job(_execute_and_convert_query) except SQLAlchemyError as err: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="query_execution_error", translation_placeholders={"error": redact_credentials(str(err))}, ) from err return {"result": result} @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for the SQL integration.""" hass.services.async_register( DOMAIN, SERVICE_QUERY, _async_query_service, schema=SERVICE_QUERY_SCHEMA, supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sql/services.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/squeezebox/util.py
"""Utility functions for Squeezebox integration.""" from __future__ import annotations from collections.abc import Awaitable, Callable from typing import Any from homeassistant.exceptions import HomeAssistantError from .const import DOMAIN async def safe_library_call( method: Callable[..., Awaitable[Any]], *args: Any, translation_key: str, translation_placeholders: dict[str, Any] | None = None, **kwargs: Any, ) -> Any: """Call a player method safely and raise HomeAssistantError on failure.""" try: result = await method(*args, **kwargs) except ValueError: result = None if result is False or result is None: raise HomeAssistantError( translation_domain=DOMAIN, translation_key=translation_key, translation_placeholders=translation_placeholders, ) return result
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/squeezebox/util.py", "license": "Apache License 2.0", "lines": 25, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/sunricher_dali/config_flow.py
"""Config flow for the Sunricher DALI integration.""" from __future__ import annotations import logging from typing import Any from PySrDaliGateway import DaliGateway from PySrDaliGateway.discovery import DaliGatewayDiscovery from PySrDaliGateway.exceptions import DaliGatewayError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, ) from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.selector import ( SelectOptionDict, SelectSelector, SelectSelectorConfig, ) from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .const import CONF_SERIAL_NUMBER, DOMAIN _LOGGER = logging.getLogger(__name__) class DaliCenterConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Sunricher DALI.""" VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._discovered_gateways: dict[str, DaliGateway] = {} async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" if user_input is not None: return await self.async_step_select_gateway() return self.async_show_form( step_id="user", data_schema=vol.Schema({}), ) async def async_step_select_gateway( self, discovery_info: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle gateway discovery.""" errors: dict[str, str] = {} if discovery_info and "selected_gateway" in discovery_info: selected_sn = discovery_info["selected_gateway"] selected_gateway = self._discovered_gateways[selected_sn] await self.async_set_unique_id(selected_gateway.gw_sn) self._abort_if_unique_id_configured() try: await selected_gateway.connect() except DaliGatewayError as err: _LOGGER.debug( "Failed to connect to gateway %s during config flow", selected_gateway.gw_sn, exc_info=err, ) errors["base"] = "cannot_connect" else: await selected_gateway.disconnect() return self.async_create_entry( title=selected_gateway.name, data={ CONF_SERIAL_NUMBER: selected_gateway.gw_sn, CONF_HOST: selected_gateway.gw_ip, CONF_PORT: selected_gateway.port, CONF_NAME: selected_gateway.name, CONF_USERNAME: selected_gateway.username, CONF_PASSWORD: selected_gateway.passwd, }, ) if not self._discovered_gateways: _LOGGER.debug("Starting gateway discovery") discovery = DaliGatewayDiscovery() try: discovered = await discovery.discover_gateways() except DaliGatewayError as err: _LOGGER.debug("Gateway discovery failed", exc_info=err) errors["base"] = "discovery_failed" else: configured_gateways = { entry.data[CONF_SERIAL_NUMBER] for entry in self.hass.config_entries.async_entries(DOMAIN) } self._discovered_gateways = { gw.gw_sn: gw for gw in discovered if gw.gw_sn not in configured_gateways } if not self._discovered_gateways: return self.async_show_form( step_id="select_gateway", errors=errors or {"base": "no_devices_found"}, data_schema=vol.Schema({}), ) gateway_options = [ SelectOptionDict( value=sn, label=f"{gateway.name} [SN {sn}, IP {gateway.gw_ip}]", ) for sn, gateway in self._discovered_gateways.items() ] return self.async_show_form( step_id="select_gateway", data_schema=vol.Schema( { vol.Optional("selected_gateway"): SelectSelector( SelectSelectorConfig(options=gateway_options, sort=True) ), } ), errors=errors, ) async def async_step_dhcp( self, discovery_info: DhcpServiceInfo ) -> ConfigFlowResult: """Handle DHCP discovery to update existing entries.""" mac_address = format_mac(discovery_info.macaddress) serial_number = mac_address.replace(":", "").upper() await self.async_set_unique_id(serial_number) self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.ip}) return self.async_abort(reason="no_dhcp_flow")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sunricher_dali/config_flow.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/sunricher_dali/light.py
"""Platform for light integration.""" from __future__ import annotations import logging from typing import Any from PySrDaliGateway import CallbackEventType, Device from PySrDaliGateway.helper import is_light_device from PySrDaliGateway.types import LightStatus from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, ATTR_HS_COLOR, ATTR_RGBW_COLOR, ColorMode, LightEntity, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN, MANUFACTURER from .entity import DaliDeviceEntity from .types import DaliCenterConfigEntry _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, entry: DaliCenterConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Sunricher DALI light entities from config entry.""" runtime_data = entry.runtime_data devices = runtime_data.devices async_add_entities( DaliCenterLight(device) for device in devices if is_light_device(device.dev_type) ) class DaliCenterLight(DaliDeviceEntity, LightEntity): """Representation of a Sunricher DALI Light.""" _attr_name = None _attr_min_color_temp_kelvin = 1000 _attr_max_color_temp_kelvin = 8000 _white_level: int | None = None def __init__(self, light: Device) -> None: """Initialize the light entity.""" super().__init__(light) self._light = light self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, light.dev_id)}, name=light.name, manufacturer=MANUFACTURER, model=light.model, via_device=(DOMAIN, light.gw_sn), ) self._determine_features() def _determine_features(self) -> None: supported_modes: set[ColorMode] = set() color_mode = self._light.color_mode color_mode_map: dict[str, ColorMode] = { "color_temp": ColorMode.COLOR_TEMP, "hs": ColorMode.HS, "rgbw": ColorMode.RGBW, } self._attr_color_mode = color_mode_map.get(color_mode, ColorMode.BRIGHTNESS) supported_modes.add(self._attr_color_mode) self._attr_supported_color_modes = supported_modes async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the light.""" _LOGGER.debug( "Turning on light %s with kwargs: %s", self._attr_unique_id, kwargs ) brightness = kwargs.get(ATTR_BRIGHTNESS) color_temp_kelvin = kwargs.get(ATTR_COLOR_TEMP_KELVIN) hs_color = kwargs.get(ATTR_HS_COLOR) rgbw_color = kwargs.get(ATTR_RGBW_COLOR) self._light.turn_on( brightness=brightness, color_temp_kelvin=color_temp_kelvin, hs_color=hs_color, rgbw_color=rgbw_color, ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the light.""" self._light.turn_off() async def async_added_to_hass(self) -> None: """Handle entity addition to Home Assistant.""" await super().async_added_to_hass() self.async_on_remove( self._light.register_listener( CallbackEventType.LIGHT_STATUS, self._handle_device_update ) ) # read_status() only queues a request on the gateway and relies on the # current event loop via call_later, so it must run in the loop thread. self._light.read_status() @callback def _handle_device_update(self, status: LightStatus) -> None: if status.get("is_on") is not None: self._attr_is_on = status["is_on"] if status.get("brightness") is not None: self._attr_brightness = status["brightness"] if status.get("white_level") is not None: self._white_level = status["white_level"] if self._attr_rgbw_color is not None and self._white_level is not None: self._attr_rgbw_color = ( self._attr_rgbw_color[0], self._attr_rgbw_color[1], self._attr_rgbw_color[2], self._white_level, ) if ( status.get("color_temp_kelvin") is not None and self._attr_supported_color_modes and ColorMode.COLOR_TEMP in self._attr_supported_color_modes ): self._attr_color_temp_kelvin = status["color_temp_kelvin"] if ( status.get("hs_color") is not None and self._attr_supported_color_modes and ColorMode.HS in self._attr_supported_color_modes ): self._attr_hs_color = status["hs_color"] if ( status.get("rgbw_color") is not None and self._attr_supported_color_modes and ColorMode.RGBW in self._attr_supported_color_modes ): self._attr_rgbw_color = status["rgbw_color"] self.schedule_update_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sunricher_dali/light.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/sunricher_dali/types.py
"""Type definitions for the Sunricher DALI integration.""" from dataclasses import dataclass from PySrDaliGateway import DaliGateway, Device, Scene from homeassistant.config_entries import ConfigEntry @dataclass class DaliCenterData: """Runtime data for the Sunricher DALI integration.""" gateway: DaliGateway devices: list[Device] scenes: list[Scene] type DaliCenterConfigEntry = ConfigEntry[DaliCenterData]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/sunricher_dali/types.py", "license": "Apache License 2.0", "lines": 11, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/telegram_bot/diagnostics.py
"""Diagnostics platform for Telegram bot integration.""" from __future__ import annotations from typing import Any from yarl import URL from homeassistant.components.diagnostics import REDACTED, async_redact_data from homeassistant.const import CONF_API_KEY, CONF_URL from homeassistant.core import HomeAssistant from . import TelegramBotConfigEntry from .const import CONF_API_ENDPOINT, CONF_CHAT_ID, DEFAULT_API_ENDPOINT TO_REDACT = [CONF_API_KEY, CONF_CHAT_ID] async def async_get_config_entry_diagnostics( hass: HomeAssistant, config_entry: TelegramBotConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" data = async_redact_data(config_entry.data, TO_REDACT) if config_entry.data.get(CONF_URL): url = URL(config_entry.data[CONF_URL]) data[CONF_URL] = url.with_host(REDACTED).human_repr() api_endpoint = config_entry.data.get(CONF_API_ENDPOINT) if api_endpoint and api_endpoint != DEFAULT_API_ENDPOINT: url = URL(config_entry.data[CONF_API_ENDPOINT]) data[CONF_API_ENDPOINT] = url.with_host(REDACTED).human_repr() return { "data": data, "options": async_redact_data(config_entry.options, TO_REDACT), "subentries_count": len(config_entry.subentries.values()), }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/telegram_bot/diagnostics.py", "license": "Apache License 2.0", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/telegram_bot/entity.py
"""Base entity for Telegram bot integration.""" import telegram from homeassistant.const import CONF_PLATFORM from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity import Entity, EntityDescription from . import TelegramBotConfigEntry from .const import DOMAIN class TelegramBotEntity(Entity): """Base entity.""" _attr_has_entity_name = True def __init__( self, config_entry: TelegramBotConfigEntry, entity_description: EntityDescription, ) -> None: """Initialize the entity.""" self.bot_id = config_entry.runtime_data.bot.id self.config_entry = config_entry self.entity_description = entity_description self.service = config_entry.runtime_data self._attr_unique_id = f"{self.bot_id}_{entity_description.key}" self._attr_device_info = DeviceInfo( name=config_entry.title, entry_type=DeviceEntryType.SERVICE, manufacturer="Telegram", model=config_entry.data[CONF_PLATFORM].capitalize(), sw_version=telegram.__version__, identifiers={(DOMAIN, f"{self.bot_id}")}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/telegram_bot/entity.py", "license": "Apache License 2.0", "lines": 29, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/telegram_bot/event.py
"""Event platform for Telegram bot integration.""" from typing import Any from homeassistant.components.event import EventEntity, EventEntityDescription from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .bot import TelegramBotConfigEntry from .const import ( EVENT_TELEGRAM_ATTACHMENT, EVENT_TELEGRAM_CALLBACK, EVENT_TELEGRAM_COMMAND, EVENT_TELEGRAM_SENT, EVENT_TELEGRAM_TEXT, ) from .entity import TelegramBotEntity from .helpers import signal async def async_setup_entry( hass: HomeAssistant, config_entry: TelegramBotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the event platform.""" async_add_entities([TelegramBotEventEntity(config_entry)]) class TelegramBotEventEntity(TelegramBotEntity, EventEntity): """An event entity.""" _attr_event_types = [ EVENT_TELEGRAM_ATTACHMENT, EVENT_TELEGRAM_CALLBACK, EVENT_TELEGRAM_COMMAND, EVENT_TELEGRAM_TEXT, EVENT_TELEGRAM_SENT, ] def __init__( self, config_entry: TelegramBotConfigEntry, ) -> None: """Initialize the entity.""" super().__init__( config_entry, EventEntityDescription(key="update_event", translation_key="update_event"), ) async def async_added_to_hass(self) -> None: """Register callbacks.""" self.async_on_remove( async_dispatcher_connect( self.hass, signal(self.config_entry.runtime_data.bot), self._async_handle_event, ) ) @callback def _async_handle_event(self, event_type: str, event_data: dict[str, Any]) -> None: """Handle the event.""" self._trigger_event(event_type, event_data) self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/telegram_bot/event.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/telegram_bot/helpers.py
"""Helper functions for Telegram bot integration.""" from telegram import Bot from .const import SIGNAL_UPDATE_EVENT def signal(bot: Bot) -> str: """Define signal name.""" return f"{SIGNAL_UPDATE_EVENT}_{bot.id}" def get_base_url(bot: Bot) -> str: """Return the base URL for the bot.""" return bot.base_url.replace(bot.token, "")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/telegram_bot/helpers.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/unifi/light.py
"""Light platform for UniFi Network integration.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import TYPE_CHECKING, Any, cast from aiounifi.interfaces.api_handlers import APIHandler, ItemEvent from aiounifi.interfaces.devices import Devices from aiounifi.models.api import ApiItem from aiounifi.models.device import Device, DeviceSetLedStatus from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_RGB_COLOR, ColorMode, LightEntity, LightEntityDescription, LightEntityFeature, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util.color import rgb_hex_to_rgb_list from . import UnifiConfigEntry from .entity import ( UnifiEntity, UnifiEntityDescription, async_device_available_fn, async_device_device_info_fn, ) if TYPE_CHECKING: from .hub import UnifiHub def convert_brightness_to_unifi(ha_brightness: int) -> int: """Convert Home Assistant brightness (0-255) to UniFi brightness (0-100).""" return round((ha_brightness / 255) * 100) def convert_brightness_to_ha( unifi_brightness: int, ) -> int: """Convert UniFi brightness (0-100) to Home Assistant brightness (0-255).""" return round((unifi_brightness / 100) * 255) def get_device_brightness_or_default(device: Device) -> int: """Get device's current LED brightness. Defaults to 100 (full brightness) if not set.""" value = device.led_override_color_brightness return value if value is not None else 100 @callback def async_device_led_supported_fn(hub: UnifiHub, obj_id: str) -> bool: """Check if device supports LED control.""" device: Device = hub.api.devices[obj_id] return device.led_override is not None or device.supports_led_ring @callback def async_device_led_is_on_fn(hub: UnifiHub, device: Device) -> bool: """Check if device LED is on.""" return device.led_override == "on" async def async_device_led_control_fn( hub: UnifiHub, obj_id: str, turn_on: bool, **kwargs: Any ) -> None: """Control device LED.""" device = hub.api.devices[obj_id] status = "on" if turn_on else "off" # Only send brightness and RGB if device has LED_RING hardware support if device.supports_led_ring: # Use provided brightness or fall back to device's current brightness if ATTR_BRIGHTNESS in kwargs: brightness = convert_brightness_to_unifi(kwargs[ATTR_BRIGHTNESS]) else: brightness = get_device_brightness_or_default(device) # Use provided RGB color or fall back to device's current color color: str | None if ATTR_RGB_COLOR in kwargs: rgb = kwargs[ATTR_RGB_COLOR] color = f"#{rgb[0]:02x}{rgb[1]:02x}{rgb[2]:02x}" else: color = device.led_override_color else: brightness = None color = None await hub.api.request( DeviceSetLedStatus.create( device=device, status=status, brightness=brightness, color=color, ) ) @dataclass(frozen=True, kw_only=True) class UnifiLightEntityDescription[HandlerT: APIHandler, ApiItemT: ApiItem]( LightEntityDescription, UnifiEntityDescription[HandlerT, ApiItemT] ): """Class describing UniFi light entity.""" control_fn: Callable[[UnifiHub, str, bool], Coroutine[Any, Any, None]] is_on_fn: Callable[[UnifiHub, ApiItemT], bool] ENTITY_DESCRIPTIONS: tuple[UnifiLightEntityDescription, ...] = ( UnifiLightEntityDescription[Devices, Device]( key="LED control", translation_key="led_control", entity_category=EntityCategory.CONFIG, allowed_fn=lambda hub, obj_id: True, api_handler_fn=lambda api: api.devices, available_fn=async_device_available_fn, control_fn=async_device_led_control_fn, device_info_fn=async_device_device_info_fn, is_on_fn=async_device_led_is_on_fn, name_fn=lambda device: "LED", object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=async_device_led_supported_fn, unique_id_fn=lambda hub, obj_id: f"led-{obj_id}", ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: UnifiConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up lights for UniFi Network integration.""" config_entry.runtime_data.entity_loader.register_platform( async_add_entities, UnifiLightEntity, ENTITY_DESCRIPTIONS, requires_admin=True, ) class UnifiLightEntity[HandlerT: APIHandler, ApiItemT: ApiItem]( UnifiEntity[HandlerT, ApiItemT], LightEntity ): """Base representation of a UniFi light.""" entity_description: UnifiLightEntityDescription[HandlerT, ApiItemT] _attr_supported_features = LightEntityFeature(0) @callback def async_initiate_state(self) -> None: """Initiate entity state.""" device = cast(Device, self.entity_description.object_fn(self.api, self._obj_id)) if device.supports_led_ring: self._attr_supported_color_modes = {ColorMode.RGB} self._attr_color_mode = ColorMode.RGB else: self._attr_supported_color_modes = {ColorMode.ONOFF} self._attr_color_mode = ColorMode.ONOFF self.async_update_state(ItemEvent.ADDED, self._obj_id) async def async_turn_on(self, **kwargs: Any) -> None: """Turn on light.""" await self.entity_description.control_fn(self.hub, self._obj_id, True, **kwargs) async def async_turn_off(self, **kwargs: Any) -> None: """Turn off light.""" await self.entity_description.control_fn( self.hub, self._obj_id, False, **kwargs ) @callback def async_update_state(self, event: ItemEvent, obj_id: str) -> None: """Update entity state.""" description = self.entity_description device_obj = description.object_fn(self.api, self._obj_id) device = cast(Device, device_obj) self._attr_is_on = description.is_on_fn(self.hub, device_obj) # Only set brightness and RGB if device has LED_RING hardware support if device.supports_led_ring: self._attr_brightness = convert_brightness_to_ha( get_device_brightness_or_default(device) ) # Parse hex color from device and convert to RGB tuple hex_color = ( device.led_override_color.lstrip("#") if self._attr_is_on and device.led_override_color else None ) if hex_color and len(hex_color) == 6: rgb_list = rgb_hex_to_rgb_list(hex_color) self._attr_rgb_color = (rgb_list[0], rgb_list[1], rgb_list[2]) else: self._attr_rgb_color = None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/unifi/light.py", "license": "Apache License 2.0", "lines": 166, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/uptimerobot/utils.py
"""Utility functions for the UptimeRobot integration.""" from __future__ import annotations from collections.abc import Callable from pyuptimerobot import UptimeRobotMonitor from .coordinator import UptimeRobotDataUpdateCoordinator def new_device_listener( coordinator: UptimeRobotDataUpdateCoordinator, new_devices_callback: Callable[[list[UptimeRobotMonitor]], None], ) -> Callable[[], None]: """Subscribe to coordinator updates to check for new devices.""" known_devices: set[int] = set() def _check_devices() -> None: """Check for new devices and call callback with any new monitors.""" new_ids = coordinator.data.keys() - known_devices if new_ids: known_devices.update(new_ids) new_devices_callback([coordinator.data[i] for i in new_ids]) # Check for devices immediately _check_devices() return coordinator.async_add_listener(_check_devices)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/uptimerobot/utils.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/vegehub/switch.py
"""Switch configuration for VegeHub integration.""" from typing import Any from homeassistant.components.switch import ( SwitchDeviceClass, SwitchEntity, SwitchEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import VegeHubConfigEntry, VegeHubCoordinator from .entity import VegeHubEntity SWITCH_TYPES: dict[str, SwitchEntityDescription] = { "switch": SwitchEntityDescription( key="switch", translation_key="switch", device_class=SwitchDeviceClass.SWITCH, ) } async def async_setup_entry( hass: HomeAssistant, config_entry: VegeHubConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up VegeHub switches from a config entry.""" coordinator = config_entry.runtime_data async_add_entities( VegeHubSwitch( index=i, duration=600, # Default duration of 10 minutes coordinator=coordinator, description=SWITCH_TYPES["switch"], ) for i in range(coordinator.vegehub.num_actuators) ) class VegeHubSwitch(VegeHubEntity, SwitchEntity): """Class for VegeHub Switches.""" _attr_device_class = SwitchDeviceClass.SWITCH def __init__( self, index: int, duration: int, coordinator: VegeHubCoordinator, description: SwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator) self.entity_description = description # Set unique ID for pulling data from the coordinator self.data_key = f"actuator_{index}" self._attr_unique_id = f"{self._mac_address}_{self.data_key}" self._attr_translation_placeholders = {"index": str(index + 1)} self._attr_available = False self.index = index self.duration = duration @property def is_on(self) -> bool: """Return True if the switch is on.""" if self.coordinator.data is None or self._attr_unique_id is None: return False return self.coordinator.data.get(self.data_key, 0) > 0 async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.coordinator.vegehub.set_actuator(1, self.index, self.duration) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.coordinator.vegehub.set_actuator(0, self.index, self.duration)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/vegehub/switch.py", "license": "Apache License 2.0", "lines": 66, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/victron_remote_monitoring/energy.py
"""Victron Remote Monitoring energy platform.""" from __future__ import annotations from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant async def async_get_solar_forecast( hass: HomeAssistant, config_entry_id: str ) -> dict[str, dict[str, float | int]] | None: """Get solar forecast for a config entry ID.""" if ( entry := hass.config_entries.async_get_entry(config_entry_id) ) is None or entry.state != ConfigEntryState.LOADED: return None data = entry.runtime_data.data.solar if data is None: return None return {"wh_hours": data.get_dict_isoformat}
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/victron_remote_monitoring/energy.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/voip/store.py
"""VOIP contact storage.""" from dataclasses import dataclass import logging from homeassistant.core import HomeAssistant from homeassistant.helpers.storage import Store from .const import STORAGE_VER _LOGGER = logging.getLogger(__name__) @dataclass class DeviceContact: """Device contact data.""" contact: str class DeviceContacts(dict[str, DeviceContact]): """Map of device contact data.""" class VoipStore(Store): """Store for VOIP device contact information.""" def __init__(self, hass: HomeAssistant, storage_key: str) -> None: """Initialize the VOIP Storage.""" super().__init__(hass, STORAGE_VER, f"voip-{storage_key}") async def async_load_devices(self) -> DeviceContacts: """Load data from store as DeviceContacts.""" raw_data: dict[str, dict[str, str]] = await self.async_load() or {} return self._dict_to_devices(raw_data) async def async_update_device(self, voip_id: str, contact_header: str) -> None: """Update the device store with the contact information.""" _LOGGER.debug("Saving new VOIP device %s contact %s", voip_id, contact_header) devices_data: DeviceContacts = await self.async_load_devices() _LOGGER.debug("devices_data: %s", devices_data) device_data: DeviceContact | None = devices_data.get(voip_id) if device_data is not None: device_data.contact = contact_header else: devices_data[voip_id] = DeviceContact(contact_header) await self.async_save(devices_data) _LOGGER.debug("Saved new VOIP device contact") def _dict_to_devices(self, raw_data: dict[str, dict[str, str]]) -> DeviceContacts: contacts = DeviceContacts() for k, v in (raw_data or {}).items(): contacts[k] = DeviceContact(**v) return contacts
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/voip/store.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/volvo/button.py
"""Volvo buttons.""" from dataclasses import dataclass import logging from volvocarsapi.models import VolvoApiException from homeassistant.components.button import ButtonEntity, ButtonEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import VolvoConfigEntry from .entity import VolvoBaseEntity, VolvoEntityDescription PARALLEL_UPDATES = 0 _LOGGER = logging.getLogger(__name__) @dataclass(frozen=True, kw_only=True) class VolvoButtonDescription(VolvoEntityDescription, ButtonEntityDescription): """Describes a Volvo button entity.""" api_command: str required_command_key: str data: dict[str, int] | None = None _DESCRIPTIONS: tuple[VolvoButtonDescription, ...] = ( VolvoButtonDescription( key="climatization_start", api_command="climatization-start", required_command_key="CLIMATIZATION_START", ), VolvoButtonDescription( key="climatization_stop", api_command="climatization-stop", required_command_key="CLIMATIZATION_STOP", ), VolvoButtonDescription( key="engine_start", api_command="engine-start", required_command_key="ENGINE_START", data={"runtimeMinutes": 15}, ), VolvoButtonDescription( key="engine_stop", api_command="engine-stop", required_command_key="ENGINE_STOP", ), VolvoButtonDescription( key="flash", api_command="flash", required_command_key="FLASH", ), VolvoButtonDescription( key="honk", api_command="honk", required_command_key="HONK", ), VolvoButtonDescription( key="honk_flash", api_command="honk-flash", required_command_key="HONK_AND_FLASH", ), VolvoButtonDescription( key="lock_reduced_guard", api_command="lock-reduced-guard", required_command_key="LOCK_REDUCED_GUARD", ), ) async def async_setup_entry( hass: HomeAssistant, entry: VolvoConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up buttons.""" async_add_entities( [ VolvoButton(entry, description) for description in _DESCRIPTIONS if description.required_command_key in entry.runtime_data.context.supported_commands ] ) class VolvoButton(VolvoBaseEntity, ButtonEntity): """Volvo button.""" entity_description: VolvoButtonDescription async def async_press(self) -> None: """Handle the button press.""" command = self.entity_description.api_command _LOGGER.debug("Command %s executing", command) try: result = await self.entry.runtime_data.context.api.async_execute_command( self.entity_description.api_command, self.entity_description.data ) except VolvoApiException as ex: _LOGGER.debug("Command '%s' error", command) self._raise(command, message=ex.message, exception=ex) status = result.invoke_status if result else "" if status != "COMPLETED": self._raise( command, status=status, message=result.message if result else "" ) def _raise( self, command: str, *, status: str = "", message: str = "", exception: Exception | None = None, ) -> None: error = HomeAssistantError( translation_domain=DOMAIN, translation_key="command_failure", translation_placeholders={ "command": command, "status": status, "message": message, }, ) if exception: raise error from exception raise error
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/volvo/button.py", "license": "Apache License 2.0", "lines": 115, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/volvo/device_tracker.py
"""Volvo device tracker.""" from dataclasses import dataclass from volvocarsapi.models import VolvoCarsApiBaseModel, VolvoCarsLocation from homeassistant.components.device_tracker import ( TrackerEntity, TrackerEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import VolvoConfigEntry from .entity import VolvoEntity, VolvoEntityDescription PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class VolvoTrackerDescription(VolvoEntityDescription, TrackerEntityDescription): """Describes a Volvo Cars tracker entity.""" _DESCRIPTIONS: tuple[VolvoTrackerDescription, ...] = ( VolvoTrackerDescription( key="location", api_field="location", ), ) async def async_setup_entry( _: HomeAssistant, entry: VolvoConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up tracker.""" coordinators = entry.runtime_data.interval_coordinators async_add_entities( VolvoDeviceTracker(coordinator, description) for coordinator in coordinators for description in _DESCRIPTIONS if description.api_field in coordinator.data ) class VolvoDeviceTracker(VolvoEntity, TrackerEntity): """Volvo tracker.""" entity_description: VolvoTrackerDescription def _update_state(self, api_field: VolvoCarsApiBaseModel | None) -> None: assert isinstance(api_field, VolvoCarsLocation) if api_field.geometry.coordinates and len(api_field.geometry.coordinates) > 1: self._attr_longitude = api_field.geometry.coordinates[0] self._attr_latitude = api_field.geometry.coordinates[1]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/volvo/device_tracker.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/volvo/diagnostics.py
"""Volvo diagnostics.""" from dataclasses import asdict from typing import Any from homeassistant.const import CONF_ACCESS_TOKEN, CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.helpers.redact import async_redact_data from .const import CONF_VIN from .coordinator import VolvoConfigEntry _TO_REDACT_ENTRY = [ CONF_ACCESS_TOKEN, CONF_API_KEY, CONF_VIN, "id_token", "refresh_token", ] _TO_REDACT_DATA = [ "coordinates", "heading", "vin", ] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: VolvoConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" context = entry.runtime_data.interval_coordinators[0].context data: dict[str, dict] = {} for coordinator in entry.runtime_data.interval_coordinators: data[coordinator.name] = { key: async_redact_data(asdict(value), _TO_REDACT_DATA) if value else None for key, value in coordinator.data.items() } return { "entry_data": async_redact_data(entry.data, _TO_REDACT_ENTRY), "vehicle": async_redact_data(asdict(context.vehicle), _TO_REDACT_DATA), **data, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/volvo/diagnostics.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/xbox/image.py
"""Image platform for the Xbox integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from enum import StrEnum from typing import TYPE_CHECKING from pythonxbox.api.provider.people.models import Person from pythonxbox.api.provider.titlehub.models import Title from homeassistant.components.image import ImageEntity, ImageEntityDescription from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util from .coordinator import XboxConfigEntry, XboxPresenceCoordinator from .entity import XboxBaseEntity, XboxBaseEntityDescription, profile_pic PARALLEL_UPDATES = 0 class XboxImage(StrEnum): """Xbox image.""" NOW_PLAYING = "now_playing" GAMERPIC = "gamerpic" AVATAR = "avatar" @dataclass(kw_only=True, frozen=True) class XboxImageEntityDescription(XboxBaseEntityDescription, ImageEntityDescription): """Xbox image description.""" image_url_fn: Callable[[Person, Title | None], str | None] IMAGE_DESCRIPTIONS: tuple[XboxImageEntityDescription, ...] = ( XboxImageEntityDescription( key=XboxImage.GAMERPIC, translation_key=XboxImage.GAMERPIC, image_url_fn=profile_pic, ), XboxImageEntityDescription( key=XboxImage.NOW_PLAYING, translation_key=XboxImage.NOW_PLAYING, image_url_fn=lambda _, title: title.display_image if title else None, ), XboxImageEntityDescription( key=XboxImage.AVATAR, translation_key=XboxImage.AVATAR, image_url_fn=( lambda person, _: ( f"https://avatar-ssl.xboxlive.com/avatar/{person.gamertag}/avatar-body.png" ) ), ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: XboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Xbox images.""" coordinator = config_entry.runtime_data.presence if TYPE_CHECKING: assert config_entry.unique_id async_add_entities( [ XboxImageEntity(hass, coordinator, config_entry.unique_id, description) for description in IMAGE_DESCRIPTIONS ] ) for subentry_id, subentry in config_entry.subentries.items(): async_add_entities( [ XboxImageEntity(hass, coordinator, subentry.unique_id, description) for description in IMAGE_DESCRIPTIONS if subentry.unique_id and subentry.unique_id in coordinator.data.presence and subentry.subentry_type == "friend" ], config_subentry_id=subentry_id, ) class XboxImageEntity(XboxBaseEntity, ImageEntity): """An image entity.""" entity_description: XboxImageEntityDescription def __init__( self, hass: HomeAssistant, coordinator: XboxPresenceCoordinator, xuid: str, entity_description: XboxImageEntityDescription, ) -> None: """Initialize the image entity.""" super().__init__(coordinator, xuid, entity_description) ImageEntity.__init__(self, hass) self._attr_image_url = self.entity_description.image_url_fn( self.data, self.title_info ) self._attr_image_last_updated = dt_util.utcnow() def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" if self.available: url = self.entity_description.image_url_fn(self.data, self.title_info) if url != self._attr_image_url: self._attr_image_url = url self._cached_image = None self._attr_image_last_updated = dt_util.utcnow() super()._handle_coordinator_update()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/xbox/image.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple