sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:homeassistant/components/watts/switch.py
"""Switch platform for Watts Vision integration.""" from __future__ import annotations import logging from typing import Any from visionpluspython.models import SwitchDevice from homeassistant.components.switch import SwitchEntity from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import WattsVisionConfigEntry from .const import DOMAIN from .coordinator import WattsVisionDeviceCoordinator from .entity import WattsVisionEntity _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: WattsVisionConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Watts Vision switch entities from a config entry.""" device_coordinators = entry.runtime_data.device_coordinators known_device_ids: set[str] = set() @callback def _check_new_switches() -> None: """Check for new switch devices.""" switch_coords = { did: coord for did, coord in device_coordinators.items() if isinstance(coord.data.device, SwitchDevice) } current_device_ids = set(switch_coords.keys()) new_device_ids = current_device_ids - known_device_ids if not new_device_ids: return _LOGGER.debug( "Adding switch entities for %d new switch(es)", len(new_device_ids), ) new_entities = [] for device_id in new_device_ids: coord = switch_coords[device_id] device = coord.data.device assert isinstance(device, SwitchDevice) new_entities.append(WattsVisionSwitch(coord, device)) known_device_ids.update(new_device_ids) async_add_entities(new_entities) _check_new_switches() entry.async_on_unload( async_dispatcher_connect( hass, f"{DOMAIN}_{entry.entry_id}_new_device", _check_new_switches, ) ) class WattsVisionSwitch(WattsVisionEntity[SwitchDevice], SwitchEntity): """Representation of a Watts Vision switch.""" _attr_name = None def __init__( self, coordinator: WattsVisionDeviceCoordinator, switch: SwitchDevice, ) -> None: """Initialize the switch entity.""" super().__init__(coordinator, switch.device_id) @property def is_on(self) -> bool: """Return true if the switch is on.""" return self.device.is_turned_on async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" try: await self.coordinator.client.set_switch_state(self.device_id, True) except RuntimeError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_switch_state_error", ) from err _LOGGER.debug( "Successfully turned on switch %s", self.device_id, ) self.coordinator.trigger_fast_polling() await self.coordinator.async_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" try: await self.coordinator.client.set_switch_state(self.device_id, False) except RuntimeError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="set_switch_state_error", ) from err _LOGGER.debug( "Successfully turned off switch %s", self.device_id, ) self.coordinator.trigger_fast_polling() await self.coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/watts/switch.py", "license": "Apache License 2.0", "lines": 100, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/watts/test_switch.py
"""Tests for the Watts Vision switch platform.""" from datetime import timedelta from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_OFF, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform async def test_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test the switch entities.""" with patch("homeassistant.components.watts.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_switch_state( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test switch state.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("switch.living_room_switch") assert state is not None assert state.state == STATE_OFF @pytest.mark.parametrize( ("service", "expected_state"), [ (SERVICE_TURN_ON, True), (SERVICE_TURN_OFF, False), ], ) async def test_turn_on_off( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, service: str, expected_state: bool, ) -> None: """Test turning switch on and off.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) mock_watts_client.set_switch_state.assert_called_once_with( "switch_789", expected_state ) async def test_fast_polling( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test that turning on triggers fast polling and it stops after duration.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) mock_watts_client.get_device.reset_mock() # Fast polling should be active freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_watts_client.get_device.called mock_watts_client.get_device.assert_called_with("switch_789", refresh=True) # Should still be in fast polling after 55s mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=50)) async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_watts_client.get_device.called mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=10)) async_fire_time_changed(hass) await hass.async_block_till_done() # Fast polling should be done now mock_watts_client.get_device.reset_mock() freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() assert not mock_watts_client.get_device.called @pytest.mark.parametrize( "service", [SERVICE_TURN_ON, SERVICE_TURN_OFF], ) async def test_api_error( hass: HomeAssistant, mock_watts_client: AsyncMock, mock_config_entry: MockConfigEntry, service: str, ) -> None: """Test error handling when turning on/off fails.""" await setup_integration(hass, mock_config_entry) mock_watts_client.set_switch_state.side_effect = RuntimeError("API Error") with pytest.raises( HomeAssistantError, match="An error occurred while setting the switch state" ): await hass.services.async_call( SWITCH_DOMAIN, service, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/watts/test_switch.py", "license": "Apache License 2.0", "lines": 124, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/intelliclima/config_flow.py
"""Config flow for IntelliClima integration.""" from typing import Any from pyintelliclima import IntelliClimaAPI, IntelliClimaAPIError, IntelliClimaAuthError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN, LOGGER STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME): str, vol.Required(CONF_PASSWORD): str, } ) class IntelliClimaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for IntelliClima VMC.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors = {} if user_input is not None: self._async_abort_entries_match({CONF_USERNAME: user_input[CONF_USERNAME]}) # Validate credentials session = async_get_clientsession(self.hass) api = IntelliClimaAPI( session, user_input[CONF_USERNAME], user_input[CONF_PASSWORD], ) try: # Test authentication await api.authenticate() # Get devices to ensure we can communicate with API devices = await api.get_all_device_status() except IntelliClimaAuthError: errors["base"] = "invalid_auth" except IntelliClimaAPIError: errors["base"] = "cannot_connect" except Exception: # noqa: BLE001 LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: if devices.num_devices == 0: errors["base"] = "no_devices" else: return self.async_create_entry( title=f"IntelliClima ({user_input[CONF_USERNAME]})", data=user_input, ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/intelliclima/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/intelliclima/const.py
"""Constants for the IntelliClima integration.""" from datetime import timedelta import logging LOGGER = logging.getLogger(__package__) DOMAIN = "intelliclima" # Update interval DEFAULT_SCAN_INTERVAL = timedelta(minutes=1)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/intelliclima/const.py", "license": "Apache License 2.0", "lines": 7, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/intelliclima/coordinator.py
"""DataUpdateCoordinator for IntelliClima.""" from pyintelliclima import IntelliClimaAPI, IntelliClimaAPIError, IntelliClimaDevices from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN, LOGGER type IntelliClimaConfigEntry = ConfigEntry[IntelliClimaCoordinator] class IntelliClimaCoordinator(DataUpdateCoordinator[IntelliClimaDevices]): """Coordinator to manage fetching IntelliClima data.""" def __init__( self, hass: HomeAssistant, entry: IntelliClimaConfigEntry, api: IntelliClimaAPI ) -> None: """Initialize the coordinator.""" super().__init__( hass, LOGGER, name=DOMAIN, update_interval=DEFAULT_SCAN_INTERVAL, config_entry=entry, ) self.api = api async def _async_setup(self) -> None: """Set up the coordinator - called once during first refresh.""" # Authenticate and get initial device list try: await self.api.authenticate() except IntelliClimaAPIError as err: raise UpdateFailed(f"Failed to set up IntelliClima: {err}") from err async def _async_update_data(self) -> IntelliClimaDevices: """Fetch data from API.""" try: # Poll status for all devices return await self.api.get_all_device_status() except IntelliClimaAPIError as err: raise UpdateFailed(f"Failed to update data: {err}") from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/intelliclima/coordinator.py", "license": "Apache License 2.0", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/intelliclima/entity.py
"""Platform for shared base classes for sensors.""" from pyintelliclima.intelliclima_types import IntelliClimaC800, IntelliClimaECO from homeassistant.const import ATTR_CONNECTIONS, ATTR_MODEL, ATTR_SW_VERSION from homeassistant.helpers.device_registry import ( CONNECTION_BLUETOOTH, CONNECTION_NETWORK_MAC, DeviceInfo, ) from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import IntelliClimaCoordinator class IntelliClimaEntity(CoordinatorEntity[IntelliClimaCoordinator]): """Define a generic class for IntelliClima entities.""" _attr_has_entity_name = True def __init__( self, coordinator: IntelliClimaCoordinator, device: IntelliClimaECO | IntelliClimaC800, ) -> None: """Class initializer.""" super().__init__(coordinator=coordinator) # Make this HA "device" use the IntelliClima device name. self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.id)}, manufacturer="Fantini Cosmi", name=device.name, serial_number=device.crono_sn, ) self._device_id = device.id self._device_sn = device.crono_sn class IntelliClimaECOEntity(IntelliClimaEntity): """Specific entity for the ECOCOMFORT 2.0.""" def __init__( self, coordinator: IntelliClimaCoordinator, device: IntelliClimaECO, ) -> None: """Class initializer.""" super().__init__(coordinator, device) self._attr_device_info: DeviceInfo = self.device_info or DeviceInfo() self._attr_device_info[ATTR_MODEL] = "ECOCOMFORT 2.0" self._attr_device_info[ATTR_SW_VERSION] = device.fw self._attr_device_info[ATTR_CONNECTIONS] = { (CONNECTION_BLUETOOTH, device.mac), (CONNECTION_NETWORK_MAC, device.macwifi), } @property def _device_data(self) -> IntelliClimaECO: return self.coordinator.data.ecocomfort2_devices[self._device_id] @property def available(self) -> bool: """Return if entity is available.""" return ( super().available and self._device_id in self.coordinator.data.ecocomfort2_devices )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/intelliclima/entity.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/intelliclima/fan.py
"""Fan platform for IntelliClima VMC.""" import math from typing import Any from pyintelliclima.const import FanMode, FanSpeed from pyintelliclima.intelliclima_types import IntelliClimaECO from homeassistant.components.fan import FanEntity, FanEntityFeature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util.percentage import ( percentage_to_ranged_value, ranged_value_to_percentage, ) from homeassistant.util.scaling import int_states_in_range from .coordinator import IntelliClimaConfigEntry, IntelliClimaCoordinator from .entity import IntelliClimaECOEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, entry: IntelliClimaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up IntelliClima VMC fans.""" coordinator = entry.runtime_data entities: list[IntelliClimaVMCFan] = [ IntelliClimaVMCFan( coordinator=coordinator, device=ecocomfort2, ) for ecocomfort2 in coordinator.data.ecocomfort2_devices.values() ] async_add_entities(entities) class IntelliClimaVMCFan(IntelliClimaECOEntity, FanEntity): """Representation of an IntelliClima VMC fan.""" _attr_name = None _attr_supported_features = ( FanEntityFeature.PRESET_MODE | FanEntityFeature.SET_SPEED | FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON ) _attr_preset_modes = ["auto"] def __init__( self, coordinator: IntelliClimaCoordinator, device: IntelliClimaECO, ) -> None: """Class initializer.""" super().__init__(coordinator, device) self._speed_range = (int(FanSpeed.sleep), int(FanSpeed.high)) self._attr_unique_id = device.id @property def is_on(self) -> bool: """Return true if fan is on.""" return bool(self._device_data.mode_set != FanMode.off) @property def percentage(self) -> int | None: """Return the current speed percentage.""" device_data = self._device_data if device_data.speed_set == FanSpeed.auto: return None return ranged_value_to_percentage(self._speed_range, int(device_data.speed_set)) @property def speed_count(self) -> int: """Return the number of speeds the fan supports.""" return int_states_in_range(self._speed_range) @property def preset_mode(self) -> str | None: """Return the current preset mode.""" device_data = self._device_data if device_data.mode_set == FanMode.off: return None if ( device_data.speed_set == FanSpeed.auto and device_data.mode_set == FanMode.sensor ): return "auto" return None async def async_turn_on( self, percentage: int | None = None, preset_mode: str | None = None, **kwargs: Any, ) -> None: """Turn on the fan. Defaults back to 25% if percentage argument is 0 to prevent loop of turning off/on infinitely. """ percentage = 25 if percentage == 0 else percentage await self.async_set_mode_speed(fan_mode=preset_mode, percentage=percentage) async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the fan.""" await self.coordinator.api.ecocomfort.turn_off(self._device_sn) await self.coordinator.async_request_refresh() async def async_set_percentage(self, percentage: int) -> None: """Set the speed percentage.""" await self.async_set_mode_speed(percentage=percentage) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set preset mode.""" await self.async_set_mode_speed(fan_mode=preset_mode) async def async_set_mode_speed( self, fan_mode: str | None = None, percentage: int | None = None ) -> None: """Set mode and speed. If percentage is None, it first defaults to the respective property. If that is also None, then percentage defaults to 25 (sleep) """ percentage = self.percentage if percentage is None else percentage percentage = 25 if percentage is None else percentage if fan_mode == "auto": # auto is a special case with special mode and speed setting await self.coordinator.api.ecocomfort.set_mode_speed_auto(self._device_sn) await self.coordinator.async_request_refresh() return if percentage == 0: # Setting fan speed to zero turns off the fan await self.async_turn_off() return # Determine the fan mode if fan_mode is not None: # Set to requested fan_mode mode = fan_mode elif not self.is_on: # Default to alternate fan mode if not turned on mode = FanMode.alternate else: # Maintain current mode mode = self._device_data.mode_set speed = str( math.ceil( percentage_to_ranged_value( self._speed_range, percentage, ) ) ) speed = FanSpeed.sleep if speed == FanSpeed.off else speed await self.coordinator.api.ecocomfort.set_mode_speed( self._device_sn, mode, speed ) await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/intelliclima/fan.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/intelliclima/test_config_flow.py
"""Test the IntelliClima config flow.""" from unittest.mock import AsyncMock from pyintelliclima.api import ( IntelliClimaAPIError, IntelliClimaAuthError, IntelliClimaDevices, ) import pytest from homeassistant.components.intelliclima.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry DATA_CONFIG = { CONF_USERNAME: "SuperUser", CONF_PASSWORD: "hunter2", } async def test_user_flow( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_cloud_interface ) -> None: """Test the full config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "IntelliClima (SuperUser)" assert result["data"] == DATA_CONFIG @pytest.mark.parametrize( ("side_effect", "error"), [ # invalid_auth (IntelliClimaAuthError, "invalid_auth"), # cannot_connect (IntelliClimaAPIError, "cannot_connect"), # unknown (RuntimeError("Unexpected error"), "unknown"), ], ) async def test_form_auth_errors( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_cloud_interface: AsyncMock, side_effect: Exception, error: str, ) -> None: """Test we handle authentication-related errors and recover.""" mock_cloud_interface.authenticate.side_effect = side_effect result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error} # Recover: clear side effect and complete flow successfully mock_cloud_interface.authenticate.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "IntelliClima (SuperUser)" assert result["data"] == DATA_CONFIG async def test_form_no_devices( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_cloud_interface: AsyncMock, single_eco_device: IntelliClimaDevices, ) -> None: """Test we handle no devices found error.""" # Return empty devices list mock_cloud_interface.get_all_device_status.return_value = IntelliClimaDevices( ecocomfort2_devices={}, c800_devices={} ) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "no_devices"} # Reset the return_value to its default state mock_cloud_interface.get_all_device_status.return_value = single_eco_device result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "IntelliClima (SuperUser)" assert result["data"] == DATA_CONFIG async def test_form_already_configured( hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_cloud_interface: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test creating a second config for the same account aborts.""" mock_config_entry.add_to_hass(hass) # Second attempt with the same account result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], DATA_CONFIG ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/intelliclima/test_config_flow.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/intelliclima/test_fan.py
"""Test IntelliClima Fans.""" from collections.abc import AsyncGenerator from unittest.mock import AsyncMock, patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.fan import ( ATTR_PERCENTAGE, ATTR_PRESET_MODE, DOMAIN as FAN_DOMAIN, SERVICE_SET_PERCENTAGE, SERVICE_SET_PRESET_MODE, ) from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform FAN_ENTITY_ID = "fan.test_vmc" @pytest.fixture(autouse=True) async def setup_intelliclima_fan_only( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_cloud_interface: AsyncMock, ) -> AsyncGenerator[None]: """Set up IntelliClima integration with only the fan platform.""" with patch("homeassistant.components.intelliclima.PLATFORMS", [Platform.FAN]): await setup_integration(hass, mock_config_entry) # Let tests run against this initialized state yield async def test_all_fan_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, device_registry: dr.DeviceRegistry, mock_cloud_interface: AsyncMock, ) -> None: """Test all entities.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) # There should be exactly one fan entity fan_entries = [ entry for entry in entity_registry.entities.values() if entry.platform == "intelliclima" and entry.domain == FAN_DOMAIN ] assert len(fan_entries) == 1 entity_entry = fan_entries[0] # Device should exist and match snapshot assert entity_entry.device_id assert (device_entry := device_registry.async_get(entity_entry.device_id)) assert device_entry == snapshot async def test_fan_turn_off_service_calls_api( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """fan.turn_off should call ecocomfort.turn_off and refresh.""" await hass.services.async_call( FAN_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: FAN_ENTITY_ID}, blocking=True, ) # Device serial from single_eco_device.crono_sn mock_cloud_interface.ecocomfort.turn_off.assert_awaited_once_with("11223344") mock_cloud_interface.ecocomfort.set_mode_speed.assert_not_awaited() async def test_fan_turn_on_service_calls_api( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """fan.turn_on should call ecocomfort.turn_on and refresh.""" await hass.services.async_call( FAN_DOMAIN, SERVICE_TURN_ON, { ATTR_ENTITY_ID: FAN_ENTITY_ID, ATTR_PERCENTAGE: 30, }, blocking=True, ) # Device serial from single_eco_device.crono_sn mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with( "11223344", "1", "2" ) async def test_fan_set_percentage_maps_to_speed( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """fan.set_percentage maps to closest IntelliClima speed via set_mode_speed.""" # 15% is closest to 25% (sleep). await hass.services.async_call( FAN_DOMAIN, SERVICE_SET_PERCENTAGE, {ATTR_ENTITY_ID: FAN_ENTITY_ID, ATTR_PERCENTAGE: 15}, blocking=True, ) # Initial mode_set="1" (forward) from single_eco_device. # Sleep speed is "1" (25%). mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with( "11223344", "1", "1" ) async def test_fan_set_preset_mode_service( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """Tests whether the set preset mode service is called and correct api call is followed.""" await hass.services.async_call( FAN_DOMAIN, SERVICE_SET_PRESET_MODE, {ATTR_ENTITY_ID: FAN_ENTITY_ID, ATTR_PRESET_MODE: "auto"}, blocking=True, ) mock_cloud_interface.ecocomfort.set_mode_speed_auto.assert_awaited_once_with( "11223344" ) mock_cloud_interface.ecocomfort.turn_off.assert_not_awaited() async def test_fan_set_percentage_zero_turns_off( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """Setting percentage to 0 should call turn_off, not set_mode_speed.""" await hass.services.async_call( FAN_DOMAIN, SERVICE_SET_PERCENTAGE, {ATTR_ENTITY_ID: FAN_ENTITY_ID, ATTR_PERCENTAGE: 0}, blocking=True, ) mock_cloud_interface.ecocomfort.turn_off.assert_awaited_once_with("11223344") mock_cloud_interface.ecocomfort.set_mode_speed.assert_not_awaited() @pytest.mark.parametrize( ("service_data", "expected_mode", "expected_speed"), [ # percentage=None, preset_mode=None -> defaults to previous speed > 75% (medium), # previous mode > "inward" ({}, "1", "3"), # percentage=0, preset_mode=None -> default 25% (sleep), previous mode (inward) ({ATTR_PERCENTAGE: 0}, "1", "1"), ], ) async def test_fan_turn_on_defaulting_behavior( hass: HomeAssistant, mock_cloud_interface: AsyncMock, service_data: dict, expected_mode: str, expected_speed: str, ) -> None: """turn_on defaults percentage/preset as expected.""" data = {ATTR_ENTITY_ID: FAN_ENTITY_ID} | service_data await hass.services.async_call( FAN_DOMAIN, SERVICE_TURN_ON, data, blocking=True, ) mock_cloud_interface.ecocomfort.set_mode_speed.assert_awaited_once_with( "11223344", expected_mode, expected_speed ) mock_cloud_interface.ecocomfort.turn_off.assert_not_awaited() async def test_fan_turn_on_defaulting_behavior_auto_preset( hass: HomeAssistant, mock_cloud_interface: AsyncMock, ) -> None: """turn_on with auto preset mode calls auto request.""" await hass.services.async_call( FAN_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: FAN_ENTITY_ID, ATTR_PRESET_MODE: "auto"}, blocking=True, ) mock_cloud_interface.ecocomfort.set_mode_speed_auto.assert_awaited_once_with( "11223344" ) mock_cloud_interface.ecocomfort.turn_off.assert_not_awaited()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/intelliclima/test_fan.py", "license": "Apache License 2.0", "lines": 177, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/hegel/config_flow.py
"""Config flow for Hegel integration.""" from __future__ import annotations import logging from typing import Any from hegel_ip_client import HegelClient from hegel_ip_client.exceptions import HegelConnectionError import voluptuous as vol from yarl import URL from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo from .const import CONF_MODEL, DEFAULT_PORT, DOMAIN, MODEL_INPUTS _LOGGER = logging.getLogger(__name__) class HegelConfigFlow(ConfigFlow, domain=DOMAIN): """Config flow for Hegel amplifiers.""" VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._host: str | None = None self._name: str | None = None self._model: str | None = None async def _async_try_connect(self, host: str) -> bool: """Try to connect to the Hegel amplifier using the library.""" client = HegelClient(host, DEFAULT_PORT) try: await client.start() await client.ensure_connected(timeout=5.0) except HegelConnectionError, TimeoutError, OSError: return False else: return True finally: await client.stop() async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle manual setup by the user.""" errors: dict[str, str] = {} if user_input is not None: host = user_input[CONF_HOST] # Prevent duplicate entries by host self._async_abort_entries_match({CONF_HOST: host}) if not await self._async_try_connect(host): errors["base"] = "cannot_connect" else: return self.async_create_entry( title=f"Hegel {user_input[CONF_MODEL]}", data=user_input, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_HOST): str, vol.Required(CONF_MODEL): vol.In(list(MODEL_INPUTS.keys())), } ), errors=errors, ) async def async_step_ssdp( self, discovery_info: SsdpServiceInfo ) -> ConfigFlowResult: """Handle SSDP discovery.""" upnp = discovery_info.upnp or {} # Get host from presentationURL or ssdp_location url = upnp.get("presentationURL") or discovery_info.ssdp_location if not url: return self.async_abort(reason="no_host_found") host = URL(url).host if not host: return self.async_abort(reason="no_host_found") # Use UDN as unique id (device UUID) unique_id = discovery_info.ssdp_udn if not unique_id: return self.async_abort(reason="no_host_found") await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) # Test connection before showing confirmation if not await self._async_try_connect(host): return self.async_abort(reason="cannot_connect") # Get device info friendly_name = upnp.get("friendlyName", f"Hegel {host}") suggested_model = upnp.get("modelName") or "" model_default = next( (m for m in MODEL_INPUTS if suggested_model.upper().startswith(m.upper())), None, ) self._host = host self._name = friendly_name self._model = model_default self.context.update( { "title_placeholders": {"name": friendly_name}, } ) return await self.async_step_discovery_confirm() async def async_step_discovery_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle discovery confirmation - user can change model if needed.""" assert self._host is not None assert self._name is not None if user_input is not None: return self.async_create_entry( title=self._name, data={ CONF_HOST: self._host, CONF_MODEL: user_input[CONF_MODEL], }, ) return self.async_show_form( step_id="discovery_confirm", data_schema=vol.Schema( { vol.Required( CONF_MODEL, default=self._model or list(MODEL_INPUTS.keys())[0], ): vol.In(list(MODEL_INPUTS.keys())), } ), description_placeholders={ "host": self._host, "name": self._name, }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hegel/config_flow.py", "license": "Apache License 2.0", "lines": 125, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/hegel/const.py
"""Constants for the Hegel integration.""" DOMAIN = "hegel" DEFAULT_PORT = 50001 CONF_MODEL = "model" CONF_MAX_VOLUME = "max_volume" # 1.0 means amp's internal max HEARTBEAT_TIMEOUT_MINUTES = 3 MODEL_INPUTS = { "Röst": [ "Balanced", "Analog 1", "Analog 2", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], "H95": [ "Analog 1", "Analog 2", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], "H120": [ "Balanced", "Analog 1", "Analog 2", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], "H190": [ "Balanced", "Analog 1", "Analog 2", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], "H190V": [ "XLR", "Analog 1", "Analog 2", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", "Phono", ], "H390": [ "XLR", "Analog 1", "Analog 2", "BNC", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], "H590": [ "XLR 1", "XLR 2", "Analog 1", "Analog 2", "BNC", "Coaxial", "Optical 1", "Optical 2", "Optical 3", "USB", "Network", ], }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hegel/const.py", "license": "Apache License 2.0", "lines": 88, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hegel/media_player.py
"""Hegel media player platform.""" from __future__ import annotations import asyncio from collections.abc import Callable import contextlib from datetime import timedelta import logging from typing import Any from hegel_ip_client import ( COMMANDS, HegelClient, apply_state_changes, parse_reply_message, ) from hegel_ip_client.exceptions import HegelConnectionError from homeassistant.components.media_player import ( MediaPlayerEntity, MediaPlayerEntityFeature, MediaPlayerState, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.event import async_track_time_interval from . import HegelConfigEntry from .const import CONF_MODEL, DOMAIN, HEARTBEAT_TIMEOUT_MINUTES, MODEL_INPUTS _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 1 async def async_setup_entry( hass: HomeAssistant, entry: HegelConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Hegel media player from a config entry.""" model = entry.data[CONF_MODEL] unique_id = entry.unique_id or entry.entry_id # map inputs (source_map) source_map: dict[int, str] = ( dict(enumerate(MODEL_INPUTS[model], start=1)) if model in MODEL_INPUTS else {} ) # Use the client from the config entry's runtime_data (already connected) client = entry.runtime_data # Create entity media = HegelMediaPlayer( entry, client, source_map, unique_id, ) async_add_entities([media]) class HegelMediaPlayer(MediaPlayerEntity): """Hegel amplifier entity.""" _attr_should_poll = False _attr_name = None _attr_has_entity_name = True _attr_supported_features = ( MediaPlayerEntityFeature.VOLUME_SET | MediaPlayerEntityFeature.VOLUME_MUTE | MediaPlayerEntityFeature.VOLUME_STEP | MediaPlayerEntityFeature.SELECT_SOURCE | MediaPlayerEntityFeature.TURN_ON | MediaPlayerEntityFeature.TURN_OFF ) def __init__( self, config_entry: HegelConfigEntry, client: HegelClient, source_map: dict[int, str], unique_id: str, ) -> None: """Initialize the Hegel media player entity.""" self._entry = config_entry self._client = client self._source_map = source_map # Set unique_id from config entry self._attr_unique_id = unique_id # Set device info self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, unique_id)}, name=config_entry.title, manufacturer="Hegel", model=config_entry.data[CONF_MODEL], ) # State will be populated by async_update on first connection self._state: dict[str, Any] = {} # Background tasks self._connected_watcher_task: asyncio.Task[None] | None = None self._push_task: asyncio.Task[None] | None = None self._push_handler: Callable[[str], None] | None = None async def async_added_to_hass(self) -> None: """Handle entity added to Home Assistant.""" await super().async_added_to_hass() _LOGGER.debug("Hegel media player added to hass: %s", self.entity_id) # Register push handler for real-time updates from the amplifier # The client expects a synchronous callable; schedule a coroutine safely def push_handler(msg: str) -> None: self._push_task = self.hass.async_create_task(self._async_handle_push(msg)) self._push_handler = push_handler self._client.add_push_callback(push_handler) # Register cleanup for push handler using async_on_remove def cleanup_push_handler() -> None: if self._push_handler: self._client.remove_push_callback(self._push_handler) _LOGGER.debug("Push callback removed") self._push_handler = None self.async_on_remove(cleanup_push_handler) # Perform initial state fetch if already connected # The watcher handles reconnections, but we need to fetch state on first setup if self._client.is_connected(): _LOGGER.debug("Client already connected, performing initial state fetch") await self.async_update() # Start a watcher task # Use config_entry.async_create_background_task for automatic cleanup on unload self._connected_watcher_task = self._entry.async_create_background_task( self.hass, self._connected_watcher(), name=f"hegel_{self.entity_id}_connected_watcher", ) # Note: No need for async_on_remove - entry.async_create_background_task # automatically cancels the task when the config entry is unloaded # Schedule the heartbeat every 2 minutes while the reset timeout is 3 minutes self.async_on_remove( async_track_time_interval( self.hass, self._send_heartbeat, timedelta(minutes=HEARTBEAT_TIMEOUT_MINUTES - 1), ) ) # Send the first heartbeat immediately self.hass.async_create_task(self._send_heartbeat()) async def _send_heartbeat(self, now=None) -> None: if not self.available: return try: await self._client.send( f"-r.{HEARTBEAT_TIMEOUT_MINUTES}", expect_reply=False ) except (HegelConnectionError, TimeoutError, OSError) as err: _LOGGER.debug("Heartbeat failed: %s", err) async def _async_handle_push(self, msg: str) -> None: """Handle incoming push message from client (runs in event loop).""" try: update = parse_reply_message(msg) if update.has_changes(): apply_state_changes(self._state, update, logger=_LOGGER, source="push") # notify HA self.async_write_ha_state() except ValueError, KeyError, AttributeError: _LOGGER.exception("Failed to handle push message") async def _connected_watcher(self) -> None: """Watch the client's connection events and update state accordingly.""" conn_event = self._client.connected_event disconn_event = self._client.disconnected_event _LOGGER.debug("Connected watcher started") try: while True: # Wait for connection _LOGGER.debug("Watcher: waiting for connection") await conn_event.wait() _LOGGER.debug("Watcher: connected, refreshing state") # Immediately notify HA that we're available again self.async_write_ha_state() # Schedule a state refresh through HA self.async_schedule_update_ha_state(force_refresh=True) # Wait for disconnection using event (no polling!) _LOGGER.debug("Watcher: waiting for disconnection") await disconn_event.wait() _LOGGER.debug("Watcher: disconnected") # Notify HA that we're unavailable self.async_write_ha_state() except asyncio.CancelledError: _LOGGER.debug("Connected watcher cancelled") except (HegelConnectionError, OSError) as err: _LOGGER.warning("Connected watcher failed: %s", err) async def async_will_remove_from_hass(self) -> None: """Handle entity removal from Home Assistant. Note: Push callback cleanup is handled by async_on_remove. _connected_watcher_task cleanup is handled automatically by entry.async_create_background_task when the config entry is unloaded. """ await super().async_will_remove_from_hass() # Cancel push task if running (short-lived task, defensive cleanup) if self._push_task and not self._push_task.done(): self._push_task.cancel() with contextlib.suppress(asyncio.CancelledError): await self._push_task async def async_update(self) -> None: """Query the amplifier for the main values and update state dict.""" for cmd in ( COMMANDS["power_query"], COMMANDS["volume_query"], COMMANDS["mute_query"], COMMANDS["input_query"], ): try: update = await self._client.send(cmd, expect_reply=True, timeout=3.0) if update and update.has_changes(): apply_state_changes( self._state, update, logger=_LOGGER, source="update" ) except (HegelConnectionError, TimeoutError, OSError) as err: _LOGGER.debug("Refresh command %s failed: %s", cmd, err) # update entity state self.async_write_ha_state() @property def available(self) -> bool: """Return True if the client is connected.""" return self._client.is_connected() @property def state(self) -> MediaPlayerState | None: """Return the current state of the media player.""" power = self._state.get("power") if power is None: return None return MediaPlayerState.ON if power else MediaPlayerState.OFF @property def volume_level(self) -> float | None: """Return the volume level.""" volume = self._state.get("volume") if volume is None: return None return float(volume) @property def is_volume_muted(self) -> bool | None: """Return whether volume is muted.""" return bool(self._state.get("mute", False)) @property def source(self) -> str | None: """Return the current input source.""" idx = self._state.get("input") return self._source_map.get(idx, f"Input {idx}") if idx else None @property def source_list(self) -> list[str] | None: """Return the list of available input sources.""" return [self._source_map[k] for k in sorted(self._source_map.keys())] or None async def async_turn_on(self) -> None: """Turn on the media player.""" try: await self._client.send(COMMANDS["power_on"], expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to turn on: {err}") from err async def async_turn_off(self) -> None: """Turn off the media player.""" try: await self._client.send(COMMANDS["power_off"], expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to turn off: {err}") from err async def async_set_volume_level(self, volume: float) -> None: """Set volume level, range 0..1.""" vol = max(0.0, min(volume, 1.0)) amp_vol = int(round(vol * 100)) try: await self._client.send(COMMANDS["volume_set"](amp_vol), expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to set volume: {err}") from err async def async_mute_volume(self, mute: bool) -> None: """Mute or unmute the volume.""" try: await self._client.send( COMMANDS["mute_on" if mute else "mute_off"], expect_reply=False ) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to set mute: {err}") from err async def async_volume_up(self) -> None: """Increase volume.""" try: await self._client.send(COMMANDS["volume_up"], expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to increase volume: {err}") from err async def async_volume_down(self) -> None: """Decrease volume.""" try: await self._client.send(COMMANDS["volume_down"], expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError(f"Failed to decrease volume: {err}") from err async def async_select_source(self, source: str) -> None: """Select input source.""" inv = {v: k for k, v in self._source_map.items()} idx = inv.get(source) if idx is None: raise ServiceValidationError(f"Unknown source: {source}") try: await self._client.send(COMMANDS["input_set"](idx), expect_reply=False) except (HegelConnectionError, TimeoutError, OSError) as err: raise HomeAssistantError( f"Failed to select source {source}: {err}" ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hegel/media_player.py", "license": "Apache License 2.0", "lines": 288, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/hegel/test_config_flow.py
"""Test the Hegel config flow.""" from unittest.mock import MagicMock from homeassistant.components.hegel.const import CONF_MODEL, DOMAIN from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo from .const import TEST_HOST, TEST_MODEL, TEST_UDN from tests.common import MockConfigEntry TEST_NAME = "Hegel H190" TEST_SSDP_LOCATION = f"http://{TEST_HOST}:8080/description.xml" async def test_user_flow_success( hass: HomeAssistant, mock_setup_entry: MagicMock, mock_hegel_client: MagicMock, ) -> None: """Test successful user flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == f"Hegel {TEST_MODEL}" assert result["data"] == { CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL, } async def test_user_flow_exception( hass: HomeAssistant, mock_setup_entry: MagicMock, mock_hegel_client: MagicMock, ) -> None: """Test user flow when connection fails.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" mock_hegel_client.ensure_connected.side_effect = OSError("Connection refused") result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} mock_hegel_client.ensure_connected.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_user_flow_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test user flow aborts when device is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_ssdp_discovery_success( hass: HomeAssistant, mock_setup_entry: MagicMock, mock_hegel_client: MagicMock, ) -> None: """Test successful SSDP discovery.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "discovery_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_MODEL: TEST_MODEL} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_NAME assert result["data"] == {CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL} assert result["result"].unique_id == TEST_UDN async def test_ssdp_discovery_from_ssdp_location( hass: HomeAssistant, mock_setup_entry: MagicMock, mock_hegel_client: MagicMock, ) -> None: """Test SSDP discovery extracts host from ssdp_location when presentationURL is not available.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={"friendlyName": TEST_NAME, "modelName": TEST_MODEL}, ), ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "discovery_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_MODEL: TEST_MODEL} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_NAME assert result["data"] == {CONF_HOST: TEST_HOST, CONF_MODEL: TEST_MODEL} async def test_ssdp_discovery_no_host(hass: HomeAssistant) -> None: """Test SSDP discovery aborts when no host can be determined.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location="", upnp={}, ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_host_found" async def test_ssdp_discovery_no_udn(hass: HomeAssistant) -> None: """Test SSDP discovery aborts when no UDN is available.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, }, ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_host_found" async def test_ssdp_discovery_already_configured( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test SSDP discovery aborts when device is already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_ssdp_discovery_already_configured_updates_host( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_hegel_client: MagicMock, ) -> None: """Test SSDP discovery updates host when device is already configured with different IP.""" new_host = "192.168.1.50" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=f"http://{new_host}:8080/description.xml", upnp={ "presentationURL": f"http://{new_host}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" # Verify the host was updated assert mock_config_entry.data[CONF_HOST] == new_host async def test_ssdp_discovery_cannot_connect( hass: HomeAssistant, mock_hegel_client: MagicMock, ) -> None: """Test SSDP discovery aborts when connection fails.""" mock_hegel_client.ensure_connected.side_effect = OSError("Connection refused") result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "cannot_connect" async def test_ssdp_discovery_unknown_model( hass: HomeAssistant, mock_hegel_client: MagicMock, ) -> None: """Test SSDP discovery with unknown model falls back to first model in list.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": "Hegel Unknown", "modelName": "UnknownModel", }, ), ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "discovery_confirm" async def test_ssdp_discovery_multiple_services_same_device( hass: HomeAssistant, mock_hegel_client: MagicMock, ) -> None: """Test that multiple SSDP discoveries from same device result in single discovery. A MediaRenderer device advertises multiple SSDP services (RenderingControl, AVTransport, ConnectionManager) each with different USN but same UDN. This test verifies that only one discovery entry is created. """ # First discovery - RenderingControl service result1 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn=f"{TEST_UDN}::urn:schemas-upnp-org:service:RenderingControl:1", ssdp_st="urn:schemas-upnp-org:service:RenderingControl:1", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) assert result1["type"] is FlowResultType.FORM assert result1["step_id"] == "discovery_confirm" flow_id = result1["flow_id"] # Second discovery - AVTransport service (different USN, same UDN) result2 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SsdpServiceInfo( ssdp_usn=f"{TEST_UDN}::urn:schemas-upnp-org:service:AVTransport:1", ssdp_st="urn:schemas-upnp-org:service:AVTransport:1", ssdp_udn=TEST_UDN, ssdp_location=TEST_SSDP_LOCATION, upnp={ "presentationURL": f"http://{TEST_HOST}/", "friendlyName": TEST_NAME, "modelName": TEST_MODEL, }, ), ) # Second discovery should abort since same UDN is already in progress assert result2["type"] is FlowResultType.ABORT assert result2["reason"] == "already_in_progress" # Original flow should still be available flows = hass.config_entries.flow.async_progress() assert len([f for f in flows if f["flow_id"] == flow_id]) == 1
{ "repo_id": "home-assistant/core", "file_path": "tests/components/hegel/test_config_flow.py", "license": "Apache License 2.0", "lines": 315, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/lunatone/diagnostics.py
"""Diagnostics support for Lunatone integration.""" from typing import Any from homeassistant.core import HomeAssistant from .coordinator import LunatoneConfigEntry async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: LunatoneConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" return { "info": entry.runtime_data.coordinator_info.data.model_dump(), "devices": [ v.data.model_dump() for v in entry.runtime_data.coordinator_devices.data.values() ], }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lunatone/diagnostics.py", "license": "Apache License 2.0", "lines": 15, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/lunatone/test_diagnostics.py
"""Define tests for Lunatone diagnostics.""" 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_config_entry_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_lunatone_devices: AsyncMock, mock_lunatone_info: AsyncMock, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test the config entry level diagnostics.""" await setup_integration(hass, mock_config_entry) diagnostics = await get_diagnostics_for_config_entry( hass, hass_client, mock_config_entry ) assert diagnostics == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/lunatone/test_diagnostics.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/waterfurnace/coordinator.py
"""Data update coordinator for WaterFurnace.""" import logging from typing import TYPE_CHECKING from waterfurnace.waterfurnace import WaterFurnace, WFException, WFGateway, WFReading from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import UPDATE_INTERVAL if TYPE_CHECKING: from . import WaterFurnaceConfigEntry _LOGGER = logging.getLogger(__name__) class WaterFurnaceCoordinator(DataUpdateCoordinator[WFReading]): """WaterFurnace data update coordinator. Polls the WaterFurnace API regularly to keep the websocket connection alive. The server closes the connection if no data is requested for 30 seconds, so frequent polling is necessary. """ device_metadata: WFGateway | None def __init__( self, hass: HomeAssistant, client: WaterFurnace, config_entry: WaterFurnaceConfigEntry, ) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, name="WaterFurnace", update_interval=UPDATE_INTERVAL, config_entry=config_entry, ) self.client = client self.unit = str(client.gwid) self.device_metadata = None if client.devices is not None: self.device_metadata = next( (device for device in client.devices if device.gwid == self.unit), None ) async def _async_update_data(self): """Fetch data from WaterFurnace API with built-in retry logic.""" try: return await self.hass.async_add_executor_job(self.client.read_with_retry) except WFException as err: raise UpdateFailed(str(err)) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/waterfurnace/coordinator.py", "license": "Apache License 2.0", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/waterfurnace/test_init.py
"""Tests for WaterFurnace integration setup.""" from unittest.mock import Mock from waterfurnace.waterfurnace import WFCredentialError from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_setup_auth_failure( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_waterfurnace_client: Mock, ) -> None: """Test setup fails with auth error.""" mock_waterfurnace_client.login.side_effect = WFCredentialError( "Invalid credentials" ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
{ "repo_id": "home-assistant/core", "file_path": "tests/components/waterfurnace/test_init.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/waterfurnace/test_sensor.py
"""Test sensor of WaterFurnace integration.""" import asyncio from unittest.mock import Mock from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from waterfurnace.waterfurnace import WFException from homeassistant.components.waterfurnace.const import UPDATE_INTERVAL from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("init_integration") async def test_sensors( hass: HomeAssistant, mock_waterfurnace_client: Mock, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_config_entry: MockConfigEntry, ) -> None: """Test that we create the expected sensors.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("init_integration") async def test_sensor( hass: HomeAssistant, mock_waterfurnace_client: Mock, freezer: FrozenDateTimeFactory, ) -> None: """Test states of the sensor.""" state = hass.states.get("sensor.wf_test_gwid_12345_totalunitpower") assert state assert state.state == "1500" mock_waterfurnace_client.read_with_retry.return_value.totalunitpower = 2000 freezer.tick(UPDATE_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("sensor.wf_test_gwid_12345_totalunitpower") assert state assert state.state == "2000" @pytest.mark.usefixtures("init_integration") @pytest.mark.parametrize( "side_effect", [ WFException("Connection failed"), asyncio.TimeoutError, ], ) async def test_availability( hass: HomeAssistant, mock_waterfurnace_client: Mock, freezer: FrozenDateTimeFactory, side_effect: Exception, ) -> None: """Ensure that we mark the entities unavailable correctly when service is offline.""" entity_id = "sensor.wf_test_gwid_12345_totalunitpower" state = hass.states.get(entity_id) assert state assert state.state == "1500" mock_waterfurnace_client.read_with_retry.side_effect = side_effect freezer.tick(UPDATE_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == STATE_UNAVAILABLE mock_waterfurnace_client.read_with_retry.side_effect = None freezer.tick(UPDATE_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "1500"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/waterfurnace/test_sensor.py", "license": "Apache License 2.0", "lines": 72, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/liebherr/diagnostics.py
"""Diagnostics support for Liebherr.""" from __future__ import annotations from dataclasses import asdict from typing import Any from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from .coordinator import LiebherrConfigEntry TO_REDACT = {CONF_API_KEY} async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: LiebherrConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" return { "devices": { device_id: { "coordinator": { "last_update_success": coordinator.last_update_success, "update_interval": str(coordinator.update_interval), "last_exception": str(coordinator.last_exception) if coordinator.last_exception else None, }, "data": asdict(coordinator.data), } for device_id, coordinator in entry.runtime_data.coordinators.items() }, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/liebherr/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:tests/components/liebherr/test_diagnostics.py
"""Tests for the diagnostics data provided by the Liebherr integration.""" from unittest.mock import MagicMock from syrupy.assertion import SnapshotAssertion 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 async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, mock_liebherr_client: MagicMock, init_integration: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test diagnostics.""" assert ( await get_diagnostics_for_config_entry(hass, hass_client, init_integration) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/liebherr/test_diagnostics.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/saunum/services.py
"""Define services for the Saunum integration.""" from __future__ import annotations from datetime import timedelta from pysaunum import MAX_DURATION, MAX_FAN_DURATION, MAX_TEMPERATURE, MIN_TEMPERATURE import voluptuous as vol from homeassistant.components.climate import DOMAIN as CLIMATE_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN ATTR_DURATION = "duration" ATTR_TARGET_TEMPERATURE = "target_temperature" ATTR_FAN_DURATION = "fan_duration" SERVICE_START_SESSION = "start_session" @callback def async_setup_services(hass: HomeAssistant) -> None: """Register services for the Saunum integration.""" service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_START_SESSION, entity_domain=CLIMATE_DOMAIN, schema={ vol.Optional(ATTR_DURATION, default=timedelta(minutes=120)): vol.All( cv.time_period, vol.Range( min=timedelta(minutes=1), max=timedelta(minutes=MAX_DURATION), ), ), vol.Optional(ATTR_TARGET_TEMPERATURE, default=80): vol.All( cv.positive_int, vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE) ), vol.Optional(ATTR_FAN_DURATION, default=timedelta(minutes=10)): vol.All( cv.time_period, vol.Range( min=timedelta(minutes=1), max=timedelta(minutes=MAX_FAN_DURATION), ), ), }, func="async_start_session", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/saunum/services.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:tests/components/saunum/test_services.py
"""Tests for Saunum services.""" from dataclasses import replace from unittest.mock import MagicMock from pysaunum import SaunumException import pytest from homeassistant.components.saunum.const import DOMAIN from homeassistant.components.saunum.services import ( ATTR_DURATION, ATTR_FAN_DURATION, ATTR_TARGET_TEMPERATURE, SERVICE_START_SESSION, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from tests.common import MockConfigEntry @pytest.fixture def platforms() -> list[Platform]: """Fixture to specify platforms to test.""" return [Platform.CLIMATE] async def test_start_session_success( hass: HomeAssistant, init_integration: MockConfigEntry, mock_saunum_client: MagicMock, ) -> None: """Test start_session service success.""" await hass.services.async_call( DOMAIN, SERVICE_START_SESSION, { ATTR_ENTITY_ID: "climate.saunum_leil", ATTR_DURATION: {"hours": 2, "minutes": 0, "seconds": 0}, ATTR_TARGET_TEMPERATURE: 80, ATTR_FAN_DURATION: {"minutes": 10}, }, blocking=True, ) mock_saunum_client.async_set_sauna_duration.assert_called_once_with(120) mock_saunum_client.async_set_target_temperature.assert_called_once_with(80) mock_saunum_client.async_set_fan_duration.assert_called_once_with(10) mock_saunum_client.async_start_session.assert_called_once() async def test_start_session_with_defaults( hass: HomeAssistant, init_integration: MockConfigEntry, mock_saunum_client: MagicMock, ) -> None: """Test start_session service uses defaults when optional fields omitted.""" await hass.services.async_call( DOMAIN, SERVICE_START_SESSION, {ATTR_ENTITY_ID: "climate.saunum_leil"}, blocking=True, ) # Defaults: duration=120, target_temperature=80, fan_duration=10 mock_saunum_client.async_set_sauna_duration.assert_called_once_with(120) mock_saunum_client.async_set_target_temperature.assert_called_once_with(80) mock_saunum_client.async_set_fan_duration.assert_called_once_with(10) mock_saunum_client.async_start_session.assert_called_once() async def test_start_session_door_open( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_saunum_client: MagicMock, ) -> None: """Test start_session service fails when door is open.""" mock_saunum_client.async_get_data.return_value = replace( mock_saunum_client.async_get_data.return_value, door_open=True ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() with pytest.raises(ServiceValidationError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_START_SESSION, {ATTR_ENTITY_ID: "climate.saunum_leil"}, blocking=True, ) assert exc_info.value.translation_key == "door_open" async def test_start_session_communication_error( hass: HomeAssistant, init_integration: MockConfigEntry, mock_saunum_client: MagicMock, ) -> None: """Test start_session service handles communication error.""" mock_saunum_client.async_set_sauna_duration.side_effect = SaunumException( "Connection lost" ) with pytest.raises(HomeAssistantError) as exc_info: await hass.services.async_call( DOMAIN, SERVICE_START_SESSION, {ATTR_ENTITY_ID: "climate.saunum_leil"}, blocking=True, ) assert exc_info.value.translation_key == "start_session_failed"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/saunum/test_services.py", "license": "Apache License 2.0", "lines": 95, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/ghost/config_flow.py
"""Config flow for Ghost integration.""" from __future__ import annotations import logging from typing import Any from aioghost import GhostAdminAPI from aioghost.exceptions import GhostAuthError, GhostError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import CONF_ADMIN_API_KEY, CONF_API_URL, DOMAIN _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_API_URL): str, vol.Required(CONF_ADMIN_API_KEY): str, } ) class GhostConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Ghost.""" 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: api_url = user_input[CONF_API_URL].rstrip("/") admin_api_key = user_input[CONF_ADMIN_API_KEY] if ":" not in admin_api_key: errors["base"] = "invalid_api_key" else: result = await self._validate_and_create(api_url, admin_api_key, errors) if result: return result return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, description_placeholders={ "docs_url": "https://account.ghost.org/?r=settings/integrations/new" }, ) async def _validate_credentials( self, api_url: str, admin_api_key: str ) -> dict[str, Any]: """Validate credentials against the Ghost API. Returns site data on success. Raises GhostAuthError or GhostError on failure. """ api = GhostAdminAPI( api_url, admin_api_key, session=async_get_clientsession(self.hass) ) return await api.get_site() async def _validate_and_create( self, api_url: str, admin_api_key: str, errors: dict[str, str], ) -> ConfigFlowResult | None: """Validate credentials and create entry.""" try: site = await self._validate_credentials(api_url, admin_api_key) except GhostAuthError: errors["base"] = "invalid_auth" return None except GhostError: errors["base"] = "cannot_connect" return None except Exception: _LOGGER.exception("Unexpected error during Ghost setup") errors["base"] = "unknown" return None site_title = site["title"] await self.async_set_unique_id(site["uuid"]) self._abort_if_unique_id_configured() return self.async_create_entry( title=site_title, data={ CONF_API_URL: api_url, CONF_ADMIN_API_KEY: admin_api_key, }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ghost/config_flow.py", "license": "Apache License 2.0", "lines": 81, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/ghost/const.py
"""Constants for the Ghost integration.""" DOMAIN: str = "ghost" CONF_ADMIN_API_KEY: str = "admin_api_key" CONF_API_URL: str = "api_url" DEFAULT_SCAN_INTERVAL: int = 300 # 5 minutes # Device info. CURRENCY: str = "USD" MANUFACTURER: str = "Ghost Foundation" MODEL: str = "Ghost"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ghost/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/ghost/coordinator.py
"""DataUpdateCoordinator for Ghost.""" from __future__ import annotations import asyncio from dataclasses import dataclass from datetime import timedelta import logging from typing import TYPE_CHECKING, Any from aioghost import GhostAdminAPI from aioghost.exceptions import GhostAuthError, GhostError from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN if TYPE_CHECKING: from . import GhostConfigEntry _LOGGER = logging.getLogger(__name__) @dataclass class GhostData: """Data returned by the Ghost coordinator.""" site: dict[str, Any] posts: dict[str, Any] members: dict[str, Any] latest_post: dict[str, Any] | None latest_email: dict[str, Any] | None activitypub: dict[str, Any] mrr: dict[str, Any] arr: dict[str, Any] comments: int newsletters: dict[str, dict[str, Any]] class GhostDataUpdateCoordinator(DataUpdateCoordinator[GhostData]): """Class to manage fetching Ghost data.""" config_entry: GhostConfigEntry def __init__( self, hass: HomeAssistant, api: GhostAdminAPI, config_entry: GhostConfigEntry, ) -> None: """Initialize the coordinator.""" self.api = api super().__init__( hass, _LOGGER, name=f"Ghost ({config_entry.title})", update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL), config_entry=config_entry, ) async def _async_update_data(self) -> GhostData: """Fetch data from Ghost API.""" try: (site, posts, members, latest_post, latest_email) = await asyncio.gather( self.api.get_site(), self.api.get_posts_count(), self.api.get_members_count(), self.api.get_latest_post(), self.api.get_latest_email(), ) (activitypub, mrr, arr, comments, newsletters) = await asyncio.gather( self.api.get_activitypub_stats(), self.api.get_mrr(), self.api.get_arr(), self.api.get_comments_count(), self.api.get_newsletters(), ) except GhostAuthError as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_api_key", ) from err except GhostError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="api_error", translation_placeholders={"error": str(err)}, ) from err return GhostData( site=site, posts=posts, members=members, latest_post=latest_post, latest_email=latest_email, activitypub=activitypub, mrr=mrr, arr=arr, comments=comments, newsletters={n["id"]: n for n in newsletters if "id" in n}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ghost/coordinator.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/ghost/sensor.py
"""Sensor platform for Ghost.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import TYPE_CHECKING, Any from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.core import HomeAssistant, callback 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 CURRENCY, DOMAIN, MANUFACTURER, MODEL from .coordinator import GhostData, GhostDataUpdateCoordinator if TYPE_CHECKING: from . import GhostConfigEntry # Coordinator handles batching, no limit needed. PARALLEL_UPDATES = 0 def _get_currency_value(currency_data: dict[str, Any]) -> int | None: """Extract the first currency value from a currency dict.""" if not currency_data: return None first_value = next(iter(currency_data.values()), None) if first_value is None: return None return int(first_value) @dataclass(frozen=True, kw_only=True) class GhostSensorEntityDescription(SensorEntityDescription): """Describes a Ghost sensor entity.""" value_fn: Callable[[GhostData], str | int | None] SENSORS: tuple[GhostSensorEntityDescription, ...] = ( # Core member metrics GhostSensorEntityDescription( key="total_members", translation_key="total_members", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.members.get("total", 0), ), GhostSensorEntityDescription( key="paid_members", translation_key="paid_members", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.members.get("paid", 0), ), GhostSensorEntityDescription( key="free_members", translation_key="free_members", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.members.get("free", 0), ), GhostSensorEntityDescription( key="comped_members", translation_key="comped_members", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.members.get("comped", 0), ), # Post metrics GhostSensorEntityDescription( key="published_posts", translation_key="published_posts", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.posts.get("published", 0), ), GhostSensorEntityDescription( key="draft_posts", translation_key="draft_posts", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.posts.get("drafts", 0), ), GhostSensorEntityDescription( key="scheduled_posts", translation_key="scheduled_posts", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.posts.get("scheduled", 0), ), GhostSensorEntityDescription( key="latest_post", translation_key="latest_post", value_fn=lambda data: ( data.latest_post.get("title") if data.latest_post else None ), ), # Email metrics GhostSensorEntityDescription( key="latest_email", translation_key="latest_email", value_fn=lambda data: ( data.latest_email.get("title") if data.latest_email else None ), ), GhostSensorEntityDescription( key="latest_email_sent", translation_key="latest_email_sent", state_class=SensorStateClass.TOTAL, value_fn=lambda data: ( data.latest_email.get("email_count") if data.latest_email else None ), ), GhostSensorEntityDescription( key="latest_email_opened", translation_key="latest_email_opened", state_class=SensorStateClass.TOTAL, value_fn=lambda data: ( data.latest_email.get("opened_count") if data.latest_email else None ), ), GhostSensorEntityDescription( key="latest_email_open_rate", translation_key="latest_email_open_rate", native_unit_of_measurement="%", value_fn=lambda data: ( data.latest_email.get("open_rate") if data.latest_email else None ), ), GhostSensorEntityDescription( key="latest_email_clicked", translation_key="latest_email_clicked", state_class=SensorStateClass.TOTAL, value_fn=lambda data: ( data.latest_email.get("clicked_count") if data.latest_email else None ), ), GhostSensorEntityDescription( key="latest_email_click_rate", translation_key="latest_email_click_rate", native_unit_of_measurement="%", value_fn=lambda data: ( data.latest_email.get("click_rate") if data.latest_email else None ), ), # Social/ActivityPub metrics GhostSensorEntityDescription( key="socialweb_followers", translation_key="socialweb_followers", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.activitypub.get("followers", 0), ), GhostSensorEntityDescription( key="socialweb_following", translation_key="socialweb_following", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.activitypub.get("following", 0), ), # Engagement metrics GhostSensorEntityDescription( key="total_comments", translation_key="total_comments", state_class=SensorStateClass.TOTAL, value_fn=lambda data: data.comments, ), ) REVENUE_SENSORS: tuple[GhostSensorEntityDescription, ...] = ( GhostSensorEntityDescription( key="mrr", translation_key="mrr", device_class=SensorDeviceClass.MONETARY, state_class=SensorStateClass.TOTAL, native_unit_of_measurement=CURRENCY, suggested_display_precision=0, value_fn=lambda data: _get_currency_value(data.mrr), ), GhostSensorEntityDescription( key="arr", translation_key="arr", device_class=SensorDeviceClass.MONETARY, state_class=SensorStateClass.TOTAL, native_unit_of_measurement=CURRENCY, suggested_display_precision=0, value_fn=lambda data: _get_currency_value(data.arr), ), ) async def async_setup_entry( hass: HomeAssistant, entry: GhostConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Ghost sensors based on a config entry.""" coordinator = entry.runtime_data.coordinator entities: list[GhostSensorEntity | GhostNewsletterSensorEntity] = [ GhostSensorEntity(coordinator, description, entry) for description in SENSORS ] # Add revenue sensors only when Stripe is linked. if coordinator.data.mrr: entities.extend( GhostSensorEntity(coordinator, description, entry) for description in REVENUE_SENSORS ) async_add_entities(entities) newsletter_added: set[str] = set() @callback def _async_add_newsletter_entities() -> None: """Add newsletter entities when new newsletters appear.""" nonlocal newsletter_added new_newsletters = { newsletter_id for newsletter_id, newsletter in coordinator.data.newsletters.items() if newsletter.get("status") == "active" } - newsletter_added if not new_newsletters: return async_add_entities( GhostNewsletterSensorEntity( coordinator, entry, newsletter_id, coordinator.data.newsletters[newsletter_id].get("name", "Newsletter"), ) for newsletter_id in new_newsletters ) newsletter_added |= new_newsletters _async_add_newsletter_entities() entry.async_on_unload( coordinator.async_add_listener(_async_add_newsletter_entities) ) class GhostSensorEntity(CoordinatorEntity[GhostDataUpdateCoordinator], SensorEntity): """Representation of a Ghost sensor.""" entity_description: GhostSensorEntityDescription _attr_has_entity_name = True def __init__( self, coordinator: GhostDataUpdateCoordinator, description: GhostSensorEntityDescription, entry: GhostConfigEntry, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{entry.unique_id}_{description.key}" self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, entry.entry_id)}, manufacturer=MANUFACTURER, model=MODEL, configuration_url=coordinator.api.api_url, ) @property def native_value(self) -> str | int | None: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data) class GhostNewsletterSensorEntity( CoordinatorEntity[GhostDataUpdateCoordinator], SensorEntity ): """Representation of a Ghost newsletter subscriber sensor.""" _attr_has_entity_name = True _attr_translation_key = "newsletter_subscribers" _attr_state_class = SensorStateClass.TOTAL def __init__( self, coordinator: GhostDataUpdateCoordinator, entry: GhostConfigEntry, newsletter_id: str, newsletter_name: str, ) -> None: """Initialize the newsletter sensor.""" super().__init__(coordinator) self._newsletter_id = newsletter_id self._newsletter_name = newsletter_name self._attr_unique_id = f"{entry.unique_id}_newsletter_{newsletter_id}" self._attr_translation_placeholders = {"newsletter_name": newsletter_name} self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, entry.entry_id)}, manufacturer=MANUFACTURER, model=MODEL, configuration_url=coordinator.api.api_url, ) def _get_newsletter_by_id(self) -> dict[str, Any] | None: """Get newsletter data by ID.""" return self.coordinator.data.newsletters.get(self._newsletter_id) @property def available(self) -> bool: """Return True if the entity is available.""" if not super().available or self.coordinator.data is None: return False return self._newsletter_id in self.coordinator.data.newsletters @property def native_value(self) -> int | None: """Return the subscriber count for this newsletter.""" if newsletter := self._get_newsletter_by_id(): count: int = newsletter.get("count", {}).get("members", 0) return count return None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ghost/sensor.py", "license": "Apache License 2.0", "lines": 285, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:tests/components/ghost/test_config_flow.py
"""Tests for Ghost config flow.""" from unittest.mock import AsyncMock from aioghost.exceptions import GhostAuthError, GhostConnectionError import pytest from homeassistant.components.ghost.const import ( CONF_ADMIN_API_KEY, CONF_API_URL, DOMAIN, ) from homeassistant.config_entries import SOURCE_USER from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .conftest import API_KEY, API_URL, SITE_UUID @pytest.mark.usefixtures("mock_setup_entry") async def test_form_user(hass: HomeAssistant, mock_ghost_api: AsyncMock) -> None: """Test the user config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert result["errors"] == {} result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Test Ghost" assert result["result"].unique_id == SITE_UUID assert result["data"] == { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, } async def test_form_invalid_api_key_format(hass: HomeAssistant) -> None: """Test error on invalid API key format.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: "invalid-no-colon", }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "invalid_api_key"} @pytest.mark.usefixtures("mock_setup_entry") async def test_form_already_configured( hass: HomeAssistant, mock_config_entry, mock_ghost_api: AsyncMock ) -> None: """Test error when already configured.""" # Add existing entry to hass mock_config_entry.add_to_hass(hass) # Try to configure a second entry with same URL result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, }, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" @pytest.mark.parametrize( ("side_effect", "error_key"), [ (GhostAuthError("Invalid API key"), "invalid_auth"), (GhostConnectionError("Connection failed"), "cannot_connect"), (RuntimeError("Unexpected"), "unknown"), ], ) @pytest.mark.usefixtures("mock_setup_entry") async def test_form_errors_can_recover( hass: HomeAssistant, mock_ghost_api: AsyncMock, side_effect: Exception, error_key: str, ) -> None: """Test errors and recovery during setup.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) mock_ghost_api.get_site.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, }, ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": error_key} mock_ghost_api.get_site.side_effect = None result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, }, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Test Ghost" assert result["result"].unique_id == SITE_UUID assert result["data"] == { CONF_API_URL: API_URL, CONF_ADMIN_API_KEY: API_KEY, }
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ghost/test_config_flow.py", "license": "Apache License 2.0", "lines": 115, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/ghost/test_init.py
"""Tests for Ghost integration setup.""" from unittest.mock import AsyncMock from aioghost.exceptions import GhostAuthError, GhostConnectionError import pytest from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from . import setup_integration @pytest.mark.parametrize( ("side_effect", "expected_state"), [ (GhostAuthError("Invalid API key"), ConfigEntryState.SETUP_ERROR), (GhostConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY), ], ) async def test_setup_entry_errors( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry, side_effect: Exception, expected_state: ConfigEntryState, ) -> None: """Test setup errors.""" mock_ghost_api.get_site.side_effect = side_effect await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is expected_state async def test_unload_entry( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry ) -> None: """Test unloading config entry.""" await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.LOADED await hass.config_entries.async_unload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ghost/test_init.py", "license": "Apache License 2.0", "lines": 34, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/ghost/test_sensor.py
"""Tests for Ghost sensors.""" from datetime import timedelta from unittest.mock import AsyncMock from aioghost.exceptions import GhostError from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from .conftest import NEWSLETTERS_DATA from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensor_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, mock_ghost_api: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Snapshot all Ghost sensor entities.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_newsletter_sensor_added_on_update( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test newsletter sensors are added after updates.""" await setup_integration(hass, mock_config_entry) assert hass.states.get("sensor.test_ghost_monthly_subscribers") is None mock_ghost_api.get_newsletters.return_value = [ *NEWSLETTERS_DATA, { "id": "nl3", "name": "Monthly", "status": "active", "count": {"members": 300}, }, ] freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) state = hass.states.get("sensor.test_ghost_monthly_subscribers") assert state is not None assert state.state == "300" async def test_revenue_sensors_not_created_without_stripe( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry ) -> None: """Test MRR/ARR sensors are not created when Stripe is not linked.""" # Return empty MRR/ARR data (no Stripe linked) mock_ghost_api.get_mrr.return_value = {} mock_ghost_api.get_arr.return_value = {} await setup_integration(hass, mock_config_entry) assert hass.states.get("sensor.test_ghost_mrr") is None assert hass.states.get("sensor.test_ghost_arr") is None async def test_newsletter_sensor_not_found( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test newsletter sensor when newsletter is removed.""" await setup_integration(hass, mock_config_entry) # Verify newsletter sensor exists state = hass.states.get("sensor.test_ghost_weekly_subscribers") assert state is not None assert state.state == "800" # Now return empty newsletters list mock_ghost_api.get_newsletters.return_value = [] freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) # Sensor should now be unavailable (newsletter not found) state = hass.states.get("sensor.test_ghost_weekly_subscribers") assert state is not None assert state.state == STATE_UNAVAILABLE async def test_entities_unavailable_on_update_failure( hass: HomeAssistant, mock_ghost_api: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test entities become unavailable on update failure.""" await setup_integration(hass, mock_config_entry) state = hass.states.get("sensor.test_ghost_total_members") assert state is not None assert state.state == "1000" mock_ghost_api.get_site.side_effect = GhostError("Update failed") freezer.tick(timedelta(minutes=5)) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) state = hass.states.get("sensor.test_ghost_total_members") assert state is not None assert state.state == STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ghost/test_sensor.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/redgtech/config_flow.py
"""Config flow for the Redgtech integration.""" from __future__ import annotations import logging from typing import Any from redgtech_api.api import RedgtechAPI, RedgtechAuthError, RedgtechConnectionError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from .const import DOMAIN, INTEGRATION_NAME _LOGGER = logging.getLogger(__name__) class RedgtechConfigFlow(ConfigFlow, domain=DOMAIN): """Config Flow for Redgtech integration.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial user step for login.""" errors: dict[str, str] = {} if user_input is not None: email = user_input[CONF_EMAIL] password = user_input[CONF_PASSWORD] self._async_abort_entries_match({CONF_EMAIL: user_input[CONF_EMAIL]}) api = RedgtechAPI() try: await api.login(email, password) except RedgtechAuthError: errors["base"] = "invalid_auth" except RedgtechConnectionError: errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected error during login") errors["base"] = "unknown" else: _LOGGER.debug("Login successful, token received") return self.async_create_entry( title=email, data={ CONF_EMAIL: email, CONF_PASSWORD: password, }, ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( vol.Schema( { vol.Required(CONF_EMAIL): str, vol.Required(CONF_PASSWORD): str, } ), user_input, ), errors=errors, description_placeholders={"integration_name": INTEGRATION_NAME}, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/redgtech/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/redgtech/coordinator.py
"""Coordinator for Redgtech integration.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from datetime import timedelta import logging from typing import Any from redgtech_api.api import RedgtechAPI, RedgtechAuthError, RedgtechConnectionError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN UPDATE_INTERVAL = timedelta(seconds=15) _LOGGER = logging.getLogger(__name__) @dataclass class RedgtechDevice: """Representation of a Redgtech device.""" unique_id: str name: str state: bool type RedgtechConfigEntry = ConfigEntry[RedgtechDataUpdateCoordinator] class RedgtechDataUpdateCoordinator(DataUpdateCoordinator[dict[str, RedgtechDevice]]): """Coordinator to manage fetching data from the Redgtech API. Uses a dictionary keyed by unique_id for O(1) device lookup instead of O(n) list iteration. """ config_entry: RedgtechConfigEntry def __init__(self, hass: HomeAssistant, config_entry: RedgtechConfigEntry) -> None: """Initialize the coordinator.""" self.api = RedgtechAPI() self.access_token: str | None = None self.email = config_entry.data[CONF_EMAIL] self.password = config_entry.data[CONF_PASSWORD] super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, config_entry=config_entry, ) async def login(self, email: str, password: str) -> str | None: """Login to the Redgtech API and return the access token.""" try: self.access_token = await self.api.login(email, password) except RedgtechAuthError as e: raise ConfigEntryError("Authentication error during login") from e except RedgtechConnectionError as e: raise UpdateFailed("Connection error during login") from e else: _LOGGER.debug("Access token obtained successfully") return self.access_token async def renew_token(self, email: str, password: str) -> None: """Renew the access token.""" self.access_token = await self.api.login(email, password) _LOGGER.debug("Access token renewed successfully") async def call_api_with_valid_token[_R, *_Ts]( self, api_call: Callable[[*_Ts], Coroutine[Any, Any, _R]], *args: *_Ts ) -> _R: """Make an API call with a valid token. Ensure we have a valid access token, renewing it if necessary. """ if not self.access_token: _LOGGER.debug("No access token, logging in") self.access_token = await self.login(self.email, self.password) else: _LOGGER.debug("Using existing access token") try: return await api_call(*args) except RedgtechAuthError: _LOGGER.debug("Auth failed, trying to renew token") await self.renew_token( self.config_entry.data[CONF_EMAIL], self.config_entry.data[CONF_PASSWORD], ) return await api_call(*args) async def _async_update_data(self) -> dict[str, RedgtechDevice]: """Fetch data from the API on demand. Returns a dictionary keyed by unique_id for efficient device lookup. """ _LOGGER.debug("Fetching data from Redgtech API on demand") try: data = await self.call_api_with_valid_token( self.api.get_data, self.access_token ) except RedgtechAuthError as e: raise ConfigEntryError("Authentication failed") from e except RedgtechConnectionError as e: raise UpdateFailed("Failed to connect to Redgtech API") from e devices: dict[str, RedgtechDevice] = {} for item in data["boards"]: display_categories = {cat.lower() for cat in item["displayCategories"]} if "light" in display_categories or "switch" not in display_categories: continue device = RedgtechDevice( unique_id=item["endpointId"], name=item["friendlyName"], state=item["value"], ) _LOGGER.debug("Processing device: %s", device) devices[device.unique_id] = device return devices
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/redgtech/coordinator.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/redgtech/switch.py
"""Integration for Redgtech switches.""" from __future__ import annotations from typing import Any from redgtech_api.api import RedgtechAuthError, RedgtechConnectionError from homeassistant.components.switch import SwitchEntity 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, INTEGRATION_NAME from .coordinator import ( RedgtechConfigEntry, RedgtechDataUpdateCoordinator, RedgtechDevice, ) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: RedgtechConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the switch platform.""" coordinator = config_entry.runtime_data async_add_entities( RedgtechSwitch(coordinator, device) for device in coordinator.data.values() ) class RedgtechSwitch(CoordinatorEntity[RedgtechDataUpdateCoordinator], SwitchEntity): """Representation of a Redgtech switch.""" _attr_has_entity_name = True _attr_name = None def __init__( self, coordinator: RedgtechDataUpdateCoordinator, device: RedgtechDevice ) -> None: """Initialize the switch.""" super().__init__(coordinator) self.coordinator = coordinator self.device = device self._attr_unique_id = device.unique_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.unique_id)}, name=device.name, manufacturer=INTEGRATION_NAME, ) @property def is_on(self) -> bool: """Return true if the switch is on.""" if device := self.coordinator.data.get(self.device.unique_id): return bool(device.state) return False async def _set_state(self, new_state: bool) -> None: """Set state of the switch.""" try: await self.coordinator.call_api_with_valid_token( self.coordinator.api.set_switch_state, self.device.unique_id, new_state, self.coordinator.access_token, ) except RedgtechAuthError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="switch_auth_error", translation_placeholders={"integration_name": INTEGRATION_NAME}, ) from err except RedgtechConnectionError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="connection_error", translation_placeholders={"integration_name": INTEGRATION_NAME}, ) from err await self.coordinator.async_refresh() async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self._set_state(True) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self._set_state(False)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/redgtech/switch.py", "license": "Apache License 2.0", "lines": 78, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:tests/components/redgtech/test_config_flow.py
"""Tests Config flow for the Redgtech integration.""" from unittest.mock import MagicMock import pytest from redgtech_api.api import RedgtechAuthError, RedgtechConnectionError from homeassistant.components.redgtech.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_EMAIL, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry TEST_EMAIL = "test@example.com" TEST_PASSWORD = "123456" FAKE_TOKEN = "fake_token" @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (RedgtechAuthError, "invalid_auth"), (RedgtechConnectionError, "cannot_connect"), (Exception("Generic error"), "unknown"), ], ) async def test_user_step_errors( hass: HomeAssistant, mock_redgtech_api: MagicMock, side_effect: type[Exception], expected_error: str, ) -> None: """Test user step with various errors.""" user_input = {CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD} mock_redgtech_api.login.side_effect = side_effect mock_redgtech_api.login.return_value = None result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input ) assert result["type"] is FlowResultType.FORM assert result["errors"]["base"] == expected_error mock_redgtech_api.login.assert_called_once_with(TEST_EMAIL, TEST_PASSWORD) async def test_user_step_creates_entry( hass: HomeAssistant, mock_redgtech_api: MagicMock, ) -> None: """Tests the correct creation of the entry in the configuration.""" user_input = {CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD} mock_redgtech_api.login.reset_mock() mock_redgtech_api.login.return_value = FAKE_TOKEN mock_redgtech_api.login.side_effect = None result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_EMAIL assert result["data"] == user_input # Verify login was called at least once with correct parameters mock_redgtech_api.login.assert_any_call(TEST_EMAIL, TEST_PASSWORD) async def test_user_step_duplicate_entry( hass: HomeAssistant, mock_redgtech_api: MagicMock, ) -> None: """Test attempt to add duplicate entry.""" existing_entry = MockConfigEntry( domain=DOMAIN, unique_id=TEST_EMAIL, data={CONF_EMAIL: TEST_EMAIL}, ) existing_entry.add_to_hass(hass) user_input = {CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" mock_redgtech_api.login.assert_not_called() @pytest.mark.parametrize( ("side_effect", "expected_error"), [ (RedgtechAuthError, "invalid_auth"), (RedgtechConnectionError, "cannot_connect"), (Exception("Generic error"), "unknown"), ], ) async def test_user_step_error_recovery( hass: HomeAssistant, mock_redgtech_api: MagicMock, side_effect: Exception, expected_error: str, ) -> None: """Test that the flow can recover from errors and complete successfully.""" user_input = {CONF_EMAIL: TEST_EMAIL, CONF_PASSWORD: TEST_PASSWORD} # Reset mock to start fresh mock_redgtech_api.login.reset_mock() mock_redgtech_api.login.return_value = None mock_redgtech_api.login.side_effect = None # First attempt fails with error mock_redgtech_api.login.side_effect = side_effect result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER}, data=user_input ) assert result["type"] is FlowResultType.FORM assert result["errors"]["base"] == expected_error # Verify login was called at least once for the first attempt assert mock_redgtech_api.login.call_count >= 1 first_call_count = mock_redgtech_api.login.call_count # Second attempt succeeds - flow recovers mock_redgtech_api.login.side_effect = None mock_redgtech_api.login.return_value = FAKE_TOKEN result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=user_input ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_EMAIL assert result["data"] == user_input # Verify login was called again for the second attempt (recovery) assert mock_redgtech_api.login.call_count > first_call_count
{ "repo_id": "home-assistant/core", "file_path": "tests/components/redgtech/test_config_flow.py", "license": "Apache License 2.0", "lines": 113, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/redgtech/test_switch.py
"""Tests for the Redgtech switch platform.""" from datetime import timedelta from unittest.mock import MagicMock from freezegun import freeze_time from freezegun.api import FrozenDateTimeFactory import pytest from redgtech_api.api import RedgtechAuthError, RedgtechConnectionError from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TOGGLE, SERVICE_TURN_OFF, SERVICE_TURN_ON, STATE_UNAVAILABLE, ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture def freezer(): """Provide a freezer fixture that works with freeze_time decorator.""" with freeze_time() as frozen_time: yield frozen_time @pytest.fixture async def setup_redgtech_integration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_redgtech_api: MagicMock, ) -> MagicMock: """Set up the Redgtech integration with mocked API.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() return mock_redgtech_api async def test_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, setup_redgtech_integration, mock_config_entry: MockConfigEntry, ) -> None: """Test entity setup.""" await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_switch_turn_on( hass: HomeAssistant, setup_redgtech_integration: MagicMock, ) -> None: """Test turning a switch on.""" mock_api = setup_redgtech_integration await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) mock_api.set_switch_state.assert_called_once_with( "switch_001", True, "mock_access_token" ) async def test_switch_turn_off( hass: HomeAssistant, setup_redgtech_integration: MagicMock, ) -> None: """Test turning a switch off.""" mock_api = setup_redgtech_integration await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: "switch.kitchen_switch"}, blocking=True, ) mock_api.set_switch_state.assert_called_once_with( "switch_002", False, "mock_access_token" ) async def test_switch_toggle( hass: HomeAssistant, setup_redgtech_integration: MagicMock, ) -> None: """Test toggling a switch.""" mock_api = setup_redgtech_integration await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TOGGLE, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) mock_api.set_switch_state.assert_called_once_with( "switch_001", True, "mock_access_token" ) @pytest.mark.parametrize( ("exception", "error_message"), [ ( RedgtechConnectionError("Connection failed"), "Connection error with Redgtech API", ), ( RedgtechAuthError("Auth failed"), "Authentication failed when controlling Redgtech switch", ), ], ) async def test_exception_handling( hass: HomeAssistant, setup_redgtech_integration: MagicMock, exception: Exception, error_message: str, ) -> None: """Test exception handling when controlling switches.""" mock_api = setup_redgtech_integration mock_api.set_switch_state.side_effect = exception with pytest.raises(HomeAssistantError, match=error_message): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) async def test_switch_auth_error_with_retry( hass: HomeAssistant, setup_redgtech_integration: MagicMock, ) -> None: """Test handling auth errors with token renewal.""" mock_api = setup_redgtech_integration # Mock fails with auth error mock_api.set_switch_state.side_effect = RedgtechAuthError("Auth failed") # Expect HomeAssistantError to be raised with pytest.raises( HomeAssistantError, match="Authentication failed when controlling Redgtech switch", ): await hass.services.async_call( SWITCH_DOMAIN, SERVICE_TURN_ON, {ATTR_ENTITY_ID: "switch.living_room_switch"}, blocking=True, ) @freeze_time("2023-01-01 12:00:00") async def test_coordinator_data_update_success( hass: HomeAssistant, setup_redgtech_integration: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test successful data update through coordinator.""" mock_api = setup_redgtech_integration # Update mock data mock_api.get_data.return_value = { "boards": [ { "endpointId": "switch_001", "friendlyName": "Living Room Switch", "value": True, # Changed to True "displayCategories": ["SWITCH"], } ] } # Use freezer to advance time and trigger update freezer.tick(delta=timedelta(minutes=2)) await hass.async_block_till_done() # Verify the entity state was updated successfully living_room_state = hass.states.get("switch.living_room_switch") assert living_room_state is not None assert living_room_state.state == "on" @freeze_time("2023-01-01 12:00:00") async def test_coordinator_connection_error_during_update( hass: HomeAssistant, setup_redgtech_integration: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test coordinator handling connection errors during data updates.""" mock_api = setup_redgtech_integration mock_api.get_data.side_effect = RedgtechConnectionError("Connection failed") # Use freezer to advance time and trigger update freezer.tick(delta=timedelta(minutes=2)) await hass.async_block_till_done() # Verify entities become unavailable due to coordinator error living_room_state = hass.states.get("switch.living_room_switch") kitchen_state = hass.states.get("switch.kitchen_switch") assert living_room_state.state == STATE_UNAVAILABLE assert kitchen_state.state == STATE_UNAVAILABLE @freeze_time("2023-01-01 12:00:00") async def test_coordinator_auth_error_with_token_renewal( hass: HomeAssistant, setup_redgtech_integration: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test coordinator handling auth errors with token renewal.""" mock_api = setup_redgtech_integration # First call fails with auth error, second succeeds after token renewal mock_api.get_data.side_effect = [ RedgtechAuthError("Auth failed"), { "boards": [ { "endpointId": "switch_001", "friendlyName": "Living Room Switch", "value": True, "displayCategories": ["SWITCH"], } ] }, ] # Use freezer to advance time and trigger update freezer.tick(delta=timedelta(minutes=2)) await hass.async_block_till_done() # Verify token renewal was attempted assert mock_api.login.call_count >= 2 # Verify entity is available after successful token renewal living_room_state = hass.states.get("switch.living_room_switch") assert living_room_state is not None assert living_room_state.state != STATE_UNAVAILABLE
{ "repo_id": "home-assistant/core", "file_path": "tests/components/redgtech/test_switch.py", "license": "Apache License 2.0", "lines": 215, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/advantage_air/services.py
"""Services for Advantage Air integration.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import DOMAIN @callback def async_setup_services(hass: HomeAssistant) -> None: """Home Assistant services.""" service.async_register_platform_entity_service( hass, DOMAIN, "set_time_to", entity_domain=SENSOR_DOMAIN, schema={vol.Required("minutes"): cv.positive_int}, func="set_time_to", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/advantage_air/services.py", "license": "Apache License 2.0", "lines": 18, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/button.py
"""Button platform for Airobot integration.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import Any from pyairobotrest.exceptions import ( AirobotConnectionError, AirobotError, AirobotTimeoutError, ) 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 .const import DOMAIN from .coordinator import AirobotConfigEntry, AirobotDataUpdateCoordinator from .entity import AirobotEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class AirobotButtonEntityDescription(ButtonEntityDescription): """Describes Airobot button entity.""" press_fn: Callable[[AirobotDataUpdateCoordinator], Coroutine[Any, Any, None]] BUTTON_TYPES: tuple[AirobotButtonEntityDescription, ...] = ( AirobotButtonEntityDescription( key="restart", device_class=ButtonDeviceClass.RESTART, entity_category=EntityCategory.CONFIG, press_fn=lambda coordinator: coordinator.client.reboot_thermostat(), ), AirobotButtonEntityDescription( key="recalibrate_co2", translation_key="recalibrate_co2", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, press_fn=lambda coordinator: coordinator.client.recalibrate_co2_sensor(), ), ) async def async_setup_entry( hass: HomeAssistant, entry: AirobotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Airobot button entities.""" coordinator = entry.runtime_data async_add_entities( AirobotButton(coordinator, description) for description in BUTTON_TYPES ) class AirobotButton(AirobotEntity, ButtonEntity): """Representation of an Airobot button.""" entity_description: AirobotButtonEntityDescription def __init__( self, coordinator: AirobotDataUpdateCoordinator, description: AirobotButtonEntityDescription, ) -> None: """Initialize the button.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.data.status.device_id}_{description.key}" async def async_press(self) -> None: """Handle the button press.""" try: await self.entity_description.press_fn(self.coordinator) except AirobotConnectionError, AirobotTimeoutError: # Connection errors during reboot are expected as device restarts pass except AirobotError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="button_press_failed", translation_placeholders={"button": self.entity_description.key}, ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/button.py", "license": "Apache License 2.0", "lines": 77, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airobot/switch.py
"""Switch platform for Airobot thermostat.""" from __future__ import annotations from collections.abc import Callable, Coroutine from dataclasses import dataclass from typing import Any from pyairobotrest.exceptions import AirobotError 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.entity_platform import AddConfigEntryEntitiesCallback from . import AirobotConfigEntry from .const import DOMAIN from .coordinator import AirobotDataUpdateCoordinator from .entity import AirobotEntity PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class AirobotSwitchEntityDescription(SwitchEntityDescription): """Describes Airobot switch entity.""" is_on_fn: Callable[[AirobotDataUpdateCoordinator], bool] turn_on_fn: Callable[[AirobotDataUpdateCoordinator], Coroutine[Any, Any, None]] turn_off_fn: Callable[[AirobotDataUpdateCoordinator], Coroutine[Any, Any, None]] SWITCH_TYPES: tuple[AirobotSwitchEntityDescription, ...] = ( AirobotSwitchEntityDescription( key="child_lock", translation_key="child_lock", entity_category=EntityCategory.CONFIG, is_on_fn=lambda coordinator: ( coordinator.data.settings.setting_flags.childlock_enabled ), turn_on_fn=lambda coordinator: coordinator.client.set_child_lock(True), turn_off_fn=lambda coordinator: coordinator.client.set_child_lock(False), ), AirobotSwitchEntityDescription( key="actuator_exercise_disabled", translation_key="actuator_exercise_disabled", entity_category=EntityCategory.CONFIG, entity_registry_enabled_default=False, is_on_fn=lambda coordinator: ( coordinator.data.settings.setting_flags.actuator_exercise_disabled ), turn_on_fn=lambda coordinator: coordinator.client.toggle_actuator_exercise( True ), turn_off_fn=lambda coordinator: coordinator.client.toggle_actuator_exercise( False ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: AirobotConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Airobot switch entities.""" coordinator = entry.runtime_data async_add_entities( AirobotSwitch(coordinator, description) for description in SWITCH_TYPES ) class AirobotSwitch(AirobotEntity, SwitchEntity): """Representation of an Airobot switch.""" entity_description: AirobotSwitchEntityDescription def __init__( self, coordinator: AirobotDataUpdateCoordinator, description: AirobotSwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.data.status.device_id}_{description.key}" @property def is_on(self) -> bool: """Return true if the switch is on.""" return self.entity_description.is_on_fn(self.coordinator) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" try: await self.entity_description.turn_on_fn(self.coordinator) except AirobotError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="switch_turn_on_failed", translation_placeholders={"switch": self.entity_description.key}, ) from err await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" try: await self.entity_description.turn_off_fn(self.coordinator) except AirobotError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="switch_turn_off_failed", translation_placeholders={"switch": self.entity_description.key}, ) from err await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airobot/switch.py", "license": "Apache License 2.0", "lines": 97, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/alarm_control_panel/condition.py
"""Provides conditions for alarm control panels.""" from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.condition import ( Condition, EntityStateConditionBase, make_entity_state_condition, ) from homeassistant.helpers.entity import get_supported_features from .const import DOMAIN, AlarmControlPanelEntityFeature, AlarmControlPanelState def supports_feature(hass: HomeAssistant, entity_id: str, features: int) -> bool: """Test if an entity supports the specified features.""" try: return bool(get_supported_features(hass, entity_id) & features) except HomeAssistantError: return False class EntityStateRequiredFeaturesCondition(EntityStateConditionBase): """State condition.""" _required_features: int def entity_filter(self, entities: set[str]) -> set[str]: """Filter entities of this domain with the required features.""" entities = super().entity_filter(entities) return { entity_id for entity_id in entities if supports_feature(self._hass, entity_id, self._required_features) } def make_entity_state_required_features_condition( domain: str, to_state: str, required_features: int ) -> type[EntityStateRequiredFeaturesCondition]: """Create an entity state condition class with required feature filtering.""" class CustomCondition(EntityStateRequiredFeaturesCondition): """Condition for entity state changes.""" _domain = domain _states = {to_state} _required_features = required_features return CustomCondition CONDITIONS: dict[str, type[Condition]] = { "is_armed": make_entity_state_condition( DOMAIN, { AlarmControlPanelState.ARMED_AWAY, AlarmControlPanelState.ARMED_CUSTOM_BYPASS, AlarmControlPanelState.ARMED_HOME, AlarmControlPanelState.ARMED_NIGHT, AlarmControlPanelState.ARMED_VACATION, }, ), "is_armed_away": make_entity_state_required_features_condition( DOMAIN, AlarmControlPanelState.ARMED_AWAY, AlarmControlPanelEntityFeature.ARM_AWAY, ), "is_armed_home": make_entity_state_required_features_condition( DOMAIN, AlarmControlPanelState.ARMED_HOME, AlarmControlPanelEntityFeature.ARM_HOME, ), "is_armed_night": make_entity_state_required_features_condition( DOMAIN, AlarmControlPanelState.ARMED_NIGHT, AlarmControlPanelEntityFeature.ARM_NIGHT, ), "is_armed_vacation": make_entity_state_required_features_condition( DOMAIN, AlarmControlPanelState.ARMED_VACATION, AlarmControlPanelEntityFeature.ARM_VACATION, ), "is_disarmed": make_entity_state_condition(DOMAIN, AlarmControlPanelState.DISARMED), "is_triggered": make_entity_state_condition( DOMAIN, AlarmControlPanelState.TRIGGERED ), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the alarm control panel conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/alarm_control_panel/condition.py", "license": "Apache License 2.0", "lines": 76, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/anthropic/repairs.py
"""Issue repair flow for Anthropic.""" from __future__ import annotations from collections.abc import Iterator from typing import TYPE_CHECKING import voluptuous as vol from homeassistant import data_entry_flow from homeassistant.components.repairs import RepairsFlow from homeassistant.config_entries import ConfigEntryState, ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.selector import ( SelectOptionDict, SelectSelector, SelectSelectorConfig, ) from .config_flow import get_model_list from .const import CONF_CHAT_MODEL, DEPRECATED_MODELS, DOMAIN if TYPE_CHECKING: from . import AnthropicConfigEntry class ModelDeprecatedRepairFlow(RepairsFlow): """Handler for an issue fixing flow.""" _subentry_iter: Iterator[tuple[str, str]] | None _current_entry_id: str | None _current_subentry_id: str | None _model_list_cache: dict[str, list[SelectOptionDict]] | None def __init__(self) -> None: """Initialize the flow.""" super().__init__() self._subentry_iter = None self._current_entry_id = None self._current_subentry_id = None self._model_list_cache = None async def async_step_init( self, user_input: dict[str, str] ) -> data_entry_flow.FlowResult: """Handle the steps of a fix flow.""" if user_input.get(CONF_CHAT_MODEL): self._async_update_current_subentry(user_input) target = await self._async_next_target() if target is None: return self.async_create_entry(data={}) entry, subentry, model = target if self._model_list_cache is None: self._model_list_cache = {} if entry.entry_id in self._model_list_cache: model_list = self._model_list_cache[entry.entry_id] else: client = entry.runtime_data model_list = [ model_option for model_option in await get_model_list(client) if not model_option["value"].startswith(tuple(DEPRECATED_MODELS)) ] self._model_list_cache[entry.entry_id] = model_list if "opus" in model: family = "claude-opus" elif "sonnet" in model: family = "claude-sonnet" else: family = "claude-haiku" suggested_model = next( ( model_option["value"] for model_option in sorted( (m for m in model_list if family in m["value"]), key=lambda x: x["value"], reverse=True, ) ), vol.UNDEFINED, ) schema = vol.Schema( { vol.Required( CONF_CHAT_MODEL, default=suggested_model, ): SelectSelector( SelectSelectorConfig(options=model_list, custom_value=True) ), } ) return self.async_show_form( step_id="init", data_schema=schema, description_placeholders={ "entry_name": entry.title, "model": model, "subentry_name": subentry.title, "subentry_type": self._format_subentry_type(subentry.subentry_type), }, ) def _iter_deprecated_subentries(self) -> Iterator[tuple[str, str]]: """Yield entry/subentry pairs that use deprecated models.""" for entry in self.hass.config_entries.async_entries(DOMAIN): if entry.state is not ConfigEntryState.LOADED: continue for subentry in entry.subentries.values(): model = subentry.data.get(CONF_CHAT_MODEL) if model and model.startswith(tuple(DEPRECATED_MODELS)): yield entry.entry_id, subentry.subentry_id async def _async_next_target( self, ) -> tuple[AnthropicConfigEntry, ConfigSubentry, str] | None: """Return the next deprecated subentry target.""" if self._subentry_iter is None: self._subentry_iter = self._iter_deprecated_subentries() while True: try: entry_id, subentry_id = next(self._subentry_iter) except StopIteration: return None # Verify that the entry/subentry still exists and the model is still # deprecated. This may have changed since we started the repair flow. entry = self.hass.config_entries.async_get_entry(entry_id) if entry is None: continue subentry = entry.subentries.get(subentry_id) if subentry is None: continue model = subentry.data.get(CONF_CHAT_MODEL) if not model or not model.startswith(tuple(DEPRECATED_MODELS)): continue self._current_entry_id = entry_id self._current_subentry_id = subentry_id return entry, subentry, model def _async_update_current_subentry(self, user_input: dict[str, str]) -> None: """Update the currently selected subentry.""" if ( self._current_entry_id is None or self._current_subentry_id is None or ( entry := self.hass.config_entries.async_get_entry( self._current_entry_id ) ) is None or (subentry := entry.subentries.get(self._current_subentry_id)) is None ): raise HomeAssistantError("Subentry not found") updated_data = { **subentry.data, CONF_CHAT_MODEL: user_input[CONF_CHAT_MODEL], } self.hass.config_entries.async_update_subentry( entry, subentry, data=updated_data, ) def _format_subentry_type(self, subentry_type: str) -> str: """Return a user-friendly subentry type label.""" if subentry_type == "conversation": return "Conversation agent" if subentry_type in ("ai_task", "ai_task_data"): return "AI task" return subentry_type async def async_create_fix_flow( hass: HomeAssistant, issue_id: str, data: dict[str, str | int | float | None] | None, ) -> RepairsFlow: """Create flow.""" if issue_id == "model_deprecated": return ModelDeprecatedRepairFlow() raise HomeAssistantError("Unknown issue ID")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anthropic/repairs.py", "license": "Apache License 2.0", "lines": 164, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/apple_tv/binary_sensor.py
"""Binary sensor support for Apple TV.""" from __future__ import annotations from pyatv.const import FeatureName, FeatureState, KeyboardFocusState from pyatv.interface import AppleTV, KeyboardListener from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.const import CONF_NAME from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import SIGNAL_CONNECTED, AppleTvConfigEntry from .entity import AppleTVEntity async def async_setup_entry( hass: HomeAssistant, config_entry: AppleTvConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Load Apple TV binary sensor based on a config entry.""" # apple_tv config entries always have a unique id manager = config_entry.runtime_data cb: CALLBACK_TYPE def setup_entities(atv: AppleTV) -> None: if atv.features.in_state(FeatureState.Available, FeatureName.TextFocusState): assert config_entry.unique_id is not None name: str = config_entry.data[CONF_NAME] async_add_entities( [AppleTVKeyboardFocused(name, config_entry.unique_id, manager)] ) cb() cb = async_dispatcher_connect( hass, f"{SIGNAL_CONNECTED}_{config_entry.unique_id}", setup_entities ) config_entry.async_on_unload(cb) class AppleTVKeyboardFocused(AppleTVEntity, BinarySensorEntity, KeyboardListener): """Binary sensor for Text input focused.""" _attr_translation_key = "keyboard_focused" _attr_available = True @callback def async_device_connected(self, atv: AppleTV) -> None: """Handle when connection is made to device.""" self._attr_available = True # Listen to keyboard updates atv.keyboard.listener = self # Set initial state based on current focus state self._update_state(atv.keyboard.text_focus_state == KeyboardFocusState.Focused) @callback def async_device_disconnected(self) -> None: """Handle when connection was lost to device.""" self._attr_available = False self._update_state(False) def focusstate_update( self, old_state: KeyboardFocusState, new_state: KeyboardFocusState ) -> None: """Update keyboard state when it changes. This is a callback function from pyatv.interface.KeyboardListener. """ self._update_state(new_state == KeyboardFocusState.Focused) def _update_state(self, new_state: bool) -> None: """Update and report.""" self._attr_is_on = new_state self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/apple_tv/binary_sensor.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/assist_satellite/condition.py
"""Provides conditions for assist satellites.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN from .entity import AssistSatelliteState CONDITIONS: dict[str, type[Condition]] = { "is_idle": make_entity_state_condition(DOMAIN, AssistSatelliteState.IDLE), "is_listening": make_entity_state_condition(DOMAIN, AssistSatelliteState.LISTENING), "is_processing": make_entity_state_condition( DOMAIN, AssistSatelliteState.PROCESSING ), "is_responding": make_entity_state_condition( DOMAIN, AssistSatelliteState.RESPONDING ), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the assist satellite conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/assist_satellite/condition.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/bang_olufsen/binary_sensor.py
"""Binary Sensor entities for the Bang & Olufsen integration.""" from __future__ import annotations from mozart_api.models import BatteryState from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import BeoConfigEntry from .const import CONNECTION_STATUS, DOMAIN, WebsocketNotification from .entity import BeoEntity from .util import supports_battery async def async_setup_entry( hass: HomeAssistant, config_entry: BeoConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Binary Sensor entities from config entry.""" if await supports_battery(config_entry.runtime_data.client): async_add_entities(new_entities=[BeoBinarySensorBatteryCharging(config_entry)]) class BeoBinarySensorBatteryCharging(BinarySensorEntity, BeoEntity): """Battery charging Binary Sensor.""" _attr_device_class = BinarySensorDeviceClass.BATTERY_CHARGING _attr_is_on = False def __init__(self, config_entry: BeoConfigEntry) -> None: """Init the battery charging Binary Sensor.""" super().__init__(config_entry, config_entry.runtime_data.client) self._attr_unique_id = f"{self._unique_id}_charging" async def async_added_to_hass(self) -> None: """Turn on the dispatchers.""" self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self._unique_id}_{CONNECTION_STATUS}", self._async_update_connection_state, ) ) self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self._unique_id}_{WebsocketNotification.BATTERY}", self._update_battery_charging, ) ) async def _update_battery_charging(self, data: BatteryState) -> None: """Update battery charging.""" self._attr_is_on = bool(data.is_charging) self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bang_olufsen/binary_sensor.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/bang_olufsen/sensor.py
"""Sensor entities for the Bang & Olufsen integration.""" from __future__ import annotations import contextlib from datetime import timedelta from aiohttp import ClientConnectorError from mozart_api.exceptions import ApiException from mozart_api.models import BatteryState, PairedRemote from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.const import PERCENTAGE from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import BeoConfigEntry from .const import CONNECTION_STATUS, DOMAIN, WebsocketNotification from .entity import BeoEntity from .util import get_remotes, supports_battery SCAN_INTERVAL = timedelta(minutes=15) PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: BeoConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Sensor entities from config entry.""" entities: list[BeoSensor] = [] # Check for Mozart device with battery if await supports_battery(config_entry.runtime_data.client): entities.append(BeoSensorBatteryLevel(config_entry)) # Add any Beoremote One remotes entities.extend( [ BeoSensorRemoteBatteryLevel(config_entry, remote) for remote in (await get_remotes(config_entry.runtime_data.client)) ] ) async_add_entities(entities, update_before_add=True) class BeoSensor(SensorEntity, BeoEntity): """Base Bang & Olufsen Sensor.""" def __init__(self, config_entry: BeoConfigEntry) -> None: """Initialize Sensor.""" super().__init__(config_entry, config_entry.runtime_data.client) class BeoSensorBatteryLevel(BeoSensor): """Battery level Sensor for Mozart devices.""" _attr_device_class = SensorDeviceClass.BATTERY _attr_native_unit_of_measurement = PERCENTAGE _attr_state_class = SensorStateClass.MEASUREMENT def __init__(self, config_entry: BeoConfigEntry) -> None: """Init the battery level Sensor.""" super().__init__(config_entry) self._attr_unique_id = f"{self._unique_id}_battery_level" async def async_added_to_hass(self) -> None: """Turn on the dispatchers.""" self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self._unique_id}_{CONNECTION_STATUS}", self._async_update_connection_state, ) ) self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self._unique_id}_{WebsocketNotification.BATTERY}", self._update_battery, ) ) async def _update_battery(self, data: BatteryState) -> None: """Update sensor value.""" self._attr_native_value = data.battery_level self.async_write_ha_state() class BeoSensorRemoteBatteryLevel(BeoSensor): """Battery level Sensor for the Beoremote One.""" _attr_device_class = SensorDeviceClass.BATTERY _attr_native_unit_of_measurement = PERCENTAGE _attr_should_poll = True _attr_state_class = SensorStateClass.MEASUREMENT def __init__(self, config_entry: BeoConfigEntry, remote: PairedRemote) -> None: """Init the battery level Sensor.""" super().__init__(config_entry) # Serial number is not None, as the remote object is provided by get_remotes assert remote.serial_number self._attr_unique_id = ( f"{remote.serial_number}_{self._unique_id}_remote_battery_level" ) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, f"{remote.serial_number}_{self._unique_id}")} ) self._attr_native_value = remote.battery_level self._remote = remote async def async_added_to_hass(self) -> None: """Turn on the dispatchers.""" self.async_on_remove( async_dispatcher_connect( self.hass, f"{DOMAIN}_{self._unique_id}_{CONNECTION_STATUS}", self._async_update_connection_state, ) ) async def async_update(self) -> None: """Poll battery status.""" with contextlib.suppress(ApiException, ClientConnectorError, TimeoutError): for remote in await get_remotes(self._client): if remote.serial_number == self._remote.serial_number: self._attr_native_value = remote.battery_level break
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bang_olufsen/sensor.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/bang_olufsen/services.py
"""Services for Bang & Olufsen integration.""" from __future__ import annotations import voluptuous as vol from homeassistant.components.media_player import DOMAIN as MEDIA_PLAYER_DOMAIN from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, service from .const import BEOLINK_JOIN_SOURCES, DOMAIN @callback def async_setup_services(hass: HomeAssistant) -> None: """Home Assistant services.""" jid_regex = vol.Match( r"(^\d{4})[.](\d{7})[.](\d{8})(@products\.bang-olufsen\.com)$" ) service.async_register_platform_entity_service( hass, DOMAIN, "beolink_join", entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Optional("beolink_jid"): jid_regex, vol.Optional("source_id"): vol.In(BEOLINK_JOIN_SOURCES), }, func="async_beolink_join", ) service.async_register_platform_entity_service( hass, DOMAIN, "beolink_expand", entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Exclusive("all_discovered", "devices", ""): cv.boolean, vol.Exclusive( "beolink_jids", "devices", "Define either specific Beolink JIDs or all discovered", ): vol.All( cv.ensure_list, [jid_regex], ), }, func="async_beolink_expand", ) service.async_register_platform_entity_service( hass, DOMAIN, "beolink_unexpand", entity_domain=MEDIA_PLAYER_DOMAIN, schema={ vol.Required("beolink_jids"): vol.All( cv.ensure_list, [jid_regex], ), }, func="async_beolink_unexpand", ) service.async_register_platform_entity_service( hass, DOMAIN, "beolink_leave", entity_domain=MEDIA_PLAYER_DOMAIN, schema=None, func="async_beolink_leave", ) service.async_register_platform_entity_service( hass, DOMAIN, "beolink_allstandby", entity_domain=MEDIA_PLAYER_DOMAIN, schema=None, func="async_beolink_allstandby", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bang_olufsen/services.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/climate/condition.py
"""Provides conditions for climates.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import ( Condition, make_entity_state_attribute_condition, make_entity_state_condition, ) from .const import ATTR_HVAC_ACTION, DOMAIN, HVACAction, HVACMode CONDITIONS: dict[str, type[Condition]] = { "is_off": make_entity_state_condition(DOMAIN, HVACMode.OFF), "is_on": make_entity_state_condition( DOMAIN, { HVACMode.AUTO, HVACMode.COOL, HVACMode.DRY, HVACMode.FAN_ONLY, HVACMode.HEAT, HVACMode.HEAT_COOL, }, ), "is_cooling": make_entity_state_attribute_condition( DOMAIN, ATTR_HVAC_ACTION, HVACAction.COOLING ), "is_drying": make_entity_state_attribute_condition( DOMAIN, ATTR_HVAC_ACTION, HVACAction.DRYING ), "is_heating": make_entity_state_attribute_condition( DOMAIN, ATTR_HVAC_ACTION, HVACAction.HEATING ), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the climate conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/climate/condition.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/cloudflare_r2/backup.py
"""Backup platform for the Cloudflare R2 integration.""" from collections.abc import AsyncIterator, Callable, Coroutine import functools import json import logging from time import time from typing import Any, cast from botocore.exceptions import BotoCoreError from homeassistant.components.backup import ( AgentBackup, BackupAgent, BackupAgentError, BackupNotFound, suggested_filename, ) from homeassistant.core import HomeAssistant, callback from . import R2ConfigEntry from .const import CONF_BUCKET, CONF_PREFIX, DATA_BACKUP_AGENT_LISTENERS, DOMAIN _LOGGER = logging.getLogger(__name__) CACHE_TTL = 300 # S3 part size requirements: 5 MiB to 5 GiB per part # We set the threshold to 20 MiB to avoid too many parts. # Note that each part is allocated in the memory. MULTIPART_MIN_PART_SIZE_BYTES = 20 * 2**20 def handle_boto_errors[T]( func: Callable[..., Coroutine[Any, Any, T]], ) -> Callable[..., Coroutine[Any, Any, T]]: """Handle BotoCoreError exceptions by converting them to BackupAgentError.""" @functools.wraps(func) async def wrapper(*args: Any, **kwargs: Any) -> T: """Catch BotoCoreError and raise BackupAgentError.""" try: return await func(*args, **kwargs) except BotoCoreError as err: error_msg = f"Failed during {func.__name__}" raise BackupAgentError(error_msg) from err return wrapper async def async_get_backup_agents( hass: HomeAssistant, ) -> list[BackupAgent]: """Return a list of backup agents.""" entries: list[R2ConfigEntry] = hass.config_entries.async_loaded_entries(DOMAIN) return [R2BackupAgent(hass, entry) for entry in entries] @callback def async_register_backup_agents_listener( hass: HomeAssistant, *, listener: Callable[[], None], **kwargs: Any, ) -> Callable[[], None]: """Register a listener to be called when agents are added or removed. :return: A function to unregister the listener. """ hass.data.setdefault(DATA_BACKUP_AGENT_LISTENERS, []).append(listener) @callback def remove_listener() -> None: """Remove the listener.""" hass.data[DATA_BACKUP_AGENT_LISTENERS].remove(listener) if not hass.data[DATA_BACKUP_AGENT_LISTENERS]: del hass.data[DATA_BACKUP_AGENT_LISTENERS] return remove_listener def suggested_filenames(backup: AgentBackup) -> tuple[str, str]: """Return the suggested filenames for the backup and metadata files.""" base_name = suggested_filename(backup).rsplit(".", 1)[0] return f"{base_name}.tar", f"{base_name}.metadata.json" class R2BackupAgent(BackupAgent): """Backup agent for the Cloudflare R2 integration.""" domain = DOMAIN def __init__(self, hass: HomeAssistant, entry: R2ConfigEntry) -> None: """Initialize the R2 agent.""" super().__init__() self._client = entry.runtime_data self._bucket: str = entry.data[CONF_BUCKET] self.name = entry.title self.unique_id = entry.entry_id self._backup_cache: dict[str, AgentBackup] = {} self._cache_expiration = time() self._prefix: str = entry.data.get(CONF_PREFIX, "").strip("/") def _with_prefix(self, key: str) -> str: if not self._prefix: return key return f"{self._prefix}/{key}" @handle_boto_errors async def async_download_backup( self, backup_id: str, **kwargs: Any, ) -> AsyncIterator[bytes]: """Download a backup file. :param backup_id: The ID of the backup that was returned in async_list_backups. :return: An async iterator that yields bytes. """ backup = await self._find_backup_by_id(backup_id) tar_filename, _ = suggested_filenames(backup) response = await self._client.get_object( Bucket=self._bucket, Key=self._with_prefix(tar_filename) ) return response["Body"].iter_chunks() async def async_upload_backup( self, *, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], backup: AgentBackup, **kwargs: Any, ) -> None: """Upload a backup. :param open_stream: A function returning an async iterator that yields bytes. :param backup: Metadata about the backup that should be uploaded. """ tar_filename, metadata_filename = suggested_filenames(backup) try: if backup.size < MULTIPART_MIN_PART_SIZE_BYTES: await self._upload_simple(tar_filename, open_stream) else: await self._upload_multipart(tar_filename, open_stream) # Upload the metadata file metadata_content = json.dumps(backup.as_dict()) await self._client.put_object( Bucket=self._bucket, Key=self._with_prefix(metadata_filename), Body=metadata_content, ) except BotoCoreError as err: raise BackupAgentError("Failed to upload backup") from err else: # Reset cache after successful upload self._cache_expiration = time() async def _upload_simple( self, tar_filename: str, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], ) -> None: """Upload a small file using simple upload. :param tar_filename: The target filename for the backup. :param open_stream: A function returning an async iterator that yields bytes. """ _LOGGER.debug("Starting simple upload for %s", tar_filename) stream = await open_stream() file_data = bytearray() async for chunk in stream: file_data.extend(chunk) await self._client.put_object( Bucket=self._bucket, Key=self._with_prefix(tar_filename), Body=bytes(file_data), ) async def _upload_multipart( self, tar_filename: str, open_stream: Callable[[], Coroutine[Any, Any, AsyncIterator[bytes]]], ): """Upload a large file using multipart upload. :param tar_filename: The target filename for the backup. :param open_stream: A function returning an async iterator that yields bytes. """ _LOGGER.debug("Starting multipart upload for %s", tar_filename) key = self._with_prefix(tar_filename) multipart_upload = await self._client.create_multipart_upload( Bucket=self._bucket, Key=key, ) upload_id = multipart_upload["UploadId"] try: parts: list[dict[str, Any]] = [] part_number = 1 buffer = bytearray() # bytes buffer to store the data offset = 0 # start index of unread data inside buffer stream = await open_stream() async for chunk in stream: buffer.extend(chunk) # Upload parts of exactly MULTIPART_MIN_PART_SIZE_BYTES to ensure # all non-trailing parts have the same size (defensive implementation) view = memoryview(buffer) try: while len(buffer) - offset >= MULTIPART_MIN_PART_SIZE_BYTES: start = offset end = offset + MULTIPART_MIN_PART_SIZE_BYTES part_data = view[start:end] offset = end _LOGGER.debug( "Uploading part number %d, size %d", part_number, len(part_data), ) part = await cast(Any, self._client).upload_part( Bucket=self._bucket, Key=key, PartNumber=part_number, UploadId=upload_id, Body=part_data.tobytes(), ) parts.append({"PartNumber": part_number, "ETag": part["ETag"]}) part_number += 1 finally: view.release() # Compact the buffer if the consumed offset has grown large enough. This # avoids unnecessary memory copies when compacting after every part upload. if offset and offset >= MULTIPART_MIN_PART_SIZE_BYTES: buffer = bytearray(buffer[offset:]) offset = 0 # Upload the final buffer as the last part (no minimum size requirement) # Offset should be 0 after the last compaction, but we use it as the start # index to be defensive in case the buffer was not compacted. if offset < len(buffer): remaining_data = memoryview(buffer)[offset:] _LOGGER.debug( "Uploading final part number %d, size %d", part_number, len(remaining_data), ) part = await cast(Any, self._client).upload_part( Bucket=self._bucket, Key=key, PartNumber=part_number, UploadId=upload_id, Body=remaining_data.tobytes(), ) parts.append({"PartNumber": part_number, "ETag": part["ETag"]}) await cast(Any, self._client).complete_multipart_upload( Bucket=self._bucket, Key=key, UploadId=upload_id, MultipartUpload={"Parts": parts}, ) except BotoCoreError: try: await self._client.abort_multipart_upload( Bucket=self._bucket, Key=key, UploadId=upload_id, ) except BotoCoreError: _LOGGER.exception("Failed to abort multipart upload") raise @handle_boto_errors async def async_delete_backup( self, backup_id: str, **kwargs: Any, ) -> None: """Delete a backup file. :param backup_id: The ID of the backup that was returned in async_list_backups. """ backup = await self._find_backup_by_id(backup_id) tar_filename, metadata_filename = suggested_filenames(backup) # Delete both the backup file and its metadata file await self._client.delete_object( Bucket=self._bucket, Key=self._with_prefix(tar_filename) ) await self._client.delete_object( Bucket=self._bucket, Key=self._with_prefix(metadata_filename) ) # Reset cache after successful deletion self._cache_expiration = time() @handle_boto_errors async def async_list_backups(self, **kwargs: Any) -> list[AgentBackup]: """List backups.""" backups = await self._list_backups() return list(backups.values()) @handle_boto_errors async def async_get_backup( self, backup_id: str, **kwargs: Any, ) -> AgentBackup: """Return a backup.""" return await self._find_backup_by_id(backup_id) async def _find_backup_by_id(self, backup_id: str) -> AgentBackup: """Find a backup by its backup ID.""" backups = await self._list_backups() if backup := backups.get(backup_id): return backup raise BackupNotFound(f"Backup {backup_id} not found") async def _list_backups(self) -> dict[str, AgentBackup]: """List backups, using a cache if possible.""" if time() <= self._cache_expiration: return self._backup_cache backups = {} # Only pass Prefix if a prefix is configured; some S3-compatible APIs # (and type checkers) do not like Prefix=None. list_kwargs = {"Bucket": self._bucket} if self._prefix: list_kwargs["Prefix"] = self._prefix + "/" response = await self._client.list_objects_v2(**list_kwargs) # Filter for metadata files only metadata_files = [ obj for obj in response.get("Contents", []) if obj["Key"].endswith(".metadata.json") ] for metadata_file in metadata_files: try: # Download and parse metadata file metadata_response = await self._client.get_object( Bucket=self._bucket, Key=metadata_file["Key"] ) metadata_content = await metadata_response["Body"].read() metadata_json = json.loads(metadata_content) except (BotoCoreError, json.JSONDecodeError) as err: _LOGGER.warning( "Failed to process metadata file %s: %s", metadata_file["Key"], err, ) continue backup = AgentBackup.from_dict(metadata_json) backups[backup.backup_id] = backup self._backup_cache = backups self._cache_expiration = time() + CACHE_TTL return self._backup_cache
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloudflare_r2/backup.py", "license": "Apache License 2.0", "lines": 310, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/cloudflare_r2/config_flow.py
"""Config flow for the Cloudflare R2 integration.""" from __future__ import annotations from typing import Any from urllib.parse import urlparse from aiobotocore.session import AioSession from botocore.exceptions import ( ClientError, ConnectionError, EndpointConnectionError, ParamValidationError, ) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers import config_validation as cv from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import ( CLOUDFLARE_R2_DOMAIN, CONF_ACCESS_KEY_ID, CONF_BUCKET, CONF_ENDPOINT_URL, CONF_PREFIX, CONF_SECRET_ACCESS_KEY, DEFAULT_ENDPOINT_URL, DESCRIPTION_R2_AUTH_DOCS_URL, DOMAIN, ) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_ACCESS_KEY_ID): cv.string, vol.Required(CONF_SECRET_ACCESS_KEY): TextSelector( config=TextSelectorConfig(type=TextSelectorType.PASSWORD) ), vol.Required(CONF_BUCKET): cv.string, vol.Required(CONF_ENDPOINT_URL, default=DEFAULT_ENDPOINT_URL): TextSelector( config=TextSelectorConfig(type=TextSelectorType.URL) ), vol.Optional(CONF_PREFIX, default=""): cv.string, } ) class R2ConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Cloudflare R2.""" async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a flow initiated by the user.""" errors: dict[str, str] = {} if user_input is not None: self._async_abort_entries_match( { CONF_BUCKET: user_input[CONF_BUCKET], CONF_ENDPOINT_URL: user_input[CONF_ENDPOINT_URL], } ) parsed = urlparse(user_input[CONF_ENDPOINT_URL]) if not parsed.hostname or not parsed.hostname.endswith( CLOUDFLARE_R2_DOMAIN ): errors[CONF_ENDPOINT_URL] = "invalid_endpoint_url" else: try: session = AioSession() async with session.create_client( "s3", endpoint_url=user_input.get(CONF_ENDPOINT_URL), aws_secret_access_key=user_input[CONF_SECRET_ACCESS_KEY], aws_access_key_id=user_input[CONF_ACCESS_KEY_ID], ) as client: await client.head_bucket(Bucket=user_input[CONF_BUCKET]) except ClientError: errors["base"] = "invalid_credentials" except ParamValidationError as err: if "Invalid bucket name" in str(err): errors[CONF_BUCKET] = "invalid_bucket_name" except ValueError: errors[CONF_ENDPOINT_URL] = "invalid_endpoint_url" except EndpointConnectionError: errors[CONF_ENDPOINT_URL] = "cannot_connect" except ConnectionError: errors[CONF_ENDPOINT_URL] = "cannot_connect" else: # Do not persist empty optional values data = dict(user_input) if not data.get(CONF_PREFIX): data.pop(CONF_PREFIX, None) return self.async_create_entry( title=user_input[CONF_BUCKET], data=data ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, user_input ), errors=errors, description_placeholders={ "auth_docs_url": DESCRIPTION_R2_AUTH_DOCS_URL, }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloudflare_r2/config_flow.py", "license": "Apache License 2.0", "lines": 101, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/cloudflare_r2/const.py
"""Constants for the Cloudflare R2 integration.""" from collections.abc import Callable from typing import Final from homeassistant.util.hass_dict import HassKey DOMAIN: Final = "cloudflare_r2" CONF_ACCESS_KEY_ID = "access_key_id" CONF_SECRET_ACCESS_KEY = "secret_access_key" CONF_ENDPOINT_URL = "endpoint_url" CONF_BUCKET = "bucket" CONF_PREFIX = "prefix" # R2 is S3-compatible. Endpoint should be like: # https://<accountid>.r2.cloudflarestorage.com CLOUDFLARE_R2_DOMAIN: Final = "r2.cloudflarestorage.com" DEFAULT_ENDPOINT_URL: Final = "https://ACCOUNT_ID." + CLOUDFLARE_R2_DOMAIN + "/" DATA_BACKUP_AGENT_LISTENERS: HassKey[list[Callable[[], None]]] = HassKey( f"{DOMAIN}.backup_agent_listeners" ) DESCRIPTION_R2_AUTH_DOCS_URL: Final = "https://developers.cloudflare.com/r2/api/tokens/"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/cloudflare_r2/const.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/compit/select.py
"""Select platform for Compit integration.""" from dataclasses import dataclass from compit_inext_api.consts import CompitParameter from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER_NAME from .coordinator import CompitConfigEntry, CompitDataUpdateCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class CompitDeviceDescription: """Class to describe a Compit device.""" name: str """Name of the device.""" parameters: dict[CompitParameter, SelectEntityDescription] """Parameters of the device.""" DESCRIPTIONS: dict[CompitParameter, SelectEntityDescription] = { CompitParameter.LANGUAGE: SelectEntityDescription( key=CompitParameter.LANGUAGE.value, translation_key="language", options=[ "polish", "english", ], ), CompitParameter.AEROKONFBYPASS: SelectEntityDescription( key=CompitParameter.AEROKONFBYPASS.value, translation_key="aero_by_pass", options=[ "off", "auto", "on", ], ), CompitParameter.NANO_MODE: SelectEntityDescription( key=CompitParameter.NANO_MODE.value, translation_key="nano_work_mode", options=[ "manual_3", "manual_2", "manual_1", "manual_0", "schedule", "christmas", "out_of_home", ], ), CompitParameter.R900_OPERATING_MODE: SelectEntityDescription( key=CompitParameter.R900_OPERATING_MODE.value, translation_key="operating_mode", options=[ "disabled", "eco", "hybrid", ], ), CompitParameter.SOLAR_COMP_OPERATING_MODE: SelectEntityDescription( key=CompitParameter.SOLAR_COMP_OPERATING_MODE.value, translation_key="solarcomp_operating_mode", options=[ "auto", "de_icing", "holiday", "disabled", ], ), CompitParameter.R490_OPERATING_MODE: SelectEntityDescription( key=CompitParameter.R490_OPERATING_MODE.value, translation_key="operating_mode", options=[ "disabled", "eco", "hybrid", ], ), CompitParameter.WORK_MODE: SelectEntityDescription( key=CompitParameter.WORK_MODE.value, translation_key="work_mode", options=[ "winter", "summer", "cooling", ], ), CompitParameter.R470_OPERATING_MODE: SelectEntityDescription( key=CompitParameter.R470_OPERATING_MODE.value, translation_key="operating_mode", options=[ "disabled", "auto", "eco", ], ), CompitParameter.HEATING_SOURCE_OF_CORRECTION: SelectEntityDescription( key=CompitParameter.HEATING_SOURCE_OF_CORRECTION.value, translation_key="heating_source_of_correction", options=[ "no_corrections", "schedule", "thermostat", "nano_nr_1", "nano_nr_2", "nano_nr_3", "nano_nr_4", "nano_nr_5", ], ), CompitParameter.BIOMAX_MIXER_MODE_ZONE_1: SelectEntityDescription( key=CompitParameter.BIOMAX_MIXER_MODE_ZONE_1.value, translation_key="mixer_mode_zone", options=[ "disabled", "without_thermostat", "schedule", "thermostat", "nano_nr_1", "nano_nr_2", "nano_nr_3", "nano_nr_4", "nano_nr_5", ], translation_placeholders={"zone": "1"}, ), CompitParameter.BIOMAX_MIXER_MODE_ZONE_2: SelectEntityDescription( key=CompitParameter.BIOMAX_MIXER_MODE_ZONE_2.value, translation_key="mixer_mode_zone", options=[ "disabled", "without_thermostat", "schedule", "thermostat", "nano_nr_1", "nano_nr_2", "nano_nr_3", "nano_nr_4", "nano_nr_5", ], translation_placeholders={"zone": "2"}, ), CompitParameter.DHW_CIRCULATION_MODE: SelectEntityDescription( key=CompitParameter.DHW_CIRCULATION_MODE.value, translation_key="dhw_circulation", options=[ "disabled", "constant", "schedule", ], ), CompitParameter.BIOMAX_HEATING_SOURCE_OF_CORRECTION: SelectEntityDescription( key=CompitParameter.BIOMAX_HEATING_SOURCE_OF_CORRECTION.value, translation_key="heating_source_of_correction", options=[ "disabled", "no_corrections", "schedule", "thermostat", "nano_nr_1", "nano_nr_2", "nano_nr_3", "nano_nr_4", "nano_nr_5", ], ), CompitParameter.MIXER_MODE: SelectEntityDescription( key=CompitParameter.MIXER_MODE.value, translation_key="mixer_mode", options=[ "no_corrections", "schedule", "thermostat", "nano_nr_1", "nano_nr_2", "nano_nr_3", "nano_nr_4", "nano_nr_5", ], ), CompitParameter.R480_OPERATING_MODE: SelectEntityDescription( key=CompitParameter.R480_OPERATING_MODE.value, translation_key="operating_mode", options=[ "disabled", "eco", "hybrid", ], ), CompitParameter.BUFFER_MODE: SelectEntityDescription( key=CompitParameter.BUFFER_MODE.value, translation_key="buffer_mode", options=[ "schedule", "manual", "disabled", ], ), } DEVICE_DEFINITIONS: dict[int, CompitDeviceDescription] = { 223: CompitDeviceDescription( name="Nano Color 2", parameters={ CompitParameter.LANGUAGE: DESCRIPTIONS[CompitParameter.LANGUAGE], CompitParameter.AEROKONFBYPASS: DESCRIPTIONS[ CompitParameter.AEROKONFBYPASS ], }, ), 12: CompitDeviceDescription( name="Nano Color", parameters={ CompitParameter.LANGUAGE: DESCRIPTIONS[CompitParameter.LANGUAGE], CompitParameter.AEROKONFBYPASS: DESCRIPTIONS[ CompitParameter.AEROKONFBYPASS ], }, ), 7: CompitDeviceDescription( name="Nano One", parameters={ CompitParameter.LANGUAGE: DESCRIPTIONS[CompitParameter.LANGUAGE], CompitParameter.NANO_MODE: DESCRIPTIONS[CompitParameter.NANO_MODE], }, ), 224: CompitDeviceDescription( name="R 900", parameters={ CompitParameter.R900_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.R900_OPERATING_MODE ], }, ), 45: CompitDeviceDescription( name="SolarComp971", parameters={ CompitParameter.SOLAR_COMP_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.SOLAR_COMP_OPERATING_MODE ], }, ), 99: CompitDeviceDescription( name="SolarComp971C", parameters={ CompitParameter.SOLAR_COMP_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.SOLAR_COMP_OPERATING_MODE ], }, ), 44: CompitDeviceDescription( name="SolarComp 951", parameters={ CompitParameter.SOLAR_COMP_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.SOLAR_COMP_OPERATING_MODE ], }, ), 92: CompitDeviceDescription( name="r490", parameters={ CompitParameter.R490_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.R490_OPERATING_MODE ], CompitParameter.WORK_MODE: DESCRIPTIONS[CompitParameter.WORK_MODE], }, ), 34: CompitDeviceDescription( name="r470", parameters={ CompitParameter.R470_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.R470_OPERATING_MODE ], CompitParameter.HEATING_SOURCE_OF_CORRECTION: DESCRIPTIONS[ CompitParameter.HEATING_SOURCE_OF_CORRECTION ], }, ), 201: CompitDeviceDescription( name="BioMax775", parameters={ CompitParameter.BIOMAX_MIXER_MODE_ZONE_1: DESCRIPTIONS[ CompitParameter.BIOMAX_MIXER_MODE_ZONE_1 ], CompitParameter.BIOMAX_MIXER_MODE_ZONE_2: DESCRIPTIONS[ CompitParameter.BIOMAX_MIXER_MODE_ZONE_2 ], CompitParameter.DHW_CIRCULATION_MODE: DESCRIPTIONS[ CompitParameter.DHW_CIRCULATION_MODE ], }, ), 36: CompitDeviceDescription( name="BioMax742", parameters={ CompitParameter.BIOMAX_HEATING_SOURCE_OF_CORRECTION: DESCRIPTIONS[ CompitParameter.BIOMAX_HEATING_SOURCE_OF_CORRECTION ], CompitParameter.BIOMAX_MIXER_MODE_ZONE_1: DESCRIPTIONS[ CompitParameter.BIOMAX_MIXER_MODE_ZONE_1 ], CompitParameter.DHW_CIRCULATION_MODE: DESCRIPTIONS[ CompitParameter.DHW_CIRCULATION_MODE ], }, ), 75: CompitDeviceDescription( name="BioMax772", parameters={ CompitParameter.BIOMAX_MIXER_MODE_ZONE_1: DESCRIPTIONS[ CompitParameter.BIOMAX_MIXER_MODE_ZONE_1 ], CompitParameter.BIOMAX_MIXER_MODE_ZONE_2: DESCRIPTIONS[ CompitParameter.BIOMAX_MIXER_MODE_ZONE_2 ], CompitParameter.DHW_CIRCULATION_MODE: DESCRIPTIONS[ CompitParameter.DHW_CIRCULATION_MODE ], }, ), 5: CompitDeviceDescription( name="R350 T3", parameters={ CompitParameter.MIXER_MODE: DESCRIPTIONS[CompitParameter.MIXER_MODE], }, ), 215: CompitDeviceDescription( name="R480", parameters={ CompitParameter.R480_OPERATING_MODE: DESCRIPTIONS[ CompitParameter.R480_OPERATING_MODE ], CompitParameter.BUFFER_MODE: DESCRIPTIONS[CompitParameter.BUFFER_MODE], }, ), } async def async_setup_entry( hass: HomeAssistant, entry: CompitConfigEntry, async_add_devices: AddConfigEntryEntitiesCallback, ) -> None: """Set up Compit select entities from a config entry.""" coordinator = entry.runtime_data select_entities = [] for device_id, device in coordinator.connector.all_devices.items(): device_definition = DEVICE_DEFINITIONS.get(device.definition.code) if not device_definition: continue for code, entity_description in device_definition.parameters.items(): param = next( (p for p in device.state.params if p.code == entity_description.key), None, ) if param is None: continue select_entities.append( CompitSelect( coordinator, device_id, device_definition.name, code, entity_description, ) ) async_add_devices(select_entities) class CompitSelect(CoordinatorEntity[CompitDataUpdateCoordinator], SelectEntity): """Representation of a Compit select entity.""" def __init__( self, coordinator: CompitDataUpdateCoordinator, device_id: int, device_name: str, parameter_code: CompitParameter, entity_description: SelectEntityDescription, ) -> None: """Initialize the select entity.""" super().__init__(coordinator) self.device_id = device_id self.entity_description = entity_description self._attr_has_entity_name = True self._attr_unique_id = f"{device_id}_{entity_description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, str(device_id))}, name=device_name, manufacturer=MANUFACTURER_NAME, model=device_name, ) self.parameter_code = parameter_code @property def available(self) -> bool: """Return if entity is available.""" return ( super().available and self.coordinator.connector.get_device(self.device_id) is not None ) @property def current_option(self) -> str | None: """Return the current option.""" return self.coordinator.connector.get_current_option( self.device_id, self.parameter_code ) async def async_select_option(self, option: str) -> None: """Change the selected option.""" await self.coordinator.connector.select_device_option( self.device_id, self.parameter_code, option ) self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/compit/select.py", "license": "Apache License 2.0", "lines": 405, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/device_tracker/condition.py
"""Provides conditions for device trackers.""" from homeassistant.const import STATE_HOME, STATE_NOT_HOME from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN CONDITIONS: dict[str, type[Condition]] = { "is_home": make_entity_state_condition(DOMAIN, STATE_HOME), "is_not_home": make_entity_state_condition(DOMAIN, STATE_NOT_HOME), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the conditions for device trackers.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/device_tracker/condition.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/digital_ocean/const.py
"""Support for Digital Ocean.""" from __future__ import annotations from datetime import timedelta from typing import TYPE_CHECKING from homeassistant.util.hass_dict import HassKey if TYPE_CHECKING: from . import DigitalOcean ATTR_CREATED_AT = "created_at" ATTR_DROPLET_ID = "droplet_id" ATTR_DROPLET_NAME = "droplet_name" ATTR_FEATURES = "features" ATTR_IPV4_ADDRESS = "ipv4_address" ATTR_IPV6_ADDRESS = "ipv6_address" ATTR_MEMORY = "memory" ATTR_REGION = "region" ATTR_VCPUS = "vcpus" ATTRIBUTION = "Data provided by Digital Ocean" CONF_DROPLETS = "droplets" DOMAIN = "digital_ocean" DATA_DIGITAL_OCEAN: HassKey[DigitalOcean] = HassKey(DOMAIN) MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=60)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/digital_ocean/const.py", "license": "Apache License 2.0", "lines": 21, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/energy/helpers.py
"""Helpers for the Energy integration.""" from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from .data import PowerConfig def generate_power_sensor_unique_id(source_type: str, config: PowerConfig) -> str: """Generate a unique ID for a power transform sensor.""" if "stat_rate_inverted" in config: sensor_id = config["stat_rate_inverted"].replace(".", "_") return f"energy_power_{source_type}_inverted_{sensor_id}" if "stat_rate_from" in config and "stat_rate_to" in config: from_id = config["stat_rate_from"].replace(".", "_") to_id = config["stat_rate_to"].replace(".", "_") return f"energy_power_{source_type}_combined_{from_id}_{to_id}" # This case is impossible: schema validation (vol.Inclusive) ensures # stat_rate_from and stat_rate_to are always present together raise RuntimeError("Invalid power config: missing required keys") def generate_power_sensor_entity_id(source_type: str, config: PowerConfig) -> str: """Generate an entity ID for a power transform sensor.""" if "stat_rate_inverted" in config: # Use source sensor name with _inverted suffix source = config["stat_rate_inverted"] if source.startswith("sensor."): return f"{source}_inverted" return f"sensor.{source.replace('.', '_')}_inverted" if "stat_rate_from" in config and "stat_rate_to" in config: # Use both sensors in entity ID to ensure uniqueness when multiple # combined configs exist. The entity represents net power (from - to), # e.g., discharge - charge for battery. from_sensor = config["stat_rate_from"].removeprefix("sensor.") to_sensor = config["stat_rate_to"].removeprefix("sensor.") return f"sensor.energy_{source_type}_{from_sensor}_{to_sensor}_net_power" # This case is impossible: schema validation (vol.Inclusive) ensures # stat_rate_from and stat_rate_to are always present together raise RuntimeError("Invalid power config: missing required keys")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/energy/helpers.py", "license": "Apache License 2.0", "lines": 35, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/esphome/water_heater.py
"""Support for ESPHome water heaters.""" from __future__ import annotations from functools import partial from typing import Any from aioesphomeapi import EntityInfo, WaterHeaterInfo, WaterHeaterMode, WaterHeaterState from homeassistant.components.water_heater import ( WaterHeaterEntity, WaterHeaterEntityFeature, ) from homeassistant.const import ATTR_TEMPERATURE, PRECISION_TENTHS, UnitOfTemperature from homeassistant.core import callback from .entity import ( EsphomeEntity, convert_api_error_ha_error, esphome_float_state_property, esphome_state_property, platform_async_setup_entry, ) from .enum_mapper import EsphomeEnumMapper PARALLEL_UPDATES = 0 _WATER_HEATER_MODES: EsphomeEnumMapper[WaterHeaterMode, str] = EsphomeEnumMapper( { WaterHeaterMode.OFF: "off", WaterHeaterMode.ECO: "eco", WaterHeaterMode.ELECTRIC: "electric", WaterHeaterMode.PERFORMANCE: "performance", WaterHeaterMode.HIGH_DEMAND: "high_demand", WaterHeaterMode.HEAT_PUMP: "heat_pump", WaterHeaterMode.GAS: "gas", } ) class EsphomeWaterHeater( EsphomeEntity[WaterHeaterInfo, WaterHeaterState], WaterHeaterEntity ): """A water heater implementation for ESPHome.""" _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_precision = PRECISION_TENTHS @callback def _on_static_info_update(self, static_info: EntityInfo) -> None: """Set attrs from static info.""" super()._on_static_info_update(static_info) static_info = self._static_info self._attr_min_temp = static_info.min_temperature self._attr_max_temp = static_info.max_temperature features = WaterHeaterEntityFeature.TARGET_TEMPERATURE if static_info.supported_modes: features |= WaterHeaterEntityFeature.OPERATION_MODE self._attr_operation_list = [ _WATER_HEATER_MODES.from_esphome(mode) for mode in static_info.supported_modes ] else: self._attr_operation_list = None self._attr_supported_features = features @property @esphome_float_state_property def current_temperature(self) -> float | None: """Return the current temperature.""" return self._state.current_temperature @property @esphome_float_state_property def target_temperature(self) -> float | None: """Return the temperature we try to reach.""" return self._state.target_temperature @property @esphome_state_property def current_operation(self) -> str | None: """Return current operation mode.""" return _WATER_HEATER_MODES.from_esphome(self._state.mode) @convert_api_error_ha_error async def async_set_temperature(self, **kwargs: Any) -> None: """Set new target temperature.""" self._client.water_heater_command( key=self._key, target_temperature=kwargs[ATTR_TEMPERATURE], device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_set_operation_mode(self, operation_mode: str) -> None: """Set new operation mode.""" self._client.water_heater_command( key=self._key, mode=_WATER_HEATER_MODES.from_hass(operation_mode), device_id=self._static_info.device_id, ) async_setup_entry = partial( platform_async_setup_entry, info_type=WaterHeaterInfo, entity_type=EsphomeWaterHeater, state_type=WaterHeaterState, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/esphome/water_heater.py", "license": "Apache License 2.0", "lines": 91, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fan/condition.py
"""Provides conditions for fans.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from . import DOMAIN CONDITIONS: dict[str, type[Condition]] = { "is_off": make_entity_state_condition(DOMAIN, STATE_OFF), "is_on": make_entity_state_condition(DOMAIN, STATE_ON), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the fan conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fan/condition.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/fressnapf_tracker/services.py
"""Services and service helpers for fressnapf_tracker.""" from fressnapftracker import FressnapfTrackerError, FressnapfTrackerInvalidTokenError from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError from .const import DOMAIN def handle_fressnapf_tracker_exception(exception: FressnapfTrackerError): """Handle the different FressnapfTracker errors.""" if isinstance(exception, FressnapfTrackerInvalidTokenError): raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth", ) from exception raise HomeAssistantError( translation_domain=DOMAIN, translation_key="api_error", translation_placeholders={"error_message": str(exception)}, ) from exception
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/fressnapf_tracker/services.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/green_planet_energy/config_flow.py
"""Config flow for Green Planet Energy integration.""" from __future__ import annotations import logging from typing import Any from greenplanet_energy_api import ( GreenPlanetEnergyAPI, GreenPlanetEnergyAPIError, GreenPlanetEnergyConnectionError, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import DOMAIN _LOGGER = logging.getLogger(__name__) class GreenPlanetEnergyConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Green Planet Energy.""" VERSION = 1 MINOR_VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} if user_input is not None: session = async_get_clientsession(self.hass) api = GreenPlanetEnergyAPI(session=session) try: await api.get_electricity_prices() except GreenPlanetEnergyConnectionError: errors["base"] = "cannot_connect" except GreenPlanetEnergyAPIError: errors["base"] = "invalid_auth" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" else: return self.async_create_entry( title="Green Planet Energy", data=user_input ) return self.async_show_form(step_id="user", errors=errors)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/green_planet_energy/config_flow.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/green_planet_energy/const.py
"""Constants for the Green Planet Energy integration.""" DOMAIN = "green_planet_energy" # Default values DEFAULT_API_URL = "https://mein.green-planet-energy.de/p2" DEFAULT_SCAN_INTERVAL = 60 # minutes # API constants API_METHOD = "getVerbrauchspreisUndWindsignal" AGGREGATS_ZEITRAUM = "" AGGREGATS_TYP = "" SOURCE = "Portal"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/green_planet_energy/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/green_planet_energy/coordinator.py
"""Data update coordinator for Green Planet Energy.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from greenplanet_energy_api import ( GreenPlanetEnergyAPI, GreenPlanetEnergyAPIError, GreenPlanetEnergyConnectionError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) type GreenPlanetEnergyConfigEntry = ConfigEntry[GreenPlanetEnergyUpdateCoordinator] class GreenPlanetEnergyUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Class to manage fetching data from Green Planet Energy API.""" def __init__( self, hass: HomeAssistant, config_entry: GreenPlanetEnergyConfigEntry ) -> None: """Initialize.""" super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(minutes=DEFAULT_SCAN_INTERVAL), config_entry=config_entry, ) self.api = GreenPlanetEnergyAPI(session=async_get_clientsession(hass)) async def _async_update_data(self) -> dict[str, Any]: """Update data via library.""" try: return await self.api.get_electricity_prices() except GreenPlanetEnergyConnectionError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="connection_error", translation_placeholders={"error": str(err)}, ) from err except GreenPlanetEnergyAPIError as err: raise UpdateFailed( translation_domain=DOMAIN, translation_key="api_error", translation_placeholders={"error": str(err)}, ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/green_planet_energy/coordinator.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/green_planet_energy/sensor.py
"""Green Planet Energy sensor platform.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from datetime import datetime import logging from typing import Any from greenplanet_energy_api import GreenPlanetEnergyAPI from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, ) from homeassistant.const import CURRENCY_EURO, UnitOfEnergy 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 homeassistant.util import dt as dt_util from . import GreenPlanetEnergyConfigEntry from .const import DOMAIN from .coordinator import GreenPlanetEnergyUpdateCoordinator _LOGGER = logging.getLogger(__name__) @dataclass(frozen=True, kw_only=True) class GreenPlanetEnergySensorEntityDescription(SensorEntityDescription): """Describes Green Planet Energy sensor entity.""" value_fn: Callable[[GreenPlanetEnergyAPI, dict[str, Any]], float | datetime | None] SENSOR_DESCRIPTIONS: list[GreenPlanetEnergySensorEntityDescription] = [ # Statistical sensors only - hourly prices available via service GreenPlanetEnergySensorEntityDescription( key="gpe_highest_price_today", translation_key="highest_price_today", native_unit_of_measurement=f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}", suggested_display_precision=4, value_fn=lambda api, data: ( price / 100 if (price := api.get_highest_price_today(data)) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_highest_price_time", translation_key="highest_price_time", device_class=SensorDeviceClass.TIMESTAMP, value_fn=lambda api, data: ( dt_util.start_of_local_day().replace(hour=hour) if (hour := api.get_highest_price_today_with_hour(data)[1]) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_lowest_price_day", translation_key="lowest_price_day", native_unit_of_measurement=f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}", suggested_display_precision=4, translation_placeholders={"time_range": "(06:00-18:00)"}, value_fn=lambda api, data: ( price / 100 if (price := api.get_lowest_price_day(data)) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_lowest_price_day_time", translation_key="lowest_price_day_time", device_class=SensorDeviceClass.TIMESTAMP, translation_placeholders={"time_range": "(06:00-18:00)"}, value_fn=lambda api, data: ( dt_util.start_of_local_day().replace(hour=hour) if (hour := api.get_lowest_price_day_with_hour(data)[1]) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_lowest_price_night", translation_key="lowest_price_night", native_unit_of_measurement=f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}", suggested_display_precision=4, translation_placeholders={"time_range": "(18:00-06:00)"}, value_fn=lambda api, data: ( price / 100 if (price := api.get_lowest_price_night(data)) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_lowest_price_night_time", translation_key="lowest_price_night_time", device_class=SensorDeviceClass.TIMESTAMP, translation_placeholders={"time_range": "(18:00-06:00)"}, value_fn=lambda api, data: ( dt_util.start_of_local_day().replace(hour=hour) if (hour := api.get_lowest_price_night_with_hour(data)[1]) is not None else None ), ), GreenPlanetEnergySensorEntityDescription( key="gpe_current_price", translation_key="current_price", native_unit_of_measurement=f"{CURRENCY_EURO}/{UnitOfEnergy.KILO_WATT_HOUR}", suggested_display_precision=4, value_fn=lambda api, data: ( price / 100 if (price := api.get_current_price(data, dt_util.now().hour)) is not None else None ), ), ] async def async_setup_entry( hass: HomeAssistant, config_entry: GreenPlanetEnergyConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Green Planet Energy sensors.""" coordinator = config_entry.runtime_data async_add_entities( GreenPlanetEnergySensor(coordinator, description) for description in SENSOR_DESCRIPTIONS ) class GreenPlanetEnergySensor( CoordinatorEntity[GreenPlanetEnergyUpdateCoordinator], SensorEntity ): """Representation of a Green Planet Energy sensor.""" entity_description: GreenPlanetEnergySensorEntityDescription _attr_has_entity_name = True def __init__( self, coordinator: GreenPlanetEnergyUpdateCoordinator, description: GreenPlanetEnergySensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description # Use fixed unique_id with just the key for predictable entity IDs self._attr_unique_id = description.key self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, DOMAIN)}, name="Green Planet Energy", entry_type=DeviceEntryType.SERVICE, ) @property def native_value(self) -> float | datetime | None: """Return the state of the sensor.""" return self.entity_description.value_fn( self.coordinator.api, self.coordinator.data )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/green_planet_energy/sensor.py", "license": "Apache License 2.0", "lines": 146, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/button.py
"""Button platform for HDFury Integration.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from hdfury import HDFuryAPI, HDFuryError 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 .const import DOMAIN from .coordinator import HDFuryConfigEntry from .entity import HDFuryEntity PARALLEL_UPDATES = 1 @dataclass(kw_only=True, frozen=True) class HDFuryButtonEntityDescription(ButtonEntityDescription): """Description for HDFury button entities.""" press_fn: Callable[[HDFuryAPI], Awaitable[None]] BUTTONS: tuple[HDFuryButtonEntityDescription, ...] = ( HDFuryButtonEntityDescription( key="reboot", device_class=ButtonDeviceClass.RESTART, entity_category=EntityCategory.CONFIG, press_fn=lambda client: client.issue_reboot(), ), HDFuryButtonEntityDescription( key="issue_hotplug", translation_key="issue_hotplug", entity_category=EntityCategory.CONFIG, press_fn=lambda client: client.issue_hotplug(), ), ) async def async_setup_entry( hass: HomeAssistant, entry: HDFuryConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up buttons using the platform schema.""" coordinator = entry.runtime_data async_add_entities( HDFuryButton(coordinator, description) for description in BUTTONS ) class HDFuryButton(HDFuryEntity, ButtonEntity): """HDFury Button Class.""" entity_description: HDFuryButtonEntityDescription async def async_press(self) -> None: """Handle Button Press.""" try: await self.entity_description.press_fn(self.coordinator.client) except HDFuryError as error: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from error
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/button.py", "license": "Apache License 2.0", "lines": 57, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/config_flow.py
"""Config flow for HDFury Integration.""" from typing import Any from hdfury import HDFuryAPI, HDFuryError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .const import DOMAIN class HDFuryConfigFlow(ConfigFlow, domain=DOMAIN): """Handle Config Flow for HDFury.""" def __init__(self) -> None: """Initialize the config flow.""" self.data: dict[str, Any] = {} async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" self.data[CONF_HOST] = host = discovery_info.host serial = await self._validate_connection(host) if serial is not None: await self.async_set_unique_id(serial) self._abort_if_unique_id_configured(updates={CONF_HOST: host}) self.context["title_placeholders"] = { CONF_HOST: self.data[CONF_HOST], } return await self.async_step_discovery_confirm() return self.async_abort(reason="cannot_connect") async def async_step_discovery_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm discovery.""" if user_input is not None: return self.async_create_entry( title=f"HDFury ({self.data[CONF_HOST]})", data={CONF_HOST: self.data[CONF_HOST]}, ) self._set_confirm_only() return self.async_show_form( step_id="discovery_confirm", description_placeholders={ CONF_HOST: self.data[CONF_HOST], }, ) async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle Initial Setup.""" errors: dict[str, str] = {} if user_input is not None: host = user_input[CONF_HOST] serial = await self._validate_connection(host) if serial is not None: await self.async_set_unique_id(serial) self._abort_if_unique_id_configured() return self.async_create_entry( title=f"HDFury ({host})", data=user_input ) errors["base"] = "cannot_connect" return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_HOST): str}), errors=errors, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration.""" errors: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: host = user_input[CONF_HOST] serial = await self._validate_connection(host) if serial is not None: await self.async_set_unique_id(serial) self._abort_if_unique_id_mismatch(reason="incorrect_device") return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates=user_input, ) errors["base"] = "cannot_connect" return self.async_show_form( step_id="reconfigure", data_schema=vol.Schema( { vol.Required( CONF_HOST, default=reconfigure_entry.data.get(CONF_HOST), ): str } ), description_placeholders={ "title": reconfigure_entry.title, }, errors=errors, ) async def _validate_connection(self, host: str) -> str | None: """Try to fetch serial number to confirm it's a valid HDFury device.""" client = HDFuryAPI(host, async_get_clientsession(self.hass)) try: data = await client.get_board() except HDFuryError: return None return data["serial"]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/config_flow.py", "license": "Apache License 2.0", "lines": 104, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/coordinator.py
"""DataUpdateCoordinator for HDFury Integration.""" from dataclasses import dataclass from datetime import timedelta import logging from typing import Final from hdfury import HDFuryAPI, HDFuryError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL: Final = timedelta(seconds=60) type HDFuryConfigEntry = ConfigEntry[HDFuryCoordinator] @dataclass(kw_only=True, frozen=True) class HDFuryData: """HDFury Data Class.""" board: dict[str, str] info: dict[str, str] config: dict[str, str] class HDFuryCoordinator(DataUpdateCoordinator[HDFuryData]): """HDFury Device Coordinator Class.""" def __init__(self, hass: HomeAssistant, entry: HDFuryConfigEntry) -> None: """Initialize the coordinator.""" super().__init__( hass, _LOGGER, config_entry=entry, name="HDFury", update_interval=SCAN_INTERVAL, ) self.host: str = entry.data[CONF_HOST] self.client = HDFuryAPI(self.host, async_get_clientsession(hass)) async def _async_update_data(self) -> HDFuryData: """Fetch the latest device data.""" try: board = await self.client.get_board() info = await self.client.get_info() config = await self.client.get_config() except HDFuryError as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="communication_error", ) from error return HDFuryData( board=board, info=info, config=config, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/coordinator.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/diagnostics.py
"""Diagnostics for HDFury Integration.""" from typing import Any from homeassistant.core import HomeAssistant from .coordinator import HDFuryConfigEntry, HDFuryCoordinator async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: HDFuryConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator: HDFuryCoordinator = entry.runtime_data return { "board": coordinator.data.board, "info": coordinator.data.info, "config": coordinator.data.config, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/diagnostics.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/entity.py
"""Base class for HDFury entities.""" from homeassistant.helpers import device_registry as dr from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from .coordinator import HDFuryCoordinator class HDFuryEntity(CoordinatorEntity[HDFuryCoordinator]): """Common elements for all entities.""" _attr_has_entity_name = True def __init__( self, coordinator: HDFuryCoordinator, entity_description: EntityDescription ) -> None: """Initialize the entity.""" super().__init__(coordinator) self.entity_description = entity_description self._attr_unique_id = ( f"{coordinator.data.board['serial']}_{entity_description.key}" ) self._attr_device_info = DeviceInfo( name=f"HDFury {coordinator.data.board['hostname']}", manufacturer="HDFury", model=coordinator.data.board["hostname"].split("-")[0], serial_number=coordinator.data.board["serial"], sw_version=coordinator.data.board["version"].removeprefix("FW: "), hw_version=coordinator.data.board.get("pcbv"), configuration_url=f"http://{coordinator.host}", connections={ (dr.CONNECTION_NETWORK_MAC, coordinator.data.config["macaddr"]) }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/entity.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/select.py
"""Select platform for HDFury Integration.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from hdfury import OPERATION_MODES, TX0_INPUT_PORTS, TX1_INPUT_PORTS, HDFuryError from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import HDFuryConfigEntry, HDFuryCoordinator from .entity import HDFuryEntity PARALLEL_UPDATES = 1 @dataclass(kw_only=True, frozen=True) class HDFurySelectEntityDescription(SelectEntityDescription): """Description for HDFury select entities.""" set_value_fn: Callable[[HDFuryCoordinator, str], Awaitable[None]] SELECT_PORTS: tuple[HDFurySelectEntityDescription, ...] = ( HDFurySelectEntityDescription( key="portseltx0", translation_key="portseltx0", options=list(TX0_INPUT_PORTS.keys()), set_value_fn=lambda coordinator, value: _set_ports(coordinator), ), HDFurySelectEntityDescription( key="portseltx1", translation_key="portseltx1", options=list(TX1_INPUT_PORTS.keys()), set_value_fn=lambda coordinator, value: _set_ports(coordinator), ), ) SELECT_OPERATION_MODE: HDFurySelectEntityDescription = HDFurySelectEntityDescription( key="opmode", translation_key="opmode", options=list(OPERATION_MODES.keys()), set_value_fn=lambda coordinator, value: coordinator.client.set_operation_mode( value ), ) async def _set_ports(coordinator: HDFuryCoordinator) -> None: tx0 = coordinator.data.info.get("portseltx0") tx1 = coordinator.data.info.get("portseltx1") if tx0 is None or tx1 is None: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="tx_state_error", translation_placeholders={"details": f"tx0={tx0}, tx1={tx1}"}, ) await coordinator.client.set_port_selection(tx0, tx1) async def async_setup_entry( hass: HomeAssistant, entry: HDFuryConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up selects using the platform schema.""" coordinator = entry.runtime_data entities: list[HDFuryEntity] = [ HDFurySelect(coordinator, description) for description in SELECT_PORTS if description.key in coordinator.data.info ] # Add OPMODE select if present if "opmode" in coordinator.data.info: entities.append(HDFurySelect(coordinator, SELECT_OPERATION_MODE)) async_add_entities(entities) class HDFurySelect(HDFuryEntity, SelectEntity): """HDFury Select Class.""" entity_description: HDFurySelectEntityDescription @property def current_option(self) -> str: """Return the current option.""" return self.coordinator.data.info[self.entity_description.key] async def async_select_option(self, option: str) -> None: """Update the current option.""" # Update local data first self.coordinator.data.info[self.entity_description.key] = option # Send command to device try: await self.entity_description.set_value_fn(self.coordinator, option) except HDFuryError as error: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from error # Trigger HA coordinator refresh await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/select.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/sensor.py
"""Sensor platform for HDFury Integration.""" from homeassistant.components.sensor import SensorEntity, SensorEntityDescription from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import HDFuryConfigEntry from .entity import HDFuryEntity PARALLEL_UPDATES = 0 SENSORS: tuple[SensorEntityDescription, ...] = ( SensorEntityDescription( key="RX0", translation_key="rx0", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="RX1", translation_key="rx1", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="TX0", translation_key="tx0", entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="TX1", translation_key="tx1", entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="AUD0", translation_key="aud0", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="AUD1", translation_key="aud1", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="AUDOUT", translation_key="audout", entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="EARCRX", translation_key="earcrx", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="SINK0", translation_key="sink0", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="SINK1", translation_key="sink1", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="SINK2", translation_key="sink2", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="EDIDA0", translation_key="edida0", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="EDIDA1", translation_key="edida1", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), SensorEntityDescription( key="EDIDA2", translation_key="edida2", entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, entry: HDFuryConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up sensors using the platform schema.""" coordinator = entry.runtime_data async_add_entities( HDFurySensor(coordinator, description) for description in SENSORS if description.key in coordinator.data.info ) class HDFurySensor(HDFuryEntity, SensorEntity): """Base HDFury Sensor Class.""" entity_description: SensorEntityDescription @property def native_value(self) -> str: """Set Sensor Value.""" return self.coordinator.data.info[self.entity_description.key]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/sensor.py", "license": "Apache License 2.0", "lines": 110, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hdfury/switch.py
"""Switch platform for HDFury Integration.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from hdfury import HDFuryAPI, HDFuryError 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.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import HDFuryConfigEntry from .entity import HDFuryEntity PARALLEL_UPDATES = 1 @dataclass(kw_only=True, frozen=True) class HDFurySwitchEntityDescription(SwitchEntityDescription): """Description for HDFury switch entities.""" set_value_fn: Callable[[HDFuryAPI, str], Awaitable[None]] SWITCHES: tuple[HDFurySwitchEntityDescription, ...] = ( HDFurySwitchEntityDescription( key="autosw", translation_key="autosw", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_auto_switch_inputs(value), ), HDFurySwitchEntityDescription( key="cec", translation_key="cec", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_cec(value), ), HDFurySwitchEntityDescription( key="cec0en", translation_key="cec0en", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_cec_rx0(value), ), HDFurySwitchEntityDescription( key="cec1en", translation_key="cec1en", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_cec_rx1(value), ), HDFurySwitchEntityDescription( key="cec2en", translation_key="cec2en", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_cec_rx2(value), ), HDFurySwitchEntityDescription( key="cec3en", translation_key="cec3en", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_cec_rx3(value), ), HDFurySwitchEntityDescription( key="htpcmode0", translation_key="htpcmode0", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_htpc_mode_rx0(value), ), HDFurySwitchEntityDescription( key="htpcmode1", translation_key="htpcmode1", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_htpc_mode_rx1(value), ), HDFurySwitchEntityDescription( key="htpcmode2", translation_key="htpcmode2", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_htpc_mode_rx2(value), ), HDFurySwitchEntityDescription( key="htpcmode3", translation_key="htpcmode3", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_htpc_mode_rx3(value), ), HDFurySwitchEntityDescription( key="mutetx0", translation_key="mutetx0", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_mute_tx0_audio(value), ), HDFurySwitchEntityDescription( key="mutetx1", translation_key="mutetx1", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_mute_tx1_audio(value), ), HDFurySwitchEntityDescription( key="oled", translation_key="oled", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_oled(value), ), HDFurySwitchEntityDescription( key="iractive", translation_key="iractive", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_ir_active(value), ), HDFurySwitchEntityDescription( key="relay", translation_key="relay", entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_relay(value), ), HDFurySwitchEntityDescription( key="tx0plus5", translation_key="tx0plus5", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_tx0_force_5v(value), ), HDFurySwitchEntityDescription( key="tx1plus5", translation_key="tx1plus5", entity_registry_enabled_default=False, entity_category=EntityCategory.CONFIG, set_value_fn=lambda client, value: client.set_tx1_force_5v(value), ), ) async def async_setup_entry( hass: HomeAssistant, entry: HDFuryConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up switches using the platform schema.""" coordinator = entry.runtime_data async_add_entities( HDFurySwitch(coordinator, description) for description in SWITCHES if description.key in coordinator.data.config ) class HDFurySwitch(HDFuryEntity, SwitchEntity): """Base HDFury Switch Class.""" entity_description: HDFurySwitchEntityDescription @property def is_on(self) -> bool: """Set Switch State.""" return self.coordinator.data.config.get(self.entity_description.key) == "1" async def async_turn_on(self, **kwargs: Any) -> None: """Handle Switch On Event.""" try: await self.entity_description.set_value_fn(self.coordinator.client, "on") except HDFuryError as error: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from error await self.coordinator.async_request_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Handle Switch Off Event.""" try: await self.entity_description.set_value_fn(self.coordinator.client, "off") except HDFuryError as error: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_error", ) from error await self.coordinator.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hdfury/switch.py", "license": "Apache License 2.0", "lines": 163, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hikvision/camera.py
"""Support for Hikvision cameras.""" from __future__ import annotations from pyhik.hikvision import VideoChannel from homeassistant.components.camera import Camera, CameraEntityFeature from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HikvisionConfigEntry from .entity import HikvisionEntity PARALLEL_UPDATES = 0 RTSP_PORT = 554 async def async_setup_entry( hass: HomeAssistant, entry: HikvisionConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Hikvision cameras from a config entry.""" data = entry.runtime_data if data.channels: # NVR with video channels from get_video_channels() async_add_entities( HikvisionCamera(entry, channel) for channel in data.channels.values() if channel.enabled ) else: # Single camera - create a default VideoChannel async_add_entities( [ HikvisionCamera( entry, VideoChannel(id=1, name=data.device_name, enabled=True), ) ] ) class HikvisionCamera(HikvisionEntity, Camera): """Representation of a Hikvision camera.""" _attr_name = None _attr_supported_features = CameraEntityFeature.STREAM def __init__( self, entry: HikvisionConfigEntry, channel: VideoChannel, ) -> None: """Initialize the camera.""" super().__init__(entry, channel.id) self._video_channel = channel # Build unique ID (unique per platform per integration) self._attr_unique_id = f"{self._data.device_id}_{channel.id}" async def async_camera_image( self, width: int | None = None, height: int | None = None ) -> bytes | None: """Return a still image from the camera.""" try: return await self.hass.async_add_executor_job( self._camera.get_snapshot, self._video_channel.id ) except Exception as err: raise HomeAssistantError( f"Error getting image from {self._video_channel.name}: {err}" ) from err async def stream_source(self) -> str | None: """Return the stream source URL.""" return self._camera.get_stream_url(self._channel)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hikvision/camera.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/hikvision/entity.py
"""Base entity for Hikvision integration.""" from __future__ import annotations from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import Entity from . import HikvisionConfigEntry from .const import DOMAIN class HikvisionEntity(Entity): """Base class for Hikvision entities.""" _attr_has_entity_name = True def __init__( self, entry: HikvisionConfigEntry, channel: int, ) -> None: """Initialize the entity.""" super().__init__() self._data = entry.runtime_data self._camera = self._data.camera self._channel = channel # Device info for device registry if self._data.device_type == "NVR": # NVR channels get their own device linked to the NVR via via_device self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, f"{self._data.device_id}_{channel}")}, via_device=(DOMAIN, self._data.device_id), translation_key="nvr_channel", translation_placeholders={ "device_name": self._data.device_name, "channel_number": str(channel), }, manufacturer="Hikvision", model="NVR channel", ) else: # Single camera device self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self._data.device_id)}, name=self._data.device_name, manufacturer="Hikvision", model=self._data.device_type, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/hikvision/entity.py", "license": "Apache License 2.0", "lines": 41, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/humidifier/condition.py
"""Provides conditions for humidifiers.""" from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import ( Condition, make_entity_state_attribute_condition, make_entity_state_condition, ) from .const import ATTR_ACTION, DOMAIN, HumidifierAction CONDITIONS: dict[str, type[Condition]] = { "is_off": make_entity_state_condition(DOMAIN, STATE_OFF), "is_on": make_entity_state_condition(DOMAIN, STATE_ON), "is_drying": make_entity_state_attribute_condition( DOMAIN, ATTR_ACTION, HumidifierAction.DRYING ), "is_humidifying": make_entity_state_attribute_condition( DOMAIN, ATTR_ACTION, HumidifierAction.HUMIDIFYING ), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the humidifier conditions.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/humidifier/condition.py", "license": "Apache License 2.0", "lines": 22, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/lawn_mower/condition.py
"""Provides conditions for lawn mowers.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN, LawnMowerActivity CONDITIONS: dict[str, type[Condition]] = { "is_docked": make_entity_state_condition(DOMAIN, LawnMowerActivity.DOCKED), "is_encountering_an_error": make_entity_state_condition( DOMAIN, LawnMowerActivity.ERROR ), "is_mowing": make_entity_state_condition(DOMAIN, LawnMowerActivity.MOWING), "is_paused": make_entity_state_condition(DOMAIN, LawnMowerActivity.PAUSED), "is_returning": make_entity_state_condition(DOMAIN, LawnMowerActivity.RETURNING), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the conditions for lawn mowers.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lawn_mower/condition.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/lg_thinq/humidifier.py
"""Support for humidifier entities.""" from __future__ import annotations from dataclasses import dataclass import logging from typing import Any from thinqconnect import DeviceType from thinqconnect.devices.const import Property as ThinQProperty from thinqconnect.integration import ActiveMode from homeassistant.components.humidifier import ( HumidifierAction, HumidifierDeviceClass, HumidifierEntity, HumidifierEntityDescription, HumidifierEntityFeature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import ThinqConfigEntry from .coordinator import DeviceDataUpdateCoordinator from .entity import ThinQEntity @dataclass(frozen=True, kw_only=True) class ThinQHumidifierEntityDescription(HumidifierEntityDescription): """Describes ThinQ humidifier entity.""" current_humidity_key: str operation_key: str mode_key: str = ThinQProperty.CURRENT_JOB_MODE DEVICE_TYPE_HUM_MAP: dict[DeviceType, ThinQHumidifierEntityDescription] = { DeviceType.DEHUMIDIFIER: ThinQHumidifierEntityDescription( key=ThinQProperty.TARGET_HUMIDITY, name=None, device_class=HumidifierDeviceClass.DEHUMIDIFIER, translation_key="dehumidifier", current_humidity_key=ThinQProperty.CURRENT_HUMIDITY, operation_key=ThinQProperty.DEHUMIDIFIER_OPERATION_MODE, ), DeviceType.HUMIDIFIER: ThinQHumidifierEntityDescription( key=ThinQProperty.TARGET_HUMIDITY, name=None, device_class=HumidifierDeviceClass.HUMIDIFIER, translation_key="humidifier", current_humidity_key=ThinQProperty.HUMIDITY, operation_key=ThinQProperty.HUMIDIFIER_OPERATION_MODE, ), } _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, entry: ThinqConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up an entry for humidifier platform.""" entities: list[ThinQHumidifierEntity] = [] for coordinator in entry.runtime_data.coordinators.values(): if ( description := DEVICE_TYPE_HUM_MAP.get(coordinator.api.device.device_type) ) is not None: entities.extend( ThinQHumidifierEntity(coordinator, description, property_id) for property_id in coordinator.api.get_active_idx( description.key, ActiveMode.READ_WRITE ) ) if entities: async_add_entities(entities) class ThinQHumidifierEntity(ThinQEntity, HumidifierEntity): """Represent a ThinQ humidifier entity.""" entity_description: ThinQHumidifierEntityDescription _attr_supported_features = HumidifierEntityFeature.MODES def __init__( self, coordinator: DeviceDataUpdateCoordinator, entity_description: ThinQHumidifierEntityDescription, property_id: str, ) -> None: """Initialize a humidifier entity.""" super().__init__(coordinator, entity_description, property_id) self._attr_available_modes = self.coordinator.data[ self.entity_description.mode_key ].options if self.data.max is not None: self._attr_max_humidity = self.data.max if self.data.min is not None: self._attr_min_humidity = self.data.min self._attr_target_humidity_step = ( self.data.step if self.data.step is not None else 1 ) def _update_status(self) -> None: """Update status itself.""" super()._update_status() self._attr_target_humidity = self.data.value self._attr_current_humidity = self.coordinator.data[ self.entity_description.current_humidity_key ].value self._attr_is_on = self.coordinator.data[ self.entity_description.operation_key ].is_on self._attr_mode = self.coordinator.data[self.entity_description.mode_key].value if self.is_on: self._attr_action = ( HumidifierAction.DRYING if self.entity_description.device_class == HumidifierDeviceClass.DEHUMIDIFIER else HumidifierAction.HUMIDIFYING ) else: self._attr_action = HumidifierAction.OFF _LOGGER.debug( "[%s:%s] update status: c:%s, t:%s, mode:%s, action:%s, is_on:%s", self.coordinator.device_name, self.property_id, self.current_humidity, self.target_humidity, self.mode, self.action, self.is_on, ) async def async_set_mode(self, mode: str) -> None: """Set new target preset mode.""" _LOGGER.debug( "[%s:%s] async_set_mode: %s", self.coordinator.device_name, self.entity_description.mode_key, mode, ) await self.async_call_api( self.coordinator.api.post(self.entity_description.mode_key, mode) ) async def async_set_humidity(self, humidity: int) -> None: """Set new target humidity.""" _target_humidity = round(humidity / (self.target_humidity_step or 1)) * ( self.target_humidity_step or 1 ) _LOGGER.debug( "[%s:%s] async_set_humidity: %s, target_humidity: %s, step: %s", self.coordinator.device_name, self.property_id, humidity, _target_humidity, self.target_humidity_step, ) if _target_humidity == self.target_humidity: return await self.async_call_api( self.coordinator.api.post(self.property_id, _target_humidity) ) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" if self.is_on: return _LOGGER.debug( "[%s:%s] async_turn_on", self.coordinator.device_name, self.entity_description.operation_key, ) await self.async_call_api( self.coordinator.api.async_turn_on(self.entity_description.operation_key) ) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" if not self.is_on: return _LOGGER.debug( "[%s:%s] async_turn_off", self.coordinator.device_name, self.entity_description.operation_key, ) await self.async_call_api( self.coordinator.api.async_turn_off(self.entity_description.operation_key) )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lg_thinq/humidifier.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/lock/condition.py
"""Provides conditions for locks.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN, LockState CONDITIONS: dict[str, type[Condition]] = { "is_jammed": make_entity_state_condition(DOMAIN, LockState.JAMMED), "is_locked": make_entity_state_condition(DOMAIN, LockState.LOCKED), "is_open": make_entity_state_condition(DOMAIN, LockState.OPEN), "is_unlocked": make_entity_state_condition(DOMAIN, LockState.UNLOCKED), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the conditions for locks.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/lock/condition.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/mastodon/binary_sensor.py
"""Binary sensor platform for the Mastodon integration.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from enum import StrEnum from mastodon.Mastodon import Account from homeassistant.components.binary_sensor import ( BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import MastodonConfigEntry from .entity import MastodonEntity # Coordinator is used to centralize the data updates PARALLEL_UPDATES = 0 class MastodonBinarySensor(StrEnum): """Mastodon binary sensors.""" BOT = "bot" SUSPENDED = "suspended" DISCOVERABLE = "discoverable" LOCKED = "locked" INDEXABLE = "indexable" LIMITED = "limited" MEMORIAL = "memorial" MOVED = "moved" @dataclass(frozen=True, kw_only=True) class MastodonBinarySensorEntityDescription(BinarySensorEntityDescription): """Mastodon binary sensor description.""" is_on_fn: Callable[[Account], bool | None] ENTITY_DESCRIPTIONS: tuple[MastodonBinarySensorEntityDescription, ...] = ( MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.BOT, translation_key=MastodonBinarySensor.BOT, is_on_fn=lambda account: account.bot, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.DISCOVERABLE, translation_key=MastodonBinarySensor.DISCOVERABLE, is_on_fn=lambda account: account.discoverable, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.LOCKED, translation_key=MastodonBinarySensor.LOCKED, is_on_fn=lambda account: account.locked, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.MOVED, translation_key=MastodonBinarySensor.MOVED, is_on_fn=lambda account: account.moved is not None, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.INDEXABLE, translation_key=MastodonBinarySensor.INDEXABLE, is_on_fn=lambda account: account.indexable, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.LIMITED, translation_key=MastodonBinarySensor.LIMITED, is_on_fn=lambda account: account.limited is True, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.MEMORIAL, translation_key=MastodonBinarySensor.MEMORIAL, is_on_fn=lambda account: account.memorial is True, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), MastodonBinarySensorEntityDescription( key=MastodonBinarySensor.SUSPENDED, translation_key=MastodonBinarySensor.SUSPENDED, is_on_fn=lambda account: account.suspended is True, entity_registry_enabled_default=False, entity_category=EntityCategory.DIAGNOSTIC, ), ) async def async_setup_entry( hass: HomeAssistant, entry: MastodonConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the binary sensor platform.""" coordinator = entry.runtime_data.coordinator async_add_entities( MastodonBinarySensorEntity( coordinator=coordinator, entity_description=entity_description, data=entry, ) for entity_description in ENTITY_DESCRIPTIONS ) class MastodonBinarySensorEntity(MastodonEntity, BinarySensorEntity): """Mastodon binary sensor entity.""" entity_description: MastodonBinarySensorEntityDescription @property def is_on(self) -> bool | None: """Return true if the binary sensor is on.""" return self.entity_description.is_on_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/mastodon/binary_sensor.py", "license": "Apache License 2.0", "lines": 107, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/media_player/condition.py
"""Provides conditions for media players.""" from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN, MediaPlayerState CONDITIONS: dict[str, type[Condition]] = { "is_off": make_entity_state_condition(DOMAIN, MediaPlayerState.OFF), "is_on": make_entity_state_condition( DOMAIN, { MediaPlayerState.BUFFERING, MediaPlayerState.IDLE, MediaPlayerState.ON, MediaPlayerState.PAUSED, MediaPlayerState.PLAYING, }, ), "is_not_playing": make_entity_state_condition( DOMAIN, { MediaPlayerState.BUFFERING, MediaPlayerState.IDLE, MediaPlayerState.OFF, MediaPlayerState.ON, MediaPlayerState.PAUSED, }, ), "is_paused": make_entity_state_condition(DOMAIN, MediaPlayerState.PAUSED), "is_playing": make_entity_state_condition(DOMAIN, MediaPlayerState.PLAYING), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the conditions for media players.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/media_player/condition.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/melcloud/coordinator.py
"""DataUpdateCoordinator for the MELCloud integration.""" from __future__ import annotations from datetime import timedelta import logging from typing import Any from aiohttp import ClientConnectionError, ClientResponseError from pymelcloud import Device from pymelcloud.atw_device import Zone from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) # Delay before refreshing after a state change to allow device to process # and avoid race conditions with rapid sequential changes REQUEST_REFRESH_DELAY = 1.5 # Default update interval in minutes (matches upstream Throttle value) DEFAULT_UPDATE_INTERVAL = 15 # Retry interval in seconds for transient failures RETRY_INTERVAL_SECONDS = 30 # Number of consecutive failures before marking device unavailable MAX_CONSECUTIVE_FAILURES = 3 type MelCloudConfigEntry = ConfigEntry[dict[str, list[MelCloudDeviceUpdateCoordinator]]] class MelCloudDeviceUpdateCoordinator(DataUpdateCoordinator[None]): """Per-device coordinator for MELCloud data updates.""" def __init__( self, hass: HomeAssistant, device: Device, config_entry: ConfigEntry, ) -> None: """Initialize the per-device coordinator.""" self.device = device self.device_available = True self._consecutive_failures = 0 super().__init__( hass, _LOGGER, config_entry=config_entry, name=f"{DOMAIN}_{device.name}", update_interval=timedelta(minutes=DEFAULT_UPDATE_INTERVAL), always_update=True, request_refresh_debouncer=Debouncer( hass, _LOGGER, cooldown=REQUEST_REFRESH_DELAY, immediate=False, ), ) @property def extra_attributes(self) -> dict[str, Any]: """Return extra device attributes.""" data: dict[str, Any] = { "device_id": self.device.device_id, "serial": self.device.serial, "mac": self.device.mac, } if (unit_infos := self.device.units) is not None: for i, unit in enumerate(unit_infos[:2]): data[f"unit_{i}_model"] = unit.get("model") data[f"unit_{i}_serial"] = unit.get("serial") return data @property def device_id(self) -> str: """Return device ID.""" return self.device.device_id @property def building_id(self) -> str: """Return building ID of the device.""" return self.device.building_id @property def device_info(self) -> DeviceInfo: """Return a device description for device registry.""" model = None if (unit_infos := self.device.units) is not None: model = ", ".join([x["model"] for x in unit_infos if x["model"]]) return DeviceInfo( connections={(CONNECTION_NETWORK_MAC, self.device.mac)}, identifiers={(DOMAIN, f"{self.device.mac}-{self.device.serial}")}, manufacturer="Mitsubishi Electric", model=model, name=self.device.name, ) def zone_device_info(self, zone: Zone) -> DeviceInfo: """Return a zone device description for device registry.""" dev = self.device return DeviceInfo( identifiers={(DOMAIN, f"{dev.mac}-{dev.serial}-{zone.zone_index}")}, manufacturer="Mitsubishi Electric", model="ATW zone device", name=f"{self.device.name} {zone.name}", via_device=(DOMAIN, f"{dev.mac}-{dev.serial}"), ) async def _async_update_data(self) -> None: """Fetch data for this specific device from MELCloud.""" try: await self.device.update() # Success - reset failure counter and restore normal interval if self._consecutive_failures > 0: _LOGGER.info( "Connection restored for %s after %d failed attempt(s)", self.device.name, self._consecutive_failures, ) self._consecutive_failures = 0 self.update_interval = timedelta(minutes=DEFAULT_UPDATE_INTERVAL) self.device_available = True except ClientResponseError as ex: if ex.status in (401, 403): raise ConfigEntryAuthFailed from ex if ex.status == 429: _LOGGER.error( "MELCloud rate limit exceeded for %s. Your account may be " "temporarily blocked", self.device.name, ) # Rate limit - mark unavailable immediately self.device_available = False raise UpdateFailed( f"Rate limit exceeded for {self.device.name}" ) from ex # Other HTTP errors - use retry logic self._handle_failure(f"Error updating {self.device.name}: {ex}", ex) except ClientConnectionError as ex: self._handle_failure(f"Connection failed for {self.device.name}: {ex}", ex) def _handle_failure(self, message: str, exception: Exception | None = None) -> None: """Handle a connection failure with retry logic. For transient failures, entities remain available with their last known values for up to MAX_CONSECUTIVE_FAILURES attempts. During retries, the update interval is shortened to RETRY_INTERVAL_SECONDS for faster recovery. After the threshold is reached, entities are marked unavailable. """ self._consecutive_failures += 1 if self._consecutive_failures < MAX_CONSECUTIVE_FAILURES: # Keep entities available with cached data, use shorter retry interval _LOGGER.warning( "%s (attempt %d/%d, retrying in %ds)", message, self._consecutive_failures, MAX_CONSECUTIVE_FAILURES, RETRY_INTERVAL_SECONDS, ) self.update_interval = timedelta(seconds=RETRY_INTERVAL_SECONDS) else: # Threshold reached - mark unavailable and restore normal interval _LOGGER.warning( "%s (attempt %d/%d, marking unavailable)", message, self._consecutive_failures, MAX_CONSECUTIVE_FAILURES, ) self.device_available = False self.update_interval = timedelta(minutes=DEFAULT_UPDATE_INTERVAL) raise UpdateFailed(message) from exception async def async_set(self, properties: dict[str, Any]) -> None: """Write state changes to the MELCloud API.""" try: await self.device.set(properties) self.device_available = True except ClientConnectionError: _LOGGER.warning("Connection failed for %s", self.device.name) self.device_available = False await self.async_request_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/melcloud/coordinator.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/melcloud/entity.py
"""Base entity for MELCloud integration.""" from __future__ import annotations from homeassistant.helpers.update_coordinator import CoordinatorEntity from .coordinator import MelCloudDeviceUpdateCoordinator class MelCloudEntity(CoordinatorEntity[MelCloudDeviceUpdateCoordinator]): """Base class for MELCloud entities.""" _attr_has_entity_name = True @property def available(self) -> bool: """Return True if entity is available.""" return super().available and self.coordinator.device_available
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/melcloud/entity.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/namecheapdns/config_flow.py
"""Config flow for the Namecheap DynamicDNS integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from aiohttp import ClientError import voluptuous as vol from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_DOMAIN, CONF_HOST, CONF_NAME, CONF_PASSWORD from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from .const import DOMAIN from .helpers import AuthFailed, update_namecheapdns from .issue import deprecate_yaml_issue _LOGGER = logging.getLogger(__name__) STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST, default="@"): cv.string, vol.Required(CONF_DOMAIN): cv.string, vol.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password" ) ), } ) STEP_RECONFIGURE_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password" ) ), } ) class NamecheapDnsConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Namecheap DynamicDNS.""" 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_HOST: user_input[CONF_HOST], CONF_DOMAIN: user_input[CONF_DOMAIN]} ) session = async_get_clientsession(self.hass) try: if not await update_namecheapdns(session, **user_input): errors["base"] = "update_failed" except ClientError: _LOGGER.debug("Cannot connect", exc_info=True) errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: return self.async_create_entry( title=f"{user_input[CONF_HOST]}.{user_input[CONF_DOMAIN]}", data=user_input, ) return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema( data_schema=STEP_USER_DATA_SCHEMA, suggested_values=user_input ), errors=errors, description_placeholders={"account_panel": "https://ap.www.namecheap.com/"}, ) async def async_step_import(self, import_info: dict[str, Any]) -> ConfigFlowResult: """Import config from yaml.""" self._async_abort_entries_match( {CONF_HOST: import_info[CONF_HOST], CONF_DOMAIN: import_info[CONF_DOMAIN]} ) result = await self.async_step_user(import_info) if errors := result.get("errors"): deprecate_yaml_issue(self.hass, import_success=False) return self.async_abort(reason=errors["base"]) deprecate_yaml_issue(self.hass, import_success=True) return result async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauth upon authentication error.""" return await self.async_step_reauth_confirm() async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfigure flow.""" return await self.async_step_reauth_confirm(user_input) async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm reauthentication dialog.""" errors: dict[str, str] = {} entry = ( self._get_reauth_entry() if self.source == SOURCE_REAUTH else self._get_reconfigure_entry() ) if user_input is not None: session = async_get_clientsession(self.hass) try: if not await update_namecheapdns( session, entry.data[CONF_HOST], entry.data[CONF_DOMAIN], user_input[CONF_PASSWORD], ): errors["base"] = "update_failed" except AuthFailed: errors["base"] = "invalid_auth" except ClientError: _LOGGER.debug("Cannot connect", exc_info=True) errors["base"] = "cannot_connect" except Exception: _LOGGER.exception("Unexpected exception") errors["base"] = "unknown" if not errors: return self.async_update_reload_and_abort( entry, data_updates=user_input, ) return self.async_show_form( step_id="reauth_confirm" if self.source == SOURCE_REAUTH else "reconfigure", data_schema=STEP_RECONFIGURE_DATA_SCHEMA, errors=errors, description_placeholders={ "account_panel": f"https://ap.www.namecheap.com/Domains/DomainControlPanel/{entry.data[CONF_DOMAIN]}/advancedns", CONF_NAME: entry.title, CONF_DOMAIN: entry.data[CONF_DOMAIN], }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/namecheapdns/config_flow.py", "license": "Apache License 2.0", "lines": 138, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/namecheapdns/coordinator.py
"""Coordinator for the Namecheap DynamicDNS integration.""" from datetime import timedelta import logging from aiohttp import ClientError from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DOMAIN, CONF_HOST, CONF_PASSWORD from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN from .helpers import AuthFailed, update_namecheapdns _LOGGER = logging.getLogger(__name__) type NamecheapConfigEntry = ConfigEntry[NamecheapDnsUpdateCoordinator] INTERVAL = timedelta(minutes=5) class NamecheapDnsUpdateCoordinator(DataUpdateCoordinator[None]): """Namecheap DynamicDNS update coordinator.""" config_entry: NamecheapConfigEntry def __init__(self, hass: HomeAssistant, config_entry: NamecheapConfigEntry) -> None: """Initialize the Namecheap DynamicDNS update coordinator.""" super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=INTERVAL, ) self.session = async_get_clientsession(hass) async def _async_update_data(self) -> None: """Update Namecheap DNS.""" host = self.config_entry.data[CONF_HOST] domain = self.config_entry.data[CONF_DOMAIN] password = self.config_entry.data[CONF_PASSWORD] try: if not await update_namecheapdns(self.session, host, domain, password): raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_failed", translation_placeholders={CONF_DOMAIN: f"{host}.{domain}"}, ) except AuthFailed as e: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_failed", translation_placeholders={CONF_DOMAIN: f"{host}.{domain}"}, ) from e except ClientError as e: raise UpdateFailed( translation_domain=DOMAIN, translation_key="connection_error", translation_placeholders={CONF_DOMAIN: f"{host}.{domain}"}, ) from e
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/namecheapdns/coordinator.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/namecheapdns/helpers.py
"""Helpers for the Namecheap DynamicDNS integration.""" import logging from aiohttp import ClientSession from homeassistant.exceptions import HomeAssistantError from .const import UPDATE_URL _LOGGER = logging.getLogger(__name__) async def update_namecheapdns( session: ClientSession, host: str, domain: str, password: str ) -> bool: """Update namecheap DNS entry.""" params = {"host": host, "domain": domain, "password": password} resp = await session.get(UPDATE_URL, params=params) xml_string = await resp.text() if "<ErrCount>0</ErrCount>" not in xml_string: if "<Err1>Passwords do not match</Err1>" in xml_string: raise AuthFailed return False return True class AuthFailed(HomeAssistantError): """Authentication error."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/namecheapdns/helpers.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/namecheapdns/issue.py
"""Issues for Namecheap DynamicDNS integration.""" from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant, callback from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from .const import DOMAIN @callback def deprecate_yaml_issue(hass: HomeAssistant, *, import_success: bool) -> None: """Deprecate yaml issue.""" if import_success: async_create_issue( hass, HOMEASSISTANT_DOMAIN, f"deprecated_yaml_{DOMAIN}", is_fixable=False, issue_domain=DOMAIN, breaks_in_ha_version="2026.8.0", severity=IssueSeverity.WARNING, translation_key="deprecated_yaml", translation_placeholders={ "domain": DOMAIN, "integration_title": "Namecheap DynamicDNS", }, ) else: async_create_issue( hass, DOMAIN, "deprecated_yaml_import_issue_error", breaks_in_ha_version="2026.8.0", is_fixable=False, issue_domain=DOMAIN, severity=IssueSeverity.WARNING, translation_key="deprecated_yaml_import_issue_error", translation_placeholders={ "url": f"/config/integrations/dashboard/add?domain={DOMAIN}" }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/namecheapdns/issue.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/nasweb/climate.py
"""Platform for NASweb thermostat.""" from __future__ import annotations import time from typing import Any from webio_api import Thermostat as NASwebThermostat from webio_api.const import KEY_THERMOSTAT from homeassistant.components.climate import ( ClimateEntity, ClimateEntityFeature, HVACAction, HVACMode, UnitOfTemperature, ) from homeassistant.components.sensor import SensorDeviceClass from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import DiscoveryInfoType from homeassistant.helpers.update_coordinator import ( BaseCoordinatorEntity, BaseDataUpdateCoordinatorProtocol, ) from . import NASwebConfigEntry from .const import DOMAIN, STATUS_UPDATE_MAX_TIME_INTERVAL CLIMATE_TRANSLATION_KEY = "thermostat" async def async_setup_entry( hass: HomeAssistant, config: NASwebConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up Climate platform.""" coordinator = config.runtime_data nasweb_thermostat: NASwebThermostat = coordinator.data[KEY_THERMOSTAT] climate = Thermostat(coordinator, nasweb_thermostat) async_add_entities([climate]) class Thermostat(ClimateEntity, BaseCoordinatorEntity): """Entity representing NASweb thermostat.""" _attr_device_class = SensorDeviceClass.TEMPERATURE _attr_has_entity_name = True _attr_hvac_modes = [ HVACMode.OFF, HVACMode.HEAT, HVACMode.COOL, HVACMode.HEAT_COOL, HVACMode.FAN_ONLY, ] _attr_max_temp = 50 _attr_min_temp = -50 _attr_precision = 1.0 _attr_should_poll = False _attr_supported_features = ClimateEntityFeature( ClimateEntityFeature.TARGET_TEMPERATURE_RANGE ) _attr_target_temperature_step = 1.0 _attr_temperature_unit = UnitOfTemperature.CELSIUS _attr_translation_key = CLIMATE_TRANSLATION_KEY def __init__( self, coordinator: BaseDataUpdateCoordinatorProtocol, nasweb_thermostat: NASwebThermostat, ) -> None: """Initialize Thermostat.""" super().__init__(coordinator) self._thermostat = nasweb_thermostat self._attr_available = False self._attr_name = nasweb_thermostat.name self._attr_unique_id = f"{DOMAIN}.{self._thermostat.webio_serial}.thermostat" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, self._thermostat.webio_serial)} ) async def async_added_to_hass(self) -> None: """When entity is added to hass.""" await super().async_added_to_hass() self._handle_coordinator_update() def _set_attr_available( self, entity_last_update: float, available: bool | None ) -> None: if ( self.coordinator.last_update is None or time.time() - entity_last_update >= STATUS_UPDATE_MAX_TIME_INTERVAL ): self._attr_available = False else: self._attr_available = available if available is not None else False @callback def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" self._attr_current_temperature = self._thermostat.current_temp self._attr_target_temperature_low = self._thermostat.temp_target_min self._attr_target_temperature_high = self._thermostat.temp_target_max self._attr_hvac_mode = self._get_current_hvac_mode() self._attr_hvac_action = self._get_current_action() self._attr_name = self._thermostat.name or None self._set_attr_available( self._thermostat.last_update, self._thermostat.available ) self.async_write_ha_state() def _get_current_hvac_mode(self) -> HVACMode: have_cooling = self._thermostat.enabled_above_output have_heating = self._thermostat.enabled_below_output if have_cooling and have_heating: return HVACMode.HEAT_COOL if have_cooling: return HVACMode.COOL if have_heating: return HVACMode.HEAT if self._thermostat.enabled_inrange_output: return HVACMode.FAN_ONLY return HVACMode.OFF def _get_current_action(self) -> HVACAction: if self._thermostat.current_temp is None: return HVACAction.OFF if ( self._thermostat.temp_target_min is not None and self._thermostat.current_temp < self._thermostat.temp_target_min and self._thermostat.enabled_below_output ): return HVACAction.HEATING if ( self._thermostat.temp_target_max is not None and self._thermostat.current_temp > self._thermostat.temp_target_max and self._thermostat.enabled_above_output ): return HVACAction.COOLING if ( self._thermostat.temp_target_min is not None and self._thermostat.temp_target_max is not None and self._thermostat.current_temp >= self._thermostat.temp_target_min and self._thermostat.current_temp <= self._thermostat.temp_target_max and self._thermostat.enabled_inrange_output ): return HVACAction.FAN return HVACAction.IDLE async def async_update(self) -> None: """Update the entity. Only used by the generic entity update service. Scheduling updates is not necessary, the coordinator takes care of updates via push notifications. """ async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set HVACMode for Thermostat.""" await self._thermostat.set_hvac_mode(hvac_mode) async def async_set_temperature(self, **kwargs: Any) -> None: """Set temperature range for Thermostat.""" await self._thermostat.set_temperature( kwargs["target_temp_low"], kwargs["target_temp_high"] )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nasweb/climate.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/nrgkick/api.py
"""API helpers and Home Assistant exceptions for the NRGkick integration.""" from __future__ import annotations from collections.abc import Awaitable import aiohttp from nrgkick_api import ( NRGkickAPIDisabledError, NRGkickAuthenticationError, NRGkickCommandRejectedError, NRGkickConnectionError, NRGkickInvalidResponseError, ) from homeassistant.exceptions import HomeAssistantError from .const import DOMAIN class NRGkickApiClientError(HomeAssistantError): """Base exception for NRGkick API client errors.""" translation_domain = DOMAIN translation_key = "unknown_error" class NRGkickApiClientCommunicationError(NRGkickApiClientError): """Exception for NRGkick API client communication errors.""" translation_domain = DOMAIN translation_key = "communication_error" class NRGkickApiClientAuthenticationError(NRGkickApiClientError): """Exception for NRGkick API client authentication errors.""" translation_domain = DOMAIN translation_key = "authentication_error" class NRGkickApiClientApiDisabledError(NRGkickApiClientError): """Exception for disabled NRGkick JSON API.""" translation_domain = DOMAIN translation_key = "json_api_disabled" class NRGkickApiClientInvalidResponseError(NRGkickApiClientError): """Exception for invalid responses from the device.""" translation_domain = DOMAIN translation_key = "invalid_response" async def async_api_call[_T](awaitable: Awaitable[_T]) -> _T: """Call the NRGkick API and map common library errors. This helper is intended for one-off API calls outside the coordinator, such as command-style calls (switch/number/etc.) and config flow validation, where errors should surface as user-facing `HomeAssistantError` exceptions. Regular polling is handled by the coordinator. """ try: return await awaitable except NRGkickCommandRejectedError as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="command_rejected", translation_placeholders={"reason": err.reason}, ) from err except NRGkickAuthenticationError as err: raise NRGkickApiClientAuthenticationError from err except NRGkickAPIDisabledError as err: raise NRGkickApiClientApiDisabledError from err except NRGkickInvalidResponseError as err: raise NRGkickApiClientInvalidResponseError from err except NRGkickConnectionError as err: raise NRGkickApiClientCommunicationError( translation_placeholders={"error": str(err)} ) from err except (TimeoutError, aiohttp.ClientError, OSError) as err: raise NRGkickApiClientCommunicationError( translation_placeholders={"error": str(err)} ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/api.py", "license": "Apache License 2.0", "lines": 62, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nrgkick/config_flow.py
"""Config flow for NRGkick integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import TYPE_CHECKING, Any from nrgkick_api import NRGkickAPI import voluptuous as vol import yarl from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .api import ( NRGkickApiClientApiDisabledError, NRGkickApiClientAuthenticationError, NRGkickApiClientCommunicationError, NRGkickApiClientError, NRGkickApiClientInvalidResponseError, async_api_call, ) from .const import DOMAIN _LOGGER = logging.getLogger(__name__) def _normalize_host(value: str) -> str: """Normalize user input to host[:port] (no scheme/path). Accepts either a plain host/IP (optionally with a port) or a full URL. If a URL is provided, we strip the scheme. """ value = value.strip() if not value: raise vol.Invalid("host is required") if "://" in value: try: url = yarl.URL(cv.url(value)) except ValueError as err: raise vol.Invalid("invalid url") from err if not url.host: raise vol.Invalid("invalid url") if url.port is not None: return f"{url.host}:{url.port}" return url.host return value.strip("/").split("/", 1)[0] STEP_USER_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): TextSelector(TextSelectorConfig(autocomplete="off")), } ) STEP_AUTH_DATA_SCHEMA = vol.Schema( { vol.Optional(CONF_USERNAME): TextSelector( TextSelectorConfig(autocomplete="off") ), vol.Optional(CONF_PASSWORD): TextSelector( TextSelectorConfig(type=TextSelectorType.PASSWORD) ), } ) async def validate_input( hass: HomeAssistant, host: str, username: str | None = None, password: str | None = None, ) -> dict[str, Any]: """Validate the user input allows us to connect.""" session = async_get_clientsession(hass) api = NRGkickAPI( host=host, username=username, password=password, session=session, ) await async_api_call(api.test_connection()) info = await async_api_call(api.get_info(["general"], raw=True)) device_name = info.get("general", {}).get("device_name") if not device_name: device_name = "NRGkick" serial = info.get("general", {}).get("serial_number") if not serial: raise NRGkickApiClientInvalidResponseError return { "title": device_name, "serial": serial, } class NRGkickConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for NRGkick.""" VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._discovered_host: str | None = None self._discovered_name: str | None = None self._pending_host: str | None = None async def _async_validate_host( self, host: str, errors: dict[str, str], ) -> tuple[dict[str, Any] | None, bool]: """Validate host connection and populate errors dict on failure. Returns (info, needs_auth). When needs_auth is True, the caller should store the host and redirect to the appropriate auth step. """ try: return await validate_input(self.hass, host), False except NRGkickApiClientApiDisabledError: errors["base"] = "json_api_disabled" except NRGkickApiClientAuthenticationError: return None, True except NRGkickApiClientInvalidResponseError: errors["base"] = "invalid_response" except NRGkickApiClientCommunicationError: errors["base"] = "cannot_connect" except NRGkickApiClientError: _LOGGER.exception("Unexpected error") errors["base"] = "unknown" return None, False async def _async_validate_credentials( self, host: str, errors: dict[str, str], username: str | None = None, password: str | None = None, ) -> dict[str, Any] | None: """Validate credentials and populate errors dict on failure.""" try: return await validate_input( self.hass, host, username=username, password=password ) except NRGkickApiClientApiDisabledError: errors["base"] = "json_api_disabled" except NRGkickApiClientAuthenticationError: errors["base"] = "invalid_auth" except NRGkickApiClientInvalidResponseError: errors["base"] = "invalid_response" except NRGkickApiClientCommunicationError: errors["base"] = "cannot_connect" except NRGkickApiClientError: _LOGGER.exception("Unexpected error") errors["base"] = "unknown" return 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: try: host = _normalize_host(user_input[CONF_HOST]) except vol.Invalid: errors["base"] = "cannot_connect" else: info, needs_auth = await self._async_validate_host(host, errors) if needs_auth: self._pending_host = host return await self.async_step_user_auth() if info: await self.async_set_unique_id( info["serial"], raise_on_progress=False ) self._abort_if_unique_id_configured() return self.async_create_entry( title=info["title"], data={CONF_HOST: host} ) return self.async_show_form( step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors, ) async def async_step_user_auth( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the authentication step only when needed.""" errors: dict[str, str] = {} if TYPE_CHECKING: assert self._pending_host is not None if user_input is not None: if info := await self._async_validate_credentials( self._pending_host, errors, username=user_input.get(CONF_USERNAME), password=user_input.get(CONF_PASSWORD), ): await self.async_set_unique_id(info["serial"], raise_on_progress=False) self._abort_if_unique_id_configured() return self.async_create_entry( title=info["title"], data={ CONF_HOST: self._pending_host, CONF_USERNAME: user_input.get(CONF_USERNAME), CONF_PASSWORD: user_input.get(CONF_PASSWORD), }, ) return self.async_show_form( step_id="user_auth", data_schema=STEP_AUTH_DATA_SCHEMA, errors=errors, description_placeholders={ "device_ip": self._pending_host, }, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Handle initiation of reauthentication.""" return await self.async_step_reauth_confirm() async def async_step_reauth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reauthentication.""" errors: dict[str, str] = {} if user_input is not None: reauth_entry = self._get_reauth_entry() if info := await self._async_validate_credentials( reauth_entry.data[CONF_HOST], errors, username=user_input.get(CONF_USERNAME), password=user_input.get(CONF_PASSWORD), ): await self.async_set_unique_id(info["serial"], raise_on_progress=False) self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( reauth_entry, data_updates=user_input, ) return self.async_show_form( step_id="reauth_confirm", data_schema=self.add_suggested_values_to_schema( STEP_AUTH_DATA_SCHEMA, self._get_reauth_entry().data, ), errors=errors, ) async def async_step_reconfigure( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration of the integration.""" errors: dict[str, str] = {} reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: try: host = _normalize_host(user_input[CONF_HOST]) except vol.Invalid: errors["base"] = "cannot_connect" else: info, needs_auth = await self._async_validate_host(host, errors) if needs_auth: self._pending_host = host return await self.async_step_reconfigure_auth() if info: await self.async_set_unique_id( info["serial"], raise_on_progress=False ) self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( reconfigure_entry, data_updates={CONF_HOST: host}, ) return self.async_show_form( step_id="reconfigure", data_schema=self.add_suggested_values_to_schema( STEP_USER_DATA_SCHEMA, reconfigure_entry.data, ), errors=errors, ) async def async_step_reconfigure_auth( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle reconfiguration authentication step.""" errors: dict[str, str] = {} if TYPE_CHECKING: assert self._pending_host is not None reconfigure_entry = self._get_reconfigure_entry() if user_input is not None: username = user_input.get(CONF_USERNAME) password = user_input.get(CONF_PASSWORD) if info := await self._async_validate_credentials( self._pending_host, errors, username=username, password=password, ): await self.async_set_unique_id(info["serial"], raise_on_progress=False) self._abort_if_unique_id_mismatch() return self.async_update_reload_and_abort( reconfigure_entry, data_updates={ CONF_HOST: self._pending_host, CONF_USERNAME: username, CONF_PASSWORD: password, }, ) return self.async_show_form( step_id="reconfigure_auth", data_schema=self.add_suggested_values_to_schema( STEP_AUTH_DATA_SCHEMA, reconfigure_entry.data, ), errors=errors, description_placeholders={ "device_ip": self._pending_host, }, ) async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" _LOGGER.debug("Discovered NRGkick device: %s", discovery_info) # Extract device information from mDNS metadata. serial = discovery_info.properties.get("serial_number") device_name = discovery_info.properties.get("device_name") model_type = discovery_info.properties.get("model_type") json_api_enabled = discovery_info.properties.get("json_api_enabled", "0") if not serial: _LOGGER.debug("NRGkick device discovered without serial number") return self.async_abort(reason="no_serial_number") # Set unique ID to prevent duplicate entries. await self.async_set_unique_id(serial) # Update the host if the device is already configured (IP might have changed). self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.host}) # Store discovery info for the confirmation step. self._discovered_host = discovery_info.host # Fallback: device_name -> model_type -> "NRGkick". discovered_name = device_name or model_type or "NRGkick" self._discovered_name = discovered_name self.context["title_placeholders"] = {"name": discovered_name} # If JSON API is disabled, guide the user through enabling it. if json_api_enabled != "1": _LOGGER.debug("NRGkick device %s does not have JSON API enabled", serial) return await self.async_step_zeroconf_enable_json_api() try: await validate_input(self.hass, self._discovered_host) except NRGkickApiClientAuthenticationError: self._pending_host = self._discovered_host return await self.async_step_user_auth() except NRGkickApiClientApiDisabledError: # mDNS metadata may be stale; fall back to the enable guidance. return await self.async_step_zeroconf_enable_json_api() except ( NRGkickApiClientCommunicationError, NRGkickApiClientInvalidResponseError, ): return self.async_abort(reason="cannot_connect") except NRGkickApiClientError: _LOGGER.exception("Unexpected error") return self.async_abort(reason="unknown") # Proceed to confirmation step (no auth required upfront). return await self.async_step_zeroconf_confirm() async def async_step_zeroconf_enable_json_api( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Guide the user to enable JSON API after discovery.""" errors: dict[str, str] = {} if TYPE_CHECKING: assert self._discovered_host is not None assert self._discovered_name is not None if user_input is not None: info, needs_auth = await self._async_validate_host( self._discovered_host, errors ) if needs_auth: self._pending_host = self._discovered_host return await self.async_step_user_auth() if info: return self.async_create_entry( title=info["title"], data={CONF_HOST: self._discovered_host} ) return self.async_show_form( step_id="zeroconf_enable_json_api", data_schema=vol.Schema({}), description_placeholders={ "name": self._discovered_name, "device_ip": _normalize_host(self._discovered_host), }, errors=errors, ) async def async_step_zeroconf_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm discovery.""" errors: dict[str, str] = {} if TYPE_CHECKING: assert self._discovered_host is not None assert self._discovered_name is not None if user_input is not None: return self.async_create_entry( title=self._discovered_name, data={CONF_HOST: self._discovered_host} ) return self.async_show_form( step_id="zeroconf_confirm", data_schema=vol.Schema({}), description_placeholders={ "name": self._discovered_name, "device_ip": self._discovered_host, }, errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/config_flow.py", "license": "Apache License 2.0", "lines": 401, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nrgkick/const.py
"""Constants for the NRGkick integration.""" from typing import Final from nrgkick_api import ( CellularMode, ChargingStatus, ConnectorType, ErrorCode, RcdTriggerStatus, WarningCode, ) DOMAIN: Final = "nrgkick" # Default polling interval (seconds). DEFAULT_SCAN_INTERVAL: Final = 30 # Note: API Endpoints are in the nrgkick-api library. # Import from nrgkick_api if needed: from nrgkick_api import ENDPOINT_INFO, ... # Human-readable status mapping for the status sensor. # Values are translation keys that match translations/<lang>.json STATUS_MAP: Final[dict[int, str | None]] = { ChargingStatus.UNKNOWN: None, ChargingStatus.STANDBY: "standby", ChargingStatus.CONNECTED: "connected", ChargingStatus.CHARGING: "charging", ChargingStatus.ERROR: "error", ChargingStatus.WAKEUP: "wakeup", } # Human-readable RCD trigger mapping. # Values are translation keys that match translations/<lang>.json RCD_TRIGGER_MAP: Final[dict[int, str]] = { RcdTriggerStatus.NO_FAULT: "no_fault", RcdTriggerStatus.AC_30MA_FAULT: "ac_30ma_fault", RcdTriggerStatus.AC_60MA_FAULT: "ac_60ma_fault", RcdTriggerStatus.AC_150MA_FAULT: "ac_150ma_fault", RcdTriggerStatus.DC_POSITIVE_6MA_FAULT: "dc_positive_6ma_fault", RcdTriggerStatus.DC_NEGATIVE_6MA_FAULT: "dc_negative_6ma_fault", } # Human-readable warning code mapping. # Values are translation keys that match translations/<lang>.json WARNING_CODE_MAP: Final[dict[int, str]] = { WarningCode.NO_WARNING: "no_warning", WarningCode.NO_PE: "no_pe", WarningCode.BLACKOUT_PROTECTION: "blackout_protection", WarningCode.ENERGY_LIMIT_REACHED: "energy_limit_reached", WarningCode.EV_DOES_NOT_COMPLY_STANDARD: "ev_does_not_comply_standard", WarningCode.UNSUPPORTED_CHARGING_MODE: "unsupported_charging_mode", WarningCode.NO_ATTACHMENT_DETECTED: "no_attachment_detected", WarningCode.NO_COMM_WITH_TYPE2_ATTACHMENT: "no_comm_with_type2_attachment", WarningCode.INCREASED_TEMPERATURE: "increased_temperature", WarningCode.INCREASED_HOUSING_TEMPERATURE: "increased_housing_temperature", WarningCode.INCREASED_ATTACHMENT_TEMPERATURE: "increased_attachment_temperature", WarningCode.INCREASED_DOMESTIC_PLUG_TEMPERATURE: ( "increased_domestic_plug_temperature" ), } # Human-readable error code mapping. # Values are translation keys that match translations/<lang>.json ERROR_CODE_MAP: Final[dict[int, str]] = { ErrorCode.NO_ERROR: "no_error", ErrorCode.GENERAL_ERROR: "general_error", ErrorCode.ATTACHMENT_32A_ON_16A_UNIT: "32a_attachment_on_16a_unit", ErrorCode.VOLTAGE_DROP_DETECTED: "voltage_drop_detected", ErrorCode.UNPLUG_DETECTION_TRIGGERED: "unplug_detection_triggered", ErrorCode.TYPE2_NOT_AUTHORIZED: "type2_not_authorized", ErrorCode.RESIDUAL_CURRENT_DETECTED: "residual_current_detected", ErrorCode.CP_SIGNAL_VOLTAGE_ERROR: "cp_signal_voltage_error", ErrorCode.CP_SIGNAL_IMPERMISSIBLE: "cp_signal_impermissible", ErrorCode.EV_DIODE_FAULT: "ev_diode_fault", ErrorCode.PE_SELF_TEST_FAILED: "pe_self_test_failed", ErrorCode.RCD_SELF_TEST_FAILED: "rcd_self_test_failed", ErrorCode.RELAY_SELF_TEST_FAILED: "relay_self_test_failed", ErrorCode.PE_AND_RCD_SELF_TEST_FAILED: "pe_and_rcd_self_test_failed", ErrorCode.PE_AND_RELAY_SELF_TEST_FAILED: "pe_and_relay_self_test_failed", ErrorCode.RCD_AND_RELAY_SELF_TEST_FAILED: "rcd_and_relay_self_test_failed", ErrorCode.PE_AND_RCD_AND_RELAY_SELF_TEST_FAILED: ( "pe_and_rcd_and_relay_self_test_failed" ), ErrorCode.SUPPLY_VOLTAGE_ERROR: "supply_voltage_error", ErrorCode.PHASE_SHIFT_ERROR: "phase_shift_error", ErrorCode.OVERVOLTAGE_DETECTED: "overvoltage_detected", ErrorCode.UNDERVOLTAGE_DETECTED: "undervoltage_detected", ErrorCode.OVERVOLTAGE_WITHOUT_PE_DETECTED: "overvoltage_without_pe_detected", ErrorCode.UNDERVOLTAGE_WITHOUT_PE_DETECTED: "undervoltage_without_pe_detected", ErrorCode.UNDERFREQUENCY_DETECTED: "underfrequency_detected", ErrorCode.OVERFREQUENCY_DETECTED: "overfrequency_detected", ErrorCode.UNKNOWN_FREQUENCY_TYPE: "unknown_frequency_type", ErrorCode.UNKNOWN_GRID_TYPE: "unknown_grid_type", ErrorCode.GENERAL_OVERTEMPERATURE: "general_overtemperature", ErrorCode.HOUSING_OVERTEMPERATURE: "housing_overtemperature", ErrorCode.ATTACHMENT_OVERTEMPERATURE: "attachment_overtemperature", ErrorCode.DOMESTIC_PLUG_OVERTEMPERATURE: "domestic_plug_overtemperature", } # Human-readable connector type mapping. # Values are translation keys that match translations/<lang>.json CONNECTOR_TYPE_MAP: Final[dict[int, str | None]] = { ConnectorType.UNKNOWN: None, ConnectorType.CEE: "cee", ConnectorType.DOMESTIC: "domestic", ConnectorType.TYPE2: "type2", ConnectorType.WALL: "wall", ConnectorType.AUS: "aus", } # Human-readable cellular mode mapping. # Values are translation keys that match translations/<lang>.json CELLULAR_MODE_MAP: Final[dict[int, str | None]] = { CellularMode.UNKNOWN: None, CellularMode.NO_SERVICE: "no_service", CellularMode.GSM: "gsm", CellularMode.LTE_CAT_M1: "lte_cat_m1", CellularMode.LTE_NB_IOT: "lte_nb_iot", }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/const.py", "license": "Apache License 2.0", "lines": 109, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nrgkick/coordinator.py
"""DataUpdateCoordinator for NRGkick integration.""" from __future__ import annotations from dataclasses import dataclass from datetime import timedelta import logging from typing import Any import aiohttp from nrgkick_api import ( NRGkickAPI, NRGkickAPIDisabledError, NRGkickAuthenticationError, NRGkickConnectionError, NRGkickInvalidResponseError, ) from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryError from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DEFAULT_SCAN_INTERVAL, DOMAIN _LOGGER = logging.getLogger(__name__) # Type alias for typed config entry with runtime_data. type NRGkickConfigEntry = ConfigEntry[NRGkickDataUpdateCoordinator] @dataclass(slots=True) class NRGkickData: """Container for coordinator data.""" info: dict[str, Any] control: dict[str, Any] values: dict[str, Any] class NRGkickDataUpdateCoordinator(DataUpdateCoordinator[NRGkickData]): """Class to manage fetching NRGkick data from the API.""" config_entry: NRGkickConfigEntry def __init__( self, hass: HomeAssistant, api: NRGkickAPI, entry: NRGkickConfigEntry ) -> None: """Initialize.""" self.api = api super().__init__( hass, _LOGGER, name=DOMAIN, update_interval=timedelta(seconds=DEFAULT_SCAN_INTERVAL), config_entry=entry, always_update=False, ) async def _async_update_data(self) -> NRGkickData: """Update data via library.""" try: info = await self.api.get_info(raw=True) control = await self.api.get_control() values = await self.api.get_values(raw=True) except NRGkickAuthenticationError as error: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="authentication_error", ) from error except NRGkickAPIDisabledError as error: raise ConfigEntryError( translation_domain=DOMAIN, translation_key="json_api_disabled", ) from error except NRGkickConnectionError as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={"error": str(error)}, ) from error except NRGkickInvalidResponseError as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="invalid_response", ) from error except (TimeoutError, aiohttp.ClientError, OSError) as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="communication_error", translation_placeholders={"error": str(error)}, ) from error return NRGkickData(info=info, control=control, values=values)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/coordinator.py", "license": "Apache License 2.0", "lines": 78, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/nrgkick/entity.py
"""Base entity for NRGkick integration.""" from __future__ import annotations from collections.abc import Awaitable from typing import Any from homeassistant.const import CONF_HOST from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .api import async_api_call from .const import DOMAIN from .coordinator import NRGkickDataUpdateCoordinator class NRGkickEntity(CoordinatorEntity[NRGkickDataUpdateCoordinator]): """Base class for NRGkick entities with common device info setup.""" _attr_has_entity_name = True def __init__(self, coordinator: NRGkickDataUpdateCoordinator, key: str) -> None: """Initialize the entity.""" super().__init__(coordinator) self._key = key data = self.coordinator.data assert data is not None info_data: dict[str, Any] = data.info device_info: dict[str, Any] = info_data.get("general", {}) network_info: dict[str, Any] = info_data.get("network", {}) # The config flow requires a serial number and sets it as unique_id. serial = self.coordinator.config_entry.unique_id assert serial is not None # Get additional device info fields. versions: dict[str, Any] = info_data.get("versions", {}) connections: set[tuple[str, str]] | None = None if (mac_address := network_info.get("mac_address")) and isinstance( mac_address, str ): connections = {(CONNECTION_NETWORK_MAC, mac_address)} self._attr_unique_id = f"{serial}_{self._key}" device_info_typed = DeviceInfo( configuration_url=f"http://{self.coordinator.config_entry.data[CONF_HOST]}", identifiers={(DOMAIN, serial)}, serial_number=serial, manufacturer="DiniTech", model=device_info.get("model_type", "NRGkick Gen2"), sw_version=versions.get("sw_sm"), hw_version=versions.get("hw_sm"), ) if connections is not None: device_info_typed["connections"] = connections self._attr_device_info = device_info_typed async def _async_call_api[_T](self, awaitable: Awaitable[_T]) -> _T: """Call the API, map errors, and refresh coordinator data.""" result = await async_api_call(awaitable) await self.coordinator.async_refresh() return result
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/entity.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/nrgkick/sensor.py
"""Sensor platform for NRGkick.""" from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any, cast from nrgkick_api import ChargingStatus from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, EntityCategory, UnitOfApparentPower, UnitOfElectricCurrent, UnitOfElectricPotential, UnitOfEnergy, UnitOfFrequency, UnitOfPower, UnitOfReactivePower, UnitOfSpeed, UnitOfTemperature, UnitOfTime, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.util.dt import utcnow from homeassistant.util.variance import ignore_variance from .const import ( CELLULAR_MODE_MAP, CONNECTOR_TYPE_MAP, ERROR_CODE_MAP, RCD_TRIGGER_MAP, STATUS_MAP, WARNING_CODE_MAP, ) from .coordinator import NRGkickConfigEntry, NRGkickData, NRGkickDataUpdateCoordinator from .entity import NRGkickEntity PARALLEL_UPDATES = 0 def _get_nested_dict_value(data: Any, *keys: str) -> Any: """Safely get a nested value from dict-like API responses.""" current: Any = data for key in keys: try: current = current.get(key) except AttributeError: return None return current @dataclass(frozen=True, kw_only=True) class NRGkickSensorEntityDescription(SensorEntityDescription): """Class describing NRGkick sensor entities.""" value_fn: Callable[[NRGkickData], StateType | datetime | None] requires_sim_module: bool = False def _seconds_to_datetime(value: int) -> datetime: """Convert seconds to a UTC timestamp.""" return utcnow().replace(microsecond=0) - timedelta(seconds=value) _seconds_to_stable_datetime = ignore_variance( _seconds_to_datetime, timedelta(minutes=1) ) def _seconds_to_stable_timestamp(value: StateType) -> datetime | None: """Convert seconds to a stable timestamp. This is used for durations that represent "seconds since X" coming from the device. Converting to a timestamp avoids UI drift due to polling cadence. """ if value is None: return None try: return _seconds_to_stable_datetime(cast(int, value)) except TypeError, OverflowError: return None def _map_code_to_translation_key( value: StateType, mapping: Mapping[int, str | None], ) -> StateType: """Map numeric API codes to translation keys. The NRGkick API returns `int` (including `IntEnum`) values for code-like fields used as sensor states. """ if value is None: return None # The API returns ints (including IntEnum). Use a cast to satisfy typing # without paying for repeated runtime type checks in this hot path. return mapping.get(cast(int, value)) def _enum_options_from_mapping(mapping: Mapping[int, str | None]) -> list[str]: """Build stable enum options from a numeric->translation-key mapping.""" # Keep ordering stable by sorting keys. unique_options: dict[str, None] = {} for key in sorted(mapping): if (option := mapping[key]) is not None: unique_options[option] = None return list(unique_options) async def async_setup_entry( _hass: HomeAssistant, entry: NRGkickConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up NRGkick sensors based on a config entry.""" coordinator: NRGkickDataUpdateCoordinator = entry.runtime_data data = coordinator.data assert data is not None info_data: dict[str, Any] = data.info general_info: dict[str, Any] = info_data.get("general", {}) model_type = general_info.get("model_type") # The cellular and GPS modules are optional. There is no dedicated API to query # module availability, but SIM-capable models include "SIM" in their model # type (e.g. "NRGkick Gen2 SIM"). # Note: GPS to be added back with future pull request, currently only cellular. has_sim_module = isinstance(model_type, str) and "SIM" in model_type.upper() async_add_entities( NRGkickSensor(coordinator, description) for description in SENSORS if has_sim_module or not description.requires_sim_module ) SENSORS: tuple[NRGkickSensorEntityDescription, ...] = ( # INFO - General NRGkickSensorEntityDescription( key="rated_current", translation_key="rated_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.info, "general", "rated_current" ), ), # INFO - Connector NRGkickSensorEntityDescription( key="connector_phase_count", translation_key="connector_phase_count", value_fn=lambda data: _get_nested_dict_value( data.info, "connector", "phase_count" ), ), NRGkickSensorEntityDescription( key="connector_max_current", translation_key="connector_max_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.info, "connector", "max_current" ), ), NRGkickSensorEntityDescription( key="connector_type", translation_key="connector_type", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(CONNECTOR_TYPE_MAP), entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _map_code_to_translation_key( cast(StateType, _get_nested_dict_value(data.info, "connector", "type")), CONNECTOR_TYPE_MAP, ), ), NRGkickSensorEntityDescription( key="connector_serial", translation_key="connector_serial", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value(data.info, "connector", "serial"), ), # INFO - Grid NRGkickSensorEntityDescription( key="grid_voltage", translation_key="grid_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value(data.info, "grid", "voltage"), ), NRGkickSensorEntityDescription( key="grid_frequency", translation_key="grid_frequency", device_class=SensorDeviceClass.FREQUENCY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfFrequency.HERTZ, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value(data.info, "grid", "frequency"), ), # INFO - Network NRGkickSensorEntityDescription( key="network_ssid", translation_key="network_ssid", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value(data.info, "network", "ssid"), ), NRGkickSensorEntityDescription( key="network_rssi", translation_key="network_rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value(data.info, "network", "rssi"), ), # INFO - Cellular (optional, only if cellular module is available) NRGkickSensorEntityDescription( key="cellular_mode", translation_key="cellular_mode", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(CELLULAR_MODE_MAP), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, requires_sim_module=True, value_fn=lambda data: _map_code_to_translation_key( cast(StateType, _get_nested_dict_value(data.info, "cellular", "mode")), CELLULAR_MODE_MAP, ), ), NRGkickSensorEntityDescription( key="cellular_rssi", translation_key="cellular_rssi", device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, requires_sim_module=True, value_fn=lambda data: _get_nested_dict_value(data.info, "cellular", "rssi"), ), NRGkickSensorEntityDescription( key="cellular_operator", translation_key="cellular_operator", entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, requires_sim_module=True, value_fn=lambda data: _get_nested_dict_value(data.info, "cellular", "operator"), ), # VALUES - Energy NRGkickSensorEntityDescription( key="total_charged_energy", translation_key="total_charged_energy", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, suggested_display_precision=3, suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, value_fn=lambda data: _get_nested_dict_value( data.values, "energy", "total_charged_energy" ), ), NRGkickSensorEntityDescription( key="charged_energy", translation_key="charged_energy", device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, native_unit_of_measurement=UnitOfEnergy.WATT_HOUR, suggested_display_precision=3, suggested_unit_of_measurement=UnitOfEnergy.KILO_WATT_HOUR, value_fn=lambda data: _get_nested_dict_value( data.values, "energy", "charged_energy" ), ), # VALUES - Powerflow (Total) NRGkickSensorEntityDescription( key="charging_voltage", translation_key="charging_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "charging_voltage" ), ), NRGkickSensorEntityDescription( key="charging_current", translation_key="charging_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "charging_current" ), ), NRGkickSensorEntityDescription( key="powerflow_grid_frequency", translation_key="powerflow_grid_frequency", device_class=SensorDeviceClass.FREQUENCY, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfFrequency.HERTZ, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "grid_frequency" ), ), NRGkickSensorEntityDescription( key="peak_power", translation_key="peak_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "peak_power" ), ), NRGkickSensorEntityDescription( key="total_active_power", translation_key="total_active_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "total_active_power" ), ), NRGkickSensorEntityDescription( key="total_reactive_power", translation_key="total_reactive_power", device_class=SensorDeviceClass.REACTIVE_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "total_reactive_power" ), ), NRGkickSensorEntityDescription( key="total_apparent_power", translation_key="total_apparent_power", device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "total_apparent_power" ), ), NRGkickSensorEntityDescription( key="total_power_factor", translation_key="total_power_factor", device_class=SensorDeviceClass.POWER_FACTOR, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "total_power_factor" ), ), # VALUES - Powerflow L1 NRGkickSensorEntityDescription( key="l1_voltage", translation_key="l1_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "voltage" ), ), NRGkickSensorEntityDescription( key="l1_current", translation_key="l1_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "current" ), ), NRGkickSensorEntityDescription( key="l1_active_power", translation_key="l1_active_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "active_power" ), ), NRGkickSensorEntityDescription( key="l1_reactive_power", translation_key="l1_reactive_power", device_class=SensorDeviceClass.REACTIVE_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "reactive_power" ), ), NRGkickSensorEntityDescription( key="l1_apparent_power", translation_key="l1_apparent_power", device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "apparent_power" ), ), NRGkickSensorEntityDescription( key="l1_power_factor", translation_key="l1_power_factor", device_class=SensorDeviceClass.POWER_FACTOR, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l1", "power_factor" ), ), # VALUES - Powerflow L2 NRGkickSensorEntityDescription( key="l2_voltage", translation_key="l2_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "voltage" ), ), NRGkickSensorEntityDescription( key="l2_current", translation_key="l2_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "current" ), ), NRGkickSensorEntityDescription( key="l2_active_power", translation_key="l2_active_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "active_power" ), ), NRGkickSensorEntityDescription( key="l2_reactive_power", translation_key="l2_reactive_power", device_class=SensorDeviceClass.REACTIVE_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "reactive_power" ), ), NRGkickSensorEntityDescription( key="l2_apparent_power", translation_key="l2_apparent_power", device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "apparent_power" ), ), NRGkickSensorEntityDescription( key="l2_power_factor", translation_key="l2_power_factor", device_class=SensorDeviceClass.POWER_FACTOR, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l2", "power_factor" ), ), # VALUES - Powerflow L3 NRGkickSensorEntityDescription( key="l3_voltage", translation_key="l3_voltage", device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricPotential.VOLT, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "voltage" ), ), NRGkickSensorEntityDescription( key="l3_current", translation_key="l3_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "current" ), ), NRGkickSensorEntityDescription( key="l3_active_power", translation_key="l3_active_power", device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfPower.WATT, suggested_display_precision=2, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "active_power" ), ), NRGkickSensorEntityDescription( key="l3_reactive_power", translation_key="l3_reactive_power", device_class=SensorDeviceClass.REACTIVE_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfReactivePower.VOLT_AMPERE_REACTIVE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "reactive_power" ), ), NRGkickSensorEntityDescription( key="l3_apparent_power", translation_key="l3_apparent_power", device_class=SensorDeviceClass.APPARENT_POWER, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfApparentPower.VOLT_AMPERE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "apparent_power" ), ), NRGkickSensorEntityDescription( key="l3_power_factor", translation_key="l3_power_factor", device_class=SensorDeviceClass.POWER_FACTOR, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "l3", "power_factor" ), ), # VALUES - Powerflow Neutral NRGkickSensorEntityDescription( key="n_current", translation_key="n_current", device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, suggested_display_precision=2, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda data: _get_nested_dict_value( data.values, "powerflow", "n", "current" ), ), # VALUES - General NRGkickSensorEntityDescription( key="charging_rate", translation_key="charging_rate", state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR, value_fn=lambda data: _get_nested_dict_value( data.values, "general", "charging_rate" ), ), NRGkickSensorEntityDescription( key="vehicle_connected_since", translation_key="vehicle_connected_since", device_class=SensorDeviceClass.TIMESTAMP, value_fn=lambda data: ( _seconds_to_stable_timestamp( cast( StateType, _get_nested_dict_value( data.values, "general", "vehicle_connect_time" ), ) ) if _get_nested_dict_value(data.values, "general", "status") != ChargingStatus.STANDBY else None ), ), NRGkickSensorEntityDescription( key="vehicle_charging_time", translation_key="vehicle_charging_time", device_class=SensorDeviceClass.DURATION, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTime.SECONDS, suggested_unit_of_measurement=UnitOfTime.MINUTES, value_fn=lambda data: _get_nested_dict_value( data.values, "general", "vehicle_charging_time" ), ), NRGkickSensorEntityDescription( key="status", translation_key="status", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(STATUS_MAP), value_fn=lambda data: _map_code_to_translation_key( cast(StateType, _get_nested_dict_value(data.values, "general", "status")), STATUS_MAP, ), ), NRGkickSensorEntityDescription( key="charge_count", translation_key="charge_count", entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.TOTAL_INCREASING, suggested_display_precision=0, value_fn=lambda data: _get_nested_dict_value( data.values, "general", "charge_count" ), ), NRGkickSensorEntityDescription( key="rcd_trigger", translation_key="rcd_trigger", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(RCD_TRIGGER_MAP), entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _map_code_to_translation_key( cast( StateType, _get_nested_dict_value(data.values, "general", "rcd_trigger") ), RCD_TRIGGER_MAP, ), ), NRGkickSensorEntityDescription( key="warning_code", translation_key="warning_code", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(WARNING_CODE_MAP), entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _map_code_to_translation_key( cast( StateType, _get_nested_dict_value(data.values, "general", "warning_code"), ), WARNING_CODE_MAP, ), ), NRGkickSensorEntityDescription( key="error_code", translation_key="error_code", device_class=SensorDeviceClass.ENUM, options=_enum_options_from_mapping(ERROR_CODE_MAP), entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _map_code_to_translation_key( cast( StateType, _get_nested_dict_value(data.values, "general", "error_code") ), ERROR_CODE_MAP, ), ), # VALUES - Temperatures NRGkickSensorEntityDescription( key="housing_temperature", translation_key="housing_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "housing" ), ), NRGkickSensorEntityDescription( key="connector_l1_temperature", translation_key="connector_l1_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "connector_l1" ), ), NRGkickSensorEntityDescription( key="connector_l2_temperature", translation_key="connector_l2_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "connector_l2" ), ), NRGkickSensorEntityDescription( key="connector_l3_temperature", translation_key="connector_l3_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "connector_l3" ), ), NRGkickSensorEntityDescription( key="domestic_plug_1_temperature", translation_key="domestic_plug_1_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "domestic_plug_1" ), ), NRGkickSensorEntityDescription( key="domestic_plug_2_temperature", translation_key="domestic_plug_2_temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTemperature.CELSIUS, entity_category=EntityCategory.DIAGNOSTIC, value_fn=lambda data: _get_nested_dict_value( data.values, "temperatures", "domestic_plug_2" ), ), ) class NRGkickSensor(NRGkickEntity, SensorEntity): """Representation of a NRGkick sensor.""" entity_description: NRGkickSensorEntityDescription def __init__( self, coordinator: NRGkickDataUpdateCoordinator, entity_description: NRGkickSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator, entity_description.key) self.entity_description = entity_description @property def native_value(self) -> StateType | datetime: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/nrgkick/sensor.py", "license": "Apache License 2.0", "lines": 770, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/openevse/config_flow.py
"""Config flow for OpenEVSE integration.""" from typing import Any from openevsehttp.__main__ import OpenEVSE from openevsehttp.exceptions import AuthenticationError, MissingSerial import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST, CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.helpers import config_validation as cv from homeassistant.helpers.service_info import zeroconf from .const import CONF_ID, CONF_SERIAL, DOMAIN USER_SCHEMA = vol.Schema({vol.Required(CONF_HOST): cv.string}) AUTH_SCHEMA = vol.Schema( {vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string} ) class OpenEVSEConfigFlow(ConfigFlow, domain=DOMAIN): """OpenEVSE config flow.""" VERSION = 1 MINOR_VERSION = 1 def __init__(self) -> None: """Set up the instance.""" self.discovery_info: dict[str, Any] = {} self._host: str | None = None async def check_status( self, host: str, user: str | None = None, password: str | None = None ) -> tuple[dict[str, str], str | None]: """Check if we can connect to the OpenEVSE charger.""" charger = OpenEVSE(host, user, password) try: result = await charger.test_and_get() except TimeoutError: return {"base": "cannot_connect"}, None except AuthenticationError: return {"base": "invalid_auth"}, None except MissingSerial: return {}, None return {}, result.get(CONF_SERIAL) 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_HOST: user_input[CONF_HOST]}) errors, serial = await self.check_status(user_input[CONF_HOST]) if not errors: if serial is not None: await self.async_set_unique_id(serial, raise_on_progress=False) self._abort_if_unique_id_configured() return self.async_create_entry( title=f"OpenEVSE {user_input[CONF_HOST]}", data=user_input, ) if errors["base"] == "invalid_auth": self._host = user_input[CONF_HOST] return await self.async_step_auth() return self.async_show_form( step_id="user", data_schema=self.add_suggested_values_to_schema(USER_SCHEMA, user_input), errors=errors, ) async def async_step_import(self, data: dict[str, str]) -> ConfigFlowResult: """Handle the initial step.""" self._async_abort_entries_match({CONF_HOST: data[CONF_HOST]}) errors, serial = await self.check_status(data[CONF_HOST]) if not errors: if serial is not None: await self.async_set_unique_id(serial) self._abort_if_unique_id_configured() else: return self.async_abort(reason="unavailable_host") return self.async_create_entry( title=f"OpenEVSE {data[CONF_HOST]}", data=data, ) async def async_step_zeroconf( self, discovery_info: zeroconf.ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" self._async_abort_entries_match({CONF_HOST: discovery_info.host}) await self.async_set_unique_id(discovery_info.properties[CONF_ID]) self._abort_if_unique_id_configured(updates={CONF_HOST: discovery_info.host}) host = discovery_info.host name = f"OpenEVSE {discovery_info.name.split('.')[0]}" self.discovery_info.update( { CONF_HOST: host, CONF_NAME: name, } ) self.context.update({"title_placeholders": {"name": name}}) return await self.async_step_discovery_confirm() async def async_step_discovery_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm discovery.""" errors, _ = await self.check_status(self.discovery_info[CONF_HOST]) if errors: if errors["base"] == "invalid_auth": return await self.async_step_auth() return self.async_abort(reason="unavailable_host") if user_input is None: self._set_confirm_only() return self.async_show_form( step_id="discovery_confirm", description_placeholders={"name": self.discovery_info[CONF_NAME]}, ) return self.async_create_entry( title=self.discovery_info[CONF_NAME], data={CONF_HOST: self.discovery_info[CONF_HOST]}, ) async def async_step_auth( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the authentication step.""" errors: dict[str, str] = {} if user_input is not None: host = self._host or self.discovery_info[CONF_HOST] errors, serial = await self.check_status( host, user_input[CONF_USERNAME], user_input[CONF_PASSWORD], ) if not errors: if self.unique_id is None and serial is not None: await self.async_set_unique_id(serial) self._abort_if_unique_id_configured() return self.async_create_entry( title=f"OpenEVSE {host}", data={ CONF_HOST: host, CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], }, ) return self.async_show_form( step_id="auth", data_schema=self.add_suggested_values_to_schema(AUTH_SCHEMA, user_input), errors=errors, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openevse/config_flow.py", "license": "Apache License 2.0", "lines": 139, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/openevse/const.py
"""Constants for the OpenEVSE integration.""" CONF_ID = "id" CONF_SERIAL = "serial" DOMAIN = "openevse" INTEGRATION_TITLE = "OpenEVSE"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openevse/const.py", "license": "Apache License 2.0", "lines": 5, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openevse/coordinator.py
"""Data update coordinator for OpenEVSE.""" from __future__ import annotations from datetime import timedelta import logging from openevsehttp.__main__ import OpenEVSE 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__) # Fallback polling interval - websocket provides real-time updates SCAN_INTERVAL = timedelta(minutes=5) type OpenEVSEConfigEntry = ConfigEntry[OpenEVSEDataUpdateCoordinator] class OpenEVSEDataUpdateCoordinator(DataUpdateCoordinator[None]): """Class to manage fetching OpenEVSE data.""" config_entry: OpenEVSEConfigEntry def __init__( self, hass: HomeAssistant, config_entry: OpenEVSEConfigEntry, charger: OpenEVSE, ) -> None: """Initialize coordinator.""" self.charger = charger super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=SCAN_INTERVAL, ) # Set up websocket callback for push updates self.charger.callback = self._async_websocket_callback async def _async_websocket_callback(self) -> None: """Handle websocket data update.""" self.async_set_updated_data(None) def start_websocket(self) -> None: """Start the websocket listener.""" self.charger.ws_start() async def async_stop_websocket(self) -> None: """Stop the websocket listener.""" if self.charger.websocket: await self.charger.ws_disconnect() async def _async_update_data(self) -> None: """Fetch data from OpenEVSE charger.""" try: await self.charger.update() except TimeoutError as error: raise UpdateFailed( f"Timeout communicating with charger: {error}" ) from error
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openevse/coordinator.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/openevse/number.py
"""Support for OpenEVSE number entities.""" from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from openevsehttp.__main__ import OpenEVSE from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberEntityDescription, ) from homeassistant.const import ( ATTR_CONNECTIONS, ATTR_SERIAL_NUMBER, EntityCategory, UnitOfElectricCurrent, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import OpenEVSEConfigEntry, OpenEVSEDataUpdateCoordinator PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class OpenEVSENumberDescription(NumberEntityDescription): """Describes an OpenEVSE number entity.""" value_fn: Callable[[OpenEVSE], float] min_value_fn: Callable[[OpenEVSE], float] max_value_fn: Callable[[OpenEVSE], float] set_value_fn: Callable[[OpenEVSE, float], Awaitable[Any]] NUMBER_TYPES: tuple[OpenEVSENumberDescription, ...] = ( OpenEVSENumberDescription( key="charge_rate", translation_key="charge_rate", value_fn=lambda ev: ev.max_current_soft, min_value_fn=lambda ev: ev.min_amps, max_value_fn=lambda ev: ev.max_amps, set_value_fn=lambda ev, value: ev.set_current(value), native_step=1.0, entity_category=EntityCategory.CONFIG, native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, device_class=NumberDeviceClass.CURRENT, ), ) async def async_setup_entry( hass: HomeAssistant, entry: OpenEVSEConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up OpenEVSE sensors based on config entry.""" coordinator = entry.runtime_data identifier = entry.unique_id or entry.entry_id async_add_entities( OpenEVSENumber(coordinator, description, identifier, entry.unique_id) for description in NUMBER_TYPES ) class OpenEVSENumber(CoordinatorEntity[OpenEVSEDataUpdateCoordinator], NumberEntity): """Implementation of an OpenEVSE sensor.""" _attr_has_entity_name = True entity_description: OpenEVSENumberDescription def __init__( self, coordinator: OpenEVSEDataUpdateCoordinator, description: OpenEVSENumberDescription, identifier: str, unique_id: str | None, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{identifier}-{description.key}" self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, identifier)}, manufacturer="OpenEVSE", ) if unique_id: self._attr_device_info[ATTR_CONNECTIONS] = { (CONNECTION_NETWORK_MAC, unique_id) } self._attr_device_info[ATTR_SERIAL_NUMBER] = unique_id @property def native_value(self) -> float: """Return the state of the number.""" return self.entity_description.value_fn(self.coordinator.charger) @property def native_min_value(self) -> float: """Return the minimum value.""" return self.entity_description.min_value_fn(self.coordinator.charger) @property def native_max_value(self) -> float: """Return the maximum value.""" return self.entity_description.max_value_fn(self.coordinator.charger) async def async_set_native_value(self, value: float) -> None: """Set new value.""" await self.entity_description.set_value_fn(self.coordinator.charger, value)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/openevse/number.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/person/condition.py
"""Provides conditions for persons.""" from homeassistant.const import STATE_HOME, STATE_NOT_HOME from homeassistant.core import HomeAssistant from homeassistant.helpers.condition import Condition, make_entity_state_condition from .const import DOMAIN CONDITIONS: dict[str, type[Condition]] = { "is_home": make_entity_state_condition(DOMAIN, STATE_HOME), "is_not_home": make_entity_state_condition(DOMAIN, STATE_NOT_HOME), } async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: """Return the conditions for persons.""" return CONDITIONS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/person/condition.py", "license": "Apache License 2.0", "lines": 12, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/person/trigger.py
"""Provides triggers for persons.""" from homeassistant.const import STATE_HOME from homeassistant.core import HomeAssistant from homeassistant.helpers.trigger import ( Trigger, make_entity_origin_state_trigger, make_entity_target_state_trigger, ) from .const import DOMAIN TRIGGERS: dict[str, type[Trigger]] = { "entered_home": make_entity_target_state_trigger(DOMAIN, STATE_HOME), "left_home": make_entity_origin_state_trigger(DOMAIN, from_state=STATE_HOME), } async def async_get_triggers(hass: HomeAssistant) -> dict[str, type[Trigger]]: """Return the triggers for persons.""" return TRIGGERS
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/person/trigger.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/pooldose/diagnostics.py
"""Diagnostics support for Pooldose.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.core import HomeAssistant from . import PooldoseConfigEntry TO_REDACT = { "IP", "MAC", "WIFI_SSID", "AP_SSID", "SERIAL_NUMBER", "DEVICE_ID", "OWNERID", "NAME", "GROUPNAME", } async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: PooldoseConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" coordinator = entry.runtime_data return { "device_info": async_redact_data(coordinator.device_info, TO_REDACT), "data": coordinator.data, }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/pooldose/diagnostics.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/prana/config_flow.py
"""Configuration flow for Prana integration.""" import logging from typing import Any from prana_local_api_client.exceptions import PranaApiCommunicationError from prana_local_api_client.models.prana_device_info import PranaDeviceInfo from prana_local_api_client.prana_api_client import PranaLocalApiClient import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_HOST from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .const import DOMAIN _LOGGER = logging.getLogger(__name__) USER_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): str, } ) class PranaConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a Prana config flow.""" _host: str _device_info: PranaDeviceInfo async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle Zeroconf discovery of a Prana device.""" _LOGGER.debug("Discovered device via Zeroconf: %s", discovery_info) friendly_name = discovery_info.properties.get("label", "") self.context["title_placeholders"] = {"name": friendly_name} self._host = discovery_info.host try: self._device_info = await self._validate_device() except ValueError: return self.async_abort(reason="invalid_device") except PranaApiCommunicationError: return self.async_abort(reason="invalid_device_or_unreachable") self._set_confirm_only() return await self.async_step_confirm() async def async_step_confirm(self, user_input=None) -> ConfigFlowResult: """Handle the user confirming a discovered Prana device.""" if user_input is not None: return self.async_create_entry( title=self._device_info.label, data={CONF_HOST: self._host}, ) return self.async_show_form( step_id="confirm", description_placeholders={ "name": self._device_info.label, "host": self._host, }, ) async def async_step_user( self, user_input: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Manual entry by IP address.""" errors: dict[str, str] = {} if user_input is not None: self._host = user_input[CONF_HOST] try: self._device_info = await self._validate_device() except ValueError: return self.async_abort(reason="invalid_device") except PranaApiCommunicationError: errors = {"base": "invalid_device_or_unreachable"} if not errors: return self.async_create_entry( title=self._device_info.label, data={CONF_HOST: self._host}, ) return self.async_show_form( step_id="user", data_schema=USER_SCHEMA, errors=errors ) async def _validate_device(self) -> PranaDeviceInfo: """Validate that a Prana device is reachable and valid.""" client = PranaLocalApiClient(host=self._host, port=80) device_info = await client.get_device_info() if not device_info.isValid: raise ValueError("invalid_device") await self.async_set_unique_id(device_info.manufactureId) self._abort_if_unique_id_configured() return device_info
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prana/config_flow.py", "license": "Apache License 2.0", "lines": 82, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/prana/coordinator.py
"""Coordinator for Prana integration. Responsible for polling the device REST endpoints and normalizing data for entities. """ from datetime import timedelta import logging from prana_local_api_client.exceptions import ( PranaApiCommunicationError, PranaApiUpdateFailed, ) from prana_local_api_client.models.prana_device_info import PranaDeviceInfo from prana_local_api_client.models.prana_state import PranaState from prana_local_api_client.prana_api_client import PranaLocalApiClient from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(seconds=10) COORDINATOR_NAME = f"{DOMAIN} coordinator" type PranaConfigEntry = ConfigEntry[PranaCoordinator] class PranaCoordinator(DataUpdateCoordinator[PranaState]): """Universal coordinator for Prana (fan, switch, sensor, light data).""" config_entry: PranaConfigEntry device_info: PranaDeviceInfo def __init__(self, hass: HomeAssistant, entry: PranaConfigEntry) -> None: """Initialize the Prana data update coordinator.""" super().__init__( hass, logger=_LOGGER, name=COORDINATOR_NAME, update_interval=UPDATE_INTERVAL, config_entry=entry, ) self.api_client = PranaLocalApiClient(host=entry.data[CONF_HOST], port=80) async def _async_setup(self) -> None: try: self.device_info = await self.api_client.get_device_info() except PranaApiCommunicationError as err: raise ConfigEntryNotReady("Could not fetch device info") from err async def _async_update_data(self) -> PranaState: """Fetch and normalize device state for all platforms.""" try: state = await self.api_client.get_state() except PranaApiUpdateFailed as err: raise UpdateFailed(f"HTTP error communicating with device: {err}") from err except PranaApiCommunicationError as err: raise UpdateFailed( f"Network error communicating with device: {err}" ) from err return state
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prana/coordinator.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/prana/entity.py
"""Defines base Prana entity.""" from dataclasses import dataclass import logging from typing import TYPE_CHECKING from homeassistant.components.switch import StrEnum from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import EntityDescription from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import PranaCoordinator _LOGGER = logging.getLogger(__name__) @dataclass(frozen=True, kw_only=True) class PranaEntityDescription(EntityDescription): """Description for all Prana entities.""" key: StrEnum class PranaBaseEntity(CoordinatorEntity[PranaCoordinator]): """Defines a base Prana entity.""" _attr_has_entity_name = True _attr_entity_description: PranaEntityDescription def __init__( self, coordinator: PranaCoordinator, description: PranaEntityDescription, ) -> None: """Initialize the Prana entity.""" super().__init__(coordinator) if TYPE_CHECKING: assert coordinator.config_entry.unique_id self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.config_entry.unique_id)}, manufacturer="Prana", name=coordinator.device_info.label, model=coordinator.device_info.pranaModel, serial_number=coordinator.device_info.manufactureId, sw_version=str(coordinator.device_info.fwVersion), ) self._attr_unique_id = f"{coordinator.config_entry.unique_id}_{description.key}" self.entity_description = description
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prana/entity.py", "license": "Apache License 2.0", "lines": 38, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/prana/switch.py
"""Switch platform for Prana integration.""" from collections.abc import Callable from typing import Any from aioesphomeapi import dataclass from homeassistant.components.switch import ( StrEnum, SwitchEntity, SwitchEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PranaConfigEntry, PranaCoordinator from .entity import PranaBaseEntity, PranaEntityDescription PARALLEL_UPDATES = 1 class PranaSwitchType(StrEnum): """Enumerates Prana switch types exposed by the device API.""" BOUND = "bound" HEATER = "heater" NIGHT = "night" BOOST = "boost" AUTO = "auto" AUTO_PLUS = "auto_plus" WINTER = "winter" @dataclass(frozen=True, kw_only=True) class PranaSwitchEntityDescription(SwitchEntityDescription, PranaEntityDescription): """Description of a Prana switch entity.""" value_fn: Callable[[PranaCoordinator], bool] ENTITIES: tuple[PranaEntityDescription, ...] = ( PranaSwitchEntityDescription( key=PranaSwitchType.BOUND, translation_key="bound", value_fn=lambda coord: coord.data.bound, ), PranaSwitchEntityDescription( key=PranaSwitchType.HEATER, translation_key="heater", value_fn=lambda coord: coord.data.heater, ), PranaSwitchEntityDescription( key=PranaSwitchType.AUTO, translation_key="auto", value_fn=lambda coord: coord.data.auto, ), PranaSwitchEntityDescription( key=PranaSwitchType.AUTO_PLUS, translation_key="auto_plus", value_fn=lambda coord: coord.data.auto_plus, ), PranaSwitchEntityDescription( key=PranaSwitchType.WINTER, translation_key="winter", value_fn=lambda coord: coord.data.winter, ), ) async def async_setup_entry( hass: HomeAssistant, entry: PranaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Prana switch entities from a config entry.""" async_add_entities( PranaSwitch(entry.runtime_data, entity_description) for entity_description in ENTITIES ) class PranaSwitch(PranaBaseEntity, SwitchEntity): """Representation of a Prana switch (bound/heater/auto/etc).""" entity_description: PranaSwitchEntityDescription @property def is_on(self) -> bool: """Return switch on/off state.""" return self.entity_description.value_fn(self.coordinator) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the switch on.""" await self.coordinator.api_client.set_switch(self.entity_description.key, True) await self.coordinator.async_refresh() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the switch off.""" await self.coordinator.api_client.set_switch(self.entity_description.key, False) await self.coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/prana/switch.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/proxmoxve/config_flow.py
"""Config flow for Proxmox VE integration.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from proxmoxer import AuthenticationError, ProxmoxAPI from proxmoxer.core import ResourceException import requests from requests.exceptions import ConnectTimeout, SSLError import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv from .const import ( CONF_CONTAINERS, CONF_NODE, CONF_NODES, CONF_REALM, CONF_VMS, DEFAULT_PORT, DEFAULT_REALM, DEFAULT_VERIFY_SSL, DOMAIN, ) _LOGGER = logging.getLogger(__name__) CONFIG_SCHEMA = vol.Schema( { vol.Required(CONF_HOST): cv.string, vol.Required(CONF_PORT, default=DEFAULT_PORT): cv.port, vol.Optional(CONF_REALM, default=DEFAULT_REALM): cv.string, vol.Required(CONF_USERNAME): cv.string, vol.Required(CONF_PASSWORD): cv.string, vol.Optional(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): cv.boolean, } ) def _sanitize_userid(data: dict[str, Any]) -> str: """Sanitize the user ID.""" return ( data[CONF_USERNAME] if "@" in data[CONF_USERNAME] else f"{data[CONF_USERNAME]}@{data[CONF_REALM]}" ) def _get_nodes_data(data: dict[str, Any]) -> list[dict[str, Any]]: """Validate the user input and fetch data (sync, for executor).""" try: client = ProxmoxAPI( data[CONF_HOST], port=data[CONF_PORT], user=_sanitize_userid(data), password=data[CONF_PASSWORD], verify_ssl=data.get(CONF_VERIFY_SSL, DEFAULT_VERIFY_SSL), ) nodes = client.nodes.get() except AuthenticationError as err: raise ProxmoxAuthenticationError from err except SSLError as err: raise ProxmoxSSLError from err except ConnectTimeout as err: raise ProxmoxConnectTimeout from err except ResourceException as err: raise ProxmoxNoNodesFound from err except requests.exceptions.ConnectionError as err: raise ProxmoxConnectionError from err nodes_data: list[dict[str, Any]] = [] for node in nodes: try: vms = client.nodes(node["node"]).qemu.get() containers = client.nodes(node["node"]).lxc.get() except ResourceException as err: raise ProxmoxNoNodesFound from err except requests.exceptions.ConnectionError as err: raise ProxmoxConnectionError from err nodes_data.append( { CONF_NODE: node["node"], CONF_VMS: [vm["vmid"] for vm in vms], CONF_CONTAINERS: [container["vmid"] for container in containers], } ) _LOGGER.debug("Nodes with data: %s", nodes_data) return nodes_data class ProxmoxveConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Proxmox VE.""" VERSION = 2 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" errors: dict[str, str] = {} proxmox_nodes: list[dict[str, Any]] = [] if user_input is not None: self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]}) proxmox_nodes, errors = await self._validate_input(user_input) if not errors: return self.async_create_entry( title=user_input[CONF_HOST], data={**user_input, CONF_NODES: proxmox_nodes}, ) return self.async_show_form( step_id="user", data_schema=CONFIG_SCHEMA, errors=errors, ) async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: """Perform reauth when Proxmox VE 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 new password and validate.""" errors: dict[str, str] = {} reauth_entry = self._get_reauth_entry() if user_input is not None: user_input = {**reauth_entry.data, **user_input} _, errors = await self._validate_input(user_input) if not errors: return self.async_update_reload_and_abort( reauth_entry, data_updates={CONF_PASSWORD: user_input[CONF_PASSWORD]}, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema({vol.Required(CONF_PASSWORD): str}), 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() suggested_values = { CONF_HOST: reconf_entry.data[CONF_HOST], CONF_PORT: reconf_entry.data[CONF_PORT], CONF_REALM: reconf_entry.data[CONF_REALM], CONF_USERNAME: reconf_entry.data[CONF_USERNAME], CONF_PASSWORD: reconf_entry.data[CONF_PASSWORD], CONF_VERIFY_SSL: reconf_entry.data[CONF_VERIFY_SSL], } if user_input: self._async_abort_entries_match({CONF_HOST: user_input[CONF_HOST]}) user_input = {**reconf_entry.data, **user_input} _, errors = await self._validate_input(user_input) if not errors: return self.async_update_reload_and_abort( reconf_entry, data_updates={ CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT], CONF_REALM: user_input[CONF_REALM], CONF_USERNAME: user_input[CONF_USERNAME], CONF_PASSWORD: user_input[CONF_PASSWORD], 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=CONFIG_SCHEMA, suggested_values=user_input or suggested_values, ), errors=errors, ) async def _validate_input( self, user_input: dict[str, Any] ) -> tuple[list[dict[str, Any]], dict[str, str]]: """Validate the user input. Return nodes data and/or errors.""" errors: dict[str, str] = {} proxmox_nodes: list[dict[str, Any]] = [] err: ProxmoxError | None = None try: proxmox_nodes = await self.hass.async_add_executor_job( _get_nodes_data, user_input ) except ProxmoxConnectTimeout as exc: errors["base"] = "connect_timeout" err = exc except ProxmoxAuthenticationError as exc: errors["base"] = "invalid_auth" err = exc except ProxmoxSSLError as exc: errors["base"] = "ssl_error" err = exc except ProxmoxNoNodesFound as exc: errors["base"] = "no_nodes_found" err = exc except ProxmoxConnectionError as exc: errors["base"] = "cannot_connect" err = exc if err is not None: _LOGGER.debug("Error: %s: %s", errors["base"], err) return proxmox_nodes, errors async def async_step_import(self, import_data: dict[str, Any]) -> ConfigFlowResult: """Handle a flow initiated by configuration file.""" self._async_abort_entries_match({CONF_HOST: import_data[CONF_HOST]}) try: proxmox_nodes = await self.hass.async_add_executor_job( _get_nodes_data, import_data ) except ProxmoxConnectTimeout: return self.async_abort(reason="connect_timeout") except ProxmoxAuthenticationError: return self.async_abort(reason="invalid_auth") except ProxmoxSSLError: return self.async_abort(reason="ssl_error") except ProxmoxNoNodesFound: return self.async_abort(reason="no_nodes_found") except ProxmoxConnectionError: return self.async_abort(reason="cannot_connect") return self.async_create_entry( title=import_data[CONF_HOST], data={**import_data, CONF_NODES: proxmox_nodes}, ) class ProxmoxError(HomeAssistantError): """Base class for Proxmox VE errors.""" class ProxmoxNoNodesFound(ProxmoxError): """Error to indicate no nodes found.""" class ProxmoxConnectTimeout(ProxmoxError): """Error to indicate a connection timeout.""" class ProxmoxSSLError(ProxmoxError): """Error to indicate an SSL error.""" class ProxmoxAuthenticationError(ProxmoxError): """Error to indicate an authentication error.""" class ProxmoxConnectionError(ProxmoxError): """Error to indicate a connection error."""
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/proxmoxve/config_flow.py", "license": "Apache License 2.0", "lines": 234, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex