sample_id
stringlengths
21
196
text
stringlengths
105
936k
metadata
dict
category
stringclasses
6 values
home-assistant/core:homeassistant/components/template/update.py
"""Support for updates which integrates with other components.""" from __future__ import annotations import logging from typing import TYPE_CHECKING, Any import voluptuous as vol from homeassistant.components.update import ( ATTR_INSTALLED_VERSION, ATTR_LATEST_VERSION, DEVICE_CLASSES_SCHEMA, DOMAIN as UPDATE_DOMAIN, ENTITY_ID_FORMAT, UpdateEntity, UpdateEntityFeature, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_DEVICE_CLASS, CONF_NAME, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, ) from homeassistant.helpers.trigger_template_entity import CONF_PICTURE from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import TriggerUpdateCoordinator, validators as template_validators from .const import DOMAIN from .entity import AbstractTemplateEntity from .helpers import ( async_setup_template_entry, async_setup_template_platform, async_setup_template_preview, ) from .schemas import ( TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA, make_template_entity_common_modern_schema, ) from .template_entity import TemplateEntity from .trigger_entity import TriggerEntity _LOGGER = logging.getLogger(__name__) DEFAULT_NAME = "Template Update" ATTR_BACKUP = "backup" ATTR_SPECIFIC_VERSION = "specific_version" CONF_BACKUP = "backup" CONF_IN_PROGRESS = "in_progress" CONF_INSTALL = "install" CONF_INSTALLED_VERSION = "installed_version" CONF_LATEST_VERSION = "latest_version" CONF_RELEASE_SUMMARY = "release_summary" CONF_RELEASE_URL = "release_url" CONF_SPECIFIC_VERSION = "specific_version" CONF_TITLE = "title" CONF_UPDATE_PERCENTAGE = "update_percentage" UPDATE_COMMON_SCHEMA = vol.Schema( { vol.Optional(CONF_BACKUP, default=False): cv.boolean, vol.Optional(CONF_DEVICE_CLASS): DEVICE_CLASSES_SCHEMA, vol.Optional(CONF_IN_PROGRESS): cv.template, vol.Optional(CONF_INSTALL): cv.SCRIPT_SCHEMA, vol.Required(CONF_INSTALLED_VERSION): cv.template, vol.Required(CONF_LATEST_VERSION): cv.template, vol.Optional(CONF_RELEASE_SUMMARY): cv.template, vol.Optional(CONF_RELEASE_URL): cv.template, vol.Optional(CONF_SPECIFIC_VERSION, default=False): cv.boolean, vol.Optional(CONF_TITLE): cv.template, vol.Optional(CONF_UPDATE_PERCENTAGE): cv.template, } ) UPDATE_YAML_SCHEMA = UPDATE_COMMON_SCHEMA.extend( make_template_entity_common_modern_schema(UPDATE_DOMAIN, DEFAULT_NAME).schema ) UPDATE_CONFIG_ENTRY_SCHEMA = UPDATE_COMMON_SCHEMA.extend( TEMPLATE_ENTITY_COMMON_CONFIG_ENTRY_SCHEMA.schema ) async def async_setup_platform( hass: HomeAssistant, config: ConfigType, async_add_entities: AddEntitiesCallback, discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the Template update.""" await async_setup_template_platform( hass, UPDATE_DOMAIN, config, StateUpdateEntity, TriggerUpdateEntity, async_add_entities, discovery_info, ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Initialize config entry.""" await async_setup_template_entry( hass, config_entry, async_add_entities, StateUpdateEntity, UPDATE_CONFIG_ENTRY_SCHEMA, ) @callback def async_create_preview_update( hass: HomeAssistant, name: str, config: dict[str, Any] ) -> StateUpdateEntity: """Create a preview.""" return async_setup_template_preview( hass, name, config, StateUpdateEntity, UPDATE_CONFIG_ENTRY_SCHEMA, ) class AbstractTemplateUpdate(AbstractTemplateEntity, UpdateEntity): """Representation of a template update features.""" _entity_id_format = ENTITY_ID_FORMAT # The super init is not called because TemplateEntity and TriggerEntity will call AbstractTemplateEntity.__init__. # This ensures that the __init__ on AbstractTemplateEntity is not called twice. def __init__(self, name: str, config: dict[str, Any]) -> None: # pylint: disable=super-init-not-called """Initialize the features.""" self._attr_device_class = config.get(CONF_DEVICE_CLASS) # Setup templates. self.setup_template( CONF_INSTALLED_VERSION, "_attr_installed_version", template_validators.string(self, CONF_INSTALLED_VERSION), ) self.setup_template( CONF_LATEST_VERSION, "_attr_latest_version", template_validators.string(self, CONF_LATEST_VERSION), ) self.setup_template( CONF_IN_PROGRESS, "_attr_in_progress", template_validators.boolean(self, CONF_IN_PROGRESS), self._update_in_progress, ) self.setup_template( CONF_RELEASE_SUMMARY, "_attr_release_summary", template_validators.string(self, CONF_RELEASE_SUMMARY), ) self.setup_template( CONF_RELEASE_URL, "_attr_release_url", template_validators.url(self, CONF_RELEASE_URL), ) self.setup_template( CONF_TITLE, "_attr_title", template_validators.string(self, CONF_TITLE), ) self.setup_template( CONF_UPDATE_PERCENTAGE, "_attr_update_percentage", template_validators.number(self, CONF_UPDATE_PERCENTAGE, 0.0, 100.0), self._update_update_percentage, ) self._attr_supported_features = UpdateEntityFeature(0) if config[CONF_BACKUP]: self._attr_supported_features |= UpdateEntityFeature.BACKUP if config[CONF_SPECIFIC_VERSION]: self._attr_supported_features |= UpdateEntityFeature.SPECIFIC_VERSION if ( CONF_IN_PROGRESS in self._templates or CONF_UPDATE_PERCENTAGE in self._templates ): self._attr_supported_features |= UpdateEntityFeature.PROGRESS self._optimistic_in_process = ( CONF_IN_PROGRESS not in self._templates and CONF_UPDATE_PERCENTAGE in self._templates ) # Scripts can be an empty list, therefore we need to check for None if (install_action := config.get(CONF_INSTALL)) is not None: self.add_script(CONF_INSTALL, install_action, name, DOMAIN) self._attr_supported_features |= UpdateEntityFeature.INSTALL @callback def _update_in_progress(self, result: bool | None) -> None: if result is None: template_validators.log_validation_result_error( self, CONF_IN_PROGRESS, result, "expected a boolean" ) self._attr_in_progress = result or False @callback def _update_update_percentage(self, result: float | None) -> None: if result is None: if self._optimistic_in_process: self._attr_in_progress = False self._attr_update_percentage = None return if self._optimistic_in_process: self._attr_in_progress = True self._attr_update_percentage = result async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Install an update.""" await self.async_run_script( self._action_scripts[CONF_INSTALL], run_variables={ATTR_SPECIFIC_VERSION: version, ATTR_BACKUP: backup}, context=self._context, ) class StateUpdateEntity(TemplateEntity, AbstractTemplateUpdate): """Representation of a Template update.""" _attr_should_poll = False def __init__( self, hass: HomeAssistant, config: ConfigType, unique_id: str | None, ) -> None: """Initialize the Template update.""" TemplateEntity.__init__(self, hass, config, unique_id) name = self._attr_name if TYPE_CHECKING: assert name is not None AbstractTemplateUpdate.__init__(self, name, config) @property def entity_picture(self) -> str | None: """Return the entity picture to use in the frontend.""" # This is needed to override the base update entity functionality if self._attr_entity_picture is None: # The default picture for update entities would use `self.platform.platform_name` in # place of `template`. This does not work when creating an entity preview because # the platform does not exist for that entity, therefore this is hardcoded as `template`. return "/api/brands/integration/template/icon.png" return self._attr_entity_picture class TriggerUpdateEntity(TriggerEntity, AbstractTemplateUpdate): """Update entity based on trigger data.""" domain = UPDATE_DOMAIN def __init__( self, hass: HomeAssistant, coordinator: TriggerUpdateCoordinator, config: ConfigType, ) -> None: """Initialize the entity.""" TriggerEntity.__init__(self, hass, coordinator, config) name = self._rendered.get(CONF_NAME, DEFAULT_NAME) AbstractTemplateUpdate.__init__(self, name, config) # Ensure the entity picture can resolve None to produce the default picture. if CONF_PICTURE in config: self._parse_result.add(CONF_PICTURE) async def async_added_to_hass(self) -> None: """Restore last state.""" await super().async_added_to_hass() if ( (last_state := await self.async_get_last_state()) is not None and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) and self._attr_installed_version is None and self._attr_latest_version is None ): self._attr_installed_version = last_state.attributes[ATTR_INSTALLED_VERSION] self._attr_latest_version = last_state.attributes[ATTR_LATEST_VERSION] self.restore_attributes(last_state) @property def entity_picture(self) -> str | None: """Return entity picture.""" if (picture := self._rendered.get(CONF_PICTURE)) is None: return UpdateEntity.entity_picture.fget(self) # type: ignore[attr-defined] return picture
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/template/update.py", "license": "Apache License 2.0", "lines": 268, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/togrill/config_flow.py
"""Config flow for the ToGrill integration.""" from __future__ import annotations from typing import Any from bleak.exc import BleakError from togrill_bluetooth import SUPPORTED_DEVICES from togrill_bluetooth.client import Client from togrill_bluetooth.packets import PacketA0Notify import voluptuous as vol from homeassistant.components.bluetooth import ( BluetoothServiceInfoBleak, async_discovered_service_info, ) from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import CONF_ADDRESS, CONF_MODEL from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import AbortFlow from .const import CONF_HAS_AMBIENT, CONF_PROBE_COUNT, DOMAIN from .coordinator import LOGGER _TIMEOUT = 10 async def read_config_data( hass: HomeAssistant, info: BluetoothServiceInfoBleak ) -> dict[str, Any]: """Read config from device.""" try: client = await Client.connect(info.device) except BleakError as exc: LOGGER.debug("Failed to connect", exc_info=True) raise AbortFlow("failed_to_read_config") from exc try: packet_a0 = await client.read(PacketA0Notify) except BleakError as exc: LOGGER.debug("Failed to read data", exc_info=True) raise AbortFlow("failed_to_read_config") from exc finally: await client.disconnect() return { CONF_MODEL: info.name, CONF_ADDRESS: info.address, CONF_PROBE_COUNT: packet_a0.probe_count, CONF_HAS_AMBIENT: packet_a0.ambient, } class ToGrillBluetoothConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for ToGrillBluetooth.""" VERSION = 1 def __init__(self) -> None: """Initialize the config flow.""" self._discovery_info: BluetoothServiceInfoBleak | None = None self._discovery_infos: dict[str, BluetoothServiceInfoBleak] = {} async def _async_create_entry_internal( self, info: BluetoothServiceInfoBleak ) -> ConfigFlowResult: config_data = await read_config_data(self.hass, info) return self.async_create_entry( title=config_data[CONF_MODEL], data=config_data, ) async def async_step_bluetooth( self, discovery_info: BluetoothServiceInfoBleak ) -> ConfigFlowResult: """Handle the bluetooth discovery step.""" await self.async_set_unique_id(discovery_info.address) self._abort_if_unique_id_configured() if discovery_info.name not in SUPPORTED_DEVICES: return self.async_abort(reason="not_supported") self._discovery_info = discovery_info return await self.async_step_bluetooth_confirm() async def async_step_bluetooth_confirm( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Confirm discovery.""" assert self._discovery_info is not None discovery_info = self._discovery_info if user_input is not None: return await self._async_create_entry_internal(discovery_info) self._set_confirm_only() placeholders = {"name": discovery_info.name} self.context["title_placeholders"] = placeholders return self.async_show_form( step_id="bluetooth_confirm", description_placeholders=placeholders ) async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the user step to pick discovered device.""" if user_input is not None: address = user_input[CONF_ADDRESS] await self.async_set_unique_id(address, raise_on_progress=False) self._abort_if_unique_id_configured() return await self._async_create_entry_internal( self._discovery_infos[address] ) current_addresses = self._async_current_ids(include_ignore=False) for discovery_info in async_discovered_service_info(self.hass, True): address = discovery_info.address if ( address in current_addresses or address in self._discovery_infos or discovery_info.name not in SUPPORTED_DEVICES ): continue self._discovery_infos[address] = discovery_info if not self._discovery_infos: return self.async_abort(reason="no_devices_found") addresses = {info.address: info.name for info in self._discovery_infos.values()} return self.async_show_form( step_id="user", data_schema=vol.Schema({vol.Required(CONF_ADDRESS): vol.In(addresses)}), )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/config_flow.py", "license": "Apache License 2.0", "lines": 108, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/togrill/const.py
"""Constants for the ToGrill integration.""" DOMAIN = "togrill" MAX_PROBE_COUNT = 6 CONF_PROBE_COUNT = "probe_count" CONF_HAS_AMBIENT = "has_ambient" CONF_VERSION = "version"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/const.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/togrill/coordinator.py
"""Coordinator for the ToGrill Bluetooth integration.""" from __future__ import annotations import asyncio from collections.abc import Callable from datetime import timedelta import logging from bleak.exc import BleakError from togrill_bluetooth.client import Client from togrill_bluetooth.exceptions import DecodeError from togrill_bluetooth.packets import ( Packet, PacketA0Notify, PacketA1Notify, PacketA8Write, ) from homeassistant.components import bluetooth from homeassistant.components.bluetooth import ( BluetoothCallbackMatcher, BluetoothChange, BluetoothScanningMode, BluetoothServiceInfoBleak, async_register_callback, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ADDRESS, CONF_MODEL from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import device_registry as dr from homeassistant.helpers.device_registry import CONNECTION_BLUETOOTH, DeviceInfo from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import CONF_PROBE_COUNT, DOMAIN type ToGrillConfigEntry = ConfigEntry[ToGrillCoordinator] SCAN_INTERVAL = timedelta(seconds=30) LOGGER = logging.getLogger(__name__) def get_version_string(packet: PacketA0Notify) -> str: """Construct a version string from packet data.""" return f"{packet.version_major}.{packet.version_minor}" class DeviceNotFound(UpdateFailed): """Update failed due to device disconnected.""" class DeviceFailed(UpdateFailed): """Update failed due to device disconnected.""" class ToGrillCoordinator(DataUpdateCoordinator[dict[tuple[int, int | None], Packet]]): """Class to manage fetching data.""" config_entry: ToGrillConfigEntry client: Client | None = None def __init__( self, hass: HomeAssistant, config_entry: ToGrillConfigEntry, ) -> None: """Initialize global data updater.""" super().__init__( hass=hass, logger=LOGGER, config_entry=config_entry, name="ToGrill", update_interval=SCAN_INTERVAL, ) self.address: str = config_entry.data[CONF_ADDRESS] self.data = {} self._packet_listeners: list[Callable[[Packet], None]] = [] device_registry = dr.async_get(self.hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, connections={(CONNECTION_BLUETOOTH, self.address)}, identifiers={(DOMAIN, self.address)}, name=config_entry.data[CONF_MODEL], model_id=config_entry.data[CONF_MODEL], ) config_entry.async_on_unload( async_register_callback( hass, self._async_handle_bluetooth_event, BluetoothCallbackMatcher(address=self.address, connectable=True), BluetoothScanningMode.ACTIVE, ) ) def get_device_info(self, probe_number: int | None) -> DeviceInfo: """Return device info.""" if probe_number is None: return DeviceInfo( identifiers={(DOMAIN, self.address)}, ) return DeviceInfo( translation_key="probe", translation_placeholders={ "probe_number": str(probe_number), }, identifiers={(DOMAIN, f"{self.address}_{probe_number}")}, via_device=(DOMAIN, self.address), ) @callback def async_add_packet_listener( self, packet_callback: Callable[[Packet], None] ) -> Callable[[], None]: """Add a listener for a given packet type.""" def _unregister(): self._packet_listeners.remove(packet_callback) self._packet_listeners.append(packet_callback) return _unregister def async_update_packet_listeners(self, packet: Packet): """Update all packet listeners.""" for listener in self._packet_listeners: listener(packet) async def _connect_and_update_registry(self) -> Client: """Update device registry data.""" device = bluetooth.async_ble_device_from_address( self.hass, self.address, connectable=True ) if not device: raise DeviceNotFound("Unable to find device") try: client = await Client.connect( device, self._notify_callback, disconnected_callback=self._disconnected_callback, ) except BleakError as exc: self.logger.debug("Connection failed", exc_info=True) raise DeviceFailed("Unable to connect to device") from exc try: async with asyncio.timeout(10): packet_a0 = await client.read(PacketA0Notify) except (BleakError, DecodeError, TimeoutError) as exc: self.logger.debug("Configuration read failed", exc_info=True) await client.disconnect() raise DeviceFailed("Failed to read device configuration") from exc config_entry = self.config_entry device_registry = dr.async_get(self.hass) device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, self.address)}, sw_version=get_version_string(packet_a0), ) return client async def async_shutdown(self) -> None: """Shutdown coordinator and disconnect from device.""" await super().async_shutdown() if self.client: await self.client.disconnect() self.client = None async def _get_connected_client(self) -> Client: if self.client: return self.client self.client = await self._connect_and_update_registry() return self.client def get_packet[PacketT: Packet]( self, packet_type: type[PacketT], probe=None ) -> PacketT | None: """Get a cached packet of a certain type.""" if packet := self.data.get((packet_type.type, probe)): assert isinstance(packet, packet_type) return packet return None def _notify_callback(self, packet: Packet): probe = getattr(packet, "probe", None) self.data[(packet.type, probe)] = packet self.async_update_packet_listeners(packet) self.async_update_listeners() async def _async_update_data(self) -> dict[tuple[int, int | None], Packet]: """Poll the device.""" if self.client and not self.client.is_connected: await self.client.disconnect() self.client = None self._debounced_refresh.async_schedule_call() raise DeviceFailed("Device was disconnected") try: client = await self._get_connected_client() except DeviceNotFound: return {} try: await client.request(PacketA0Notify) await client.request(PacketA1Notify) for probe in range(1, self.config_entry.data[CONF_PROBE_COUNT] + 1): await client.write(PacketA8Write(probe=probe)) except BleakError as exc: raise DeviceFailed(f"Device failed {exc}") from exc return self.data @callback def _disconnected_callback(self) -> None: """Handle Bluetooth device being disconnected.""" self._debounced_refresh.async_schedule_call() @callback def _async_handle_bluetooth_event( self, service_info: BluetoothServiceInfoBleak, change: BluetoothChange, ) -> None: """Handle a Bluetooth event.""" if self.client is None: self._debounced_refresh.async_schedule_call()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/coordinator.py", "license": "Apache License 2.0", "lines": 190, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/togrill/entity.py
"""Provides the base entities.""" from __future__ import annotations from bleak.exc import BleakError from togrill_bluetooth.client import Client from togrill_bluetooth.exceptions import BaseError from togrill_bluetooth.packets import PacketWrite from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import LOGGER, ToGrillCoordinator class ToGrillEntity(CoordinatorEntity[ToGrillCoordinator]): """Coordinator entity for Gardena Bluetooth.""" _attr_has_entity_name = True def __init__( self, coordinator: ToGrillCoordinator, probe_number: int | None = None ) -> None: """Initialize coordinator entity.""" super().__init__(coordinator) self._attr_device_info = coordinator.get_device_info(probe_number) def _get_client(self) -> Client: client = self.coordinator.client if client is None or not client.is_connected: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="disconnected" ) return client async def _write_packet(self, packet: PacketWrite) -> None: client = self._get_client() try: await client.write(packet) except BleakError as exc: LOGGER.debug("Failed to write", exc_info=True) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="communication_failed" ) from exc except BaseError as exc: LOGGER.debug("Failed to write", exc_info=True) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="rejected" ) from exc await self.coordinator.async_request_refresh() @property def available(self) -> bool: """Return if entity is available.""" return ( self.coordinator.last_update_success and self.coordinator.client is not None )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/entity.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/togrill/event.py
"""Support for event entities.""" from __future__ import annotations from togrill_bluetooth.packets import Packet, PacketA5Notify from homeassistant.components.event import EventEntity from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import slugify from . import ToGrillConfigEntry from .const import CONF_PROBE_COUNT from .coordinator import ToGrillCoordinator from .entity import ToGrillEntity PARALLEL_UPDATES = 0 async def async_setup_entry( hass: HomeAssistant, config_entry: ToGrillConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up event platform.""" async_add_entities( ToGrillEventEntity(config_entry.runtime_data, probe_number=probe_number) for probe_number in range(1, config_entry.data[CONF_PROBE_COUNT] + 1) ) class ToGrillEventEntity(ToGrillEntity, EventEntity): """Representation of a Hue Event entity from a button resource.""" def __init__(self, coordinator: ToGrillCoordinator, probe_number: int) -> None: """Initialize the entity.""" super().__init__(coordinator=coordinator, probe_number=probe_number) self._attr_translation_key = "event" self._attr_translation_placeholders = {"probe_number": f"{probe_number}"} self._attr_unique_id = f"{coordinator.address}_{probe_number}" self._probe_number = probe_number self._attr_event_types: list[str] = [ slugify(event.name) for event in PacketA5Notify.Message ] self.async_on_remove(coordinator.async_add_packet_listener(self._handle_event)) @callback def _handle_event(self, packet: Packet) -> None: if not isinstance(packet, PacketA5Notify): return try: message = PacketA5Notify.Message(packet.message) except ValueError: return if packet.probe != self._probe_number: return self._trigger_event(message.name.lower())
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/event.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/togrill/number.py
"""Support for number entities.""" from __future__ import annotations from collections.abc import Callable, Generator, Mapping from dataclasses import dataclass from typing import Any from togrill_bluetooth.packets import ( AlarmType, PacketA0Notify, PacketA6Write, PacketA8Notify, PacketA300Write, PacketA301Write, PacketWrite, ) from homeassistant.components.number import ( NumberDeviceClass, NumberEntity, NumberEntityDescription, NumberMode, ) from homeassistant.const import UnitOfTemperature, UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import ToGrillConfigEntry from .const import CONF_PROBE_COUNT, MAX_PROBE_COUNT from .coordinator import ToGrillCoordinator from .entity import ToGrillEntity PARALLEL_UPDATES = 0 @dataclass(kw_only=True, frozen=True) class ToGrillNumberEntityDescription(NumberEntityDescription): """Description of entity.""" get_value: Callable[[ToGrillCoordinator], float | None] set_packet: Callable[[ToGrillCoordinator, float], PacketWrite] entity_supported: Callable[[Mapping[str, Any]], bool] = lambda _: True probe_number: int | None = None def _get_temperature_descriptions( probe_number: int, ) -> Generator[ToGrillNumberEntityDescription]: def _get_description( variant: str, icon: str | None, set_packet: Callable[[ToGrillCoordinator, float], PacketWrite], get_value: Callable[[ToGrillCoordinator], float | None], ) -> ToGrillNumberEntityDescription: return ToGrillNumberEntityDescription( key=f"temperature_{variant}_{probe_number}", translation_key=f"temperature_{variant}", translation_placeholders={"probe_number": f"{probe_number}"}, device_class=NumberDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, native_min_value=0, native_max_value=250, mode=NumberMode.BOX, icon=icon, set_packet=set_packet, get_value=get_value, entity_supported=lambda x: probe_number <= x[CONF_PROBE_COUNT], probe_number=probe_number, ) def _get_temperatures( coordinator: ToGrillCoordinator, alarm_type: AlarmType ) -> tuple[None | float, None | float]: if not (packet := coordinator.get_packet(PacketA8Notify, probe_number)): return None, None if packet.alarm_type != alarm_type: return None, None return packet.temperature_1, packet.temperature_2 def _set_target( coordinator: ToGrillCoordinator, value: float | None ) -> PacketWrite: if value == 0.0: value = None return PacketA301Write(probe=probe_number, target=value) def _set_minimum( coordinator: ToGrillCoordinator, value: float | None ) -> PacketWrite: _, maximum = _get_temperatures(coordinator, AlarmType.TEMPERATURE_RANGE) if value == 0.0: value = None return PacketA300Write(probe=probe_number, minimum=value, maximum=maximum) def _set_maximum( coordinator: ToGrillCoordinator, value: float | None ) -> PacketWrite: minimum, _ = _get_temperatures(coordinator, AlarmType.TEMPERATURE_RANGE) if value == 0.0: value = None return PacketA300Write(probe=probe_number, minimum=minimum, maximum=value) yield _get_description( "target", "mdi:thermometer-check", _set_target, lambda x: _get_temperatures(x, AlarmType.TEMPERATURE_TARGET)[0], ) yield _get_description( "minimum", "mdi:thermometer-chevron-down", _set_minimum, lambda x: _get_temperatures(x, AlarmType.TEMPERATURE_RANGE)[0], ) yield _get_description( "maximum", "mdi:thermometer-chevron-up", _set_maximum, lambda x: _get_temperatures(x, AlarmType.TEMPERATURE_RANGE)[1], ) ENTITY_DESCRIPTIONS = ( *[ description for probe_number in range(1, MAX_PROBE_COUNT + 1) for description in _get_temperature_descriptions(probe_number) ], ToGrillNumberEntityDescription( key="alarm_interval", translation_key="alarm_interval", device_class=NumberDeviceClass.DURATION, native_unit_of_measurement=UnitOfTime.MINUTES, native_min_value=0, native_max_value=15, native_step=5, mode=NumberMode.BOX, set_packet=lambda coordinator, x: PacketA6Write( temperature_unit=None, alarm_interval=round(x) ), get_value=lambda x: ( packet.alarm_interval if (packet := x.get_packet(PacketA0Notify)) else None ), ), ) async def async_setup_entry( hass: HomeAssistant, entry: ToGrillConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up number based on a config entry.""" coordinator = entry.runtime_data async_add_entities( ToGrillNumber(coordinator, entity_description) for entity_description in ENTITY_DESCRIPTIONS if entity_description.entity_supported(entry.data) ) class ToGrillNumber(ToGrillEntity, NumberEntity): """Representation of a number.""" entity_description: ToGrillNumberEntityDescription def __init__( self, coordinator: ToGrillCoordinator, entity_description: ToGrillNumberEntityDescription, ) -> None: """Initialize.""" super().__init__(coordinator, probe_number=entity_description.probe_number) self.entity_description = entity_description self._attr_unique_id = f"{coordinator.address}_{entity_description.key}" @property def native_value(self) -> float | None: """Return the value reported by the number.""" return self.entity_description.get_value(self.coordinator) async def async_set_native_value(self, value: float) -> None: """Set value on device.""" packet = self.entity_description.set_packet(self.coordinator, value) await self._write_packet(packet)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/number.py", "license": "Apache License 2.0", "lines": 160, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/togrill/sensor.py
"""Support for sensor entities.""" from __future__ import annotations from collections.abc import Callable, Mapping from dataclasses import dataclass from typing import Any, cast from togrill_bluetooth.packets import Packet, PacketA0Notify, PacketA1Notify from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, StateType, ) from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfTemperature from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import ToGrillConfigEntry from .const import CONF_HAS_AMBIENT, CONF_PROBE_COUNT, MAX_PROBE_COUNT from .coordinator import ToGrillCoordinator from .entity import ToGrillEntity PARALLEL_UPDATES = 0 @dataclass(kw_only=True, frozen=True) class ToGrillSensorEntityDescription(SensorEntityDescription): """Description of entity.""" packet_type: int packet_extract: Callable[[Packet], StateType] entity_supported: Callable[[Mapping[str, Any]], bool] = lambda _: True probe_number: int | None = None def _get_temperature_description(probe_number: int): def _get(packet: Packet) -> StateType: assert isinstance(packet, PacketA1Notify) if len(packet.temperatures) < probe_number: return None temperature = packet.temperatures[probe_number - 1] if temperature is None: return None return temperature def _supported(config: Mapping[str, Any]): return probe_number <= config[CONF_PROBE_COUNT] return ToGrillSensorEntityDescription( key=f"temperature_{probe_number}", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=1, packet_type=PacketA1Notify.type, packet_extract=_get, entity_supported=_supported, probe_number=probe_number, ) def _get_ambient_temperature(packet: Packet) -> StateType: """Extract ambient temperature from packet. The ambient temperature is the last value in the temperatures list when the device has an ambient sensor. """ assert isinstance(packet, PacketA1Notify) if not packet.temperatures: return None # Ambient is always the last temperature value temperature = packet.temperatures[-1] if temperature is None: return None return temperature def _ambient_supported(config: Mapping[str, Any]) -> bool: """Check if ambient sensor is supported.""" return config.get(CONF_HAS_AMBIENT, False) ENTITY_DESCRIPTIONS = ( ToGrillSensorEntityDescription( key="battery", device_class=SensorDeviceClass.BATTERY, native_unit_of_measurement=PERCENTAGE, entity_category=EntityCategory.DIAGNOSTIC, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, packet_type=PacketA0Notify.type, packet_extract=lambda packet: cast(PacketA0Notify, packet).battery, ), *[ _get_temperature_description(probe_number) for probe_number in range(1, MAX_PROBE_COUNT + 1) ], ToGrillSensorEntityDescription( key="ambient_temperature", translation_key="ambient_temperature", device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=1, packet_type=PacketA1Notify.type, packet_extract=_get_ambient_temperature, entity_supported=_ambient_supported, ), ) async def async_setup_entry( hass: HomeAssistant, entry: ToGrillConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up sensor based on a config entry.""" coordinator = entry.runtime_data async_add_entities( ToGrillSensor(coordinator, entity_description) for entity_description in ENTITY_DESCRIPTIONS if entity_description.entity_supported(entry.data) ) class ToGrillSensor(ToGrillEntity, SensorEntity): """Representation of a sensor.""" entity_description: ToGrillSensorEntityDescription def __init__( self, coordinator: ToGrillCoordinator, entity_description: ToGrillSensorEntityDescription, ) -> None: """Initialize sensor.""" super().__init__(coordinator, entity_description.probe_number) self.entity_description = entity_description self._attr_unique_id = f"{coordinator.address}_{entity_description.key}" @property def available(self) -> bool: """Return if entity is available.""" return super().available and self.native_value is not None @property def native_value(self) -> StateType: """Get current value.""" if packet := self.coordinator.data.get( (self.entity_description.packet_type, None) ): return self.entity_description.packet_extract(packet) return None
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/togrill/sensor.py", "license": "Apache License 2.0", "lines": 129, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/tuya/valve.py
"""Support for Tuya valves.""" from __future__ import annotations from tuya_device_handlers.device_wrapper.base import DeviceWrapper from tuya_device_handlers.device_wrapper.common import DPCodeBooleanWrapper from tuya_sharing import CustomerDevice, Manager from homeassistant.components.valve import ( ValveDeviceClass, ValveEntity, ValveEntityDescription, ValveEntityFeature, ) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DeviceCategory, DPCode from .entity import TuyaEntity VALVES: dict[DeviceCategory, tuple[ValveEntityDescription, ...]] = { DeviceCategory.SFKZQ: ( ValveEntityDescription( key=DPCode.SWITCH, translation_key="valve", device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_1, translation_key="indexed_valve", translation_placeholders={"index": "1"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_2, translation_key="indexed_valve", translation_placeholders={"index": "2"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_3, translation_key="indexed_valve", translation_placeholders={"index": "3"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_4, translation_key="indexed_valve", translation_placeholders={"index": "4"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_5, translation_key="indexed_valve", translation_placeholders={"index": "5"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_6, translation_key="indexed_valve", translation_placeholders={"index": "6"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_7, translation_key="indexed_valve", translation_placeholders={"index": "7"}, device_class=ValveDeviceClass.WATER, ), ValveEntityDescription( key=DPCode.SWITCH_8, translation_key="indexed_valve", translation_placeholders={"index": "8"}, device_class=ValveDeviceClass.WATER, ), ), } async def async_setup_entry( hass: HomeAssistant, entry: TuyaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up tuya valves dynamically through tuya discovery.""" manager = entry.runtime_data.manager @callback def async_discover_device(device_ids: list[str]) -> None: """Discover and add a discovered tuya valve.""" entities: list[TuyaValveEntity] = [] for device_id in device_ids: device = manager.device_map[device_id] if descriptions := VALVES.get(device.category): entities.extend( TuyaValveEntity(device, manager, description, dpcode_wrapper) for description in descriptions if ( dpcode_wrapper := DPCodeBooleanWrapper.find_dpcode( device, description.key, prefer_function=True ) ) ) async_add_entities(entities) async_discover_device([*manager.device_map]) entry.async_on_unload( async_dispatcher_connect(hass, TUYA_DISCOVERY_NEW, async_discover_device) ) class TuyaValveEntity(TuyaEntity, ValveEntity): """Tuya Valve Device.""" _attr_supported_features = ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE def __init__( self, device: CustomerDevice, device_manager: Manager, description: ValveEntityDescription, dpcode_wrapper: DeviceWrapper[bool], ) -> None: """Init TuyaValveEntity.""" super().__init__(device, device_manager) self.entity_description = description self._attr_unique_id = f"{super().unique_id}{description.key}" self._dpcode_wrapper = dpcode_wrapper @property def is_closed(self) -> bool | None: """Return if the valve is closed.""" if (is_open := self._read_wrapper(self._dpcode_wrapper)) is None: return None return not is_open async def _process_device_update( self, updated_status_properties: list[str], dp_timestamps: dict[str, int] | None, ) -> bool: """Called when Tuya device sends an update with updated properties. Returns True if the Home Assistant state should be written, or False if the state write should be skipped. """ return not self._dpcode_wrapper.skip_update( self.device, updated_status_properties, dp_timestamps ) async def async_open_valve(self) -> None: """Open the valve.""" await self._async_send_wrapper_updates(self._dpcode_wrapper, True) async def async_close_valve(self) -> None: """Close the valve.""" await self._async_send_wrapper_updates(self._dpcode_wrapper, False)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/tuya/valve.py", "license": "Apache License 2.0", "lines": 141, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/volvo/binary_sensor.py
"""Volvo binary sensors.""" from __future__ import annotations from dataclasses import dataclass, field from volvocarsapi.models import VolvoCarsApiBaseModel, VolvoCarsValue from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import API_NONE_VALUE from .coordinator import VolvoConfigEntry from .entity import VolvoEntity, VolvoEntityDescription PARALLEL_UPDATES = 0 @dataclass(frozen=True, kw_only=True) class VolvoBinarySensorDescription( BinarySensorEntityDescription, VolvoEntityDescription ): """Describes a Volvo binary sensor entity.""" on_values: tuple[str, ...] @dataclass(frozen=True, kw_only=True) class VolvoCarsDoorDescription(VolvoBinarySensorDescription): """Describes a Volvo door entity.""" device_class: BinarySensorDeviceClass = BinarySensorDeviceClass.DOOR on_values: tuple[str, ...] = field(default=("OPEN", "AJAR"), init=False) @dataclass(frozen=True, kw_only=True) class VolvoCarsTireDescription(VolvoBinarySensorDescription): """Describes a Volvo tire entity.""" device_class: BinarySensorDeviceClass = BinarySensorDeviceClass.PROBLEM on_values: tuple[str, ...] = field( default=("VERY_LOW_PRESSURE", "LOW_PRESSURE", "HIGH_PRESSURE"), init=False ) @dataclass(frozen=True, kw_only=True) class VolvoCarsWindowDescription(VolvoBinarySensorDescription): """Describes a Volvo window entity.""" device_class: BinarySensorDeviceClass = BinarySensorDeviceClass.WINDOW on_values: tuple[str, ...] = field(default=("OPEN", "AJAR"), init=False) _DESCRIPTIONS: tuple[VolvoBinarySensorDescription, ...] = ( # brakes endpoint VolvoBinarySensorDescription( key="brake_fluid_level_warning", api_field="brakeFluidLevelWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("TOO_LOW",), ), # warnings endpoint VolvoBinarySensorDescription( key="brake_light_center_warning", api_field="brakeLightCenterWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="brake_light_left_warning", api_field="brakeLightLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="brake_light_right_warning", api_field="brakeLightRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # engine endpoint VolvoBinarySensorDescription( key="coolant_level_warning", api_field="engineCoolantLevelWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("TOO_LOW",), ), # warnings endpoint VolvoBinarySensorDescription( key="daytime_running_light_left_warning", api_field="daytimeRunningLightLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="daytime_running_light_right_warning", api_field="daytimeRunningLightRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # doors endpoint VolvoCarsDoorDescription( key="door_front_left", api_field="frontLeftDoor", ), # doors endpoint VolvoCarsDoorDescription( key="door_front_right", api_field="frontRightDoor", ), # doors endpoint VolvoCarsDoorDescription( key="door_rear_left", api_field="rearLeftDoor", ), # doors endpoint VolvoCarsDoorDescription( key="door_rear_right", api_field="rearRightDoor", ), # engine-status endpoint VolvoBinarySensorDescription( key="engine_status", api_field="engineStatus", device_class=BinarySensorDeviceClass.RUNNING, on_values=("RUNNING",), ), # warnings endpoint VolvoBinarySensorDescription( key="fog_light_front_warning", api_field="fogLightFrontWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="fog_light_rear_warning", api_field="fogLightRearWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="hazard_lights_warning", api_field="hazardLightsWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="high_beam_left_warning", api_field="highBeamLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="high_beam_right_warning", api_field="highBeamRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # doors endpoint VolvoCarsDoorDescription( key="hood", api_field="hood", ), # warnings endpoint VolvoBinarySensorDescription( key="low_beam_left_warning", api_field="lowBeamLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="low_beam_right_warning", api_field="lowBeamRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # engine endpoint VolvoBinarySensorDescription( key="oil_level_warning", api_field="oilLevelWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("SERVICE_REQUIRED", "TOO_LOW", "TOO_HIGH"), ), # position lights VolvoBinarySensorDescription( key="position_light_front_left_warning", api_field="positionLightFrontLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # position lights VolvoBinarySensorDescription( key="position_light_front_right_warning", api_field="positionLightFrontRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # position lights VolvoBinarySensorDescription( key="position_light_rear_left_warning", api_field="positionLightRearLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # position lights VolvoBinarySensorDescription( key="position_light_rear_right_warning", api_field="positionLightRearRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # registration plate light VolvoBinarySensorDescription( key="registration_plate_light_warning", api_field="registrationPlateLightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # reverse lights VolvoBinarySensorDescription( key="reverse_lights_warning", api_field="reverseLightsWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="side_mark_lights_warning", api_field="sideMarkLightsWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # windows endpoint VolvoCarsWindowDescription( key="sunroof", api_field="sunroof", ), # tyres endpoint VolvoCarsTireDescription( key="tire_front_left", api_field="frontLeft", ), # tyres endpoint VolvoCarsTireDescription( key="tire_front_right", api_field="frontRight", ), # tyres endpoint VolvoCarsTireDescription( key="tire_rear_left", api_field="rearLeft", ), # tyres endpoint VolvoCarsTireDescription( key="tire_rear_right", api_field="rearRight", ), # doors endpoint VolvoCarsDoorDescription( key="tailgate", api_field="tailgate", ), # doors endpoint VolvoCarsDoorDescription( key="tank_lid", api_field="tankLid", ), # warnings endpoint VolvoBinarySensorDescription( key="turn_indication_front_left_warning", api_field="turnIndicationFrontLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="turn_indication_front_right_warning", api_field="turnIndicationFrontRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="turn_indication_rear_left_warning", api_field="turnIndicationRearLeftWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # warnings endpoint VolvoBinarySensorDescription( key="turn_indication_rear_right_warning", api_field="turnIndicationRearRightWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("FAILURE",), entity_category=EntityCategory.DIAGNOSTIC, ), # diagnostics endpoint VolvoBinarySensorDescription( key="washer_fluid_level_warning", api_field="washerFluidLevelWarning", device_class=BinarySensorDeviceClass.PROBLEM, on_values=("TOO_LOW",), ), # windows endpoint VolvoCarsWindowDescription( key="window_front_left", api_field="frontLeftWindow", ), # windows endpoint VolvoCarsWindowDescription( key="window_front_right", api_field="frontRightWindow", ), # windows endpoint VolvoCarsWindowDescription( key="window_rear_left", api_field="rearLeftWindow", ), # windows endpoint VolvoCarsWindowDescription( key="window_rear_right", api_field="rearRightWindow", ), ) async def async_setup_entry( hass: HomeAssistant, entry: VolvoConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up binary sensors.""" coordinators = entry.runtime_data.interval_coordinators async_add_entities( VolvoBinarySensor(coordinator, description) for coordinator in coordinators for description in _DESCRIPTIONS if description.api_field in coordinator.data ) class VolvoBinarySensor(VolvoEntity, BinarySensorEntity): """Volvo binary sensor.""" entity_description: VolvoBinarySensorDescription def _update_state(self, api_field: VolvoCarsApiBaseModel | None) -> None: """Update the state of the entity.""" if api_field is None: self._attr_is_on = None return assert isinstance(api_field, VolvoCarsValue) assert isinstance(api_field.value, str) value = api_field.value self._attr_is_on = ( value in self.entity_description.on_values if value.upper() != API_NONE_VALUE else None )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/volvo/binary_sensor.py", "license": "Apache License 2.0", "lines": 369, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/waze_travel_time/coordinator.py
"""The Waze Travel Time data coordinator.""" import asyncio from collections.abc import Collection from dataclasses import dataclass from datetime import timedelta import logging from typing import Literal from pywaze.route_calculator import CalcRoutesResponse, WazeRouteCalculator, WRCError from homeassistant.config_entries import ConfigEntry from homeassistant.const import UnitOfLength from homeassistant.core import HomeAssistant from homeassistant.helpers.location import find_coordinates from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util.unit_conversion import DistanceConverter from .const import ( CONF_AVOID_FERRIES, CONF_AVOID_SUBSCRIPTION_ROADS, CONF_AVOID_TOLL_ROADS, CONF_DESTINATION, CONF_EXCL_FILTER, CONF_INCL_FILTER, CONF_ORIGIN, CONF_REALTIME, CONF_TIME_DELTA, CONF_UNITS, CONF_VEHICLE_TYPE, DOMAIN, IMPERIAL_UNITS, SEMAPHORE, ) _LOGGER = logging.getLogger(__name__) SCAN_INTERVAL = timedelta(minutes=5) SECONDS_BETWEEN_API_CALLS = 0.5 async def async_get_travel_times( client: WazeRouteCalculator, origin: str, destination: str, vehicle_type: str, avoid_toll_roads: bool, avoid_subscription_roads: bool, avoid_ferries: bool, realtime: bool, units: Literal["metric", "imperial"] = "metric", incl_filters: Collection[str] | None = None, excl_filters: Collection[str] | None = None, time_delta: int = 0, ) -> list[CalcRoutesResponse]: """Get all available routes.""" incl_filters = incl_filters or () excl_filters = excl_filters or () _LOGGER.debug( "Getting update for origin: %s destination: %s", origin, destination, ) routes = [] vehicle_type = "" if vehicle_type.upper() == "CAR" else vehicle_type.upper() try: routes = await client.calc_routes( origin, destination, vehicle_type=vehicle_type, avoid_toll_roads=avoid_toll_roads, avoid_subscription_roads=avoid_subscription_roads, avoid_ferries=avoid_ferries, real_time=realtime, alternatives=3, time_delta=time_delta, ) if len(routes) < 1: _LOGGER.warning("No routes found") return routes _LOGGER.debug("Got routes: %s", routes) incl_routes: list[CalcRoutesResponse] = [] def should_include_route(route: CalcRoutesResponse) -> bool: if len(incl_filters) < 1: return True should_include = any( street_name in incl_filters or "" in incl_filters for street_name in route.street_names ) if not should_include: _LOGGER.debug( "Excluding route [%s], because no inclusive filter matched any streetname", route.name, ) return False return True incl_routes = [route for route in routes if should_include_route(route)] filtered_routes: list[CalcRoutesResponse] = [] def should_exclude_route(route: CalcRoutesResponse) -> bool: for street_name in route.street_names: for excl_filter in excl_filters: if excl_filter == street_name: _LOGGER.debug( "Excluding route, because exclusive filter [%s] matched streetname: %s", excl_filter, route.name, ) return True return False filtered_routes = [ route for route in incl_routes if not should_exclude_route(route) ] if len(filtered_routes) < 1: _LOGGER.warning("No routes matched your filters") return filtered_routes if units == IMPERIAL_UNITS: filtered_routes = [ CalcRoutesResponse( name=route.name, distance=DistanceConverter.convert( route.distance, UnitOfLength.KILOMETERS, UnitOfLength.MILES ), duration=route.duration, street_names=route.street_names, ) for route in filtered_routes if route.distance is not None ] except WRCError as exp: raise UpdateFailed(f"Error on retrieving data: {exp}") from exp else: return filtered_routes @dataclass class WazeTravelTimeData: """WazeTravelTime data class.""" origin: str destination: str duration: float | None distance: float | None route: str | None class WazeTravelTimeCoordinator(DataUpdateCoordinator[WazeTravelTimeData]): """Waze Travel Time DataUpdateCoordinator.""" config_entry: ConfigEntry def __init__( self, hass: HomeAssistant, config_entry: ConfigEntry, client: WazeRouteCalculator, ) -> None: """Initialize.""" super().__init__( hass, _LOGGER, name=DOMAIN, config_entry=config_entry, update_interval=SCAN_INTERVAL, ) self.client = client self._origin = config_entry.data[CONF_ORIGIN] self._destination = config_entry.data[CONF_DESTINATION] async def _async_update_data(self) -> WazeTravelTimeData: """Get the latest data from Waze.""" origin_coordinates = find_coordinates(self.hass, self._origin) destination_coordinates = find_coordinates(self.hass, self._destination) _LOGGER.debug( "Fetching Route for %s, from %s to %s", self.config_entry.title, self._origin, self._destination, ) await self.hass.data[DOMAIN][SEMAPHORE].acquire() try: if origin_coordinates is None or destination_coordinates is None: raise UpdateFailed("Unable to determine origin or destination") # Grab options on every update incl_filter = self.config_entry.options[CONF_INCL_FILTER] excl_filter = self.config_entry.options[CONF_EXCL_FILTER] realtime = self.config_entry.options[CONF_REALTIME] vehicle_type = self.config_entry.options[CONF_VEHICLE_TYPE] avoid_toll_roads = self.config_entry.options[CONF_AVOID_TOLL_ROADS] avoid_subscription_roads = self.config_entry.options[ CONF_AVOID_SUBSCRIPTION_ROADS ] avoid_ferries = self.config_entry.options[CONF_AVOID_FERRIES] time_delta = int( timedelta(**self.config_entry.options[CONF_TIME_DELTA]).total_seconds() / 60 ) routes = await async_get_travel_times( self.client, origin_coordinates, destination_coordinates, vehicle_type, avoid_toll_roads, avoid_subscription_roads, avoid_ferries, realtime, self.config_entry.options[CONF_UNITS], incl_filter, excl_filter, time_delta, ) if len(routes) < 1: travel_data = WazeTravelTimeData( origin=origin_coordinates, destination=destination_coordinates, duration=None, distance=None, route=None, ) else: route = routes[0] travel_data = WazeTravelTimeData( origin=origin_coordinates, destination=destination_coordinates, duration=route.duration, distance=route.distance, route=route.name, ) await asyncio.sleep(SECONDS_BETWEEN_API_CALLS) finally: self.hass.data[DOMAIN][SEMAPHORE].release() return travel_data
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/waze_travel_time/coordinator.py", "license": "Apache License 2.0", "lines": 215, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/workday/entity.py
"""Base workday entity.""" from __future__ import annotations from abc import abstractmethod from datetime import date, datetime, timedelta from holidays import HolidayBase, __version__ as python_holidays_version from homeassistant.core import CALLBACK_TYPE, ServiceResponse, callback from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity import Entity from homeassistant.helpers.event import async_track_point_in_utc_time from homeassistant.util import dt as dt_util from .const import ALLOWED_DAYS, DOMAIN class BaseWorkdayEntity(Entity): """Implementation of a base Workday entity.""" _attr_has_entity_name = True _attr_translation_key = DOMAIN _attr_should_poll = False unsub: CALLBACK_TYPE | None = None def __init__( self, obj_holidays: HolidayBase, workdays: list[str], excludes: list[str], days_offset: int, name: str, entry_id: str, ) -> None: """Initialize the Workday entity.""" self._obj_holidays = obj_holidays self._workdays = workdays self._excludes = excludes self._days_offset = days_offset self._attr_unique_id = entry_id self._attr_device_info = DeviceInfo( entry_type=DeviceEntryType.SERVICE, identifiers={(DOMAIN, entry_id)}, manufacturer="python-holidays", model=python_holidays_version, name=name, ) def is_include(self, day: str, now: date) -> bool: """Check if given day is in the includes list.""" if day in self._workdays: return True if "holiday" in self._workdays and now in self._obj_holidays: return True return False def is_exclude(self, day: str, now: date) -> bool: """Check if given day is in the excludes list.""" if day in self._excludes: return True if "holiday" in self._excludes and now in self._obj_holidays: return True return False def get_next_interval(self, now: datetime) -> datetime: """Compute next time an update should occur.""" tomorrow = dt_util.as_local(now) + timedelta(days=1) return dt_util.start_of_local_day(tomorrow) def _update_state_and_setup_listener(self) -> None: """Update state and setup listener for next interval.""" now = dt_util.now() self.update_data(now) self.unsub = async_track_point_in_utc_time( self.hass, self.point_in_time_listener, self.get_next_interval(now) ) @callback def point_in_time_listener(self, time_date: datetime) -> None: """Get the latest data and update state.""" self._update_state_and_setup_listener() self.async_write_ha_state() async def async_added_to_hass(self) -> None: """Set up first update.""" self._update_state_and_setup_listener() @abstractmethod def update_data(self, now: datetime) -> None: """Update data.""" def check_date(self, check_date: date) -> ServiceResponse: """Service to check if date is workday or not.""" return {"workday": self.date_is_workday(check_date)} def date_is_workday(self, check_date: date) -> bool: """Check if date is workday.""" # Default is no workday is_workday = False # Get ISO day of the week (1 = Monday, 7 = Sunday) adjusted_date = check_date + timedelta(days=self._days_offset) day = adjusted_date.isoweekday() - 1 day_of_week = ALLOWED_DAYS[day] if self.is_include(day_of_week, adjusted_date): is_workday = True if self.is_exclude(day_of_week, adjusted_date): is_workday = False return is_workday
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/workday/entity.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/workday/util.py
"""Helpers functions for the Workday component.""" from __future__ import annotations from datetime import date, timedelta from functools import partial from typing import TYPE_CHECKING from holidays import PUBLIC, DateLike, HolidayBase, country_holidays from homeassistant.const import CONF_COUNTRY from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryError from homeassistant.helpers.issue_registry import IssueSeverity, async_create_issue from homeassistant.setup import SetupPhases, async_pause_setup from homeassistant.util import dt as dt_util, slugify if TYPE_CHECKING: from . import WorkdayConfigEntry from .const import CONF_REMOVE_HOLIDAYS, DOMAIN, LOGGER async def async_validate_country_and_province( hass: HomeAssistant, entry: WorkdayConfigEntry, country: str | None, province: str | None, ) -> None: """Validate country and province.""" if not country: return try: with async_pause_setup(hass, SetupPhases.WAIT_IMPORT_PACKAGES): # import executor job is used here because multiple integrations use # the holidays library and it is not thread safe to import it in parallel # https://github.com/python/cpython/issues/83065 await hass.async_add_import_executor_job(country_holidays, country) except NotImplementedError as ex: async_create_issue( hass, DOMAIN, "bad_country", is_fixable=True, is_persistent=False, severity=IssueSeverity.ERROR, translation_key="bad_country", translation_placeholders={"title": entry.title}, data={"entry_id": entry.entry_id, "country": None}, ) raise ConfigEntryError(f"Selected country {country} is not valid") from ex if not province: return try: with async_pause_setup(hass, SetupPhases.WAIT_IMPORT_PACKAGES): # import executor job is used here because multiple integrations use # the holidays library and it is not thread safe to import it in parallel # https://github.com/python/cpython/issues/83065 await hass.async_add_import_executor_job( partial(country_holidays, country, subdiv=province) ) except NotImplementedError as ex: async_create_issue( hass, DOMAIN, "bad_province", is_fixable=True, is_persistent=False, severity=IssueSeverity.ERROR, translation_key="bad_province", translation_placeholders={ CONF_COUNTRY: country, "title": entry.title, }, data={"entry_id": entry.entry_id, "country": country}, ) raise ConfigEntryError( f"Selected province {province} for country {country} is not valid" ) from ex def validate_dates(holiday_list: list[str]) -> list[str]: """Validate and add to list of dates to add or remove.""" calc_holidays: list[str] = [] for add_date in holiday_list: if add_date.find(",") > 0: dates = add_date.split(",", maxsplit=1) d1 = dt_util.parse_date(dates[0]) d2 = dt_util.parse_date(dates[1]) if d1 is None or d2 is None: LOGGER.error("Incorrect dates in date range: %s", add_date) continue _range: timedelta = d2 - d1 for i in range(_range.days + 1): day: date = d1 + timedelta(days=i) calc_holidays.append(day.strftime("%Y-%m-%d")) continue calc_holidays.append(add_date) return calc_holidays def get_holidays_object( country: str | None, province: str | None, year: int, language: str | None, categories: list[str] | None, ) -> HolidayBase: """Get the object for the requested country and year.""" if not country: return HolidayBase() set_categories = None if categories: category_list = [PUBLIC] category_list.extend(categories) set_categories = tuple(category_list) obj_holidays: HolidayBase = country_holidays( country, subdiv=province, years=[year, year + 1], language=language, categories=set_categories, ) supported_languages = obj_holidays.supported_languages default_language = obj_holidays.default_language if default_language and not language: # If no language is set, use the default language LOGGER.debug("Changing language from None to %s", default_language) return country_holidays( # Return default if no language country, subdiv=province, years=year, language=default_language, categories=set_categories, ) if ( default_language and language and language not in supported_languages and language.startswith("en") ): # If language does not match supported languages, use the first English variant if default_language.startswith("en"): LOGGER.debug("Changing language from %s to %s", language, default_language) return country_holidays( # Return default English if default language country, subdiv=province, years=year, language=default_language, categories=set_categories, ) for lang in supported_languages: if lang.startswith("en"): LOGGER.debug("Changing language from %s to %s", language, lang) return country_holidays( country, subdiv=province, years=year, language=lang, categories=set_categories, ) if default_language and language and language not in supported_languages: # If language does not match supported languages, use the default language LOGGER.debug("Changing language from %s to %s", language, default_language) return country_holidays( # Return default English if default language country, subdiv=province, years=year, language=default_language, categories=set_categories, ) return obj_holidays def add_remove_custom_holidays( hass: HomeAssistant, entry: WorkdayConfigEntry, country: str | None, calc_add_holidays: list[DateLike], calc_remove_holidays: list[str], ) -> None: """Add or remove custom holidays.""" next_year = dt_util.now().year + 1 # Add custom holidays try: entry.runtime_data.append(calc_add_holidays) except ValueError as error: LOGGER.error("Could not add custom holidays: %s", error) # Remove custom holidays for remove_holiday in calc_remove_holidays: try: # is this formatted as a date? if dt_util.parse_date(remove_holiday): # remove holiday by date removed = entry.runtime_data.pop(remove_holiday) LOGGER.debug("Removed %s", remove_holiday) else: # remove holiday by name LOGGER.debug("Treating '%s' as named holiday", remove_holiday) removed = entry.runtime_data.pop_named(remove_holiday) for holiday in removed: LOGGER.debug("Removed %s by name '%s'", holiday, remove_holiday) except KeyError as unmatched: LOGGER.warning("No holiday found matching %s", unmatched) if _date := dt_util.parse_date(remove_holiday): if _date.year <= next_year: # Only check and raise issues for max next year async_create_issue( hass, DOMAIN, f"bad_date_holiday-{entry.entry_id}-{slugify(remove_holiday)}", is_fixable=True, is_persistent=False, severity=IssueSeverity.WARNING, translation_key="bad_date_holiday", translation_placeholders={ CONF_COUNTRY: country or "-", "title": entry.title, CONF_REMOVE_HOLIDAYS: remove_holiday, }, data={ "entry_id": entry.entry_id, "country": country, "named_holiday": remove_holiday, }, ) else: async_create_issue( hass, DOMAIN, f"bad_named_holiday-{entry.entry_id}-{slugify(remove_holiday)}", is_fixable=True, is_persistent=False, severity=IssueSeverity.WARNING, translation_key="bad_named_holiday", translation_placeholders={ CONF_COUNTRY: country or "-", "title": entry.title, CONF_REMOVE_HOLIDAYS: remove_holiday, }, data={ "entry_id": entry.entry_id, "country": country, "named_holiday": remove_holiday, }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/workday/util.py", "license": "Apache License 2.0", "lines": 232, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/yalexs_ble/config_cache.py
"""The Yale Access Bluetooth integration.""" from __future__ import annotations from yalexs_ble import ValidatedLockConfig from homeassistant.core import HomeAssistant, callback from homeassistant.util.hass_dict import HassKey CONFIG_CACHE: HassKey[dict[str, ValidatedLockConfig]] = HassKey( "yalexs_ble_config_cache" ) @callback def async_add_validated_config( hass: HomeAssistant, address: str, config: ValidatedLockConfig, ) -> None: """Add a validated config.""" hass.data.setdefault(CONFIG_CACHE, {})[address] = config @callback def async_get_validated_config( hass: HomeAssistant, address: str, ) -> ValidatedLockConfig | None: """Get the config for a specific address.""" return hass.data.get(CONFIG_CACHE, {}).get(address)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/yalexs_ble/config_cache.py", "license": "Apache License 2.0", "lines": 23, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/yolink/select.py
"""YoLink select platform.""" from __future__ import annotations from collections.abc import Awaitable, Callable from dataclasses import dataclass from typing import Any from yolink.client_request import ClientRequest from yolink.const import ATTR_DEVICE_SPRINKLER from yolink.device import YoLinkDevice from yolink.message_resolver import sprinkler_message_resolve from homeassistant.components.select import SelectEntity, SelectEntityDescription from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import YoLinkCoordinator from .entity import YoLinkEntity @dataclass(frozen=True, kw_only=True) class YoLinkSelectEntityDescription(SelectEntityDescription): """YoLink SelectEntityDescription.""" state_key: str = "state" exists_fn: Callable[[YoLinkDevice], bool] = lambda _: True should_update_entity: Callable = lambda state: True value: Callable = lambda data: data on_option_selected: Callable[[YoLinkCoordinator, str], Awaitable[bool]] async def set_sprinker_mode_fn(coordinator: YoLinkCoordinator, option: str) -> bool: """Set sprinkler mode.""" data: dict[str, Any] = await coordinator.call_device( ClientRequest( "setState", { "state": { "mode": option, } }, ) ) sprinkler_message_resolve(coordinator.device, data, None) coordinator.async_set_updated_data(data) return True SELECTOR_MAPPINGS: tuple[YoLinkSelectEntityDescription, ...] = ( YoLinkSelectEntityDescription( key="model", options=["auto", "manual", "off"], translation_key="sprinkler_mode", value=lambda data: ( data.get("mode") if data is not None else None ), # watering state report will missing state field exists_fn=lambda device: device.device_type == ATTR_DEVICE_SPRINKLER, should_update_entity=lambda value: value is not None, on_option_selected=set_sprinker_mode_fn, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up YoLink select from a config entry.""" device_coordinators = hass.data[DOMAIN][config_entry.entry_id].device_coordinators async_add_entities( YoLinkSelectEntity(config_entry, selector_device_coordinator, description) for selector_device_coordinator in device_coordinators.values() if selector_device_coordinator.device.device_type == ATTR_DEVICE_SPRINKLER for description in SELECTOR_MAPPINGS if description.exists_fn(selector_device_coordinator.device) ) class YoLinkSelectEntity(YoLinkEntity, SelectEntity): """YoLink Select Entity.""" entity_description: YoLinkSelectEntityDescription def __init__( self, config_entry: ConfigEntry, coordinator: YoLinkCoordinator, description: YoLinkSelectEntityDescription, ) -> None: """Init YoLink Select.""" super().__init__(config_entry, coordinator) self.entity_description = description self._attr_unique_id = ( f"{coordinator.device.device_id} {self.entity_description.key}" ) @callback def update_entity_state(self, state: dict[str, Any]) -> None: """Update HA Entity State.""" if ( current_value := self.entity_description.value( state.get(self.entity_description.state_key) ) ) is None and self.entity_description.should_update_entity( current_value ) is False: return self._attr_current_option = current_value self.async_write_ha_state() async def async_select_option(self, option: str) -> None: """Change the selected option.""" if await self.entity_description.on_option_selected(self.coordinator, option): self._attr_current_option = option self.async_write_ha_state()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/yolink/select.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/helpers/automation.py
"""Helpers for automation.""" from typing import Any import voluptuous as vol from homeassistant.const import CONF_OPTIONS from .typing import ConfigType def get_absolute_description_key(domain: str, key: str) -> str: """Return the absolute description key.""" if not key.startswith("_"): return f"{domain}.{key}" key = key[1:] # Remove leading underscore if not key: return domain return key def get_relative_description_key(domain: str, key: str) -> str: """Return the relative description key.""" platform, *subtype = key.split(".", 1) if platform != domain: return f"_{key}" if not subtype: return "_" return subtype[0] def move_top_level_schema_fields_to_options( config: ConfigType, options_schema_dict: dict[vol.Marker, Any] ) -> ConfigType: """Move top-level fields to options. This function is used to help migrating old-style configs to new-style configs for triggers and conditions. If options is already present, the config is returned as-is. """ if CONF_OPTIONS in config: return config config = config.copy() options = config.setdefault(CONF_OPTIONS, {}) # Move top-level fields to options for key_marked in options_schema_dict: key = key_marked.schema if key in config: options[key] = config.pop(key) return config def move_options_fields_to_top_level( config: ConfigType, base_schema: vol.Schema ) -> ConfigType: """Move options fields to top-level. This function is used to provide backwards compatibility for new-style configs for triggers and conditions. The config is returned as-is, if any of the following is true: - options is not present - options is not a dict - the config with options field removed fails the base_schema validation (most likely due to additional keys being present) Those conditions are checked to make it so that only configs that have the structure of the new-style are modified, whereas valid old-style configs are preserved. """ options = config.get(CONF_OPTIONS) if not isinstance(options, dict): return config new_config: ConfigType = config.copy() new_config.pop(CONF_OPTIONS) try: new_config = base_schema(new_config) except vol.Invalid: return config new_config.update(options) return new_config
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/helpers/automation.py", "license": "Apache License 2.0", "lines": 64, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:pylint/plugins/hass_enforce_greek_micro_char.py
"""Plugin for checking preferred coding of μ is used.""" from __future__ import annotations from typing import Any from astroid import nodes from pylint.checkers import BaseChecker from pylint.lint import PyLinter class HassEnforceGreekMicroCharChecker(BaseChecker): """Checker for micro char.""" name = "hass-enforce-greek-micro-char" priority = -1 msgs = { "W7452": ( "Constants with a micro unit prefix must encode the " "small Greek Letter Mu as U+03BC (\u03bc), not as U+00B5 (\u00b5)", "hass-enforce-greek-micro-char", "According to [The Unicode Consortium]" "(https://en.wikipedia.org/wiki/Micro-#Symbol_encoding_in_character_sets)," " the Greek letter character is preferred. " "To search a specific encoded μ char in Microsoft Visual Studio Code, " 'make sure the "Match case" option is enabled. Note that this only works ' "when searching globally, and not while searching a single document.", ), } options = () def visit_annassign(self, node: nodes.AnnAssign) -> None: """Check for micro char const or StrEnum with type annotations.""" self._do_micro_check(node.target, node) def visit_assign(self, node: nodes.Assign) -> None: """Check for micro char const without type annotations.""" for target in node.targets: self._do_micro_check(target, node) def _do_micro_check( self, target: nodes.NodeNG, node: nodes.Assign | nodes.AnnAssign ) -> None: """Check const assignment is not containing ANSI micro char.""" def _check_const(node_const: nodes.Const | Any) -> bool: if ( isinstance(node_const, nodes.Const) and isinstance(node_const.value, str) and "\u00b5" in node_const.value ): self.add_message(self.name, node=node) return True return False # Check constant assignments if ( isinstance(target, nodes.AssignName) and isinstance(node.value, nodes.Const) and _check_const(node.value) ): return # Check dict with EntityDescription calls if isinstance(target, nodes.AssignName) and isinstance(node.value, nodes.Dict): for _, subnode in node.value.items: if not isinstance(subnode, nodes.Call): continue for keyword in subnode.keywords: if _check_const(keyword.value): return def register(linter: PyLinter) -> None: """Register the checker.""" linter.register_checker(HassEnforceGreekMicroCharChecker(linter))
{ "repo_id": "home-assistant/core", "file_path": "pylint/plugins/hass_enforce_greek_micro_char.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:tests/components/ai_task/test_media_source.py
"""Test ai_task media source.""" import pytest from homeassistant.components import media_source from homeassistant.components.ai_task.media_source import async_get_media_source from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError async def test_local_media_source(hass: HomeAssistant, init_components: None) -> None: """Test that the image media source is created.""" item = await media_source.async_browse_media(hass, "media-source://") assert any(c.title == "AI Generated Images" for c in item.children) source = await async_get_media_source(hass) assert isinstance(source, media_source.local_source.LocalSource) assert source.name == "AI Generated Images" assert source.domain == "ai_task" assert list(source.media_dirs) == ["image"] # Depending on Docker, the default is one of the two paths assert source.media_dirs["image"] in ( "/media/ai_task/image", hass.config.path("media/ai_task/image"), ) assert source.url_prefix == "/ai_task" hass.config.media_dirs = {} with pytest.raises( HomeAssistantError, match="AI Task media source requires at least one media directory configured", ): await async_get_media_source(hass)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/ai_task/test_media_source.py", "license": "Apache License 2.0", "lines": 27, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airos/test_binary_sensor.py
"""Test the Ubiquiti airOS binary sensors.""" from unittest.mock import AsyncMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.parametrize( ("ap_fixture"), [ "airos_loco5ac_ap-ptp.json", # v8 ptp "airos_liteapgps_ap_ptmp_40mhz.json", # v8 ptmp "airos_NanoStation_loco_M5_v6.3.16_XM_sta.json", # v6 XM (different login process) "airos_NanoStation_M5_sta_v6.3.16.json", # v6 XW ], indirect=True, ) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_all_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, mock_airos_client: AsyncMock, mock_async_get_firmware_data: AsyncMock, ) -> None: """Test all entities.""" await setup_integration(hass, mock_config_entry, [Platform.BINARY_SENSOR]) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airos/test_binary_sensor.py", "license": "Apache License 2.0", "lines": 31, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airq/common.py
"""Common methods used across tests for air-Q.""" from aioairq import DeviceInfo from homeassistant.const import CONF_IP_ADDRESS, CONF_PASSWORD TEST_USER_DATA = { CONF_IP_ADDRESS: "192.168.0.0", CONF_PASSWORD: "password", } TEST_DEVICE_INFO = DeviceInfo( id="id", name="name", model="model", sw_version="sw", hw_version="hw", ) TEST_DEVICE_DATA = {"co2": 500.0, "Status": "OK"} TEST_BRIGHTNESS = 42
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airq/common.py", "license": "Apache License 2.0", "lines": 16, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/airq/test_number.py
"""Test the NUMBER platform from air-Q integration.""" from unittest.mock import AsyncMock import pytest from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from . import setup_platform from .common import TEST_BRIGHTNESS, TEST_DEVICE_INFO ENTITY_ID = f"number.{TEST_DEVICE_INFO['name']}_led_brightness" @pytest.fixture(autouse=True) async def number_platform(hass: HomeAssistant, mock_airq: AsyncMock) -> None: """Configure AirQ integration and validate the setup for NUMBER platform.""" await setup_platform(hass, Platform.NUMBER) # Validate the setup state = hass.states.get(ENTITY_ID) assert state is not None, ( f"{ENTITY_ID} not found among {hass.states.async_entity_ids()}" ) assert float(state.state) == TEST_BRIGHTNESS @pytest.mark.parametrize("new_brightness", [0, 100, (TEST_BRIGHTNESS + 10) % 100]) async def test_number_set_value( hass: HomeAssistant, mock_airq: AsyncMock, new_brightness ) -> None: """Test that setting value works.""" # Simulate the device confirming the new brightness on the next poll mock_airq.get_current_brightness.return_value = new_brightness await hass.services.async_call( "number", "set_value", {"entity_id": ENTITY_ID, "value": new_brightness}, blocking=True, ) await hass.async_block_till_done() # Verify the API methods were called correctly mock_airq.set_current_brightness.assert_called_once_with(new_brightness) # Validate that the update propagated to the state state = hass.states.get(ENTITY_ID) assert state is not None, ( f"{ENTITY_ID} not found among {hass.states.async_entity_ids()}" ) assert float(state.state) == new_brightness @pytest.mark.parametrize("new_brightness", [-1, 110]) async def test_number_set_invalid_value_caught_by_hass( hass: HomeAssistant, mock_airq: AsyncMock, new_brightness ) -> None: """Test that setting incorrect values errors.""" with pytest.raises(ServiceValidationError): await hass.services.async_call( "number", "set_value", {"entity_id": ENTITY_ID, "value": new_brightness}, blocking=True, ) mock_airq.set_current_brightness.assert_not_called()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/airq/test_number.py", "license": "Apache License 2.0", "lines": 54, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/asuswrt/test_helpers.py
"""Tests for AsusWRT helpers.""" from typing import Any import pytest from homeassistant.components.asuswrt.helpers import clean_dict, translate_to_legacy DICT_TO_CLEAN = { "key1": "value1", "key2": None, "key3_state": "value3", "key4_state": None, "state": None, } DICT_CLEAN = { "key1": "value1", "key3_state": "value3", "key4_state": None, "state": None, } TRANSLATE_0_INPUT = { "usage": "value1", "cpu": "value2", } TRANSLATE_0_OUTPUT = { "mem_usage_perc": "value1", "CPU": "value2", } TRANSLATE_1_INPUT = { "wan_rx": "value1", "wan_rrx": "value2", } TRANSLATE_1_OUTPUT = { "sensor_rx_bytes": "value1", "wan_rrx": "value2", } TRANSLATE_2_INPUT = [ "free", "used", ] TRANSLATE_2_OUTPUT = [ "mem_free", "mem_used", ] TRANSLATE_3_INPUT = [ "2ghz", "2ghz2", ] TRANSLATE_3_OUTPUT = [ "2.4GHz", "2ghz2", ] def test_clean_dict() -> None: """Test clean_dict method.""" assert clean_dict(DICT_TO_CLEAN) == DICT_CLEAN @pytest.mark.parametrize( ("input", "expected"), [ # Case set 0: None as input -> None on output (None, None), # Case set 1: Dict structure should stay intact or translated ({"key1": "value1", "key2": None}, {"key1": "value1", "key2": None}), (TRANSLATE_0_INPUT, TRANSLATE_0_OUTPUT), (TRANSLATE_1_INPUT, TRANSLATE_1_OUTPUT), ({}, {}), # Case set 2: List structure should stay intact or translated (["key1", "key2"], ["key1", "key2"]), (TRANSLATE_2_INPUT, TRANSLATE_2_OUTPUT), (TRANSLATE_3_INPUT, TRANSLATE_3_OUTPUT), ([], []), # Case set 3: Anything else should be simply returned (123, 123), ("string", "string"), (3.1415926535, 3.1415926535), ], ) def test_translate(input: Any, expected: Any) -> None: """Test translate method.""" assert translate_to_legacy(input) == expected
{ "repo_id": "home-assistant/core", "file_path": "tests/components/asuswrt/test_helpers.py", "license": "Apache License 2.0", "lines": 76, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/bayesian/test_config_flow.py
"""Test the Config flow for the Bayesian integration.""" from __future__ import annotations from types import MappingProxyType from unittest.mock import patch import pytest import voluptuous as vol from homeassistant import config_entries from homeassistant.components.bayesian.config_flow import ( OBSERVATION_SELECTOR, USER, ObservationTypes, OptionsFlowSteps, ) from homeassistant.components.bayesian.const import ( CONF_P_GIVEN_F, CONF_P_GIVEN_T, CONF_PRIOR, CONF_PROBABILITY_THRESHOLD, CONF_TO_STATE, DOMAIN, ) from homeassistant.config_entries import ( ConfigEntry, ConfigSubentry, ConfigSubentryDataWithId, ) from homeassistant.const import ( CONF_ABOVE, CONF_BELOW, CONF_DEVICE_CLASS, CONF_ENTITY_ID, CONF_NAME, CONF_PLATFORM, CONF_STATE, CONF_VALUE_TEMPLATE, ) from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry async def test_config_flow_step_user(hass: HomeAssistant) -> None: """Test the config flow with an example.""" with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ): # Open config flow result0 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result0["step_id"] == USER assert result0["type"] is FlowResultType.FORM assert ( result0["description_placeholders"]["url"] == "https://www.home-assistant.io/integrations/bayesian/" ) # Enter basic settings result1 = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 15, CONF_DEVICE_CLASS: "occupancy", }, ) await hass.async_block_till_done() # We move on to the next step - the observation selector assert result1["step_id"] == OBSERVATION_SELECTOR assert result1["type"] is FlowResultType.MENU assert result1["flow_id"] is not None async def test_subentry_flow(hass: HomeAssistant) -> None: """Test the subentry flow with a full example.""" with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ) as mock_setup_entry: # Set up the initial config entry as a mock to isolate testing of subentry flows config_entry = MockConfigEntry( domain=DOMAIN, data={ CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 15, CONF_DEVICE_CLASS: "occupancy", }, ) config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() # Open subentry flow result = await hass.config_entries.subentries.async_init( (config_entry.entry_id, "observation"), context={"source": config_entries.SOURCE_USER}, ) # Confirm the next page is the observation type selector assert result["step_id"] == "user" assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # Set up a numeric state observation first result = await hass.config_entries.subentries.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.NUMERIC_STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.NUMERIC_STATE) assert result["type"] is FlowResultType.FORM # Set up a numeric range with only 'Above' # Also indirectly tests the conversion of proabilities to fractions result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 85, CONF_P_GIVEN_F: 45, CONF_NAME: "Office is bright", }, ) await hass.async_block_till_done() # Open another subentry flow result = await hass.config_entries.subentries.async_init( (config_entry.entry_id, "observation"), context={"source": config_entries.SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # Add a state observation result = await hass.config_entries.subentries.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.STATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 60, CONF_P_GIVEN_F: 20, CONF_NAME: "Work laptop on network", }, ) await hass.async_block_till_done() # Open another subentry flow result = await hass.config_entries.subentries.async_init( (config_entry.entry_id, "observation"), context={"source": config_entries.SOURCE_USER}, ) assert result["step_id"] == "user" assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # Lastly, add a template observation result = await hass.config_entries.subentries.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.TEMPLATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.TEMPLATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_VALUE_TEMPLATE: """ {% set current_time = now().time() %} {% set start_time = strptime("07:00", "%H:%M").time() %} {% set end_time = strptime("18:30", "%H:%M").time() %} {% if start_time <= current_time <= end_time %} True {% else %} False {% endif %} """, CONF_P_GIVEN_T: 45, CONF_P_GIVEN_F: 5, CONF_NAME: "Daylight hours", }, ) observations = [ dict(subentry.data) for subentry in config_entry.subentries.values() ] # assert config_entry["version"] == 1 assert observations == [ { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 0.85, CONF_P_GIVEN_F: 0.45, CONF_NAME: "Office is bright", }, { CONF_PLATFORM: str(ObservationTypes.STATE), CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.6, CONF_P_GIVEN_F: 0.2, CONF_NAME: "Work laptop on network", }, { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: '{% set current_time = now().time() %}\n{% set start_time = strptime("07:00", "%H:%M").time() %}\n{% set end_time = strptime("18:30", "%H:%M").time() %}\n{% if start_time <= current_time <= end_time %}\nTrue\n{% else %}\nFalse\n{% endif %}', CONF_P_GIVEN_T: 0.45, CONF_P_GIVEN_F: 0.05, CONF_NAME: "Daylight hours", }, ] assert len(mock_setup_entry.mock_calls) == 1 async def test_single_state_observation(hass: HomeAssistant) -> None: """Test a Bayesian sensor with just one state observation added. This test combines the config flow for a single state observation. """ with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["step_id"] == USER assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_NAME: "Anyone home", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 66, CONF_DEVICE_CLASS: "occupancy", }, ) await hass.async_block_till_done() # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None assert result["menu_options"] == ["state", "numeric_state", "template"] result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.STATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.kitchen_occupancy", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 40, CONF_P_GIVEN_F: 0.5, CONF_NAME: "Kitchen Motion", }, ) assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None assert result["menu_options"] == [ "state", "numeric_state", "template", "finish", ] result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": "finish"} ) await hass.async_block_till_done() entry_id = result["result"].entry_id config_entry = hass.config_entries.async_get_entry(entry_id) assert config_entry is not None assert type(config_entry) is ConfigEntry assert config_entry.version == 1 assert config_entry.options == { CONF_NAME: "Anyone home", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.66, CONF_DEVICE_CLASS: "occupancy", } assert len(config_entry.subentries) == 1 assert list(config_entry.subentries.values())[0].data == { CONF_PLATFORM: CONF_STATE, CONF_ENTITY_ID: "sensor.kitchen_occupancy", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.4, CONF_P_GIVEN_F: 0.005, CONF_NAME: "Kitchen Motion", } assert len(mock_setup_entry.mock_calls) == 1 async def test_single_numeric_state_observation(hass: HomeAssistant) -> None: """Test a Bayesian sensor with just one numeric_state observation added. Combines the config flow and the options flow for a single numeric_state observation. """ with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["step_id"] == USER assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_NAME: "Nice day", CONF_PROBABILITY_THRESHOLD: 51, CONF_PRIOR: 20, }, ) await hass.async_block_till_done() # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # select numeric state observation result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.NUMERIC_STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.NUMERIC_STATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 20, CONF_BELOW: 35, CONF_P_GIVEN_T: 95, CONF_P_GIVEN_F: 8, CONF_NAME: "20 - 35 outside", }, ) assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None assert result["menu_options"] == [ "state", "numeric_state", "template", "finish", ] result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": "finish"} ) await hass.async_block_till_done() config_entry = result["result"] assert config_entry.options == { CONF_NAME: "Nice day", CONF_PROBABILITY_THRESHOLD: 0.51, CONF_PRIOR: 0.2, } assert len(config_entry.subentries) == 1 assert list(config_entry.subentries.values())[0].data == { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 20, CONF_BELOW: 35, CONF_P_GIVEN_T: 0.95, CONF_P_GIVEN_F: 0.08, CONF_NAME: "20 - 35 outside", } assert len(mock_setup_entry.mock_calls) == 1 async def test_multi_numeric_state_observation(hass: HomeAssistant) -> None: """Test a Bayesian sensor with just more than one numeric_state observation added. Technically a subset of the tests in test_config_flow() but may help to narrow down errors more quickly. """ with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["step_id"] == USER assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_NAME: "Nice day", CONF_PROBABILITY_THRESHOLD: 51, CONF_PRIOR: 20, }, ) await hass.async_block_till_done() # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # select numeric state observation result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.NUMERIC_STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.NUMERIC_STATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 20, CONF_BELOW: 35, CONF_P_GIVEN_T: 95, CONF_P_GIVEN_F: 8, CONF_NAME: "20 - 35 outside", }, ) # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.NUMERIC_STATE)} ) await hass.async_block_till_done() # This should fail as overlapping ranges for the same entity are not allowed current_step = result["step_id"] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 30, CONF_BELOW: 40, CONF_P_GIVEN_T: 95, CONF_P_GIVEN_F: 8, CONF_NAME: "30 - 40 outside", }, ) await hass.async_block_till_done() assert result["errors"] == {"base": "overlapping_ranges"} assert result["step_id"] == current_step # This should fail as above should always be less than below current_step = result["step_id"] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 40, CONF_BELOW: 35, CONF_P_GIVEN_T: 95, CONF_P_GIVEN_F: 8, CONF_NAME: "35 - 40 outside", }, ) await hass.async_block_till_done() assert result["step_id"] == current_step assert result["errors"] == {"base": "above_below"} # This should work result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 35, CONF_BELOW: 40, CONF_P_GIVEN_T: 70, CONF_P_GIVEN_F: 20, CONF_NAME: "35 - 40 outside", }, ) assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None assert result["menu_options"] == [ "state", "numeric_state", "template", "finish", ] result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": "finish"} ) await hass.async_block_till_done() config_entry = result["result"] assert config_entry.version == 1 assert config_entry.options == { CONF_NAME: "Nice day", CONF_PROBABILITY_THRESHOLD: 0.51, CONF_PRIOR: 0.2, } observations = [ dict(subentry.data) for subentry in config_entry.subentries.values() ] assert observations == [ { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 20.0, CONF_BELOW: 35.0, CONF_P_GIVEN_T: 0.95, CONF_P_GIVEN_F: 0.08, CONF_NAME: "20 - 35 outside", }, { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.outside_temperature", CONF_ABOVE: 35.0, CONF_BELOW: 40.0, CONF_P_GIVEN_T: 0.7, CONF_P_GIVEN_F: 0.2, CONF_NAME: "35 - 40 outside", }, ] assert len(mock_setup_entry.mock_calls) == 1 async def test_single_template_observation(hass: HomeAssistant) -> None: """Test a Bayesian sensor with just one template observation added. Technically a subset of the tests in test_config_flow() but may help to narrow down errors more quickly. """ with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ) as mock_setup_entry: result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["step_id"] == USER assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_NAME: "Paulus Home", CONF_PROBABILITY_THRESHOLD: 90, CONF_PRIOR: 50, CONF_DEVICE_CLASS: "occupancy", }, ) await hass.async_block_till_done() # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None # Select template observation result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.TEMPLATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.TEMPLATE) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_VALUE_TEMPLATE: "{{is_state('device_tracker.paulus','not_home') and ((as_timestamp(now()) - as_timestamp(states.device_tracker.paulus.last_changed)) > 300)}}", CONF_P_GIVEN_T: 5, CONF_P_GIVEN_F: 99, CONF_NAME: "Not seen in last 5 minutes", }, ) assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None assert result["menu_options"] == [ "state", "numeric_state", "template", "finish", ] result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": "finish"} ) await hass.async_block_till_done() config_entry = result["result"] assert config_entry.version == 1 assert config_entry.options == { CONF_NAME: "Paulus Home", CONF_PROBABILITY_THRESHOLD: 0.9, CONF_PRIOR: 0.5, CONF_DEVICE_CLASS: "occupancy", } assert len(config_entry.subentries) == 1 assert list(config_entry.subentries.values())[0].data == { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: "{{is_state('device_tracker.paulus','not_home') and ((as_timestamp(now()) - as_timestamp(states.device_tracker.paulus.last_changed)) > 300)}}", CONF_P_GIVEN_T: 0.05, CONF_P_GIVEN_F: 0.99, CONF_NAME: "Not seen in last 5 minutes", } assert len(mock_setup_entry.mock_calls) == 1 async def test_basic_options(hass: HomeAssistant) -> None: """Test reconfiguring the basic options using an options flow.""" config_entry = MockConfigEntry( data={}, domain=DOMAIN, options={ CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.15, CONF_DEVICE_CLASS: "occupancy", }, subentries_data=[ ConfigSubentryDataWithId( data=MappingProxyType( { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 0.85, CONF_P_GIVEN_F: 0.45, CONF_NAME: "Office is bright", } ), subentry_id="01JXCPHRM64Y84GQC58P5EKVHY", subentry_type="observation", title="Office is bright", unique_id=None, ) ], title="Office occupied", ) # Setup the mock config entry config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() # Give the sensor a real value hass.states.async_set("sensor.office_illuminance_lux", 50) # Start the options flow result = await hass.config_entries.options.async_init(config_entry.entry_id) # Confirm the first page is the form for editing the basic options assert result["type"] is FlowResultType.FORM assert result["step_id"] == str(OptionsFlowSteps.INIT) # Change all possible settings (name can be changed elsewhere in the UI) await hass.config_entries.options.async_configure( result["flow_id"], { CONF_PROBABILITY_THRESHOLD: 49, CONF_PRIOR: 14, CONF_DEVICE_CLASS: "presence", }, ) await hass.async_block_till_done() # Confirm the changes stuck assert hass.config_entries.async_get_entry(config_entry.entry_id).options == { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.49, CONF_PRIOR: 0.14, CONF_DEVICE_CLASS: "presence", } assert config_entry.subentries == { "01JXCPHRM64Y84GQC58P5EKVHY": ConfigSubentry( data=MappingProxyType( { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 0.85, CONF_P_GIVEN_F: 0.45, CONF_NAME: "Office is bright", } ), subentry_id="01JXCPHRM64Y84GQC58P5EKVHY", subentry_type="observation", title="Office is bright", unique_id=None, ) } async def test_reconfiguring_observations(hass: HomeAssistant) -> None: """Test editing observations through options flow, once of each of the 3 types.""" # Setup the config entry config_entry = MockConfigEntry( data={}, domain=DOMAIN, options={ CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.15, CONF_DEVICE_CLASS: "occupancy", }, subentries_data=[ ConfigSubentryDataWithId( data=MappingProxyType( { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 0.85, CONF_P_GIVEN_F: 0.45, CONF_NAME: "Office is bright", } ), subentry_id="01JXCPHRM64Y84GQC58P5EKVHY", subentry_type="observation", title="Office is bright", unique_id=None, ), ConfigSubentryDataWithId( data=MappingProxyType( { CONF_PLATFORM: str(ObservationTypes.STATE), CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.6, CONF_P_GIVEN_F: 0.2, CONF_NAME: "Work laptop on network", }, ), subentry_id="13TCPHRM64Y84GQC58P5EKTHF", subentry_type="observation", title="Work laptop on network", unique_id=None, ), ConfigSubentryDataWithId( data=MappingProxyType( { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: '{% set current_time = now().time() %}\n{% set start_time = strptime("07:00", "%H:%M").time() %}\n{% set end_time = strptime("18:30", "%H:%M").time() %}\n{% if start_time <= current_time <= end_time %}\nTrue\n{% else %}\nFalse\n{% endif %}', CONF_P_GIVEN_T: 0.45, CONF_P_GIVEN_F: 0.05, CONF_NAME: "Daylight hours", } ), subentry_id="27TCPHRM64Y84GQC58P5EIES", subentry_type="observation", title="Daylight hours", unique_id=None, ), ], title="Office occupied", ) # Set up the mock entry config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() hass.states.async_set("sensor.office_illuminance_lux", 50) # select a subentry for reconfiguration result = await config_entry.start_subentry_reconfigure_flow( hass, subentry_id="13TCPHRM64Y84GQC58P5EKTHF" ) await hass.async_block_till_done() # confirm the first page is the form for editing the observation assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" assert result["description_placeholders"]["parent_sensor_name"] == "Office occupied" assert result["description_placeholders"]["device_class_on"] == "Detected" assert result["description_placeholders"]["device_class_off"] == "Clear" # Edit all settings await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.desktop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 70, CONF_P_GIVEN_F: 12, CONF_NAME: "Desktop on network", }, ) await hass.async_block_till_done() # Confirm the changes to the state config assert hass.config_entries.async_get_entry(config_entry.entry_id).options == { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.15, CONF_DEVICE_CLASS: "occupancy", } observations = [ dict(subentry.data) for subentry in hass.config_entries.async_get_entry( config_entry.entry_id ).subentries.values() ] assert observations == [ { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 0.85, CONF_P_GIVEN_F: 0.45, CONF_NAME: "Office is bright", }, { CONF_PLATFORM: str(ObservationTypes.STATE), CONF_ENTITY_ID: "sensor.desktop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.7, CONF_P_GIVEN_F: 0.12, CONF_NAME: "Desktop on network", }, { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: '{% set current_time = now().time() %}\n{% set start_time = strptime("07:00", "%H:%M").time() %}\n{% set end_time = strptime("18:30", "%H:%M").time() %}\n{% if start_time <= current_time <= end_time %}\nTrue\n{% else %}\nFalse\n{% endif %}', CONF_P_GIVEN_T: 0.45, CONF_P_GIVEN_F: 0.05, CONF_NAME: "Daylight hours", }, ] # Next test editing a numeric_state observation # select the subentry for reconfiguration result = await config_entry.start_subentry_reconfigure_flow( hass, subentry_id="01JXCPHRM64Y84GQC58P5EKVHY" ) await hass.async_block_till_done() # confirm the first page is the form for editing the observation assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" await hass.async_block_till_done() # Test an invalid re-configuration # This should fail as the probabilities are equal current_step = result["step_id"] result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.office_illuminance_lumens", CONF_ABOVE: 2000, CONF_P_GIVEN_T: 80, CONF_P_GIVEN_F: 80, CONF_NAME: "Office is bright", }, ) await hass.async_block_till_done() assert result["step_id"] == current_step assert result["errors"] == {"base": "equal_probabilities"} # This should work result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.office_illuminance_lumens", CONF_ABOVE: 2000, CONF_P_GIVEN_T: 80, CONF_P_GIVEN_F: 40, CONF_NAME: "Office is bright", }, ) await hass.async_block_till_done() assert "errors" not in result # Confirm the changes to the state config assert hass.config_entries.async_get_entry(config_entry.entry_id).options == { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.15, CONF_DEVICE_CLASS: "occupancy", } observations = [ dict(subentry.data) for subentry in hass.config_entries.async_get_entry( config_entry.entry_id ).subentries.values() ] assert observations == [ { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lumens", CONF_ABOVE: 2000, CONF_P_GIVEN_T: 0.8, CONF_P_GIVEN_F: 0.4, CONF_NAME: "Office is bright", }, { CONF_PLATFORM: str(ObservationTypes.STATE), CONF_ENTITY_ID: "sensor.desktop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.7, CONF_P_GIVEN_F: 0.12, CONF_NAME: "Desktop on network", }, { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: '{% set current_time = now().time() %}\n{% set start_time = strptime("07:00", "%H:%M").time() %}\n{% set end_time = strptime("18:30", "%H:%M").time() %}\n{% if start_time <= current_time <= end_time %}\nTrue\n{% else %}\nFalse\n{% endif %}', CONF_P_GIVEN_T: 0.45, CONF_P_GIVEN_F: 0.05, CONF_NAME: "Daylight hours", }, ] # Next test editing a template observation # select the subentry for reconfiguration result = await config_entry.start_subentry_reconfigure_flow( hass, subentry_id="27TCPHRM64Y84GQC58P5EIES" ) await hass.async_block_till_done() # confirm the first page is the form for editing the observation assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reconfigure" await hass.async_block_till_done() await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_VALUE_TEMPLATE: """ {% set current_time = now().time() %} {% set start_time = strptime("07:00", "%H:%M").time() %} {% set end_time = strptime("17:30", "%H:%M").time() %} {% if start_time <= current_time <= end_time %} True {% else %} False {% endif %} """, # changed the end_time CONF_P_GIVEN_T: 55, CONF_P_GIVEN_F: 13, CONF_NAME: "Office hours", }, ) await hass.async_block_till_done() # Confirm the changes to the state config assert hass.config_entries.async_get_entry(config_entry.entry_id).options == { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0.5, CONF_PRIOR: 0.15, CONF_DEVICE_CLASS: "occupancy", } observations = [ dict(subentry.data) for subentry in hass.config_entries.async_get_entry( config_entry.entry_id ).subentries.values() ] assert observations == [ { CONF_PLATFORM: str(ObservationTypes.NUMERIC_STATE), CONF_ENTITY_ID: "sensor.office_illuminance_lumens", CONF_ABOVE: 2000, CONF_P_GIVEN_T: 0.8, CONF_P_GIVEN_F: 0.4, CONF_NAME: "Office is bright", }, { CONF_PLATFORM: str(ObservationTypes.STATE), CONF_ENTITY_ID: "sensor.desktop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0.7, CONF_P_GIVEN_F: 0.12, CONF_NAME: "Desktop on network", }, { CONF_PLATFORM: str(ObservationTypes.TEMPLATE), CONF_VALUE_TEMPLATE: '{% set current_time = now().time() %}\n{% set start_time = strptime("07:00", "%H:%M").time() %}\n{% set end_time = strptime("17:30", "%H:%M").time() %}\n{% if start_time <= current_time <= end_time %}\nTrue\n{% else %}\nFalse\n{% endif %}', CONF_P_GIVEN_T: 0.55, CONF_P_GIVEN_F: 0.13, CONF_NAME: "Office hours", }, ] async def test_invalid_configs(hass: HomeAssistant) -> None: """Test that invalid configs are refused.""" with patch( "homeassistant.components.bayesian.async_setup_entry", return_value=True ): result0 = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result0["step_id"] == USER assert result0["type"] is FlowResultType.FORM # priors should never be Zero, because then the sensor can never return 'on' with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 0, }, ) assert CONF_PRIOR in excinfo.value.path assert excinfo.value.error_message == "extreme_prior_error" # priors should never be 100% because then the sensor can never be 'off' with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 100, }, ) assert CONF_PRIOR in excinfo.value.path assert excinfo.value.error_message == "extreme_prior_error" # Threshold should never be 100% because then the sensor can never be 'on' with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 100, CONF_PRIOR: 50, }, ) assert CONF_PROBABILITY_THRESHOLD in excinfo.value.path assert excinfo.value.error_message == "extreme_threshold_error" # Threshold should never be 0 because then the sensor can never be 'off' with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 0, CONF_PRIOR: 50, }, ) assert CONF_PROBABILITY_THRESHOLD in excinfo.value.path assert excinfo.value.error_message == "extreme_threshold_error" # Now lets submit a valid config so we can test the observation flows result = await hass.config_entries.flow.async_configure( result0["flow_id"], { CONF_NAME: "Office occupied", CONF_PROBABILITY_THRESHOLD: 50, CONF_PRIOR: 30, }, ) await hass.async_block_till_done() assert result.get("errors") is None # Confirm the next step is the menu assert result["step_id"] == OBSERVATION_SELECTOR assert result["type"] is FlowResultType.MENU assert result["flow_id"] is not None result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.STATE)} ) await hass.async_block_till_done() assert result["step_id"] == str(ObservationTypes.STATE) assert result["type"] is FlowResultType.FORM # Observations with a probability of 0 will create certainties with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 0, CONF_P_GIVEN_F: 60, CONF_NAME: "Work laptop on network", }, ) assert CONF_P_GIVEN_T in excinfo.value.path assert excinfo.value.error_message == "extreme_prob_given_error" # Observations with a probability of 1 will create certainties with pytest.raises(vol.Invalid) as excinfo: result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 60, CONF_P_GIVEN_F: 100, CONF_NAME: "Work laptop on network", }, ) assert CONF_P_GIVEN_F in excinfo.value.path assert excinfo.value.error_message == "extreme_prob_given_error" # Observations with equal probabilities have no effect # Try with a ObservationTypes.STATE observation current_step = result["step_id"] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 60, CONF_P_GIVEN_F: 60, CONF_NAME: "Work laptop on network", }, ) await hass.async_block_till_done() assert result["step_id"] == current_step assert result["errors"] == {"base": "equal_probabilities"} # now submit a valid result result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.work_laptop", CONF_TO_STATE: "on", CONF_P_GIVEN_T: 60, CONF_P_GIVEN_F: 70, CONF_NAME: "Work laptop on network", }, ) await hass.async_block_till_done() result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.NUMERIC_STATE)} ) await hass.async_block_till_done() current_step = result["step_id"] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 85, CONF_P_GIVEN_F: 85, CONF_NAME: "Office is bright", }, ) await hass.async_block_till_done() assert result["step_id"] == current_step assert result["errors"] == {"base": "equal_probabilities"} result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_ENTITY_ID: "sensor.office_illuminance_lux", CONF_ABOVE: 40, CONF_P_GIVEN_T: 85, CONF_P_GIVEN_F: 10, CONF_NAME: "Office is bright", }, ) await hass.async_block_till_done() # Try with a ObservationTypes.TEMPLATE observation result = await hass.config_entries.flow.async_configure( result["flow_id"], {"next_step_id": str(ObservationTypes.TEMPLATE)} ) await hass.async_block_till_done() current_step = result["step_id"] result = await hass.config_entries.flow.async_configure( result["flow_id"], { CONF_VALUE_TEMPLATE: "{{ is_state('device_tracker.paulus', 'not_home') }}", CONF_P_GIVEN_T: 50, CONF_P_GIVEN_F: 50, CONF_NAME: "Paulus not home", }, ) await hass.async_block_till_done() assert result["step_id"] == current_step assert result["errors"] == {"base": "equal_probabilities"}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/bayesian/test_config_flow.py", "license": "Apache License 2.0", "lines": 1099, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/emoncms_history/test_init.py
"""The tests for the emoncms_history init.""" from collections.abc import AsyncGenerator from datetime import timedelta from unittest.mock import AsyncMock, patch import aiohttp from freezegun.api import FrozenDateTimeFactory import pytest from homeassistant.const import CONF_API_KEY, CONF_URL, STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component async def test_setup_valid_config(hass: HomeAssistant) -> None: """Test setting up the emoncms_history component with valid configuration.""" config = { "emoncms_history": { CONF_API_KEY: "dummy", CONF_URL: "https://emoncms.example", "inputnode": 42, "whitelist": ["sensor.temp"], } } # Simulate a sensor hass.states.async_set("sensor.temp", "23.4", {"unit_of_measurement": "°C"}) await hass.async_block_till_done() assert await async_setup_component(hass, "emoncms_history", config) await hass.async_block_till_done() async def test_setup_missing_config(hass: HomeAssistant) -> None: """Test setting up the emoncms_history component with missing configuration.""" config = {"emoncms_history": {"api_key": "dummy"}} success = await async_setup_component(hass, "emoncms_history", config) assert not success @pytest.fixture async def emoncms_client() -> AsyncGenerator[AsyncMock]: """Mock pyemoncms client with successful responses.""" with patch( "homeassistant.components.emoncms_history.EmoncmsClient", autospec=True ) as mock_client: client = mock_client.return_value client.async_input_post.return_value = '{"success": true}' yield client async def test_emoncms_send_data( hass: HomeAssistant, emoncms_client: AsyncMock, caplog: pytest.LogCaptureFixture, freezer: FrozenDateTimeFactory, ) -> None: """Test sending data to Emoncms with and without success.""" config = { "emoncms_history": { "api_key": "dummy", "url": "http://fake-url", "inputnode": 42, "whitelist": ["sensor.temp"], } } assert await async_setup_component(hass, "emoncms_history", config) await hass.async_block_till_done() for state in None, "", STATE_UNAVAILABLE, STATE_UNKNOWN: hass.states.async_set("sensor.temp", state, {"unit_of_measurement": "°C"}) await hass.async_block_till_done() freezer.tick(timedelta(seconds=60)) await hass.async_block_till_done() assert emoncms_client.async_input_post.call_args is None hass.states.async_set("sensor.temp", "not_a_number", {"unit_of_measurement": "°C"}) await hass.async_block_till_done() freezer.tick(timedelta(seconds=60)) await hass.async_block_till_done() emoncms_client.async_input_post.assert_not_called() hass.states.async_set("sensor.temp", "23.4", {"unit_of_measurement": "°C"}) await hass.async_block_till_done() freezer.tick(timedelta(seconds=60)) await hass.async_block_till_done() emoncms_client.async_input_post.assert_called_once() assert emoncms_client.async_input_post.return_value == '{"success": true}' _, kwargs = emoncms_client.async_input_post.call_args assert kwargs["data"] == {"sensor.temp": 23.4} assert kwargs["node"] == "42" emoncms_client.async_input_post.side_effect = aiohttp.ClientError( "Connection refused" ) await hass.async_block_till_done() freezer.tick(timedelta(seconds=60)) await hass.async_block_till_done() assert any( "Network error when sending data to Emoncms" in message for message in caplog.text.splitlines() ) emoncms_client.async_input_post.side_effect = ValueError("Invalid value format") await hass.async_block_till_done() freezer.tick(timedelta(seconds=60)) await hass.async_block_till_done() assert any( "Value error when preparing data for Emoncms" in message for message in caplog.text.splitlines() )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/emoncms_history/test_init.py", "license": "Apache License 2.0", "lines": 94, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/fan/test_intent.py
"""Intent tests for the fan platform.""" from homeassistant.components.fan import ( ATTR_PERCENTAGE, DOMAIN, SERVICE_TURN_ON, intent as fan_intent, ) from homeassistant.const import STATE_OFF from homeassistant.core import HomeAssistant from homeassistant.helpers import intent from tests.common import async_mock_service async def test_set_speed_intent(hass: HomeAssistant) -> None: """Test set speed intent for fans.""" await fan_intent.async_setup_intents(hass) entity_id = f"{DOMAIN}.test_fan" hass.states.async_set(entity_id, STATE_OFF) calls = async_mock_service(hass, DOMAIN, SERVICE_TURN_ON) response = await intent.async_handle( hass, "test", fan_intent.INTENT_FAN_SET_SPEED, {"name": {"value": "test fan"}, ATTR_PERCENTAGE: {"value": 50}}, ) await hass.async_block_till_done() assert response.response_type == intent.IntentResponseType.ACTION_DONE assert len(calls) == 1 call = calls[0] assert call.domain == DOMAIN assert call.service == SERVICE_TURN_ON assert call.data == {"entity_id": entity_id, "percentage": 50}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/fan/test_intent.py", "license": "Apache License 2.0", "lines": 30, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/foscam/test_switch.py
"""Test for the switch platform entity of the foscam component.""" from unittest.mock import patch from syrupy.assertion import SnapshotAssertion from homeassistant.components.foscam.const import DOMAIN from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .conftest import setup_mock_foscam_camera from .const import ENTRY_ID, VALID_CONFIG from tests.common import MockConfigEntry, snapshot_platform async def test_entities( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test that coordinator returns the data we expect after the first refresh.""" entry = MockConfigEntry(domain=DOMAIN, data=VALID_CONFIG, entry_id=ENTRY_ID) entry.add_to_hass(hass) with ( # Mock a valid camera instance" patch("homeassistant.components.foscam.FoscamCamera") as mock_foscam_camera, patch("homeassistant.components.foscam.PLATFORMS", [Platform.SWITCH]), ): setup_mock_foscam_camera(mock_foscam_camera) assert await hass.config_entries.async_setup(entry.entry_id) await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/foscam/test_switch.py", "license": "Apache License 2.0", "lines": 26, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/husqvarna_automower/test_event.py
"""Tests for init module.""" from collections.abc import Callable from copy import deepcopy from datetime import UTC, datetime from unittest.mock import AsyncMock, patch from aioautomower.model import MowerAttributes, SingleMessageData from aioautomower.model.model_message import Message, Severity, SingleMessageAttributes from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.event import ATTR_EVENT_TYPE from homeassistant.components.husqvarna_automower.coordinator import SCAN_INTERVAL from homeassistant.config_entries import ConfigEntryState from homeassistant.const import Platform from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_registry import EntityRegistry from . import setup_integration from .const import TEST_MOWER_ID from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.freeze_time(datetime(2023, 6, 5, 12)) async def test_event( hass: HomeAssistant, entity_registry: EntityRegistry, mock_automower_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, values: dict[str, MowerAttributes], automower_ws_ready: list[Callable[[], None]], ) -> None: """Test that a new message arriving over the websocket creates and updates the sensor.""" callbacks: list[Callable[[SingleMessageData], None]] = [] @callback def fake_register_websocket_response( cb: Callable[[SingleMessageData], None], ) -> None: callbacks.append(cb) mock_automower_client.register_single_message_callback.side_effect = ( fake_register_websocket_response ) mock_automower_client.send_empty_message.return_value = True # Set up integration await setup_integration(hass, mock_config_entry) await hass.async_block_till_done() # Start the watchdog and let it run once to set websocket_alive=True for cb in automower_ws_ready: cb() await hass.async_block_till_done() # Ensure callback was registered for the test mower assert mock_automower_client.register_single_message_callback.called # Check initial state (event entity not available yet) state = hass.states.get("event.test_mower_1_message") assert state is None # Simulate a new message for this mower and check entity creation message = SingleMessageData( type="messages", id=TEST_MOWER_ID, attributes=SingleMessageAttributes( message=Message( time=datetime(2025, 7, 13, 15, 30, tzinfo=UTC), code="wheel_motor_overloaded_rear_left", severity=Severity.ERROR, latitude=49.0, longitude=10.0, ) ), ) for cb in callbacks: cb(message) await hass.async_block_till_done() state = hass.states.get("event.test_mower_1_message") assert state is not None assert state.attributes[ATTR_EVENT_TYPE] == "wheel_motor_overloaded_rear_left" # Reload the config entry to ensure the entity is created again await hass.config_entries.async_reload(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.LOADED # Start the new watchdog and let it run for cb in automower_ws_ready: cb() await hass.async_block_till_done() state = hass.states.get("event.test_mower_1_message") assert state is not None assert state.attributes[ATTR_EVENT_TYPE] == "wheel_motor_overloaded_rear_left" # Check updating event with a new message message = SingleMessageData( type="messages", id=TEST_MOWER_ID, attributes=SingleMessageAttributes( message=Message( time=datetime(2025, 7, 13, 16, 00, tzinfo=UTC), code="alarm_mower_lifted", severity=Severity.ERROR, latitude=48.0, longitude=11.0, ) ), ) for cb in callbacks: cb(message) await hass.async_block_till_done() state = hass.states.get("event.test_mower_1_message") assert state is not None assert state.attributes[ATTR_EVENT_TYPE] == "alarm_mower_lifted" # Check message for another mower, creates an new entity and dont # change the state of the first entity message = SingleMessageData( type="messages", id="1234", attributes=SingleMessageAttributes( message=Message( time=datetime(2025, 7, 13, 16, 00, tzinfo=UTC), code="battery_problem", severity=Severity.ERROR, latitude=48.0, longitude=11.0, ) ), ) for cb in callbacks: cb(message) await hass.async_block_till_done() entry = entity_registry.async_get("event.test_mower_1_message") assert entry is not None assert state.attributes[ATTR_EVENT_TYPE] == "alarm_mower_lifted" state = hass.states.get("event.test_mower_2_message") assert state is not None assert state.attributes[ATTR_EVENT_TYPE] == "battery_problem" # Check event entity is removed, when the mower is removed values_copy = deepcopy(values) values_copy.pop("1234") mock_automower_client.get_status.return_value = values_copy freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("event.test_mower_2_message") assert state is None entry = entity_registry.async_get("event.test_mower_2_message") assert entry is None @pytest.mark.freeze_time(datetime(2023, 6, 5, 12)) async def test_event_snapshot( hass: HomeAssistant, mock_automower_client: AsyncMock, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, automower_ws_ready: list[Callable[[], None]], ) -> None: """Test that a new message arriving over the websocket updates the sensor.""" with patch( "homeassistant.components.husqvarna_automower.PLATFORMS", [Platform.EVENT], ): callbacks: list[Callable[[SingleMessageData], None]] = [] @callback def fake_register_websocket_response( cb: Callable[[SingleMessageData], None], ) -> None: callbacks.append(cb) mock_automower_client.register_single_message_callback.side_effect = ( fake_register_websocket_response ) # Set up integration await setup_integration(hass, mock_config_entry) await hass.async_block_till_done() # Start the watchdog and let it run once for cb in automower_ws_ready: cb() await hass.async_block_till_done() # Ensure callback was registered for the test mower assert mock_automower_client.register_single_message_callback.called # Simulate a new message for this mower message = SingleMessageData( type="messages", id=TEST_MOWER_ID, attributes=SingleMessageAttributes( message=Message( time=datetime(2025, 7, 13, 15, 30, tzinfo=UTC), code="wheel_motor_overloaded_rear_left", severity=Severity.ERROR, latitude=49.0, longitude=10.0, ) ), ) for cb in callbacks: cb(message) await hass.async_block_till_done() await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/husqvarna_automower/test_event.py", "license": "Apache License 2.0", "lines": 191, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/huum/test_number.py
"""Tests for the Huum number entity.""" from unittest.mock import AsyncMock from huum.const import SaunaStatus from syrupy.assertion import SnapshotAssertion from homeassistant.components.number import ( ATTR_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_with_selected_platforms from tests.common import MockConfigEntry, snapshot_platform ENTITY_ID = "number.huum_sauna_humidity" async def test_number_entity( hass: HomeAssistant, mock_huum: AsyncMock, mock_config_entry: MockConfigEntry, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, ) -> None: """Test the initial parameters.""" await setup_with_selected_platforms(hass, mock_config_entry, [Platform.NUMBER]) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_set_humidity( hass: HomeAssistant, mock_huum: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting the humidity.""" await setup_with_selected_platforms(hass, mock_config_entry, [Platform.NUMBER]) mock_huum.status = SaunaStatus.ONLINE_HEATING await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: ENTITY_ID, ATTR_VALUE: 5, }, blocking=True, ) mock_huum.turn_on.assert_called_once_with(temperature=80, humidity=5) async def test_dont_set_humidity_when_sauna_not_heating( hass: HomeAssistant, mock_huum: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test setting the humidity.""" await setup_with_selected_platforms(hass, mock_config_entry, [Platform.NUMBER]) mock_huum.status = SaunaStatus.ONLINE_NOT_HEATING await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, { ATTR_ENTITY_ID: ENTITY_ID, ATTR_VALUE: 5, }, blocking=True, ) mock_huum.turn_on.assert_not_called()
{ "repo_id": "home-assistant/core", "file_path": "tests/components/huum/test_number.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/letpot/test_select.py
"""Test select entities for the LetPot integration.""" from unittest.mock import MagicMock, patch from letpot.exceptions import LetPotConnectionException, LetPotException from letpot.models import LightMode import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.select import ( DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION, ) from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION, 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, snapshot_platform @pytest.mark.parametrize("device_type", ["LPH62", "LPH31"]) async def test_all_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_client: MagicMock, mock_device_client: MagicMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, device_type: str, ) -> None: """Test switch entities.""" with patch("homeassistant.components.letpot.PLATFORMS", [Platform.SELECT]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize("device_type", ["LPH31"]) async def test_set_select( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock, mock_device_client: MagicMock, device_type: str, ) -> None: """Test select entity set to value.""" await setup_integration(hass, mock_config_entry) await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.garden_light_brightness", ATTR_OPTION: "high", }, blocking=True, ) mock_device_client.set_light_brightness.assert_awaited_once_with( f"{device_type}ABCD", 1000 ) @pytest.mark.parametrize( ("exception", "user_error"), [ ( LetPotConnectionException("Connection failed"), "An error occurred while communicating with the LetPot device: Connection failed", ), ( LetPotException("Random thing failed"), "An unknown error occurred while communicating with the LetPot device: Random thing failed", ), ], ) async def test_select_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock, mock_device_client: MagicMock, exception: Exception, user_error: str, ) -> None: """Test select entity exception handling.""" await setup_integration(hass, mock_config_entry) mock_device_client.set_light_mode.side_effect = exception with pytest.raises(HomeAssistantError, match=user_error): await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, { ATTR_ENTITY_ID: "select.garden_light_mode", ATTR_OPTION: LightMode.FLOWER.name.lower(), }, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/letpot/test_select.py", "license": "Apache License 2.0", "lines": 86, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/lg_thinq/test_switch.py
"""Tests for the LG ThinQ switch platform.""" from unittest.mock import AsyncMock, patch from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration from tests.common import MockConfigEntry, snapshot_platform async def test_switch_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, devices: AsyncMock, mock_thinq_api: AsyncMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, ) -> None: """Test all entities.""" with patch("homeassistant.components.lg_thinq.PLATFORMS", [Platform.SWITCH]): await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/lg_thinq/test_switch.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/nina/test_diagnostics.py
"""Test the Nina diagnostics.""" from unittest.mock import AsyncMock from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from . import setup_platform 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, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, mock_nina_class: AsyncMock, nina_warnings: list[Warning], ) -> None: """Test diagnostics.""" await setup_platform(hass, mock_config_entry, mock_nina_class, nina_warnings) assert ( await get_diagnostics_for_config_entry(hass, hass_client, mock_config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/nina/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:tests/components/opower/test_repairs.py
"""Test the Opower repairs.""" from homeassistant.components.opower.const import DOMAIN from homeassistant.components.recorder import Recorder from homeassistant.components.repairs import DOMAIN as REPAIRS_DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import issue_registry as ir from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry from tests.components.repairs import ( async_process_repairs_platforms, process_repair_fix_flow, start_repair_fix_flow, ) from tests.typing import ClientSessionGenerator async def test_unsupported_utility_fix_flow( recorder_mock: Recorder, hass: HomeAssistant, hass_client: ClientSessionGenerator, issue_registry: ir.IssueRegistry, ) -> None: """Test the unsupported utility fix flow.""" assert await async_setup_component(hass, REPAIRS_DOMAIN, {REPAIRS_DOMAIN: {}}) mock_config_entry = MockConfigEntry( domain=DOMAIN, data={ "utility": "Unsupported Utility", "username": "test-user", "password": "test-password", }, title="My Unsupported Utility", ) mock_config_entry.add_to_hass(hass) # Setting up the component with an unsupported utility should fail and create an issue assert not 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 # Verify the issue was created correctly issue_id = f"unsupported_utility_{mock_config_entry.entry_id}" issue = issue_registry.async_get_issue(DOMAIN, issue_id) assert issue is not None assert issue.translation_key == "unsupported_utility" assert issue.is_fixable is True assert issue.data == { "entry_id": mock_config_entry.entry_id, "utility": "Unsupported Utility", "title": "My Unsupported Utility", } await async_process_repairs_platforms(hass) http_client = await hass_client() # Start the repair flow data = await start_repair_fix_flow(http_client, DOMAIN, issue_id) flow_id = data["flow_id"] # The flow should go directly to the confirm step assert data["step_id"] == "confirm" assert data["description_placeholders"] == { "utility": "Unsupported Utility", "title": "My Unsupported Utility", } # Submit the confirmation form data = await process_repair_fix_flow(http_client, flow_id, json={}) # The flow should complete and create an empty entry, signaling success assert data["type"] == "create_entry" await hass.async_block_till_done() # Check that the config entry has been removed assert hass.config_entries.async_get_entry(mock_config_entry.entry_id) is None # Check that the issue has been resolved assert not issue_registry.async_get_issue(DOMAIN, issue_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/opower/test_repairs.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/pooldose/test_config_flow.py
"""Test the PoolDose config flow.""" from datetime import timedelta from typing import Any from unittest.mock import AsyncMock from freezegun.api import FrozenDateTimeFactory import pytest from homeassistant.components.pooldose.const import DOMAIN from homeassistant.config_entries import SOURCE_DHCP, SOURCE_USER from homeassistant.const import CONF_HOST, CONF_MAC from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .conftest import RequestStatus from tests.common import MockConfigEntry, async_fire_time_changed async def test_full_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> 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["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "PoolDose TEST123456789" assert result["data"] == {CONF_HOST: "192.168.1.100"} assert result["result"].unique_id == "TEST123456789" async def test_device_unreachable( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that the form shows error when device is unreachable.""" mock_pooldose_client.is_connected = False mock_pooldose_client.connect.return_value = RequestStatus.HOST_UNREACHABLE 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} mock_pooldose_client.is_connected = True mock_pooldose_client.connect.return_value = RequestStatus.SUCCESS result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_api_version_unsupported( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that the form shows error when API version is unsupported.""" mock_pooldose_client.check_apiversion_supported.return_value = ( RequestStatus.API_VERSION_UNSUPPORTED, {"api_version_is": "v0.9", "api_version_should": "v1.0"}, ) 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "api_not_supported"} mock_pooldose_client.is_connected = True mock_pooldose_client.check_apiversion_supported.return_value = ( RequestStatus.SUCCESS, {}, ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_form_no_device_info( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, device_info: dict[str, Any], ) -> None: """Test that the form shows error when device_info is None.""" mock_pooldose_client.device_info = None 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "no_device_info"} mock_pooldose_client.device_info = device_info result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY @pytest.mark.parametrize( ("client_status", "expected_error"), [ (RequestStatus.HOST_UNREACHABLE, "cannot_connect"), (RequestStatus.PARAMS_FETCH_FAILED, "params_fetch_failed"), (RequestStatus.UNKNOWN_ERROR, "cannot_connect"), ], ) async def test_connection_errors( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, client_status: str, expected_error: str, ) -> None: """Test that the form shows appropriate errors for various connection issues.""" mock_pooldose_client.connect.return_value = client_status result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": expected_error} mock_pooldose_client.connect.return_value = RequestStatus.SUCCESS result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_api_no_data( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that the form shows error when API returns NO_DATA.""" mock_pooldose_client.check_apiversion_supported.return_value = ( RequestStatus.NO_DATA, {}, ) 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "api_not_set"} mock_pooldose_client.check_apiversion_supported.return_value = ( RequestStatus.SUCCESS, {}, ) result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_form_no_serial_number( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, device_info: dict[str, Any], ) -> None: """Test that the form shows error when device_info has no serial number.""" mock_pooldose_client.device_info = {"NAME": "Pool Device", "MODEL": "POOL DOSE"} 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "no_serial_number"} mock_pooldose_client.device_info = device_info result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_HOST: "192.168.1.100"} ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_duplicate_entry_aborts( hass: HomeAssistant, mock_config_entry: MockConfigEntry ) -> None: """Test that the flow aborts if the 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: "192.168.1.100"} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" async def test_dhcp_flow(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None: """Test the full DHCP config flow.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "dhcp_confirm" result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "PoolDose TEST123456789" assert result["data"][CONF_HOST] == "192.168.0.123" assert result["data"][CONF_MAC] == "a4e57caabbcc" assert result["result"].unique_id == "TEST123456789" async def test_dhcp_no_serial_number( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that the DHCP flow aborts if no serial number is found.""" mock_pooldose_client.device_info = {"NAME": "Pool Device", "MODEL": "POOL DOSE"} result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_serial_number" @pytest.mark.parametrize( ("client_status"), [ (RequestStatus.HOST_UNREACHABLE), (RequestStatus.PARAMS_FETCH_FAILED), (RequestStatus.UNKNOWN_ERROR), ], ) async def test_dhcp_connection_errors( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, client_status: str, ) -> None: """Test that the DHCP flow aborts on connection errors.""" mock_pooldose_client.connect.return_value = client_status result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_serial_number" @pytest.mark.parametrize( "api_status", [ RequestStatus.NO_DATA, RequestStatus.API_VERSION_UNSUPPORTED, ], ) async def test_dhcp_api_errors( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, api_status: str, ) -> None: """Test that the DHCP flow aborts on API errors.""" mock_pooldose_client.check_apiversion_supported.return_value = (api_status, {}) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_serial_number" async def test_dhcp_updates_host( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_setup_entry: AsyncMock ) -> None: """Test that DHCP discovery updates the host if it has changed.""" mock_config_entry.add_to_hass(hass) # Verify initial host IP assert mock_config_entry.data[CONF_HOST] == "192.168.1.100" # Simulate DHCP discovery event with different IP result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) # Verify flow aborts as device is already configured assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" assert mock_config_entry.data[CONF_HOST] == "192.168.0.123" async def test_dhcp_adds_mac_if_not_present( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that DHCP flow adds MAC address if not already in config entry data.""" # Create a config entry without MAC address entry = MockConfigEntry( domain=DOMAIN, unique_id="TEST123456789", data={CONF_HOST: "192.168.1.100"}, ) entry.add_to_hass(hass) # Verify initial state has no MAC assert CONF_MAC not in entry.data # Simulate DHCP discovery event result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="a4e57caabbcc" ), ) # Verify flow aborts as device is already configured assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" # Verify MAC was added to the config entry assert entry.data[CONF_HOST] == "192.168.0.123" assert entry.data[CONF_MAC] == "a4e57caabbcc" async def test_dhcp_preserves_existing_mac( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock ) -> None: """Test that DHCP flow preserves existing MAC in config entry data.""" # Create a config entry with MAC address already set entry = MockConfigEntry( domain=DOMAIN, unique_id="TEST123456789", data={ CONF_HOST: "192.168.1.100", CONF_MAC: "existing11aabb", # Existing MAC that should be preserved }, ) entry.add_to_hass(hass) # Verify initial state has the expected MAC assert entry.data[CONF_MAC] == "existing11aabb" # Simulate DHCP discovery event with different MAC result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_DHCP}, data=DhcpServiceInfo( ip="192.168.0.123", hostname="kommspot", macaddress="different22ccdd" ), ) # Verify flow aborts as device is already configured assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" # Verify MAC in config entry was NOT updated (original MAC preserved) assert entry.data[CONF_HOST] == "192.168.0.123" # IP was updated assert entry.data[CONF_MAC] == "existing11aabb" # MAC remains unchanged assert entry.data[CONF_MAC] != "different22ccdd" # Not updated to new MAC async def _start_reconfigure_flow( hass: HomeAssistant, mock_config_entry: MockConfigEntry, host_ip: str ) -> Any: """Initialize a reconfigure flow for PoolDose and submit new host.""" mock_config_entry.add_to_hass(hass) reconfigure_result = await mock_config_entry.start_reconfigure_flow(hass) assert reconfigure_result["type"] is FlowResultType.FORM assert reconfigure_result["step_id"] == "reconfigure" return await hass.config_entries.flow.async_configure( reconfigure_result["flow_id"], {CONF_HOST: host_ip} ) async def test_reconfigure_flow_success( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test successful reconfigure updates host and reloads entry.""" # Ensure the mocked device returns the same serial number as the # config entry so the reconfigure flow matches the device mock_pooldose_client.device_info = {"SERIAL_NUMBER": mock_config_entry.unique_id} result = await _start_reconfigure_flow(hass, mock_config_entry, "192.168.0.200") assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" # Config entry should have updated host assert mock_config_entry.data.get(CONF_HOST) == "192.168.0.200" freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() # Config entry should have updated host entry = hass.config_entries.async_get_entry(mock_config_entry.entry_id) assert entry is not None assert entry.data.get(CONF_HOST) == "192.168.0.200" async def test_reconfigure_flow_cannot_connect( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconfigure shows cannot_connect when device unreachable.""" mock_pooldose_client.connect.return_value = RequestStatus.HOST_UNREACHABLE result = await _start_reconfigure_flow(hass, mock_config_entry, "192.168.0.200") assert result["type"] is FlowResultType.FORM assert result["errors"] == {"base": "cannot_connect"} async def test_reconfigure_flow_wrong_device( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_setup_entry: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test reconfigure aborts when serial number doesn't match existing entry.""" # Return device info with different serial number mock_pooldose_client.device_info = {"SERIAL_NUMBER": "OTHER123"} result = await _start_reconfigure_flow(hass, mock_config_entry, "192.168.0.200") assert result["type"] is FlowResultType.ABORT assert result["reason"] == "wrong_device"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/pooldose/test_config_flow.py", "license": "Apache License 2.0", "lines": 408, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/pooldose/test_init.py
"""Test the PoolDose integration initialization.""" from unittest.mock import AsyncMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.pooldose.const import DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from .conftest import RequestStatus from tests.common import MockConfigEntry async def test_devices( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, device_registry: dr.DeviceRegistry, ) -> None: """Test all entities.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() device = device_registry.async_get_device({(DOMAIN, "TEST123456789")}) assert device is not None assert device == snapshot async def test_setup_entry_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: """Test successful setup of config entry.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() 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 async def test_setup_entry_coordinator_refresh_fails( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, ) -> None: """Test setup failure when coordinator first refresh fails.""" mock_config_entry.add_to_hass(hass) mock_pooldose_client.instant_values_structured.side_effect = Exception( "API communication failed" ) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY @pytest.mark.parametrize( "status", [ RequestStatus.HOST_UNREACHABLE, RequestStatus.PARAMS_FETCH_FAILED, RequestStatus.API_VERSION_UNSUPPORTED, RequestStatus.NO_DATA, RequestStatus.UNKNOWN_ERROR, ], ) async def test_setup_entry_various_client_failures( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, status: RequestStatus, ) -> None: """Test setup fails with various client error statuses.""" mock_pooldose_client.connect.return_value = RequestStatus.HOST_UNREACHABLE mock_pooldose_client.is_connected = False mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY @pytest.mark.parametrize( "exception", [ TimeoutError("Connection timeout"), OSError("Network error"), ], ) async def test_setup_entry_timeout_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, exception: Exception, ) -> None: """Test setup failure when client connection times out.""" mock_pooldose_client.connect.side_effect = exception mock_pooldose_client.is_connected = False mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY async def test_migrate_entity_unique_ids( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_config_entry_v1_1: MockConfigEntry, ) -> None: """Test migration of entity unique IDs.""" mock_config_entry_v1_1.add_to_hass(hass) # Create entities with old unique ID format entity_registry.async_get_or_create( "sensor", DOMAIN, "TEST123456789_ofa_orp_value", config_entry=mock_config_entry_v1_1, ) entity_registry.async_get_or_create( "sensor", DOMAIN, "TEST123456789_ofa_ph_value", config_entry=mock_config_entry_v1_1, ) # Create entity with correct unique ID that should not be changed unchanged_entity = entity_registry.async_get_or_create( "sensor", DOMAIN, "TEST123456789_orp", config_entry=mock_config_entry_v1_1, ) assert mock_config_entry_v1_1.version == 1 assert mock_config_entry_v1_1.minor_version == 1 # Setup the integration - this will trigger migration await hass.config_entries.async_setup(mock_config_entry_v1_1.entry_id) await hass.async_block_till_done() # Verify the config entry version was updated from 1.1 to 1.2 assert mock_config_entry_v1_1.version == 1 assert mock_config_entry_v1_1.minor_version == 2 # Verify the entities have been migrated assert entity_registry.async_get_entity_id( "sensor", DOMAIN, "TEST123456789_ofa_orp_time" ) assert entity_registry.async_get_entity_id( "sensor", DOMAIN, "TEST123456789_ofa_ph_time" ) # Verify old unique IDs no longer exist assert not entity_registry.async_get_entity_id( "sensor", DOMAIN, "TEST123456789_ofa_orp_value" ) assert not entity_registry.async_get_entity_id( "sensor", DOMAIN, "TEST123456789_ofa_ph_value" ) # Verify entity that didn't need migration is unchanged assert ( entity_registry.async_get_entity_id("sensor", DOMAIN, "TEST123456789_orp") == unchanged_entity.entity_id )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/pooldose/test_init.py", "license": "Apache License 2.0", "lines": 145, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/pooldose/test_sensor.py
"""Test the PoolDose sensor platform.""" from datetime import timedelta from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory from pooldose.request_status import RequestStatus import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import ( ATTR_UNIT_OF_MEASUREMENT, STATE_UNAVAILABLE, Platform, UnitOfElectricPotential, ) 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("entity_registry_enabled_by_default") async def test_all_sensors( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the Pooldose sensors.""" with patch("homeassistant.components.pooldose.PLATFORMS", [Platform.SENSOR]): mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize("exception", [TimeoutError, ConnectionError, OSError]) async def test_exception_raising( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_config_entry: MockConfigEntry, exception: Exception, freezer: FrozenDateTimeFactory, ) -> None: """Test the Pooldose sensors.""" 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 hass.states.get("sensor.pool_device_ph").state == "6.8" mock_pooldose_client.instant_values_structured.side_effect = exception freezer.tick(timedelta(minutes=10)) async_fire_time_changed(hass) await hass.async_block_till_done() assert hass.states.get("sensor.pool_device_ph").state == STATE_UNAVAILABLE async def test_no_data( hass: HomeAssistant, mock_pooldose_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, ) -> None: """Test the Pooldose sensors.""" 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 hass.states.get("sensor.pool_device_ph").state == "6.8" mock_pooldose_client.instant_values_structured.return_value = ( RequestStatus.SUCCESS, None, ) freezer.tick(timedelta(minutes=10)) async_fire_time_changed(hass) await hass.async_block_till_done() assert hass.states.get("sensor.pool_device_ph").state == STATE_UNAVAILABLE async def test_ph_sensor_dynamic_unit( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, ) -> None: """Test pH sensor unit behavior - pH should not have unit_of_measurement.""" # Mock pH data with custom unit (should be ignored for pH sensor) current_data = mock_pooldose_client.instant_values_structured.return_value[1] updated_data = current_data.copy() updated_data["sensor"]["ph"]["unit"] = "pH units" mock_pooldose_client.instant_values_structured.return_value = ( RequestStatus.SUCCESS, updated_data, ) mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # pH sensor should not have unit_of_measurement (device class pH) ph_state = hass.states.get("sensor.pool_device_ph") assert ATTR_UNIT_OF_MEASUREMENT not in ph_state.attributes async def test_sensor_entity_unavailable_no_coordinator_data( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, freezer: FrozenDateTimeFactory, ) -> None: """Test sensor entity becomes unavailable when coordinator has no data.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Verify initial working state temp_state = hass.states.get("sensor.pool_device_temperature") assert temp_state.state == "25" # Set coordinator data to None by making API return empty mock_pooldose_client.instant_values_structured.return_value = ( RequestStatus.HOST_UNREACHABLE, None, ) freezer.tick(timedelta(minutes=10)) async_fire_time_changed(hass) await hass.async_block_till_done() # Check sensor becomes unavailable temp_state = hass.states.get("sensor.pool_device_temperature") assert temp_state.state == STATE_UNAVAILABLE @pytest.mark.usefixtures("mock_pooldose_client") async def test_sensor_unit_fallback_to_description( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_pooldose_client: AsyncMock, ) -> None: """Test sensor falls back to entity description unit when no dynamic unit.""" mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() # Test ORP sensor - should use static unit from entity description orp_state = hass.states.get("sensor.pool_device_orp") assert orp_state is not None assert ( orp_state.attributes[ATTR_UNIT_OF_MEASUREMENT] == UnitOfElectricPotential.MILLIVOLT ) assert orp_state.state == "718" # Test pH sensor - should have no unit (None in description) ph_state = hass.states.get("sensor.pool_device_ph") assert ph_state is not None assert ATTR_UNIT_OF_MEASUREMENT not in ph_state.attributes assert ph_state.state == "6.8"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/pooldose/test_sensor.py", "license": "Apache License 2.0", "lines": 134, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/qbus/test_binary_sensor.py
"""Test Qbus binary sensors.""" from collections.abc import Awaitable, Callable from unittest.mock import patch from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform async def test_binary_sensor( hass: HomeAssistant, setup_integration_deferred: Callable[[], Awaitable], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test binary sensor.""" with patch("homeassistant.components.qbus.PLATFORMS", [Platform.BINARY_SENSOR]): await setup_integration_deferred() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/qbus/test_binary_sensor.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/qbus/test_sensor.py
"""Test Qbus sensors.""" from collections.abc import Awaitable, Callable from unittest.mock import patch from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform async def test_sensor( hass: HomeAssistant, setup_integration_deferred: Callable[[], Awaitable], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test sensor.""" with patch("homeassistant.components.qbus.PLATFORMS", [Platform.SENSOR]): await setup_integration_deferred() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/qbus/test_sensor.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/russound_rio/test_media_browser.py
"""Tests for the Russound RIO media browser.""" from unittest.mock import AsyncMock from syrupy.assertion import SnapshotAssertion from homeassistant.core import HomeAssistant from . import setup_integration from .const import ENTITY_ID_ZONE_1 from tests.common import MockConfigEntry from tests.typing import WebSocketGenerator async def test_browse_media_root( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_russound_client: AsyncMock, hass_ws_client: WebSocketGenerator, snapshot: SnapshotAssertion, ) -> None: """Test the root browse page.""" await setup_integration(hass, mock_config_entry) client = await hass_ws_client() await client.send_json( { "id": 1, "type": "media_player/browse_media", "entity_id": ENTITY_ID_ZONE_1, } ) response = await client.receive_json() assert response["success"] assert response["result"]["children"] == snapshot async def test_browse_presets( hass: HomeAssistant, mock_russound_client: AsyncMock, mock_config_entry: MockConfigEntry, hass_ws_client: WebSocketGenerator, snapshot: SnapshotAssertion, ) -> None: """Test the presets browse page.""" await setup_integration(hass, mock_config_entry) client = await hass_ws_client() await client.send_json( { "id": 1, "type": "media_player/browse_media", "entity_id": ENTITY_ID_ZONE_1, "media_content_type": "presets", "media_content_id": "", } ) response = await client.receive_json() assert response["success"] assert response["result"]["children"] == snapshot
{ "repo_id": "home-assistant/core", "file_path": "tests/components/russound_rio/test_media_browser.py", "license": "Apache License 2.0", "lines": 50, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sleep_as_android/test_config_flow.py
"""Test the Sleep as Android config flow.""" from unittest.mock import AsyncMock, patch from homeassistant.components.sleep_as_android.const import DOMAIN from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_WEBHOOK_ID from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType async def test_form(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None: """Test we get the form.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM with ( patch( "homeassistant.components.webhook.async_generate_id", return_value="webhook_id", ), patch( "homeassistant.components.webhook.async_generate_url", return_value="http://example.com:8123", ), ): result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Sleep as Android" assert result["data"] == { "cloudhook": False, CONF_WEBHOOK_ID: "webhook_id", } assert len(mock_setup_entry.mock_calls) == 1
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sleep_as_android/test_config_flow.py", "license": "Apache License 2.0", "lines": 32, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sleep_as_android/test_diagnostics.py
"""Tests for Sleep as Android diagnostics.""" 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, config_entry: MockConfigEntry, snapshot: SnapshotAssertion, ) -> None: """Test diagnostics.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert ( await get_diagnostics_for_config_entry(hass, hass_client, config_entry) == snapshot )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sleep_as_android/test_diagnostics.py", "license": "Apache License 2.0", "lines": 20, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sleep_as_android/test_event.py
"""Test the Sleep as Android event platform.""" from collections.abc import Generator from http import HTTPStatus from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform from tests.typing import ClientSessionGenerator @pytest.fixture(autouse=True) def event_only() -> Generator[None]: """Enable only the event platform.""" with patch( "homeassistant.components.sleep_as_android.PLATFORMS", [Platform.EVENT], ): yield @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.freeze_time("2025-01-01T03:30:00.000Z") async def test_setup( hass: HomeAssistant, config_entry: MockConfigEntry, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, ) -> None: """Snapshot test states of event platform.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id) @pytest.mark.parametrize( ("entity", "payload"), [ ("sleep_tracking", {"event": "sleep_tracking_paused"}), ("sleep_tracking", {"event": "sleep_tracking_resumed"}), ("sleep_tracking", {"event": "sleep_tracking_started"}), ("sleep_tracking", {"event": "sleep_tracking_stopped"}), ( "alarm_clock", { "event": "alarm_alert_dismiss", "value1": "1582719660934", "value2": "label", }, ), ( "alarm_clock", { "event": "alarm_alert_start", "value1": "1582719660934", "value2": "label", }, ), ("alarm_clock", {"event": "alarm_rescheduled"}), ( "alarm_clock", {"event": "alarm_skip_next", "value1": "1582719660934", "value2": "label"}, ), ( "alarm_clock", { "event": "alarm_snooze_canceled", "value1": "1582719660934", "value2": "label", }, ), ( "alarm_clock", { "event": "alarm_snooze_clicked", "value1": "1582719660934", "value2": "label", }, ), ("smart_wake_up", {"event": "before_smart_period", "value1": "label"}), ("smart_wake_up", {"event": "smart_period"}), ("sleep_health", {"event": "antisnoring"}), ("sleep_health", {"event": "apnea_alarm"}), ("lullaby", {"event": "lullaby_start"}), ("lullaby", {"event": "lullaby_stop"}), ("lullaby", {"event": "lullaby_volume_down"}), ("sleep_phase", {"event": "awake"}), ("sleep_phase", {"event": "deep_sleep"}), ("sleep_phase", {"event": "light_sleep"}), ("sleep_phase", {"event": "not_awake"}), ("sleep_phase", {"event": "rem"}), ("sound_recognition", {"event": "sound_event_baby"}), ("sound_recognition", {"event": "sound_event_cough"}), ("sound_recognition", {"event": "sound_event_laugh"}), ("sound_recognition", {"event": "sound_event_snore"}), ("sound_recognition", {"event": "sound_event_talk"}), ("user_notification", {"event": "alarm_wake_up_check"}), ( "user_notification", { "event": "show_skip_next_alarm", "value1": "1582719660934", "value2": "label", }, ), ( "user_notification", { "event": "time_to_bed_alarm_alert", "value1": "1582719660934", "value2": "label", }, ), ("jet_lag_prevention", {"event": "jet_lag_start"}), ("jet_lag_prevention", {"event": "jet_lag_stop"}), ], ) @pytest.mark.usefixtures("entity_registry_enabled_by_default") @pytest.mark.freeze_time("2025-01-01T03:30:00.000+00:00") async def test_webhook_event( hass: HomeAssistant, config_entry: MockConfigEntry, hass_client_no_auth: ClientSessionGenerator, entity: str, payload: dict[str, str], ) -> None: """Test webhook events.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert (state := hass.states.get(f"event.sleep_as_android_{entity}")) assert state.state == STATE_UNKNOWN client = await hass_client_no_auth() response = await client.post("/api/webhook/webhook_id", json=payload) assert response.status == HTTPStatus.NO_CONTENT assert (state := hass.states.get(f"event.sleep_as_android_{entity}")) assert state.state == "2025-01-01T03:30:00.000+00:00" async def test_webhook_invalid( hass: HomeAssistant, config_entry: MockConfigEntry, hass_client_no_auth: ClientSessionGenerator, ) -> None: """Test webhook event call with invalid data.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED client = await hass_client_no_auth() response = await client.post("/api/webhook/webhook_id", json={}) assert response.status == HTTPStatus.UNPROCESSABLE_ENTITY
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sleep_as_android/test_event.py", "license": "Apache License 2.0", "lines": 150, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sleep_as_android/test_init.py
"""Test the Sleep as Android integration setup.""" from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry async def test_entry_setup_unload( hass: HomeAssistant, config_entry: MockConfigEntry ) -> None: """Test integration setup and unload.""" config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert await hass.config_entries.async_unload(config_entry.entry_id) assert config_entry.state is ConfigEntryState.NOT_LOADED
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sleep_as_android/test_init.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/sleep_as_android/test_sensor.py
"""Test the Sleep as Android sensor platform.""" from collections.abc import Generator from datetime import datetime from http import HTTPStatus from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant, State from homeassistant.helpers import entity_registry as er from tests.common import ( MockConfigEntry, mock_restore_cache_with_extra_data, snapshot_platform, ) from tests.typing import ClientSessionGenerator @pytest.fixture(autouse=True) def sensor_only() -> Generator[None]: """Enable only the sensor platform.""" with patch( "homeassistant.components.sleep_as_android.PLATFORMS", [Platform.SENSOR], ): yield async def test_setup( hass: HomeAssistant, config_entry: MockConfigEntry, snapshot: SnapshotAssertion, entity_registry: er.EntityRegistry, ) -> None: """Snapshot test states of sensor platform.""" mock_restore_cache_with_extra_data( hass, ( ( State( "sensor.sleep_as_android_next_alarm", "", ), { "native_value": datetime.fromisoformat("2020-02-26T12:21:00+00:00"), "native_unit_of_measurement": None, }, ), ( State( "sensor.sleep_as_android_alarm_label", "", ), { "native_value": "label", "native_unit_of_measurement": None, }, ), ), ) config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id) @pytest.mark.parametrize( "event", [ "alarm_snooze_clicked", "alarm_snooze_canceled", "alarm_skip_next", "show_skip_next_alarm", "alarm_rescheduled", ], ) async def test_webhook_sensor( hass: HomeAssistant, config_entry: MockConfigEntry, hass_client_no_auth: ClientSessionGenerator, event: str, ) -> None: """Test webhook updates sensor.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED assert (state := hass.states.get("sensor.sleep_as_android_next_alarm")) assert state.state == STATE_UNKNOWN assert (state := hass.states.get("sensor.sleep_as_android_alarm_label")) assert state.state == STATE_UNKNOWN client = await hass_client_no_auth() response = await client.post( "/api/webhook/webhook_id", json={ "event": event, "value1": "1582719660934", "value2": "label", }, ) assert response.status == HTTPStatus.NO_CONTENT assert (state := hass.states.get("sensor.sleep_as_android_next_alarm")) assert state.state == "2020-02-26T12:21:00+00:00" assert (state := hass.states.get("sensor.sleep_as_android_alarm_label")) assert state.state == "label" async def test_webhook_sensor_alarm_unset( hass: HomeAssistant, config_entry: MockConfigEntry, hass_client_no_auth: ClientSessionGenerator, ) -> None: """Test unsetting sensors if there is no next alarm.""" config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() assert config_entry.state is ConfigEntryState.LOADED client = await hass_client_no_auth() response = await client.post( "/api/webhook/webhook_id", json={ "event": "alarm_rescheduled", "value1": "1582719660934", "value2": "label", }, ) assert response.status == HTTPStatus.NO_CONTENT assert (state := hass.states.get("sensor.sleep_as_android_next_alarm")) assert state.state == "2020-02-26T12:21:00+00:00" assert (state := hass.states.get("sensor.sleep_as_android_alarm_label")) assert state.state == "label" response = await client.post( "/api/webhook/webhook_id", json={"event": "alarm_rescheduled"}, ) assert (state := hass.states.get("sensor.sleep_as_android_next_alarm")) assert state.state == STATE_UNKNOWN assert (state := hass.states.get("sensor.sleep_as_android_alarm_label")) assert state.state == STATE_UNKNOWN
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sleep_as_android/test_sensor.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/smarla/test_sensor.py
"""Test sensor platform for Swing2Sleep Smarla integration.""" from unittest.mock import MagicMock, patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import setup_integration, update_property_listeners from tests.common import MockConfigEntry, snapshot_platform SENSOR_ENTITIES = [ { "entity_id": "sensor.smarla_amplitude", "service": "analyser", "property": "oscillation", "test_value": [1, 0], }, { "entity_id": "sensor.smarla_period", "service": "analyser", "property": "oscillation", "test_value": [0, 1], }, { "entity_id": "sensor.smarla_activity", "service": "analyser", "property": "activity", "test_value": 1, }, { "entity_id": "sensor.smarla_swing_count", "service": "analyser", "property": "swing_count", "test_value": 1, }, ] @pytest.mark.usefixtures("mock_federwiege") async def test_entities( hass: HomeAssistant, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test the Smarla entities.""" with ( patch("homeassistant.components.smarla.PLATFORMS", [Platform.SENSOR]), ): assert await setup_integration(hass, mock_config_entry) await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id ) @pytest.mark.parametrize("entity_info", SENSOR_ENTITIES) async def test_sensor_state_update( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_federwiege: MagicMock, entity_info: dict[str, str], ) -> None: """Test Smarla Sensor callback.""" assert await setup_integration(hass, mock_config_entry) mock_sensor_property = mock_federwiege.get_property( entity_info["service"], entity_info["property"] ) entity_id = entity_info["entity_id"] state = hass.states.get(entity_id) assert state is not None assert state.state == "0" mock_sensor_property.get.return_value = entity_info["test_value"] await update_property_listeners(mock_sensor_property) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state is not None assert state.state == "1"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/smarla/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:tests/components/sonos/test_select.py
"""Tests for the Sonos select platform.""" import logging from unittest.mock import patch from freezegun.api import FrozenDateTimeFactory import pytest from homeassistant.components.select import ( DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION, ) from homeassistant.components.sonos.const import ( ATTR_DIALOG_LEVEL, MODEL_SONOS_ARC_ULTRA, SCAN_INTERVAL, ) from homeassistant.const import ATTR_ENTITY_ID, ATTR_OPTION, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .conftest import create_rendering_control_event from tests.common import async_fire_time_changed SELECT_DIALOG_LEVEL_ENTITY = "select.zone_a_speech_enhancement" @pytest.fixture(name="platform_select", autouse=True) async def platform_binary_sensor_fixture(): """Patch Sonos to only load select platform.""" with patch("homeassistant.components.sonos.PLATFORMS", [Platform.SELECT]): yield @pytest.mark.parametrize( ("level", "result"), [ (0, "off"), (1, "low"), ("2", "medium"), ("3", "high"), ("4", "max"), ], ) async def test_select_dialog_level( hass: HomeAssistant, async_setup_sonos, soco, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], level: int | str, result: str, ) -> None: """Test dialog level select entity.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = level await async_setup_sonos() dialog_level_select = entity_registry.entities[SELECT_DIALOG_LEVEL_ENTITY] dialog_level_state = hass.states.get(dialog_level_select.entity_id) assert dialog_level_state.state == result async def test_select_dialog_invalid_level( hass: HomeAssistant, async_setup_sonos, soco, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], caplog: pytest.LogCaptureFixture, ) -> None: """Test receiving an invalid level from the speaker.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = 10 with caplog.at_level(logging.WARNING): await async_setup_sonos() assert "Invalid option 10 for dialog_level" in caplog.text dialog_level_select = entity_registry.entities[SELECT_DIALOG_LEVEL_ENTITY] dialog_level_state = hass.states.get(dialog_level_select.entity_id) assert dialog_level_state.state == STATE_UNKNOWN @pytest.mark.parametrize( ("value", "result"), [ ("invalid_integer", "Invalid value for dialog_level_enum invalid_integer"), (None, "Missing value for dialog_level_enum"), ], ) async def test_select_dialog_value_error( hass: HomeAssistant, async_setup_sonos, soco, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], caplog: pytest.LogCaptureFixture, value: str | None, result: str, ) -> None: """Test receiving a value from Sonos that is not convertible to an integer.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = value with caplog.at_level(logging.WARNING): await async_setup_sonos() assert result in caplog.text assert SELECT_DIALOG_LEVEL_ENTITY not in entity_registry.entities @pytest.mark.parametrize( ("result", "option"), [ (0, "off"), (1, "low"), (2, "medium"), (3, "high"), (4, "max"), ], ) async def test_select_dialog_level_set( hass: HomeAssistant, async_setup_sonos, soco, speaker_info: dict[str, str], result: int, option: str, ) -> None: """Test setting dialog level select entity.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = 0 await async_setup_sonos() await hass.services.async_call( SELECT_DOMAIN, SERVICE_SELECT_OPTION, {ATTR_ENTITY_ID: SELECT_DIALOG_LEVEL_ENTITY, ATTR_OPTION: option}, blocking=True, ) assert soco.dialog_level == result async def test_select_dialog_level_only_arc_ultra( hass: HomeAssistant, async_setup_sonos, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], ) -> None: """Test the dialog level select is only created for Sonos Arc Ultra.""" speaker_info["model_name"] = "Sonos S1" await async_setup_sonos() assert SELECT_DIALOG_LEVEL_ENTITY not in entity_registry.entities async def test_select_dialog_level_event( hass: HomeAssistant, async_setup_sonos, soco, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], ) -> None: """Test dialog level select entity updated by event.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = "0" await async_setup_sonos() event = create_rendering_control_event(soco) event.variables[ATTR_DIALOG_LEVEL] = "3" soco.renderingControl.subscribe.return_value._callback(event) await hass.async_block_till_done(wait_background_tasks=True) dialog_level_select = entity_registry.entities[SELECT_DIALOG_LEVEL_ENTITY] dialog_level_state = hass.states.get(dialog_level_select.entity_id) assert dialog_level_state.state == "high" async def test_select_dialog_level_poll( hass: HomeAssistant, async_setup_sonos, soco, entity_registry: er.EntityRegistry, speaker_info: dict[str, str], freezer: FrozenDateTimeFactory, ) -> None: """Test entity updated by poll when subscription fails.""" speaker_info["model_name"] = MODEL_SONOS_ARC_ULTRA.lower() soco.get_speaker_info.return_value = speaker_info soco.dialog_level = "0" await async_setup_sonos() soco.dialog_level = "4" freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done(wait_background_tasks=True) dialog_level_select = entity_registry.entities[SELECT_DIALOG_LEVEL_ENTITY] dialog_level_state = hass.states.get(dialog_level_select.entity_id) assert dialog_level_state.state == "max"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/sonos/test_select.py", "license": "Apache License 2.0", "lines": 174, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/switchbot_cloud/test_cover.py
"""Test for the switchbot_cloud Cover.""" from unittest.mock import patch import pytest from switchbot_api import ( BlindTiltCommands, CommonCommands, CurtainCommands, Device, RollerShadeCommands, ) from homeassistant.components.cover import DOMAIN as COVER_DOMAIN from homeassistant.components.switchbot_cloud import SwitchBotAPI from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_CLOSE_COVER, SERVICE_CLOSE_COVER_TILT, SERVICE_OPEN_COVER, SERVICE_OPEN_COVER_TILT, SERVICE_SET_COVER_POSITION, SERVICE_SET_COVER_TILT_POSITION, SERVICE_STOP_COVER, STATE_CLOSED, STATE_OPEN, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant from . import configure_integration async def test_cover_set_attributes_normal( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test cover set_attributes normal.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Roller Shade", hubDeviceId="test-hub-id", ), ] cover_id = "cover.cover_1" mock_get_status.return_value = {"slidePosition": 100, "direction": "up"} await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_CLOSED @pytest.mark.parametrize( "device_model", [ "Roller Shade", "Blind Tilt", ], ) async def test_cover_set_attributes_position_is_none( hass: HomeAssistant, mock_list_devices, mock_get_status, device_model ) -> None: """Test cover_set_attributes position is none.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType=device_model, hubDeviceId="test-hub-id", ), ] cover_id = "cover.cover_1" mock_get_status.side_effect = [{"direction": "up"}, {"direction": "up"}] await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_UNKNOWN @pytest.mark.parametrize( "device_model", [ "Roller Shade", "Blind Tilt", ], ) async def test_cover_set_attributes_coordinator_is_none( hass: HomeAssistant, mock_list_devices, mock_get_status, device_model ) -> None: """Test cover set_attributes coordinator is none.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType=device_model, hubDeviceId="test-hub-id", ), ] cover_id = "cover.cover_1" mock_get_status.return_value = None await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_UNKNOWN async def test_curtain_features( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test curtain features.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Curtain", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ { "slidePosition": 95, }, { "slidePosition": 95, }, { "slidePosition": 95, }, { "slidePosition": 95, }, { "slidePosition": 95, }, { "slidePosition": 95, }, { "slidePosition": 95, }, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CommonCommands.ON, "command", "default" ) with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CommonCommands.OFF, "command", "default" ) with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_STOP_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CurtainCommands.PAUSE, "command", "default" ) with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_SET_COVER_POSITION, {"position": 50, ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CurtainCommands.SET_POSITION, "command", "0,ff,50" ) async def test_blind_tilt_features( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test blind_tilt features.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Blind Tilt", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ {"slidePosition": 95, "direction": "up"}, {"slidePosition": 95, "direction": "up"}, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_OPEN_COVER_TILT, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", BlindTiltCommands.FULLY_OPEN, "command", "default" ) with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_CLOSE_COVER_TILT, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", BlindTiltCommands.CLOSE_UP, "command", "default" ) with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_SET_COVER_TILT_POSITION, {"tilt_position": 25, ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", BlindTiltCommands.SET_POSITION, "command", "up;25" ) async def test_blind_tilt_features_close_down( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test blind tilt features close_down.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Blind Tilt", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ {"slidePosition": 25, "direction": "down"}, {"slidePosition": 25, "direction": "down"}, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_CLOSE_COVER_TILT, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", BlindTiltCommands.CLOSE_DOWN, "command", "default" ) async def test_roller_shade_features( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test roller shade features.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Roller Shade", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ { "slidePosition": 95, }, { "slidePosition": 95, }, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", RollerShadeCommands.SET_POSITION, "command", 0 ) await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_OPEN with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", RollerShadeCommands.SET_POSITION, "command", 100 ) await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_OPEN with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_SET_COVER_POSITION, {"position": 50, ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", RollerShadeCommands.SET_POSITION, "command", 50 ) async def test_cover_set_attributes_coordinator_is_none_for_garage_door( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test cover set_attributes coordinator is none for garage_door.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Garage Door Opener", hubDeviceId="test-hub-id", ), ] cover_id = "cover.cover_1" mock_get_status.return_value = None await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_UNKNOWN async def test_garage_door_features_close( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test garage door features close.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Garage Door Opener", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ { "doorStatus": 1, }, { "doorStatus": 1, }, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_CLOSE_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CommonCommands.OFF, "command", "default" ) await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_CLOSED async def test_garage_door_features_open( hass: HomeAssistant, mock_list_devices, mock_get_status ) -> None: """Test garage_door features open cover.""" mock_list_devices.return_value = [ Device( version="V1.0", deviceId="cover-id-1", deviceName="cover-1", deviceType="Garage Door Opener", hubDeviceId="test-hub-id", ), ] mock_get_status.side_effect = [ { "doorStatus": 0, }, { "doorStatus": 0, }, ] entry = await configure_integration(hass) assert entry.state is ConfigEntryState.LOADED cover_id = "cover.cover_1" with patch.object(SwitchBotAPI, "send_command") as mock_send_command: await hass.services.async_call( COVER_DOMAIN, SERVICE_OPEN_COVER, {ATTR_ENTITY_ID: cover_id}, blocking=True, ) mock_send_command.assert_called_once_with( "cover-id-1", CommonCommands.ON, "command", "default" ) await configure_integration(hass) state = hass.states.get(cover_id) assert state.state == STATE_OPEN
{ "repo_id": "home-assistant/core", "file_path": "tests/components/switchbot_cloud/test_cover.py", "license": "Apache License 2.0", "lines": 407, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/telegram_bot/test_notify.py
"""Test the telegram bot notify platform.""" from datetime import datetime from unittest.mock import AsyncMock, patch import pytest from telegram import Chat, Message from telegram.constants import ChatType, ParseMode from homeassistant.components.notify import ( ATTR_MESSAGE, ATTR_TITLE, DOMAIN as NOTIFY_DOMAIN, SERVICE_SEND_MESSAGE, ) from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import Context, HomeAssistant from tests.common import async_capture_events @pytest.mark.freeze_time("2025-01-09T12:00:00+00:00") async def test_send_message( hass: HomeAssistant, webhook_bot: None, ) -> None: """Test send message.""" context = Context() events = async_capture_events(hass, "telegram_sent") with patch( "homeassistant.components.telegram_bot.bot.Bot.send_message", AsyncMock( return_value=Message( message_id=12345, date=datetime.now(), chat=Chat(id=12345678, type=ChatType.PRIVATE), ) ), ) as mock_send_message: await hass.services.async_call( NOTIFY_DOMAIN, SERVICE_SEND_MESSAGE, { ATTR_ENTITY_ID: "notify.mock_title_mock_chat", ATTR_MESSAGE: "mock message", ATTR_TITLE: "mock title", }, blocking=True, context=context, ) await hass.async_block_till_done() mock_send_message.assert_called_once_with( 12345678, "mock title\nmock message", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=None, disable_notification=False, reply_to_message_id=None, reply_markup=None, read_timeout=None, message_thread_id=None, ) state = hass.states.get("notify.mock_title_mock_chat") assert state assert state.state == "2025-01-09T12:00:00+00:00" assert len(events) == 1 assert events[0].context == context
{ "repo_id": "home-assistant/core", "file_path": "tests/components/telegram_bot/test_notify.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/template/test_event.py
"""The tests for the Template event platform.""" from typing import Any import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components import event, template from homeassistant.const import ( ATTR_ENTITY_PICTURE, ATTR_ICON, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, State from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.setup import async_setup_component from .conftest import ConfigurationStyle, async_get_flow_preview_state from tests.common import ( MockConfigEntry, assert_setup_component, mock_restore_cache_with_extra_data, ) from tests.conftest import WebSocketGenerator TEST_OBJECT_ID = "template_event" TEST_ENTITY_ID = f"event.{TEST_OBJECT_ID}" TEST_SENSOR = "sensor.event" TEST_STATE_TRIGGER = { "trigger": {"trigger": "state", "entity_id": TEST_SENSOR}, "variables": {"triggering_entity": "{{ trigger.entity_id }}"}, "action": [ {"event": "action_event", "event_data": {"what": "{{ triggering_entity }}"}} ], } TEST_EVENT_TYPES_TEMPLATE = "{{ ['single', 'double', 'hold'] }}" TEST_EVENT_TYPE_TEMPLATE = "{{ 'single' }}" TEST_EVENT_CONFIG = { "event_types": TEST_EVENT_TYPES_TEMPLATE, "event_type": TEST_EVENT_TYPE_TEMPLATE, } TEST_UNIQUE_ID_CONFIG = { **TEST_EVENT_CONFIG, "unique_id": "not-so-unique-anymore", } TEST_FROZEN_INPUT = "2024-07-09 00:00:00+00:00" TEST_FROZEN_STATE = "2024-07-09T00:00:00.000+00:00" async def async_setup_modern_format( hass: HomeAssistant, count: int, event_config: dict[str, Any], extra_config: dict[str, Any] | None, ) -> None: """Do setup of event integration via new format.""" extra = extra_config or {} config = {**event_config, **extra} with assert_setup_component(count, template.DOMAIN): assert await async_setup_component( hass, template.DOMAIN, {"template": {"event": config}}, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() async def async_setup_trigger_format( hass: HomeAssistant, count: int, event_config: dict[str, Any], extra_config: dict[str, Any] | None, ) -> None: """Do setup of event integration via trigger format.""" extra = extra_config or {} config = { "template": { **TEST_STATE_TRIGGER, "event": {**event_config, **extra}, } } with assert_setup_component(count, template.DOMAIN): assert await async_setup_component( hass, template.DOMAIN, config, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() async def async_setup_event_config( hass: HomeAssistant, count: int, style: ConfigurationStyle, event_config: dict[str, Any], extra_config: dict[str, Any] | None, ) -> None: """Do setup of event integration.""" if style == ConfigurationStyle.MODERN: await async_setup_modern_format(hass, count, event_config, extra_config) elif style == ConfigurationStyle.TRIGGER: await async_setup_trigger_format(hass, count, event_config, extra_config) @pytest.fixture async def setup_base_event( hass: HomeAssistant, count: int, style: ConfigurationStyle, event_config: dict[str, Any], ) -> None: """Do setup of event integration.""" await async_setup_event_config( hass, count, style, event_config, None, ) @pytest.fixture async def setup_event( hass: HomeAssistant, count: int, style: ConfigurationStyle, event_type_template: str, event_types_template: str, extra_config: dict[str, Any] | None, ) -> None: """Do setup of event integration.""" await async_setup_event_config( hass, count, style, { "name": TEST_OBJECT_ID, "event_type": event_type_template, "event_types": event_types_template, }, extra_config, ) @pytest.fixture async def setup_single_attribute_state_event( hass: HomeAssistant, count: int, style: ConfigurationStyle, event_type_template: str, event_types_template: str, attribute: str, attribute_template: str, ) -> None: """Do setup of event integration testing a single attribute.""" extra = {attribute: attribute_template} if attribute and attribute_template else {} config = { "name": TEST_OBJECT_ID, "event_type": event_type_template, "event_types": event_types_template, } if style == ConfigurationStyle.MODERN: await async_setup_modern_format(hass, count, config, extra) elif style == ConfigurationStyle.TRIGGER: await async_setup_trigger_format(hass, count, config, extra) async def test_legacy_platform_config(hass: HomeAssistant) -> None: """Test a legacy platform does not create event entities.""" with assert_setup_component(1, event.DOMAIN): assert await async_setup_component( hass, event.DOMAIN, {"event": {"platform": "template", "events": {TEST_OBJECT_ID: {}}}}, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert hass.states.async_all("event") == [] @pytest.mark.freeze_time(TEST_FROZEN_INPUT) async def test_setup_config_entry( hass: HomeAssistant, snapshot: SnapshotAssertion, ) -> None: """Test the config flow.""" hass.states.async_set( TEST_SENSOR, "single", {}, ) template_config_entry = MockConfigEntry( data={}, domain=template.DOMAIN, options={ "name": TEST_OBJECT_ID, "event_type": TEST_EVENT_TYPE_TEMPLATE, "event_types": TEST_EVENT_TYPES_TEMPLATE, "template_type": event.DOMAIN, }, title="My template", ) template_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(template_config_entry.entry_id) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state is not None assert state == snapshot @pytest.mark.freeze_time(TEST_FROZEN_INPUT) async def test_device_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test for device for Template.""" device_config_entry = MockConfigEntry() device_config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=device_config_entry.entry_id, identifiers={("test", "identifier_test")}, connections={("mac", "30:31:32:33:34:35")}, ) await hass.async_block_till_done() assert device_entry is not None assert device_entry.id is not None template_config_entry = MockConfigEntry( data={}, domain=template.DOMAIN, options={ "name": "My template", "event_type": TEST_EVENT_TYPE_TEMPLATE, "event_types": TEST_EVENT_TYPES_TEMPLATE, "template_type": "event", "device_id": device_entry.id, }, title="My template", ) template_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(template_config_entry.entry_id) await hass.async_block_till_done() template_entity = entity_registry.async_get("event.my_template") assert template_entity is not None assert template_entity.device_id == device_entry.id @pytest.mark.parametrize( ("count", "event_types_template", "extra_config"), [(1, TEST_EVENT_TYPES_TEMPLATE, None)], ) @pytest.mark.parametrize( ("style", "expected_state"), [ (ConfigurationStyle.MODERN, STATE_UNKNOWN), (ConfigurationStyle.TRIGGER, STATE_UNKNOWN), ], ) @pytest.mark.parametrize("event_type_template", ["{{states.test['big.fat...']}}"]) @pytest.mark.usefixtures("setup_event") async def test_event_type_syntax_error( hass: HomeAssistant, expected_state: str, ) -> None: """Test template event_type with render error.""" state = hass.states.get(TEST_ENTITY_ID) assert state.state == expected_state @pytest.mark.parametrize( ("count", "event_type_template", "event_types_template", "extra_config"), [(1, "{{ states('sensor.event') }}", TEST_EVENT_TYPES_TEMPLATE, None)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.parametrize( ("event", "expected"), [ ("single", "single"), ("double", "double"), ("hold", "hold"), ], ) @pytest.mark.usefixtures("setup_event") async def test_event_type_template( hass: HomeAssistant, event: str, expected: str, ) -> None: """Test template event_type.""" hass.states.async_set(TEST_SENSOR, event) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["event_type"] == expected @pytest.mark.parametrize( ("count", "event_type_template", "event_types_template", "extra_config"), [(1, "{{ states('sensor.event') }}", TEST_EVENT_TYPES_TEMPLATE, None)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.usefixtures("setup_event") @pytest.mark.freeze_time(TEST_FROZEN_INPUT) async def test_event_type_template_updates( hass: HomeAssistant, ) -> None: """Test template event_type updates.""" hass.states.async_set(TEST_SENSOR, "single") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == TEST_FROZEN_STATE assert state.attributes["event_type"] == "single" hass.states.async_set(TEST_SENSOR, "double") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == TEST_FROZEN_STATE assert state.attributes["event_type"] == "double" hass.states.async_set(TEST_SENSOR, "hold") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == TEST_FROZEN_STATE assert state.attributes["event_type"] == "hold" @pytest.mark.parametrize( ("count", "event_types_template", "extra_config"), [(1, TEST_EVENT_TYPES_TEMPLATE, None)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.parametrize( "event_type_template", [ "{{ None }}", "{{ 7 }}", "{{ 'unknown' }}", "{{ 'tripple_double' }}", ], ) @pytest.mark.usefixtures("setup_event") async def test_event_type_invalid( hass: HomeAssistant, ) -> None: """Test template event_type.""" state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_UNKNOWN assert state.attributes["event_type"] is None @pytest.mark.parametrize( ("count", "event_type_template", "event_types_template"), [(1, "{{ states('sensor.event') }}", TEST_EVENT_TYPES_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.parametrize( ("attribute", "attribute_template", "key", "expected"), [ ( "picture", "{% if is_state('sensor.event', 'double') %}something{% endif %}", ATTR_ENTITY_PICTURE, "something", ), ( "icon", "{% if is_state('sensor.event', 'double') %}mdi:something{% endif %}", ATTR_ICON, "mdi:something", ), ], ) @pytest.mark.usefixtures("setup_single_attribute_state_event") async def test_entity_picture_and_icon_templates( hass: HomeAssistant, key: str, expected: str ) -> None: """Test picture and icon template.""" state = hass.states.async_set(TEST_SENSOR, "single") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.attributes.get(key) in ("", None) state = hass.states.async_set(TEST_SENSOR, "double") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.attributes[key] == expected @pytest.mark.parametrize( ("count", "event_type_template", "extra_config"), [(1, "{{ None }}", None)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.parametrize( ("event_types_template", "expected"), [ ( "{{ ['Strobe color', 'Police', 'Christmas', 'RGB', 'Random Loop'] }}", ["Strobe color", "Police", "Christmas", "RGB", "Random Loop"], ), ( "{{ ['Police', 'RGB', 'Random Loop'] }}", ["Police", "RGB", "Random Loop"], ), ("{{ [] }}", []), ("{{ '[]' }}", []), ("{{ 124 }}", []), ("{{ '124' }}", []), ("{{ none }}", []), ("", []), ], ) @pytest.mark.usefixtures("setup_event") async def test_event_types_template(hass: HomeAssistant, expected: str) -> None: """Test template event_types.""" hass.states.async_set(TEST_SENSOR, "anything") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["event_types"] == expected @pytest.mark.parametrize( ("count", "event_type_template", "event_types_template", "extra_config"), [ ( 1, "{{ states('sensor.event') }}", "{{ state_attr('sensor.event', 'options') or ['unknown'] }}", None, ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.usefixtures("setup_event") @pytest.mark.freeze_time(TEST_FROZEN_INPUT) async def test_event_types_template_updates(hass: HomeAssistant) -> None: """Test template event_type update with entity.""" hass.states.async_set( TEST_SENSOR, "single", {"options": ["single", "double", "hold"]} ) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == TEST_FROZEN_STATE assert state.attributes["event_type"] == "single" assert state.attributes["event_types"] == ["single", "double", "hold"] hass.states.async_set(TEST_SENSOR, "double", {"options": ["double", "hold"]}) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == TEST_FROZEN_STATE assert state.attributes["event_type"] == "double" assert state.attributes["event_types"] == ["double", "hold"] @pytest.mark.parametrize( ( "count", "event_type_template", "event_types_template", "attribute", "attribute_template", ), [ ( 1, "{{ states('sensor.event') }}", TEST_EVENT_TYPES_TEMPLATE, "availability", "{{ states('sensor.event') in ['single', 'double', 'hold'] }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.usefixtures("setup_single_attribute_state_event") async def test_available_template_with_entities(hass: HomeAssistant) -> None: """Test availability templates with values from other entities.""" hass.states.async_set(TEST_SENSOR, "single") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state != STATE_UNAVAILABLE assert state.attributes["event_type"] == "single" hass.states.async_set(TEST_SENSOR, "triple") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_UNAVAILABLE assert "event_type" not in state.attributes @pytest.mark.parametrize(("count", "domain"), [(1, "template")]) @pytest.mark.parametrize( "config", [ { "template": { "trigger": {"platform": "event", "event_type": "test_event"}, "event": { "name": TEST_OBJECT_ID, "event_type": "{{ trigger.event.data.action }}", "event_types": TEST_EVENT_TYPES_TEMPLATE, "picture": "{{ '/local/dogs.png' }}", "icon": "{{ 'mdi:pirate' }}", "attributes": { "plus_one": "{{ trigger.event.data.beer + 1 }}", "plus_two": "{{ trigger.event.data.beer + 2 }}", }, }, }, }, ], ) async def test_trigger_entity_restore_state( hass: HomeAssistant, count: int, domain: str, config: dict, ) -> None: """Test restoring trigger event entities.""" restored_attributes = { "entity_picture": "/local/cats.png", "event_type": "hold", "icon": "mdi:ship", "plus_one": 55, } fake_state = State( TEST_ENTITY_ID, "2021-01-01T23:59:59.123+00:00", restored_attributes, ) fake_extra_data = { "last_event_type": "hold", "last_event_attributes": restored_attributes, } mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) with assert_setup_component(count, domain): assert await async_setup_component( hass, domain, config, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() test_state = "2021-01-01T23:59:59.123+00:00" state = hass.states.get(TEST_ENTITY_ID) assert state.state == test_state for attr, value in restored_attributes.items(): assert state.attributes[attr] == value assert "plus_two" not in state.attributes hass.bus.async_fire("test_event", {"action": "double", "beer": 2}) await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state != test_state assert state.attributes["icon"] == "mdi:pirate" assert state.attributes["entity_picture"] == "/local/dogs.png" assert state.attributes["event_type"] == "double" assert state.attributes["event_types"] == ["single", "double", "hold"] assert state.attributes["plus_one"] == 3 assert state.attributes["plus_two"] == 4 @pytest.mark.parametrize(("count", "domain"), [(1, "template")]) @pytest.mark.parametrize( "config", [ { "template": { "event": { "name": TEST_OBJECT_ID, "event_type": "{{ states('sensor.event') }}", "event_types": TEST_EVENT_TYPES_TEMPLATE, }, }, }, ], ) async def test_event_entity_restore_state( hass: HomeAssistant, count: int, domain: str, config: dict, ) -> None: """Test restoring trigger event entities.""" fake_state = State( TEST_ENTITY_ID, "2021-01-01T23:59:59.123+00:00", {}, ) fake_extra_data = { "last_event_type": "hold", "last_event_attributes": {}, } mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) with assert_setup_component(count, domain): assert await async_setup_component( hass, domain, config, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() test_state = "2021-01-01T23:59:59.123+00:00" state = hass.states.get(TEST_ENTITY_ID) assert state.state == test_state hass.states.async_set(TEST_SENSOR, "double") await hass.async_block_till_done() state = hass.states.get(TEST_ENTITY_ID) assert state.state != test_state assert state.attributes["event_type"] == "double" @pytest.mark.parametrize( ( "count", "event_type_template", "event_types_template", "attribute", "attribute_template", ), [ ( 1, TEST_EVENT_TYPE_TEMPLATE, TEST_EVENT_TYPES_TEMPLATE, "availability", "{{ x - 12 }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], ) @pytest.mark.usefixtures("setup_single_attribute_state_event") async def test_invalid_availability_template_keeps_component_available( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, caplog_setup_text, ) -> None: """Test that an invalid availability keeps the device available.""" hass.states.async_set(TEST_SENSOR, "anything") await hass.async_block_till_done() assert hass.states.get(TEST_ENTITY_ID).state != STATE_UNAVAILABLE error = "UndefinedError: 'x' is undefined" assert error in caplog_setup_text or error in caplog.text @pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( ("events", "style"), [ ( [ { "name": "test_template_event_01", **TEST_UNIQUE_ID_CONFIG, }, { "name": "test_template_event_02", **TEST_UNIQUE_ID_CONFIG, }, ], ConfigurationStyle.MODERN, ), ( [ { "name": "test_template_event_01", **TEST_UNIQUE_ID_CONFIG, }, { "name": "test_template_event_02", **TEST_UNIQUE_ID_CONFIG, }, ], ConfigurationStyle.TRIGGER, ), ], ) async def test_unique_id( hass: HomeAssistant, count: int, events: list[dict], style: ConfigurationStyle ) -> None: """Test unique_id option only creates one event per id.""" config = {"event": events} if style == ConfigurationStyle.TRIGGER: config = {**config, **TEST_STATE_TRIGGER} with assert_setup_component(count, template.DOMAIN): assert await async_setup_component( hass, template.DOMAIN, {"template": config}, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert len(hass.states.async_all("event")) == 1 async def test_nested_unique_id( hass: HomeAssistant, entity_registry: er.EntityRegistry ) -> None: """Test unique_id option creates one event per nested id.""" with assert_setup_component(1, template.DOMAIN): assert await async_setup_component( hass, template.DOMAIN, { "template": { "unique_id": "x", "event": [ { "name": "test_a", **TEST_EVENT_CONFIG, "unique_id": "a", }, { "name": "test_b", **TEST_EVENT_CONFIG, "unique_id": "b", }, ], } }, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert len(hass.states.async_all("event")) == 2 entry = entity_registry.async_get("event.test_a") assert entry assert entry.unique_id == "x-a" entry = entity_registry.async_get("event.test_b") assert entry assert entry.unique_id == "x-b" @pytest.mark.freeze_time(TEST_FROZEN_INPUT) async def test_flow_preview( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, ) -> None: """Test the config flow preview.""" state = await async_get_flow_preview_state( hass, hass_ws_client, event.DOMAIN, {"name": "My template", **TEST_EVENT_CONFIG}, ) assert state["state"] == TEST_FROZEN_STATE assert state["attributes"]["event_type"] == "single" assert state["attributes"]["event_types"] == ["single", "double", "hold"]
{ "repo_id": "home-assistant/core", "file_path": "tests/components/template/test_event.py", "license": "Apache License 2.0", "lines": 722, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/template/test_update.py
"""The tests for the Template update platform.""" from typing import Any import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components import template, update from homeassistant.const import ( ATTR_ENTITY_PICTURE, ATTR_ICON, STATE_OFF, STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import HomeAssistant, ServiceCall, State from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.typing import ConfigType from homeassistant.setup import async_setup_component from .conftest import ( ConfigurationStyle, TemplatePlatformSetup, async_get_flow_preview_state, make_test_trigger, setup_and_test_nested_unique_id, setup_and_test_unique_id, setup_entity, ) from tests.common import ( MockConfigEntry, assert_setup_component, mock_restore_cache_with_extra_data, ) from tests.conftest import WebSocketGenerator TEST_INSTALLED_SENSOR = "sensor.installed_update" TEST_LATEST_SENSOR = "sensor.latest_update" TEST_SENSOR_ID = "sensor.test_update" TEST_INSTALLED_TEMPLATE = "{{ '1.0' }}" TEST_LATEST_TEMPLATE = "{{ '2.0' }}" TEST_UPDATE = TemplatePlatformSetup( update.DOMAIN, None, "template_update", make_test_trigger(TEST_INSTALLED_SENSOR, TEST_LATEST_SENSOR, TEST_SENSOR_ID), ) TEST_UPDATE_CONFIG = { "installed_version": TEST_INSTALLED_TEMPLATE, "latest_version": TEST_LATEST_TEMPLATE, } INSTALL_ACTION = { "install": { "action": "test.automation", "data": { "caller": "{{ this.entity_id }}", "action": "install", "backup": "{{ backup }}", "specific_version": "{{ specific_version }}", }, } } @pytest.fixture async def setup_base( hass: HomeAssistant, count: int, style: ConfigurationStyle, config: dict[str, Any], ) -> None: """Do setup of update integration.""" await setup_entity(hass, TEST_UPDATE, style, count, config) @pytest.fixture async def setup_update( hass: HomeAssistant, count: int, style: ConfigurationStyle, installed_template: str, latest_template: str, extra_config: dict[str, Any] | None, ) -> None: """Do setup of update integration.""" await setup_entity( hass, TEST_UPDATE, style, count, { "installed_version": installed_template, "latest_version": latest_template, }, extra_config=extra_config, ) @pytest.fixture async def setup_single_attribute_update( hass: HomeAssistant, style: ConfigurationStyle, installed_template: str, latest_template: str, attribute: str, attribute_template: str, ) -> None: """Do setup of update platform testing a single attribute.""" await setup_entity( hass, TEST_UPDATE, style, 1, { "installed_version": installed_template, "latest_version": latest_template, }, extra_config=( {attribute: attribute_template} if attribute and attribute_template else {} ), ) async def test_legacy_platform_config(hass: HomeAssistant) -> None: """Test a legacy platform does not create update entities.""" with assert_setup_component(1, update.DOMAIN): assert await async_setup_component( hass, update.DOMAIN, {"update": {"platform": "template", "updates": {"anything": {}}}}, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() assert hass.states.async_all("update") == [] async def test_setup_config_entry( hass: HomeAssistant, snapshot: SnapshotAssertion, ) -> None: """Test the config flow.""" template_config_entry = MockConfigEntry( data={}, domain=template.DOMAIN, options={ "name": TEST_UPDATE.object_id, "template_type": update.DOMAIN, **TEST_UPDATE_CONFIG, }, title="My template", ) template_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(template_config_entry.entry_id) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state == snapshot async def test_device_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: """Test for device for Template.""" device_config_entry = MockConfigEntry() device_config_entry.add_to_hass(hass) device_entry = device_registry.async_get_or_create( config_entry_id=device_config_entry.entry_id, identifiers={("test", "identifier_test")}, connections={("mac", "30:31:32:33:34:35")}, ) await hass.async_block_till_done() assert device_entry is not None assert device_entry.id is not None template_config_entry = MockConfigEntry( data={}, domain=template.DOMAIN, options={ "name": TEST_UPDATE.object_id, "template_type": update.DOMAIN, **TEST_UPDATE_CONFIG, "device_id": device_entry.id, }, title="My template", ) template_config_entry.add_to_hass(hass) assert await hass.config_entries.async_setup(template_config_entry.entry_id) await hass.async_block_till_done() template_entity = entity_registry.async_get(TEST_UPDATE.entity_id) assert template_entity is not None assert template_entity.device_id == device_entry.id @pytest.mark.parametrize(("count", "extra_config"), [(1, None)]) @pytest.mark.parametrize( ("style", "expected_state"), [ (ConfigurationStyle.MODERN, STATE_UNKNOWN), (ConfigurationStyle.TRIGGER, STATE_UNKNOWN), ], ) @pytest.mark.parametrize( ("installed_template", "latest_template"), [ ("{{states.test['big.fat...']}}", TEST_LATEST_TEMPLATE), (TEST_INSTALLED_TEMPLATE, "{{states.test['big.fat...']}}"), ("{{states.test['big.fat...']}}", "{{states.test['big.fat...']}}"), ], ) @pytest.mark.usefixtures("setup_update") async def test_syntax_error( hass: HomeAssistant, expected_state: str, ) -> None: """Test template update with render error.""" state = hass.states.get(TEST_UPDATE.entity_id) assert state.state == expected_state @pytest.mark.parametrize( ("count", "extra_config", "installed_template", "latest_template"), [ ( 1, None, "{{ states('sensor.installed_update') }}", "{{ states('sensor.latest_update') }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("installed", "latest", "expected"), [ ("1.0", "2.0", STATE_ON), ("2.0", "2.0", STATE_OFF), ], ) @pytest.mark.usefixtures("setup_update") async def test_update_templates( hass: HomeAssistant, installed: str, latest: str, expected: str ) -> None: """Test update template.""" hass.states.async_set(TEST_INSTALLED_SENSOR, installed) hass.states.async_set(TEST_LATEST_SENSOR, latest) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == expected assert state.attributes["installed_version"] == installed assert state.attributes["latest_version"] == latest # ensure that the entity picture exists when not provided. assert ( state.attributes["entity_picture"] == "/api/brands/integration/template/icon.png" ) @pytest.mark.parametrize( ("count", "extra_config", "installed_template", "latest_template"), [ ( 1, None, "{{ states('sensor.installed_update') }}", "{{ states('sensor.latest_update') }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.usefixtures("setup_update") async def test_installed_and_latest_template_updates_from_entity( hass: HomeAssistant, ) -> None: """Test template installed and latest version templates updates from entities.""" hass.states.async_set(TEST_INSTALLED_SENSOR, "1.0") hass.states.async_set(TEST_LATEST_SENSOR, "2.0") await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == STATE_ON assert state.attributes["installed_version"] == "1.0" assert state.attributes["latest_version"] == "2.0" hass.states.async_set(TEST_INSTALLED_SENSOR, "2.0") hass.states.async_set(TEST_LATEST_SENSOR, "2.0") await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == STATE_OFF assert state.attributes["installed_version"] == "2.0" assert state.attributes["latest_version"] == "2.0" hass.states.async_set(TEST_INSTALLED_SENSOR, "2.0") hass.states.async_set(TEST_LATEST_SENSOR, "3.0") await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == STATE_ON assert state.attributes["installed_version"] == "2.0" assert state.attributes["latest_version"] == "3.0" @pytest.mark.parametrize( ("count", "extra_config", "latest_template"), [(1, None, TEST_LATEST_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("installed_template", "expected", "expected_attr"), [ ("{{ '1.0' }}", STATE_ON, "1.0"), ("{{ 1.0 }}", STATE_ON, "1.0"), ("{{ '2.0' }}", STATE_OFF, "2.0"), ("{{ 2.0 }}", STATE_OFF, "2.0"), ("{{ None }}", STATE_UNKNOWN, None), ("{{ 'foo' }}", STATE_ON, "foo"), ("{{ x + 2 }}", STATE_UNKNOWN, None), ], ) @pytest.mark.usefixtures("setup_update") async def test_installed_version_template( hass: HomeAssistant, expected: str, expected_attr: Any ) -> None: """Test installed_version template results.""" # Ensure trigger based template entities update hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_ON) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == expected assert state.attributes["installed_version"] == expected_attr @pytest.mark.parametrize( ("count", "extra_config", "installed_template"), [(1, None, TEST_INSTALLED_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("latest_template", "expected", "expected_attr"), [ ("{{ '1.0' }}", STATE_OFF, "1.0"), ("{{ 1.0 }}", STATE_OFF, "1.0"), ("{{ '2.0' }}", STATE_ON, "2.0"), ("{{ 2.0 }}", STATE_ON, "2.0"), ("{{ None }}", STATE_UNKNOWN, None), ("{{ 'foo' }}", STATE_ON, "foo"), ("{{ x + 2 }}", STATE_UNKNOWN, None), ], ) @pytest.mark.usefixtures("setup_update") async def test_latest_version_template( hass: HomeAssistant, expected: str, expected_attr: Any ) -> None: """Test latest_version template results.""" # Ensure trigger based template entities update hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_ON) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state is not None assert state.state == expected assert state.attributes["latest_version"] == expected_attr @pytest.mark.parametrize( ("count", "extra_config", "installed_template", "latest_template"), [ ( 1, INSTALL_ACTION, "{{ states('sensor.installed_update') }}", "{{ states('sensor.latest_update') }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.usefixtures("setup_update") async def test_install_action(hass: HomeAssistant, calls: list[ServiceCall]) -> None: """Test install action.""" hass.states.async_set(TEST_INSTALLED_SENSOR, "1.0") hass.states.async_set(TEST_LATEST_SENSOR, "2.0") await hass.async_block_till_done() await hass.services.async_call( update.DOMAIN, update.SERVICE_INSTALL, {"entity_id": TEST_UPDATE.entity_id}, blocking=True, ) await hass.async_block_till_done() # verify assert len(calls) == 1 assert calls[-1].data["action"] == "install" assert calls[-1].data["caller"] == TEST_UPDATE.entity_id hass.states.async_set(TEST_INSTALLED_SENSOR, "2.0") hass.states.async_set(TEST_LATEST_SENSOR, "2.0") await hass.async_block_till_done() # Ensure an error is raised when there's no update. with pytest.raises(HomeAssistantError): await hass.services.async_call( update.DOMAIN, update.SERVICE_INSTALL, {"entity_id": TEST_UPDATE.entity_id}, blocking=True, ) await hass.async_block_till_done() # verify assert len(calls) == 1 assert calls[-1].data["action"] == "install" assert calls[-1].data["caller"] == TEST_UPDATE.entity_id @pytest.mark.parametrize( ("installed_template", "latest_template"), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("attribute", "attribute_template", "key", "expected"), [ ( "picture", "{% if is_state('sensor.installed_update', 'on') %}something{% endif %}", ATTR_ENTITY_PICTURE, "something", ), ( "icon", "{% if is_state('sensor.installed_update', 'on') %}mdi:something{% endif %}", ATTR_ICON, "mdi:something", ), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_entity_picture_and_icon_templates( hass: HomeAssistant, key: str, expected: str ) -> None: """Test picture and icon template.""" state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes.get(key) in ("", None) state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_ON) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes[key] == expected @pytest.mark.parametrize( ("installed_template", "latest_template"), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("attribute", "attribute_template"), [ ( "picture", "{{ 'foo.png' if is_state('sensor.installed_update', 'on') else None }}", ), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_entity_picture_uses_default(hass: HomeAssistant) -> None: """Test entity picture when template resolves None.""" state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_ON) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes[ATTR_ENTITY_PICTURE] == "foo.png" state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert ( state.attributes[ATTR_ENTITY_PICTURE] == "/api/brands/integration/template/icon.png" ) @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute"), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "in_progress")], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("attribute_template", "expected", "error"), [ ("{{ True }}", True, None), ("{{ False }}", False, None), ("{{ None }}", False, "Received invalid update in_progress: None"), ( "{{ 'foo' }}", False, "Received invalid update in_progress: foo", ), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_in_process_template( hass: HomeAssistant, attribute: str, expected: Any, error: str | None, caplog: pytest.LogCaptureFixture, caplog_setup_text: str, ) -> None: """Test in process templates.""" # Ensure trigger entities trigger. state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes.get(attribute) == expected assert error is None or error in caplog_setup_text or error in caplog.text @pytest.mark.parametrize( ( "installed_template", "latest_template", ), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize("attribute", ["release_summary", "title"]) @pytest.mark.parametrize( ("attribute_template", "expected"), [ ("{{ True }}", "True"), ("{{ False }}", "False"), ("{{ None }}", None), ("{{ 'foo' }}", "foo"), ("{{ 1.0 }}", "1.0"), ("{{ x + 2 }}", None), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_release_summary_and_title_templates( hass: HomeAssistant, attribute: str, expected: Any, ) -> None: """Test release summary and title templates.""" # Ensure trigger entities trigger. state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes.get(attribute) == expected @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute"), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "release_url")], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("attribute_template", "expected", "error"), [ ("{{ 'http://foo.bar' }}", "http://foo.bar", None), ("{{ 'https://foo.bar' }}", "https://foo.bar", None), ("{{ None }}", None, None), ( "{{ '/local/thing' }}", None, "Received invalid update release_url: /local/thing", ), ( "{{ 'foo' }}", None, "Received invalid update release_url: foo", ), ( "{{ 1.0 }}", None, "Received invalid update release_url: 1", ), ( "{{ True }}", None, "Received invalid update release_url: True", ), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_release_url_template( hass: HomeAssistant, attribute: str, expected: Any, error: str | None, caplog: pytest.LogCaptureFixture, caplog_setup_text: str, ) -> None: """Test release url templates.""" # Ensure trigger entities trigger. state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes.get(attribute) == expected assert error is None or error in caplog_setup_text or error in caplog.text @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute"), [(TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "update_percentage")], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ("attribute_template", "expected", "error"), [ ("{{ 100 }}", 100, None), ("{{ 0 }}", 0, None), ("{{ 45 }}", 45, None), ("{{ None }}", None, None), ("{{ -1 }}", None, "Received invalid update update_percentage: -1"), ("{{ 101 }}", None, "Received invalid update update_percentage: 101"), ("{{ 'foo' }}", None, "Received invalid update update_percentage: foo"), ("{{ x - 4 }}", None, "UndefinedError: 'x' is undefined"), ], ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_update_percent_template( hass: HomeAssistant, attribute: str, expected: Any, error: str | None, caplog: pytest.LogCaptureFixture, caplog_setup_text: str, ) -> None: """Test update percent templates.""" # Ensure trigger entities trigger. state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes.get(attribute) == expected assert error is None or error in caplog_setup_text or error in caplog.text @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute", "attribute_template"), [ ( TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "update_percentage", "{% set e = 'sensor.test_update' %}{{ states(e) if e | has_value else None }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_optimistic_in_progress_with_update_percent_template( hass: HomeAssistant, ) -> None: """Test optimistic in_progress attribute with update percent templates.""" # Ensure trigger entities trigger. state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes["in_progress"] is False assert state.attributes["update_percentage"] is None for i in range(101): state = hass.states.async_set(TEST_SENSOR_ID, i) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes["in_progress"] is True assert state.attributes["update_percentage"] == i state = hass.states.async_set(TEST_SENSOR_ID, STATE_UNAVAILABLE) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes["in_progress"] is False assert state.attributes["update_percentage"] is None @pytest.mark.parametrize( ( "count", "installed_template", "latest_template", ), [(1, TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE)], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.parametrize( ( "extra_config", "supported_feature", "action_data", "expected_backup", "expected_version", ), [ ( {"backup": True, **INSTALL_ACTION}, update.UpdateEntityFeature.BACKUP | update.UpdateEntityFeature.INSTALL, {"backup": True}, True, None, ), ( {"specific_version": True, **INSTALL_ACTION}, update.UpdateEntityFeature.SPECIFIC_VERSION | update.UpdateEntityFeature.INSTALL, {"version": "v2.0"}, False, "v2.0", ), ( {"backup": True, "specific_version": True, **INSTALL_ACTION}, update.UpdateEntityFeature.SPECIFIC_VERSION | update.UpdateEntityFeature.BACKUP | update.UpdateEntityFeature.INSTALL, {"backup": True, "version": "v2.0"}, True, "v2.0", ), (INSTALL_ACTION, update.UpdateEntityFeature.INSTALL, {}, False, None), ], ) @pytest.mark.usefixtures("setup_update") async def test_supported_features( hass: HomeAssistant, supported_feature: update.UpdateEntityFeature, action_data: dict, calls: list[ServiceCall], expected_backup: bool, expected_version: str | None, ) -> None: """Test release summary and title templates.""" # Ensure trigger entities trigger. state = hass.states.async_set(TEST_INSTALLED_SENSOR, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.attributes["supported_features"] == supported_feature await hass.services.async_call( update.DOMAIN, update.SERVICE_INSTALL, {"entity_id": TEST_UPDATE.entity_id, **action_data}, blocking=True, ) await hass.async_block_till_done() # verify assert len(calls) == 1 data = calls[-1].data assert data["action"] == "install" assert data["caller"] == TEST_UPDATE.entity_id assert data["backup"] == expected_backup assert data["specific_version"] == expected_version @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute", "attribute_template"), [ ( TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "availability", "{{ 'sensor.test_update' | has_value }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_available_template_with_entities(hass: HomeAssistant) -> None: """Test availability templates with values from other entities.""" hass.states.async_set(TEST_SENSOR_ID, STATE_ON) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.state != STATE_UNAVAILABLE hass.states.async_set(TEST_SENSOR_ID, STATE_UNAVAILABLE) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.state == STATE_UNAVAILABLE hass.states.async_set(TEST_SENSOR_ID, STATE_OFF) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.state != STATE_UNAVAILABLE @pytest.mark.parametrize( ("installed_template", "latest_template", "attribute", "attribute_template"), [ ( TEST_INSTALLED_TEMPLATE, TEST_LATEST_TEMPLATE, "availability", "{{ x - 12 }}", ) ], ) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) @pytest.mark.usefixtures("setup_single_attribute_update") async def test_invalid_availability_template_keeps_component_available( hass: HomeAssistant, caplog: pytest.LogCaptureFixture, caplog_setup_text, ) -> None: """Test that an invalid availability keeps the device available.""" # Ensure entity triggers hass.states.async_set(TEST_SENSOR_ID, "anything") await hass.async_block_till_done() assert hass.states.get(TEST_UPDATE.entity_id).state != STATE_UNAVAILABLE error = "UndefinedError: 'x' is undefined" assert error in caplog_setup_text or error in caplog.text @pytest.mark.parametrize(("count", "domain"), [(1, "template")]) @pytest.mark.parametrize( "config", [ { "template": { "trigger": {"platform": "event", "event_type": "test_event"}, "update": { "name": TEST_UPDATE.object_id, "installed_version": "{{ trigger.event.data.action }}", "latest_version": "{{ '1.0.2' }}", "picture": "{{ '/local/dogs.png' }}", "icon": "{{ 'mdi:pirate' }}", }, }, }, ], ) async def test_trigger_entity_restore_state( hass: HomeAssistant, count: int, domain: str, config: dict, ) -> None: """Test restoring trigger entities.""" restored_attributes = { "installed_version": "1.0.0", "latest_version": "1.0.1", "entity_picture": "/local/cats.png", "icon": "mdi:ship", "skipped_version": "1.0.1", } fake_state = State( TEST_UPDATE.entity_id, STATE_OFF, restored_attributes, ) mock_restore_cache_with_extra_data(hass, ((fake_state, {}),)) with assert_setup_component(count, domain): assert await async_setup_component( hass, domain, config, ) await hass.async_block_till_done() await hass.async_start() await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.state == STATE_OFF for attr, value in restored_attributes.items(): assert state.attributes[attr] == value hass.bus.async_fire("test_event", {"action": "1.0.0"}) await hass.async_block_till_done() state = hass.states.get(TEST_UPDATE.entity_id) assert state.state == STATE_ON assert state.attributes["icon"] == "mdi:pirate" assert state.attributes["entity_picture"] == "/local/dogs.png" @pytest.mark.parametrize("config", [TEST_UPDATE_CONFIG]) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) async def test_unique_id( hass: HomeAssistant, style: ConfigurationStyle, config: ConfigType ) -> None: """Test unique_id option only creates one update entity per id.""" await setup_and_test_unique_id(hass, TEST_UPDATE, style, config) @pytest.mark.parametrize("config", [TEST_UPDATE_CONFIG]) @pytest.mark.parametrize( "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] ) async def test_nested_unique_id( hass: HomeAssistant, style: ConfigurationStyle, config: ConfigType, entity_registry: er.EntityRegistry, ) -> None: """Test unique_id option creates one update entity per nested id.""" await setup_and_test_nested_unique_id( hass, TEST_UPDATE, style, entity_registry, config ) async def test_flow_preview( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, ) -> None: """Test the config flow preview.""" state = await async_get_flow_preview_state( hass, hass_ws_client, update.DOMAIN, {"name": "My template", **TEST_UPDATE_CONFIG}, ) assert state["state"] == STATE_ON assert state["attributes"]["installed_version"] == "1.0" assert state["attributes"]["latest_version"] == "2.0"
{ "repo_id": "home-assistant/core", "file_path": "tests/components/template/test_update.py", "license": "Apache License 2.0", "lines": 877, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/togrill/test_config_flow.py
"""Test the ToGrill config flow.""" from unittest.mock import Mock from bleak.exc import BleakError import pytest from homeassistant import config_entries from homeassistant.components.togrill.const import DOMAIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from . import TOGRILL_SERVICE_INFO, TOGRILL_SERVICE_INFO_NO_NAME, setup_entry from tests.common import MockConfigEntry from tests.components.bluetooth import inject_bluetooth_service_info pytestmark = pytest.mark.usefixtures("mock_setup_entry") async def test_user_selection( hass: HomeAssistant, ) -> None: """Test we can select a device.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO_NO_NAME) await hass.async_block_till_done(wait_background_tasks=True) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"address": TOGRILL_SERVICE_INFO.address}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"] == { "address": TOGRILL_SERVICE_INFO.address, "model": "Pro-05", "probe_count": 0, "has_ambient": False, } assert result["title"] == "Pro-05" assert result["result"].unique_id == TOGRILL_SERVICE_INFO.address async def test_user_selection_ignored( hass: HomeAssistant, ) -> None: """Test we can select a device.""" entry = MockConfigEntry( domain=DOMAIN, unique_id=TOGRILL_SERVICE_INFO.address, source=config_entries.SOURCE_IGNORE, ) entry.add_to_hass(hass) inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await hass.async_block_till_done(wait_background_tasks=True) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"address": TOGRILL_SERVICE_INFO.address}, ) assert result["type"] is FlowResultType.CREATE_ENTRY async def test_failed_connect( hass: HomeAssistant, mock_client: Mock, mock_client_class: Mock, ) -> None: """Test failure to connect result.""" mock_client_class.connect.side_effect = BleakError("Failed to connect") inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"address": TOGRILL_SERVICE_INFO.address}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "failed_to_read_config" async def test_failed_read( hass: HomeAssistant, mock_client: Mock, ) -> None: """Test failure to read from device.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" mock_client.read.side_effect = BleakError("something went wrong") result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"address": TOGRILL_SERVICE_INFO.address}, ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "failed_to_read_config" async def test_no_devices( hass: HomeAssistant, ) -> None: """Test missing device.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO_NO_NAME) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_devices_found" async def test_duplicate_setup( hass: HomeAssistant, mock_entry: MockConfigEntry, ) -> None: """Test we can not setup a device again.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await hass.async_block_till_done(wait_background_tasks=True) await setup_entry(hass, mock_entry, []) result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": config_entries.SOURCE_USER} ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_devices_found" async def test_bluetooth( hass: HomeAssistant, ) -> None: """Test bluetooth device discovery.""" # Inject the service info will trigger the flow to start inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await hass.async_block_till_done(wait_background_tasks=True) result = next(iter(hass.config_entries.flow.async_progress_by_handler(DOMAIN))) assert result["step_id"] == "bluetooth_confirm" result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["data"] == { "address": TOGRILL_SERVICE_INFO.address, "model": "Pro-05", "probe_count": 0, "has_ambient": False, } assert result["title"] == "Pro-05" assert result["result"].unique_id == TOGRILL_SERVICE_INFO.address
{ "repo_id": "home-assistant/core", "file_path": "tests/components/togrill/test_config_flow.py", "license": "Apache License 2.0", "lines": 140, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/togrill/test_event.py
"""Test events for ToGrill integration.""" from unittest.mock import Mock import pytest from syrupy.assertion import SnapshotAssertion from togrill_bluetooth.packets import PacketA1Notify, PacketA5Notify from homeassistant.components.event import ATTR_EVENT_TYPE from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.util import slugify from . import TOGRILL_SERVICE_INFO, setup_entry from tests.common import MockConfigEntry, snapshot_platform from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.freeze_time("2023-10-21") @pytest.mark.parametrize( "packets", [ pytest.param([], id="no_data"), pytest.param([PacketA1Notify([10, None])], id="non_event_packet"), pytest.param([PacketA5Notify(probe=1, message=99)], id="non_known_message"), ], ) async def test_setup( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, packets, ) -> None: """Test standard events.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.EVENT]) for packet in packets: mock_client.mocked_notify(packet) await snapshot_platform(hass, entity_registry, snapshot, mock_entry.entry_id) @pytest.mark.freeze_time("2023-10-21") @pytest.mark.parametrize( "message", [pytest.param(message, id=message.name) for message in PacketA5Notify.Message], ) async def test_events( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, message: PacketA5Notify.Message, ) -> None: """Test all possible events.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.EVENT]) mock_client.mocked_notify(PacketA5Notify(probe=1, message=message)) state = hass.states.get("event.probe_2_event") assert state assert state.state == STATE_UNKNOWN state = hass.states.get("event.probe_1_event") assert state assert state.state == "2023-10-21T00:00:00.000+00:00" assert state.attributes.get(ATTR_EVENT_TYPE) == slugify(message.name)
{ "repo_id": "home-assistant/core", "file_path": "tests/components/togrill/test_event.py", "license": "Apache License 2.0", "lines": 60, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/togrill/test_init.py
"""Test for initialization of ToGrill integration.""" from unittest.mock import Mock from bleak.exc import BleakError from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from . import TOGRILL_SERVICE_INFO, setup_entry from tests.common import MockConfigEntry from tests.components.bluetooth import inject_bluetooth_service_info async def test_setup_device_present( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, mock_client_class: Mock, device_registry: dr.DeviceRegistry, ) -> None: """Test that setup works with device present.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, []) assert mock_entry.state is ConfigEntryState.LOADED device = device_registry.async_get_device( connections={(dr.CONNECTION_BLUETOOTH, TOGRILL_SERVICE_INFO.address)} ) assert device == snapshot async def test_setup_device_not_present( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, mock_client_class: Mock, ) -> None: """Test that setup succeeds if device is missing.""" await setup_entry(hass, mock_entry, []) assert mock_entry.state is ConfigEntryState.LOADED async def test_setup_device_failing( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, mock_client_class: Mock, ) -> None: """Test that setup fails if device is not responding.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) mock_client.is_connected = False mock_client.read.side_effect = BleakError("Failed to read data") await setup_entry(hass, mock_entry, []) assert mock_entry.state is ConfigEntryState.SETUP_RETRY
{ "repo_id": "home-assistant/core", "file_path": "tests/components/togrill/test_init.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/togrill/test_number.py
"""Test numbers for ToGrill integration.""" from unittest.mock import Mock from bleak.exc import BleakError import pytest from syrupy.assertion import SnapshotAssertion from togrill_bluetooth.exceptions import BaseError from togrill_bluetooth.packets import ( PacketA0Notify, PacketA6Write, PacketA8Notify, PacketA300Write, PacketA301Write, ) from homeassistant.components.number import ( ATTR_VALUE, DOMAIN as NUMBER_DOMAIN, SERVICE_SET_VALUE, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import TOGRILL_SERVICE_INFO, setup_entry from tests.common import MockConfigEntry, snapshot_platform from tests.components.bluetooth import inject_bluetooth_service_info @pytest.mark.parametrize( "packets", [ pytest.param([], id="no_data"), pytest.param( [ PacketA0Notify( battery=45, version_major=1, version_minor=5, function_type=1, probe_count=2, ambient=False, alarm_interval=5, alarm_sound=True, ), PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET, temperature_1=50.0, ), PacketA8Notify(probe=2, alarm_type=None), ], id="one_probe_with_target_alarm", ), ], ) async def test_setup( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, packets, ) -> None: """Test the numbers.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.NUMBER]) for packet in packets: mock_client.mocked_notify(packet) await snapshot_platform(hass, entity_registry, snapshot, mock_entry.entry_id) @pytest.mark.parametrize( ("packets", "entity_id", "value", "write_packet"), [ pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET, temperature_1=50.0, ), ], "number.probe_1_target_temperature", 100.0, PacketA301Write(probe=1, target=100), id="probe", ), pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET, temperature_1=50.0, ), ], "number.probe_1_target_temperature", 0.0, PacketA301Write(probe=1, target=None), id="probe_clear", ), pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_RANGE, temperature_1=50.0, temperature_2=80.0, ), ], "number.probe_1_minimum_temperature", 100.0, PacketA300Write(probe=1, minimum=100.0, maximum=80.0), id="minimum", ), pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_RANGE, temperature_1=None, temperature_2=80.0, ), ], "number.probe_1_minimum_temperature", 0.0, PacketA300Write(probe=1, minimum=None, maximum=80.0), id="minimum_clear", ), pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_RANGE, temperature_1=50.0, temperature_2=80.0, ), ], "number.probe_1_maximum_temperature", 100.0, PacketA300Write(probe=1, minimum=50.0, maximum=100.0), id="maximum", ), pytest.param( [ PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_RANGE, temperature_1=50.0, temperature_2=None, ), ], "number.probe_1_maximum_temperature", 0.0, PacketA300Write(probe=1, minimum=50.0, maximum=None), id="maximum_clear", ), pytest.param( [ PacketA0Notify( battery=45, version_major=1, version_minor=5, function_type=1, probe_count=2, ambient=False, alarm_interval=5, alarm_sound=True, ) ], "number.pro_05_alarm_interval", 15, PacketA6Write(temperature_unit=None, alarm_interval=15), id="alarm_interval", ), ], ) async def test_set_number( hass: HomeAssistant, mock_entry: MockConfigEntry, mock_client: Mock, packets, entity_id, value, write_packet, ) -> None: """Test the number set.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.NUMBER]) for packet in packets: mock_client.mocked_notify(packet) await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, service_data={ ATTR_VALUE: value, }, target={ ATTR_ENTITY_ID: entity_id, }, blocking=True, ) mock_client.write.assert_any_call(write_packet) @pytest.mark.parametrize( ("error", "message"), [ pytest.param( BleakError("Some error"), "Communication failed with the device", id="bleak", ), pytest.param( BaseError("Some error"), "Data was rejected by device", id="base", ), ], ) async def test_set_number_write_error( hass: HomeAssistant, mock_entry: MockConfigEntry, mock_client: Mock, error, message, ) -> None: """Test the number set.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.NUMBER]) mock_client.mocked_notify( PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET, temperature_1=50.0, ), ) mock_client.write.side_effect = error with pytest.raises(HomeAssistantError, match=message): await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, service_data={ ATTR_VALUE: 100, }, target={ ATTR_ENTITY_ID: "number.probe_1_target_temperature", }, blocking=True, ) async def test_set_number_disconnected( hass: HomeAssistant, mock_entry: MockConfigEntry, mock_client: Mock, ) -> None: """Test the number set.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.NUMBER]) mock_client.mocked_notify( PacketA8Notify( probe=1, alarm_type=PacketA8Notify.AlarmType.TEMPERATURE_TARGET, temperature_1=50.0, ), ) mock_client.is_connected = False with pytest.raises(HomeAssistantError): await hass.services.async_call( NUMBER_DOMAIN, SERVICE_SET_VALUE, service_data={ ATTR_VALUE: 100, }, target={ ATTR_ENTITY_ID: "number.probe_1_target_temperature", }, blocking=True, )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/togrill/test_number.py", "license": "Apache License 2.0", "lines": 270, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/togrill/test_sensor.py
"""Test sensors for ToGrill integration.""" from unittest.mock import Mock, patch from habluetooth import BluetoothServiceInfoBleak import pytest from syrupy.assertion import SnapshotAssertion from togrill_bluetooth.packets import PacketA0Notify, PacketA1Notify from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import TOGRILL_SERVICE_INFO, setup_entry from tests.common import MockConfigEntry, snapshot_platform from tests.components.bluetooth import inject_bluetooth_service_info def patch_async_ble_device_from_address( return_value: BluetoothServiceInfoBleak | None = None, ): """Patch async_ble_device_from_address to return a mocked BluetoothServiceInfoBleak.""" return patch( "homeassistant.components.bluetooth.async_ble_device_from_address", return_value=return_value, ) @pytest.mark.parametrize( "packets", [ pytest.param([], id="no_data"), pytest.param( [ PacketA0Notify( battery=45, version_major=1, version_minor=5, function_type=1, probe_count=2, ambient=False, alarm_interval=5, alarm_sound=True, ) ], id="battery", ), pytest.param([PacketA1Notify([10, None])], id="temp_data"), pytest.param([PacketA1Notify([10])], id="temp_data_missing_probe"), ], ) async def test_setup( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_entry: MockConfigEntry, mock_client: Mock, packets, ) -> None: """Test the sensors.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.SENSOR]) for packet in packets: mock_client.mocked_notify(packet) await snapshot_platform(hass, entity_registry, snapshot, mock_entry.entry_id) @pytest.mark.parametrize( "packets", [ pytest.param([], id="no_data"), pytest.param( [PacketA1Notify([10, 20, 25])], id="ambient_temp_data", ), pytest.param( [PacketA1Notify([10, None, 25])], id="ambient_temp_with_missing_probe", ), pytest.param( [PacketA1Notify([])], id="ambient_empty_temperatures", ), pytest.param( [PacketA1Notify([10, 20, None])], id="ambient_temp_none", ), ], ) async def test_setup_with_ambient( hass: HomeAssistant, entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_entry_with_ambient: MockConfigEntry, mock_client: Mock, packets, ) -> None: """Test the sensors with ambient temperature sensor enabled.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry_with_ambient, [Platform.SENSOR]) for packet in packets: mock_client.mocked_notify(packet) await snapshot_platform( hass, entity_registry, snapshot, mock_entry_with_ambient.entry_id ) async def test_device_disconnected( hass: HomeAssistant, mock_entry: MockConfigEntry, mock_client: Mock, ) -> None: """Test the switch set.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.SENSOR]) entity_id = "sensor.pro_05_battery" state = hass.states.get(entity_id) assert state assert state.state == "0" with patch_async_ble_device_from_address(): mock_client.mocked_disconnected_callback() await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "unavailable" async def test_device_discovered( hass: HomeAssistant, mock_entry: MockConfigEntry, mock_client: Mock, ) -> None: """Test the switch set.""" await setup_entry(hass, mock_entry, [Platform.SENSOR]) entity_id = "sensor.pro_05_battery" state = hass.states.get(entity_id) assert state assert state.state == "unavailable" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await hass.async_block_till_done() state = hass.states.get(entity_id) assert state assert state.state == "0" async def test_ambient_sensor_not_created_without_config( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_entry: MockConfigEntry, mock_client: Mock, ) -> None: """Test ambient temperature sensor is not created when not configured.""" inject_bluetooth_service_info(hass, TOGRILL_SERVICE_INFO) await setup_entry(hass, mock_entry, [Platform.SENSOR]) entity_id = "sensor.pro_05_ambient_temperature" # Entity should not exist when CONF_HAS_AMBIENT is not set state = hass.states.get(entity_id) assert state is None # Verify it's not in the entity registry entry = entity_registry.async_get(entity_id) assert entry is None
{ "repo_id": "home-assistant/core", "file_path": "tests/components/togrill/test_sensor.py", "license": "Apache License 2.0", "lines": 145, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/totalconnect/const.py
"""Constants for the Total Connect tests.""" LOCATION_ID = 1234567 CODE = "7890" USERNAME = "username@me.com" PASSWORD = "password" USERCODES = {LOCATION_ID: "7890"}
{ "repo_id": "home-assistant/core", "file_path": "tests/components/totalconnect/const.py", "license": "Apache License 2.0", "lines": 6, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tuya/test_button.py
"""Test Tuya button platform.""" from __future__ import annotations from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from tuya_sharing import CustomerDevice, Manager from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import initialize_entry from tests.common import MockConfigEntry, snapshot_platform @patch("homeassistant.components.tuya.PLATFORMS", [Platform.BUTTON]) @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_platform_setup_and_discovery( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_devices: list[CustomerDevice], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test platform setup and discovery.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.BUTTON]) @pytest.mark.parametrize( "mock_device_code", ["sd_lr33znaodtyarrrz"], ) async def test_action( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, ) -> None: """Test button action.""" entity_id = "button.v20_reset_duster_cloth" await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) state = hass.states.get(entity_id) assert state is not None, f"{entity_id} does not exist" await hass.services.async_call( BUTTON_DOMAIN, SERVICE_PRESS, { ATTR_ENTITY_ID: entity_id, }, blocking=True, ) mock_manager.send_commands.assert_called_once_with( mock_device.id, [{"code": "reset_duster_cloth", "value": True}] )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tuya/test_button.py", "license": "Apache License 2.0", "lines": 52, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tuya/test_camera.py
"""Test Tuya camera platform.""" from __future__ import annotations from typing import Any from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from tuya_sharing import CustomerDevice, Manager from homeassistant.components.camera import ( DOMAIN as CAMERA_DOMAIN, SERVICE_DISABLE_MOTION, SERVICE_ENABLE_MOTION, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import initialize_entry from tests.common import MockConfigEntry, snapshot_platform @pytest.fixture(autouse=True) def mock_getrandbits(): """Mock camera access token which normally is randomized.""" with patch( "homeassistant.components.camera.SystemRandom.getrandbits", return_value=1, ): yield @patch("homeassistant.components.tuya.PLATFORMS", [Platform.CAMERA]) async def test_platform_setup_and_discovery( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_devices: list[CustomerDevice], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test platform setup and discovery.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices) await snapshot_platform( hass, entity_registry, snapshot, mock_config_entry.entry_id, ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.CAMERA]) @pytest.mark.parametrize( "mock_device_code", ["sp_rudejjigkywujjvs"], ) @pytest.mark.parametrize( ("service", "expected_command"), [ ( SERVICE_DISABLE_MOTION, {"code": "motion_switch", "value": False}, ), ( SERVICE_ENABLE_MOTION, {"code": "motion_switch", "value": True}, ), ], ) async def test_action( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, service: str, expected_command: dict[str, Any], ) -> None: """Test camera action.""" entity_id = "camera.burocam" await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) state = hass.states.get(entity_id) assert state is not None, f"{entity_id} does not exist" await hass.services.async_call( CAMERA_DOMAIN, service, { ATTR_ENTITY_ID: entity_id, }, blocking=True, ) mock_manager.send_commands.assert_called_once_with( mock_device.id, [expected_command] )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tuya/test_camera.py", "license": "Apache License 2.0", "lines": 84, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/tuya/test_vacuum.py
"""Test Tuya vacuum platform.""" from __future__ import annotations from typing import Any from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from tuya_sharing import CustomerDevice, Manager from homeassistant.components.vacuum import ( ATTR_FAN_SPEED, DOMAIN as VACUUM_DOMAIN, SERVICE_LOCATE, SERVICE_PAUSE, SERVICE_RETURN_TO_BASE, SERVICE_SET_FAN_SPEED, SERVICE_START, SERVICE_STOP, ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import initialize_entry from tests.common import MockConfigEntry, snapshot_platform @patch("homeassistant.components.tuya.PLATFORMS", [Platform.VACUUM]) async def test_platform_setup_and_discovery( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_devices: list[CustomerDevice], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test platform setup and discovery.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( ("mock_device_code", "entity_id", "service", "service_data", "expected_command"), [ ( "sd_i6hyjg3af7doaswm", "vacuum.hoover", SERVICE_RETURN_TO_BASE, {}, {"code": "mode", "value": "chargego"}, ), ( # Based on #141278 "sd_lr33znaodtyarrrz", "vacuum.v20", SERVICE_RETURN_TO_BASE, {}, {"code": "switch_charge", "value": True}, ), ( "sd_lr33znaodtyarrrz", "vacuum.v20", SERVICE_SET_FAN_SPEED, {ATTR_FAN_SPEED: "gentle"}, {"code": "suction", "value": "gentle"}, ), ( "sd_i6hyjg3af7doaswm", "vacuum.hoover", SERVICE_LOCATE, {}, {"code": "seek", "value": True}, ), ( "sd_i6hyjg3af7doaswm", "vacuum.hoover", SERVICE_START, {}, {"code": "power_go", "value": True}, ), ( "sd_i6hyjg3af7doaswm", "vacuum.hoover", SERVICE_STOP, {}, {"code": "power_go", "value": False}, ), ( "sd_lr33znaodtyarrrz", "vacuum.v20", SERVICE_PAUSE, {}, {"code": "power_go", "value": False}, ), ], ) async def test_action( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, entity_id: str, service: str, service_data: dict[str, Any], expected_command: dict[str, Any], ) -> None: """Test vacuum action.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) state = hass.states.get(entity_id) assert state is not None, f"{entity_id} does not exist" await hass.services.async_call( VACUUM_DOMAIN, service, { ATTR_ENTITY_ID: entity_id, **service_data, }, blocking=True, ) mock_manager.send_commands.assert_called_once_with( mock_device.id, [expected_command] )
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tuya/test_vacuum.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/tuya/test_valve.py
"""Test Tuya valve platform.""" from __future__ import annotations from typing import Any from unittest.mock import patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion from tuya_sharing import CustomerDevice, Manager from homeassistant.components.valve import ( DOMAIN as VALVE_DOMAIN, SERVICE_CLOSE_VALVE, SERVICE_OPEN_VALVE, ) from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import MockDeviceListener, check_selective_state_update, initialize_entry from tests.common import MockConfigEntry, snapshot_platform @patch("homeassistant.components.tuya.PLATFORMS", [Platform.VALVE]) async def test_platform_setup_and_discovery( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_devices: list[CustomerDevice], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, ) -> None: """Test platform setup and discovery.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_devices) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.parametrize( "mock_device_code", ["sfkzq_ed7frwissyqrejic"], ) @pytest.mark.parametrize( ("updates", "expected_state", "last_reported"), [ # Update without dpcode - state should not change, last_reported stays # at available_reported ({"battery_percentage": 50}, "open", "2024-01-01T00:00:20+00:00"), # Update with dpcode - state should change, last_reported advances ({"switch_1": False}, "closed", "2024-01-01T00:01:00+00:00"), # Update with multiple properties including dpcode - state should change ( {"battery_percentage": 50, "switch_1": False}, "closed", "2024-01-01T00:01:00+00:00", ), ], ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.VALVE]) @pytest.mark.freeze_time("2024-01-01") async def test_selective_state_update( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, mock_listener: MockDeviceListener, freezer: FrozenDateTimeFactory, updates: dict[str, Any], expected_state: str, last_reported: str, ) -> None: """Test skip_update/last_reported.""" await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) await check_selective_state_update( hass, mock_device, mock_listener, freezer, entity_id="valve.jie_hashui_fa_valve_1", dpcode="switch_1", initial_state="open", updates=updates, expected_state=expected_state, last_reported=last_reported, ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.VALVE]) @pytest.mark.parametrize( "mock_device_code", ["sfkzq_ed7frwissyqrejic"], ) @pytest.mark.parametrize( ("service", "expected_commands"), [ ( SERVICE_OPEN_VALVE, [{"code": "switch_1", "value": True}], ), ( SERVICE_CLOSE_VALVE, [{"code": "switch_1", "value": False}], ), ], ) async def test_action( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, service: str, expected_commands: list[dict[str, Any]], ) -> None: """Test valve action.""" entity_id = "valve.jie_hashui_fa_valve_1" await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) state = hass.states.get(entity_id) assert state is not None, f"{entity_id} does not exist" await hass.services.async_call( VALVE_DOMAIN, service, { ATTR_ENTITY_ID: entity_id, }, blocking=True, ) mock_manager.send_commands.assert_called_once_with( mock_device.id, expected_commands ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.VALVE]) @pytest.mark.parametrize( "mock_device_code", ["sfkzq_ed7frwissyqrejic"], ) @pytest.mark.parametrize( ("initial_status", "expected_state"), [ (True, "open"), (False, "closed"), (None, STATE_UNKNOWN), ("some string", STATE_UNKNOWN), ], ) async def test_state( hass: HomeAssistant, mock_manager: Manager, mock_config_entry: MockConfigEntry, mock_device: CustomerDevice, initial_status: Any, expected_state: str, ) -> None: """Test valve state.""" entity_id = "valve.jie_hashui_fa_valve_1" mock_device.status["switch_1"] = initial_status await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) state = hass.states.get(entity_id) assert state is not None, f"{entity_id} does not exist" assert state.state == expected_state
{ "repo_id": "home-assistant/core", "file_path": "tests/components/tuya/test_valve.py", "license": "Apache License 2.0", "lines": 148, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/volvo/test_binary_sensor.py
"""Test Volvo binary sensors.""" from collections.abc import Awaitable, Callable from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.volvo.const import DOMAIN from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.usefixtures("mock_api", "full_model") @pytest.mark.parametrize( "full_model", ["ex30_2024", "s90_diesel_2018", "xc40_electric_2024", "xc90_petrol_2019"], ) async def test_binary_sensor( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], entity_registry: er.EntityRegistry, snapshot: SnapshotAssertion, mock_config_entry: MockConfigEntry, ) -> None: """Test binary sensor.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BINARY_SENSOR]): assert await setup_integration() await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) @pytest.mark.usefixtures("mock_api", "full_model") @pytest.mark.parametrize( "full_model", [ "ex30_2024", "s90_diesel_2018", "xc40_electric_2024", "xc60_phev_2020", "xc90_petrol_2019", "xc90_phev_2024", ], ) async def test_unique_ids( hass: HomeAssistant, setup_integration: Callable[[], Awaitable[bool]], caplog: pytest.LogCaptureFixture, ) -> None: """Test binary sensor for unique id's.""" with patch("homeassistant.components.volvo.PLATFORMS", [Platform.BINARY_SENSOR]): assert await setup_integration() assert f"Platform {DOMAIN} does not generate unique IDs" not in caplog.text
{ "repo_id": "home-assistant/core", "file_path": "tests/components/volvo/test_binary_sensor.py", "license": "Apache License 2.0", "lines": 47, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/zimi/common.py
"""Common items for testing the zimi component.""" from unittest.mock import MagicMock, create_autospec, patch from zcc.device import ControlPointDevice from homeassistant.components.zimi.const import DOMAIN from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry DEVICE_INFO = { "id": "test-device-id", "name": "unknown", "manufacturer": "Zimi", "model": "Controller XYZ", "hwVersion": "2.2.2", "fwVersion": "3.3.3", } ENTITY_INFO = { "id": "test-entity-id", "name": "Test Entity Name", "room": "Test Entity Room", "type": "unknown", } INPUT_HOST = "192.168.1.100" INPUT_PORT = 5003 def mock_api_device( device_name: str | None = None, entity_type: str | None = None, entity_id: str | None = None, ) -> MagicMock: """Mock a Zimi ControlPointDevice which is used in the zcc API with defaults.""" mock_api_device = create_autospec(ControlPointDevice) mock_api_device.identifier = entity_id or ENTITY_INFO["id"] mock_api_device.room = ENTITY_INFO["room"] mock_api_device.name = ENTITY_INFO["name"] mock_api_device.type = entity_type or ENTITY_INFO["type"] mock_manfacture_info = MagicMock() mock_manfacture_info.identifier = DEVICE_INFO["id"] mock_manfacture_info.manufacturer = DEVICE_INFO["manufacturer"] mock_manfacture_info.model = DEVICE_INFO["model"] mock_manfacture_info.name = device_name or DEVICE_INFO["name"] mock_manfacture_info.hwVersion = DEVICE_INFO["hwVersion"] mock_manfacture_info.firmwareVersion = DEVICE_INFO["fwVersion"] mock_api_device.manufacture_info = mock_manfacture_info mock_api_device.brightness = 0 mock_api_device.percentage = 0 return mock_api_device async def setup_platform( hass: HomeAssistant, platform: str, ) -> MockConfigEntry: """Set up the specified Zimi platform.""" if not platform: raise ValueError("Platform must be specified") mock_config = MockConfigEntry( domain=DOMAIN, data={CONF_HOST: INPUT_HOST, CONF_PORT: INPUT_PORT} ) mock_config.add_to_hass(hass) with patch("homeassistant.components.zimi.PLATFORMS", [platform]): assert await async_setup_component(hass, DOMAIN, {}) await hass.async_block_till_done() return mock_config
{ "repo_id": "home-assistant/core", "file_path": "tests/components/zimi/common.py", "license": "Apache License 2.0", "lines": 61, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/zimi/test_cover.py
"""Test the Zimi cover entity.""" from unittest.mock import MagicMock from syrupy.assertion import SnapshotAssertion from homeassistant.components.cover import CoverEntityFeature from homeassistant.const import ( SERVICE_CLOSE_COVER, SERVICE_OPEN_COVER, SERVICE_SET_COVER_POSITION, Platform, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .common import mock_api_device, setup_platform async def test_cover_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_api: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Tests cover entity.""" blind_device_name = "Blind Controller" blind_entity_key = "cover.blind_controller_test_entity_name" blind_entity_id = "test-entity-id-blind" door_device_name = "Cover Controller" door_entity_key = "cover.cover_controller_test_entity_name" door_entity_id = "test-entity-id-door" entity_type = Platform.COVER mock_api.blinds = [ mock_api_device( device_name=blind_device_name, entity_type=entity_type, entity_id=blind_entity_id, ) ] mock_api.doors = [ mock_api_device( device_name=door_device_name, entity_type=entity_type, entity_id=door_entity_id, ) ] await setup_platform(hass, entity_type) blind_entity = entity_registry.entities[blind_entity_key] assert blind_entity.unique_id == blind_entity_id assert ( blind_entity.supported_features == CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION ) door_entity = entity_registry.entities[door_entity_key] assert door_entity.unique_id == door_entity_id assert ( door_entity.supported_features == CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE | CoverEntityFeature.STOP | CoverEntityFeature.SET_POSITION ) state = hass.states.get(door_entity_key) assert state == snapshot services = hass.services.async_services() assert SERVICE_CLOSE_COVER in services[entity_type] await hass.services.async_call( entity_type, SERVICE_CLOSE_COVER, {"entity_id": door_entity_key}, blocking=True, ) assert mock_api.doors[0].close_door.called assert SERVICE_OPEN_COVER in services[entity_type] await hass.services.async_call( entity_type, SERVICE_OPEN_COVER, {"entity_id": door_entity_key}, blocking=True, ) assert mock_api.doors[0].open_door.called assert SERVICE_SET_COVER_POSITION in services[entity_type] await hass.services.async_call( entity_type, SERVICE_SET_COVER_POSITION, {"entity_id": door_entity_key, "position": 50}, blocking=True, ) assert mock_api.doors[0].open_to_percentage.called
{ "repo_id": "home-assistant/core", "file_path": "tests/components/zimi/test_cover.py", "license": "Apache License 2.0", "lines": 87, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/zimi/test_fan.py
"""Test the Zimi fan entity.""" from unittest.mock import MagicMock from syrupy.assertion import SnapshotAssertion from homeassistant.components.fan import FanEntityFeature from homeassistant.const import SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .common import ENTITY_INFO, mock_api_device, setup_platform async def test_fan_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_api: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Tests fan entity.""" device_name = "Fan Controller" entity_key = "fan.fan_controller_test_entity_name" entity_type = Platform.FAN mock_api.fans = [mock_api_device(device_name=device_name, entity_type=entity_type)] await setup_platform(hass, entity_type) entity = entity_registry.entities[entity_key] assert entity.unique_id == ENTITY_INFO["id"] assert ( entity.supported_features == FanEntityFeature.SET_SPEED | FanEntityFeature.TURN_OFF | FanEntityFeature.TURN_ON ) state = hass.states.get(entity_key) assert state == snapshot services = hass.services.async_services() assert SERVICE_TURN_ON in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_ON, {"entity_id": entity_key}, blocking=True, ) assert mock_api.fans[0].turn_on.called assert SERVICE_TURN_OFF in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_OFF, {"entity_id": entity_key}, blocking=True, ) assert mock_api.fans[0].turn_off.called assert "set_percentage" in services[entity_type] await hass.services.async_call( entity_type, "set_percentage", {"entity_id": entity_key, "percentage": 50}, blocking=True, ) assert mock_api.fans[0].set_fanspeed.called
{ "repo_id": "home-assistant/core", "file_path": "tests/components/zimi/test_fan.py", "license": "Apache License 2.0", "lines": 55, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/zimi/test_light.py
"""Test the Zimi light entity.""" from unittest.mock import MagicMock from syrupy.assertion import SnapshotAssertion from homeassistant.components.light import ColorMode from homeassistant.const import SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .common import ENTITY_INFO, mock_api_device, setup_platform async def test_light_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_api: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Tests lights entity.""" device_name = "Light Controller" entity_key = "light.light_controller_test_entity_name" entity_type = "light" mock_api.lights = [ mock_api_device(device_name=device_name, entity_type=entity_type) ] await setup_platform(hass, Platform.LIGHT) entity = entity_registry.entities[entity_key] assert entity.unique_id == ENTITY_INFO["id"] assert entity.capabilities == { "supported_color_modes": [ColorMode.ONOFF], } state = hass.states.get(entity_key) assert state == snapshot services = hass.services.async_services() assert SERVICE_TURN_ON in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_ON, {"entity_id": entity_key}, blocking=True, ) assert mock_api.lights[0].turn_on.called assert SERVICE_TURN_OFF in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_OFF, {"entity_id": entity_key}, blocking=True, ) assert mock_api.lights[0].turn_off.called async def test_dimmer_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_api: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Tests dimmer entity.""" device_name = "Light Controller" entity_key = "light.light_controller_test_entity_name" entity_type = "dimmer" entity_type_override = "light" mock_api.lights = [ mock_api_device(device_name=device_name, entity_type=entity_type) ] await setup_platform(hass, Platform.LIGHT) entity = entity_registry.entities[entity_key] assert entity.unique_id == ENTITY_INFO["id"] assert entity.capabilities == { "supported_color_modes": [ColorMode.BRIGHTNESS], } state = hass.states.get(entity_key) assert state == snapshot services = hass.services.async_services() assert SERVICE_TURN_ON in services[entity_type_override] await hass.services.async_call( entity_type_override, SERVICE_TURN_ON, {"entity_id": entity_key}, blocking=True, ) assert mock_api.lights[0].set_brightness.called assert SERVICE_TURN_OFF in services[entity_type_override] await hass.services.async_call( entity_type_override, SERVICE_TURN_OFF, {"entity_id": entity_key}, blocking=True, ) assert mock_api.lights[0].set_brightness.called
{ "repo_id": "home-assistant/core", "file_path": "tests/components/zimi/test_light.py", "license": "Apache License 2.0", "lines": 85, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/components/zimi/test_switch.py
"""Test the Zimi switch entity.""" from unittest.mock import MagicMock from syrupy.assertion import SnapshotAssertion from homeassistant.const import SERVICE_TURN_OFF, SERVICE_TURN_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .common import ENTITY_INFO, mock_api_device, setup_platform async def test_switch_entity( hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_api: MagicMock, snapshot: SnapshotAssertion, ) -> None: """Tests switch entity.""" device_name = "Switch Controller" entity_key = "switch.switch_controller_test_entity_name" entity_type = "switch" mock_api.outlets = [ mock_api_device(device_name=device_name, entity_type=entity_type) ] await setup_platform(hass, Platform.SWITCH) entity = entity_registry.entities[entity_key] assert entity.unique_id == ENTITY_INFO["id"] state = hass.states.get(entity_key) assert state == snapshot services = hass.services.async_services() assert SERVICE_TURN_ON in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_ON, {"entity_id": entity_key}, blocking=True, ) assert mock_api.outlets[0].turn_on.called assert SERVICE_TURN_OFF in services[entity_type] await hass.services.async_call( entity_type, SERVICE_TURN_OFF, {"entity_id": entity_key}, blocking=True, ) assert mock_api.outlets[0].turn_off.called
{ "repo_id": "home-assistant/core", "file_path": "tests/components/zimi/test_switch.py", "license": "Apache License 2.0", "lines": 42, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/helpers/test_automation.py
"""Test automation helpers.""" import pytest import voluptuous as vol from homeassistant.helpers.automation import ( get_absolute_description_key, get_relative_description_key, move_options_fields_to_top_level, move_top_level_schema_fields_to_options, ) @pytest.mark.parametrize( ("relative_key", "absolute_key"), [ ("turned_on", "homeassistant.turned_on"), ("_", "homeassistant"), ("_state", "state"), ], ) def test_absolute_description_key(relative_key: str, absolute_key: str) -> None: """Test absolute description key.""" DOMAIN = "homeassistant" assert get_absolute_description_key(DOMAIN, relative_key) == absolute_key @pytest.mark.parametrize( ("relative_key", "absolute_key"), [ ("turned_on", "homeassistant.turned_on"), ("_", "homeassistant"), ("_state", "state"), ], ) def test_relative_description_key(relative_key: str, absolute_key: str) -> None: """Test relative description key.""" DOMAIN = "homeassistant" assert get_relative_description_key(DOMAIN, absolute_key) == relative_key @pytest.mark.parametrize( ("config", "schema_dict", "expected_config"), [ ( { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, "attribute": "state", "value_template": "{{ value_json.val }}", "extra_field": "extra_value", }, {}, { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, "attribute": "state", "value_template": "{{ value_json.val }}", "extra_field": "extra_value", "options": {}, }, ), ( { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, "attribute": "state", "value_template": "{{ value_json.val }}", "extra_field": "extra_value", }, { vol.Required("entity"): str, vol.Optional("from"): str, vol.Optional("to"): str, vol.Optional("for"): dict, vol.Optional("attribute"): str, vol.Optional("value_template"): str, }, { "platform": "test", "extra_field": "extra_value", "options": { "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, "attribute": "state", "value_template": "{{ value_json.val }}", }, }, ), ], ) async def test_move_schema_fields_to_options( config, schema_dict, expected_config ) -> None: """Test moving schema fields to options.""" assert ( move_top_level_schema_fields_to_options(config, schema_dict) == expected_config ) @pytest.mark.parametrize( ("config", "expected_config"), [ ( { "platform": "test", "options": { "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, }, }, { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, }, ), ( { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, }, { "platform": "test", "entity": "sensor.test", "from": "open", "to": "closed", "for": {"hours": 1}, }, ), ( { "platform": "test", "options": 456, }, { "platform": "test", "options": 456, }, ), ( { "platform": "test", "options": { "entity": "sensor.test", }, "extra_field": "extra_value", }, { "platform": "test", "options": { "entity": "sensor.test", }, "extra_field": "extra_value", }, ), ], ) async def test_move_options_fields_to_top_level(config, expected_config) -> None: """Test moving options fields to top-level.""" base_schema = vol.Schema({vol.Required("platform"): str}) original_config = config.copy() assert move_options_fields_to_top_level(config, base_schema) == expected_config assert config == original_config # Ensure original config is not modified
{ "repo_id": "home-assistant/core", "file_path": "tests/helpers/test_automation.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:tests/pylint/test_enforce_greek_micro_char.py
"""Tests for pylint hass_enforce_greek_micro_char plugin.""" from __future__ import annotations import astroid from pylint.checkers import BaseChecker from pylint.testutils.unittest_linter import UnittestLinter from pylint.utils.ast_walker import ASTWalker import pytest from . import assert_no_messages @pytest.mark.parametrize( "code", [ pytest.param( # Test using the correct μ-sign \u03bc with annotation """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: Final = "μg/m³" """, id="good_const_with_annotation", ), pytest.param( # Test using the correct μ-sign \u03bc with annotation using unicode encoding """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: Final = "\u03bcg/m³" """, id="good_unicode_const_with_annotation", ), pytest.param( # Test using the correct μ-sign \u03bc without annotation """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER = "μg/m³" """, id="good_const_without_annotation", ), pytest.param( # Test using the correct μ-sign \u03bc in a StrEnum class """ class UnitOfElectricPotential(StrEnum): \"\"\"Electric potential units.\"\"\" MICROVOLT = "μV" MILLIVOLT = "mV" VOLT = "V" KILOVOLT = "kV" MEGAVOLT = "MV" """, id="good_str_enum", ), pytest.param( # Test using the correct μ-sign \u03bc in a sensor description dict """ SENSOR_DESCRIPTION = { "radiation_rate": AranetSensorEntityDescription( key="radiation_rate", translation_key="radiation_rate", name="Radiation Dose Rate", native_unit_of_measurement="μSv/h", state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=2, scale=0.001, ), } OTHER_DICT = { "value_with_bad_mu_should_pass": "µ" } """, id="good_sensor_description", ), ], ) def test_enforce_greek_micro_char( linter: UnittestLinter, enforce_greek_micro_char_checker: BaseChecker, code: str, ) -> None: """Good test cases.""" root_node = astroid.parse(code, "homeassistant.components.pylint_test") walker = ASTWalker(linter) walker.add_checker(enforce_greek_micro_char_checker) with assert_no_messages(linter): walker.walk(root_node) @pytest.mark.parametrize( "code", [ pytest.param( # Test we can detect the legacy coding of μ \u00b5 # instead of recommended coding of μ \u03bc" with annotation """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: Final = "µg/m³" """, id="bad_const_with_annotation", ), pytest.param( # Test we can detect the unicode variant of the legacy coding of μ \u00b5 # instead of recommended coding of μ \u03bc" with annotation """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: Final = "\u00b5g/m³" """, id="bad_unicode_const_with_annotation", ), pytest.param( # Test we can detect the legacy coding of μ \u00b5 # instead of recommended coding of μ \u03bc" without annotation """ CONCENTRATION_MICROGRAMS_PER_CUBIC_METER = "µg/m³" """, id="bad_const_without_annotation", ), pytest.param( # Test we can detect the legacy coding of μ \u00b5 # instead of recommended coding of μ \u03bc" in a StrEnum class """ class UnitOfElectricPotential(StrEnum): \"\"\"Electric potential units.\"\"\" MICROVOLT = "µV" MILLIVOLT = "mV" VOLT = "V" KILOVOLT = "kV" MEGAVOLT = "MV" """, id="bad_str_enum", ), pytest.param( # Test we can detect the legacy coding of μ \u00b5 # instead of recommended coding of μ \u03bc" in a sensor description dict """ SENSOR_DESCRIPTION = { "radiation_rate": AranetSensorEntityDescription( key="radiation_rate", translation_key="radiation_rate", name="Radiation Dose Rate", native_unit_of_measurement="µSv/h", state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=2, scale=0.001, ), } """, id="bad_sensor_description", ), ], ) def test_enforce_greek_micro_char_assign_bad( linter: UnittestLinter, enforce_greek_micro_char_checker: BaseChecker, code: str, ) -> None: """Bad assignment test cases.""" root_node = astroid.parse(code, "homeassistant.components.pylint_test") walker = ASTWalker(linter) walker.add_checker(enforce_greek_micro_char_checker) walker.walk(root_node) messages = linter.release_messages() assert len(messages) == 1 message = next(iter(messages)) assert message.msg_id == "hass-enforce-greek-micro-char"
{ "repo_id": "home-assistant/core", "file_path": "tests/pylint/test_enforce_greek_micro_char.py", "license": "Apache License 2.0", "lines": 153, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
test
home-assistant/core:homeassistant/components/airos/config_flow.py
"""Config flow for the Ubiquiti airOS integration.""" from __future__ import annotations import asyncio from collections.abc import Mapping import logging from typing import Any from airos.airos6 import AirOS6 from airos.airos8 import AirOS8 from airos.discovery import airos_discover_devices from airos.exceptions import ( AirOSConnectionAuthenticationError, AirOSConnectionSetupError, AirOSDataMissingError, AirOSDeviceConnectionError, AirOSEndpointError, AirOSKeyDataMissingError, AirOSListenerError, ) from airos.helpers import DetectDeviceData, async_get_firmware_data import voluptuous as vol from homeassistant.config_entries import ( SOURCE_REAUTH, SOURCE_RECONFIGURE, ConfigFlow, ConfigFlowResult, ) from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, CONF_SSL, CONF_USERNAME, CONF_VERIFY_SSL, ) from homeassistant.data_entry_flow import section from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, TextSelectorType, ) from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from .const import ( DEFAULT_SSL, DEFAULT_USERNAME, DEFAULT_VERIFY_SSL, DEVICE_NAME, DOMAIN, HOSTNAME, IP_ADDRESS, MAC_ADDRESS, SECTION_ADVANCED_SETTINGS, ) _LOGGER = logging.getLogger(__name__) AirOSDeviceDetect = AirOS8 | AirOS6 # Discovery duration in seconds, airOS announces every 20 seconds DISCOVER_INTERVAL: int = 30 STEP_DISCOVERY_DATA_SCHEMA = vol.Schema( { vol.Required(CONF_USERNAME, default=DEFAULT_USERNAME): str, vol.Required(CONF_PASSWORD): str, vol.Required(SECTION_ADVANCED_SETTINGS): section( vol.Schema( { vol.Required(CONF_SSL, default=DEFAULT_SSL): bool, vol.Required(CONF_VERIFY_SSL, default=DEFAULT_VERIFY_SSL): bool, } ), {"collapsed": True}, ), } ) STEP_MANUAL_DATA_SCHEMA = STEP_DISCOVERY_DATA_SCHEMA.extend( {vol.Required(CONF_HOST): str} ) class AirOSConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Ubiquiti airOS.""" VERSION = 2 MINOR_VERSION = 1 _discovery_task: asyncio.Task | None = None def __init__(self) -> None: """Initialize the config flow.""" super().__init__() self.airos_device: AirOSDeviceDetect self.errors: dict[str, str] = {} self.discovered_devices: dict[str, dict[str, Any]] = {} self.discovery_abort_reason: str | None = None self.selected_device_info: dict[str, Any] = {} async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the initial step.""" self.errors = {} return self.async_show_menu( step_id="user", menu_options=["discovery", "manual"] ) async def async_step_manual( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the manual input of host and credentials.""" self.errors = {} if user_input is not None: validated_info = await self._validate_and_get_device_info(user_input) if validated_info: return self.async_create_entry( title=validated_info["title"], data=validated_info["data"], ) return self.async_show_form( step_id="manual", data_schema=STEP_MANUAL_DATA_SCHEMA, errors=self.errors ) async def _validate_and_get_device_info( self, config_data: dict[str, Any] ) -> dict[str, Any] | None: """Validate user input with the device API.""" # By default airOS 8 comes with self-signed SSL certificates, # with no option in the web UI to change or upload a custom certificate. session = async_get_clientsession( self.hass, verify_ssl=config_data[SECTION_ADVANCED_SETTINGS][CONF_VERIFY_SSL], ) try: device_data: DetectDeviceData = await async_get_firmware_data( host=config_data[CONF_HOST], username=config_data[CONF_USERNAME], password=config_data[CONF_PASSWORD], session=session, use_ssl=config_data[SECTION_ADVANCED_SETTINGS][CONF_SSL], ) except ( AirOSConnectionSetupError, AirOSDeviceConnectionError, ): self.errors["base"] = "cannot_connect" except AirOSConnectionAuthenticationError, AirOSDataMissingError: self.errors["base"] = "invalid_auth" except AirOSKeyDataMissingError: self.errors["base"] = "key_data_missing" except Exception: _LOGGER.exception("Unexpected exception during credential validation") self.errors["base"] = "unknown" else: await self.async_set_unique_id(device_data["mac"]) if self.source in [SOURCE_REAUTH, SOURCE_RECONFIGURE]: self._abort_if_unique_id_mismatch() else: self._abort_if_unique_id_configured() return {"title": device_data["hostname"], "data": config_data} return None async def async_step_reauth( self, user_input: Mapping[str, Any], ) -> ConfigFlowResult: """Perform reauthentication upon an API authentication error.""" return await self.async_step_reauth_confirm(user_input) async def async_step_reauth_confirm( self, user_input: Mapping[str, Any], ) -> ConfigFlowResult: """Perform reauthentication upon an API authentication error.""" self.errors = {} if user_input: validate_data = {**self._get_reauth_entry().data, **user_input} if await self._validate_and_get_device_info(config_data=validate_data): return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=validate_data, ) return self.async_show_form( step_id="reauth_confirm", data_schema=vol.Schema( { vol.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password", ) ), } ), errors=self.errors, ) async def async_step_reconfigure( self, user_input: Mapping[str, Any] | None = None, ) -> ConfigFlowResult: """Handle reconfiguration of airOS.""" self.errors = {} entry = self._get_reconfigure_entry() current_data = entry.data if user_input is not None: validate_data = {**current_data, **user_input} if await self._validate_and_get_device_info(config_data=validate_data): return self.async_update_reload_and_abort( entry, data_updates=validate_data, ) return self.async_show_form( step_id="reconfigure", data_schema=vol.Schema( { vol.Required(CONF_PASSWORD): TextSelector( TextSelectorConfig( type=TextSelectorType.PASSWORD, autocomplete="current-password", ) ), vol.Required(SECTION_ADVANCED_SETTINGS): section( vol.Schema( { vol.Required( CONF_SSL, default=current_data[SECTION_ADVANCED_SETTINGS][ CONF_SSL ], ): bool, vol.Required( CONF_VERIFY_SSL, default=current_data[SECTION_ADVANCED_SETTINGS][ CONF_VERIFY_SSL ], ): bool, } ), {"collapsed": True}, ), } ), errors=self.errors, ) async def async_step_discovery( self, discovery_info: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Start the discovery process.""" if self._discovery_task and self._discovery_task.done(): self._discovery_task = None # Handle appropriate 'errors' as abort through progress_done if self.discovery_abort_reason: return self.async_show_progress_done( next_step_id=self.discovery_abort_reason ) # Abort through progress_done if no devices were found if not self.discovered_devices: _LOGGER.debug( "No (new or unconfigured) airOS devices found during discovery" ) return self.async_show_progress_done( next_step_id="discovery_no_devices" ) # Skip selecting a device if only one new/unconfigured device was found if len(self.discovered_devices) == 1: self.selected_device_info = list(self.discovered_devices.values())[0] return self.async_show_progress_done(next_step_id="configure_device") return self.async_show_progress_done(next_step_id="select_device") if not self._discovery_task: self.discovered_devices = {} self._discovery_task = self.hass.async_create_task( self._async_run_discovery_with_progress() ) # Show the progress bar and wait for discovery to complete return self.async_show_progress( step_id="discovery", progress_action="discovering", progress_task=self._discovery_task, description_placeholders={"seconds": str(DISCOVER_INTERVAL)}, ) async def async_step_select_device( self, discovery_info: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Select a discovered device.""" if discovery_info is not None: selected_mac = discovery_info[MAC_ADDRESS] self.selected_device_info = self.discovered_devices[selected_mac] return await self.async_step_configure_device() list_options = { mac: f"{device.get(HOSTNAME, mac)} ({device.get(IP_ADDRESS, DEVICE_NAME)})" for mac, device in self.discovered_devices.items() } return self.async_show_form( step_id="select_device", data_schema=vol.Schema({vol.Required(MAC_ADDRESS): vol.In(list_options)}), ) async def async_step_configure_device( self, user_input: dict[str, Any] | None = None, ) -> ConfigFlowResult: """Configure the selected device.""" self.errors = {} if user_input is not None: config_data = { **user_input, CONF_HOST: self.selected_device_info[IP_ADDRESS], } validated_info = await self._validate_and_get_device_info(config_data) if validated_info: return self.async_create_entry( title=validated_info["title"], data=validated_info["data"], ) device_name = self.selected_device_info.get( HOSTNAME, self.selected_device_info.get(IP_ADDRESS, DEVICE_NAME) ) return self.async_show_form( step_id="configure_device", data_schema=STEP_DISCOVERY_DATA_SCHEMA, errors=self.errors, description_placeholders={"device_name": device_name}, ) async def _async_run_discovery_with_progress(self) -> None: """Run discovery with an embedded progress update loop.""" progress_bar = self.hass.async_create_task(self._async_update_progress_bar()) known_mac_addresses = { entry.unique_id.lower() for entry in self.hass.config_entries.async_entries(DOMAIN) if entry.unique_id } try: devices = await airos_discover_devices(DISCOVER_INTERVAL) except AirOSEndpointError: self.discovery_abort_reason = "discovery_detect_error" except AirOSListenerError: self.discovery_abort_reason = "discovery_listen_error" except Exception: self.discovery_abort_reason = "discovery_failed" _LOGGER.exception("An error occurred during discovery") else: self.discovered_devices = { mac_addr: info for mac_addr, info in devices.items() if mac_addr.lower() not in known_mac_addresses } _LOGGER.debug( "Discovery task finished. Found %s new devices", len(self.discovered_devices), ) finally: progress_bar.cancel() async def _async_update_progress_bar(self) -> None: """Update progress bar every second.""" try: for i in range(DISCOVER_INTERVAL): progress = (i + 1) / DISCOVER_INTERVAL self.async_update_progress(progress) await asyncio.sleep(1) except asyncio.CancelledError: pass async def async_step_dhcp( self, discovery_info: DhcpServiceInfo ) -> ConfigFlowResult: """Automatically handle a DHCP discovered IP change.""" ip_address = discovery_info.ip # python-airos defaults to upper for derived mac_address normalized_mac = format_mac(discovery_info.macaddress).upper() await self.async_set_unique_id(normalized_mac) self._abort_if_unique_id_configured(updates={CONF_HOST: ip_address}) return self.async_abort(reason="unreachable") async def async_step_discovery_no_devices( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Abort if discovery finds no (unconfigured) devices.""" return self.async_abort(reason="no_devices_found") async def async_step_discovery_listen_error( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Abort if discovery is unable to listen on the port.""" return self.async_abort(reason="listen_error") async def async_step_discovery_detect_error( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Abort if discovery receives incorrect broadcasts.""" return self.async_abort(reason="detect_error") async def async_step_discovery_failed( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Abort if discovery fails for other reasons.""" return self.async_abort(reason="discovery_failed")
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/config_flow.py", "license": "Apache License 2.0", "lines": 378, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/airos/const.py
"""Constants for the Ubiquiti airOS integration.""" from datetime import timedelta DOMAIN = "airos" SCAN_INTERVAL = timedelta(minutes=1) MANUFACTURER = "Ubiquiti" DEFAULT_VERIFY_SSL = False DEFAULT_SSL = True SECTION_ADVANCED_SETTINGS = "advanced_settings" # Discovery related DEFAULT_USERNAME = "ubnt" HOSTNAME = "hostname" IP_ADDRESS = "ip_address" MAC_ADDRESS = "mac_address" DEVICE_NAME = "airOS device"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/const.py", "license": "Apache License 2.0", "lines": 14, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airos/coordinator.py
"""DataUpdateCoordinator for AirOS.""" from __future__ import annotations import logging from airos.airos6 import AirOS6, AirOS6Data from airos.airos8 import AirOS8, AirOS8Data from airos.exceptions import ( AirOSConnectionAuthenticationError, AirOSConnectionSetupError, AirOSDataMissingError, AirOSDeviceConnectionError, ) from airos.helpers import DetectDeviceData from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import DOMAIN, SCAN_INTERVAL _LOGGER = logging.getLogger(__name__) AirOSDeviceDetect = AirOS8 | AirOS6 AirOSDataDetect = AirOS8Data | AirOS6Data type AirOSConfigEntry = ConfigEntry[AirOSDataUpdateCoordinator] class AirOSDataUpdateCoordinator(DataUpdateCoordinator[AirOSDataDetect]): """Class to manage fetching AirOS data from single endpoint.""" airos_device: AirOSDeviceDetect config_entry: AirOSConfigEntry def __init__( self, hass: HomeAssistant, config_entry: AirOSConfigEntry, device_data: DetectDeviceData, airos_device: AirOSDeviceDetect, ) -> None: """Initialize the coordinator.""" self.airos_device = airos_device self.device_data = device_data super().__init__( hass, _LOGGER, config_entry=config_entry, name=DOMAIN, update_interval=SCAN_INTERVAL, ) async def _async_update_data(self) -> AirOSDataDetect: """Fetch data from AirOS.""" try: await self.airos_device.login() return await self.airos_device.status() except AirOSConnectionAuthenticationError as err: _LOGGER.exception("Error authenticating with airOS device") raise ConfigEntryAuthFailed( translation_domain=DOMAIN, translation_key="invalid_auth" ) from err except ( AirOSConnectionSetupError, AirOSDeviceConnectionError, TimeoutError, ) as err: _LOGGER.error("Error connecting to airOS device: %s", err) raise UpdateFailed( translation_domain=DOMAIN, translation_key="cannot_connect", ) from err except AirOSDataMissingError as err: _LOGGER.error("Expected data not returned by airOS device: %s", err) raise UpdateFailed( translation_domain=DOMAIN, translation_key="error_data_missing", ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/coordinator.py", "license": "Apache License 2.0", "lines": 68, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airos/diagnostics.py
"""Diagnostics support for airOS.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import CONF_HOST, CONF_PASSWORD from homeassistant.core import HomeAssistant from .coordinator import AirOSConfigEntry IP_REDACT = ["addr", "ipaddr", "ip6addr", "lastip"] # IP related HW_REDACT = ["apmac", "hwaddr", "mac"] # MAC address TO_REDACT_HA = [CONF_HOST, CONF_PASSWORD] TO_REDACT_AIROS = [ "hostname", # Prevent leaking device naming "essid", # Network SSID "lat", # GPS latitude to prevent exposing location data. "lon", # GPS longitude to prevent exposing location data. *HW_REDACT, *IP_REDACT, ] async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: AirOSConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" return { "entry_data": async_redact_data(entry.data, TO_REDACT_HA), "data": async_redact_data(entry.runtime_data.data.to_dict(), TO_REDACT_AIROS), }
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/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/airos/entity.py
"""Generic AirOS Entity Class.""" from __future__ import annotations from homeassistant.const import CONF_HOST, CONF_SSL from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC, DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN, MANUFACTURER, SECTION_ADVANCED_SETTINGS from .coordinator import AirOSDataUpdateCoordinator class AirOSEntity(CoordinatorEntity[AirOSDataUpdateCoordinator]): """Represent a AirOS Entity.""" _attr_has_entity_name = True def __init__(self, coordinator: AirOSDataUpdateCoordinator) -> None: """Initialise the gateway.""" super().__init__(coordinator) airos_data = self.coordinator.data url_schema = ( "https" if coordinator.config_entry.data[SECTION_ADVANCED_SETTINGS][CONF_SSL] else "http" ) configuration_url: str | None = ( f"{url_schema}://{coordinator.config_entry.data[CONF_HOST]}" ) self._attr_device_info = DeviceInfo( connections={(CONNECTION_NETWORK_MAC, airos_data.derived.mac)}, configuration_url=configuration_url, identifiers={(DOMAIN, airos_data.derived.mac)}, manufacturer=MANUFACTURER, model=airos_data.host.devmodel, model_id=( sku if (sku := airos_data.derived.sku) not in ["UNKNOWN", "AMBIGUOUS"] else None ), name=airos_data.host.hostname, sw_version=airos_data.host.fwversion, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/entity.py", "license": "Apache License 2.0", "lines": 36, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/airos/sensor.py
"""AirOS Sensor component for Home Assistant.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass import logging from typing import Generic, TypeVar from airos.data import ( AirOSDataBaseClass, DerivedWirelessMode, DerivedWirelessRole, NetRole, ) from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import ( PERCENTAGE, SIGNAL_STRENGTH_DECIBELS, UnitOfDataRate, UnitOfFrequency, UnitOfLength, UnitOfTime, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from .coordinator import AirOS8Data, AirOSConfigEntry, AirOSDataUpdateCoordinator from .entity import AirOSEntity _LOGGER = logging.getLogger(__name__) NETROLE_OPTIONS = [mode.value for mode in NetRole] WIRELESS_MODE_OPTIONS = [mode.value for mode in DerivedWirelessMode] WIRELESS_ROLE_OPTIONS = [mode.value for mode in DerivedWirelessRole] PARALLEL_UPDATES = 0 AirOSDataModel = TypeVar("AirOSDataModel", bound=AirOSDataBaseClass) @dataclass(frozen=True, kw_only=True) class AirOSSensorEntityDescription(SensorEntityDescription, Generic[AirOSDataModel]): """Describe an AirOS sensor.""" value_fn: Callable[[AirOSDataModel], StateType] AirOS8SensorEntityDescription = AirOSSensorEntityDescription[AirOS8Data] COMMON_SENSORS: tuple[AirOSSensorEntityDescription, ...] = ( AirOSSensorEntityDescription( key="host_cpuload", translation_key="host_cpuload", native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=1, value_fn=lambda data: data.host.cpuload, entity_registry_enabled_default=False, ), AirOSSensorEntityDescription( key="host_netrole", translation_key="host_netrole", device_class=SensorDeviceClass.ENUM, value_fn=lambda data: data.host.netrole.value, options=NETROLE_OPTIONS, ), AirOSSensorEntityDescription( key="wireless_frequency", translation_key="wireless_frequency", native_unit_of_measurement=UnitOfFrequency.MEGAHERTZ, device_class=SensorDeviceClass.FREQUENCY, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda data: data.wireless.frequency, ), AirOSSensorEntityDescription( key="wireless_essid", translation_key="wireless_essid", value_fn=lambda data: data.wireless.essid, ), AirOSSensorEntityDescription( key="host_uptime", translation_key="host_uptime", native_unit_of_measurement=UnitOfTime.SECONDS, device_class=SensorDeviceClass.DURATION, suggested_display_precision=0, suggested_unit_of_measurement=UnitOfTime.DAYS, value_fn=lambda data: data.host.uptime, entity_registry_enabled_default=False, ), AirOSSensorEntityDescription( key="wireless_distance", translation_key="wireless_distance", native_unit_of_measurement=UnitOfLength.METERS, device_class=SensorDeviceClass.DISTANCE, suggested_display_precision=1, suggested_unit_of_measurement=UnitOfLength.KILOMETERS, value_fn=lambda data: data.wireless.distance, ), AirOSSensorEntityDescription( key="wireless_mode", translation_key="wireless_mode", device_class=SensorDeviceClass.ENUM, value_fn=lambda data: data.derived.mode.value, options=WIRELESS_MODE_OPTIONS, entity_registry_enabled_default=False, ), AirOSSensorEntityDescription( key="wireless_role", translation_key="wireless_role", device_class=SensorDeviceClass.ENUM, value_fn=lambda data: data.derived.role.value, options=WIRELESS_ROLE_OPTIONS, entity_registry_enabled_default=False, ), AirOSSensorEntityDescription( key="wireless_antenna_gain", translation_key="wireless_antenna_gain", native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS, device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda data: data.wireless.antenna_gain, ), AirOSSensorEntityDescription( key="wireless_polling_dl_capacity", translation_key="wireless_polling_dl_capacity", native_unit_of_measurement=UnitOfDataRate.KILOBITS_PER_SECOND, device_class=SensorDeviceClass.DATA_RATE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, suggested_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND, value_fn=lambda data: data.wireless.polling.dl_capacity, ), AirOSSensorEntityDescription( key="wireless_polling_ul_capacity", translation_key="wireless_polling_ul_capacity", native_unit_of_measurement=UnitOfDataRate.KILOBITS_PER_SECOND, device_class=SensorDeviceClass.DATA_RATE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, suggested_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND, value_fn=lambda data: data.wireless.polling.ul_capacity, ), ) AIROS8_SENSORS: tuple[AirOS8SensorEntityDescription, ...] = ( AirOS8SensorEntityDescription( key="wireless_throughput_tx", translation_key="wireless_throughput_tx", native_unit_of_measurement=UnitOfDataRate.KILOBITS_PER_SECOND, device_class=SensorDeviceClass.DATA_RATE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, suggested_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND, value_fn=lambda data: data.wireless.throughput.tx, ), AirOS8SensorEntityDescription( key="wireless_throughput_rx", translation_key="wireless_throughput_rx", native_unit_of_measurement=UnitOfDataRate.KILOBITS_PER_SECOND, device_class=SensorDeviceClass.DATA_RATE, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, suggested_unit_of_measurement=UnitOfDataRate.MEGABITS_PER_SECOND, value_fn=lambda data: data.wireless.throughput.rx, ), ) async def async_setup_entry( hass: HomeAssistant, config_entry: AirOSConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the AirOS sensors from a config entry.""" coordinator = config_entry.runtime_data entities = [AirOSSensor(coordinator, description) for description in COMMON_SENSORS] if coordinator.device_data["fw_major"] == 8: entities.extend( AirOSSensor(coordinator, description) for description in AIROS8_SENSORS ) async_add_entities(entities) class AirOSSensor(AirOSEntity, SensorEntity): """Representation of a Sensor.""" entity_description: AirOSSensorEntityDescription def __init__( self, coordinator: AirOSDataUpdateCoordinator, description: AirOSSensorEntityDescription, ) -> None: """Initialize the sensor.""" super().__init__(coordinator) self.entity_description = description self._attr_unique_id = f"{coordinator.data.derived.mac}_{description.key}" @property def native_value(self) -> StateType: """Return the state of the sensor.""" return self.entity_description.value_fn(self.coordinator.data)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/airos/sensor.py", "license": "Apache License 2.0", "lines": 187, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/alexa_devices/services.py
"""Support for services.""" from aioamazondevices.const.metadata import ALEXA_INFO_SKILLS from aioamazondevices.const.sounds import SOUNDS_LIST import voluptuous as vol from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_DEVICE_ID from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import config_validation as cv, device_registry as dr from .const import DOMAIN, INFO_SKILLS_MAPPING from .coordinator import AmazonConfigEntry ATTR_TEXT_COMMAND = "text_command" ATTR_SOUND = "sound" ATTR_INFO_SKILL = "info_skill" SCHEMA_SOUND_SERVICE = vol.Schema( { vol.Required(ATTR_SOUND): cv.string, vol.Required(ATTR_DEVICE_ID): cv.string, }, ) SCHEMA_CUSTOM_COMMAND = vol.Schema( { vol.Required(ATTR_TEXT_COMMAND): cv.string, vol.Required(ATTR_DEVICE_ID): cv.string, } ) SCHEMA_INFO_SKILL = vol.Schema( { vol.Required(ATTR_INFO_SKILL): cv.string, vol.Required(ATTR_DEVICE_ID): cv.string, } ) @callback def async_get_entry_id_for_service_call( call: ServiceCall, ) -> tuple[dr.DeviceEntry, AmazonConfigEntry]: """Get the entry ID related to a service call (by device ID).""" device_registry = dr.async_get(call.hass) device_id = call.data[ATTR_DEVICE_ID] if (device_entry := device_registry.async_get(device_id)) is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_device_id", translation_placeholders={"device_id": device_id}, ) for entry_id in device_entry.config_entries: if (entry := call.hass.config_entries.async_get_entry(entry_id)) is None: continue if entry.domain == DOMAIN: if entry.state is not ConfigEntryState.LOADED: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="entry_not_loaded", translation_placeholders={"entry": entry.title}, ) return (device_entry, entry) raise ServiceValidationError( translation_domain=DOMAIN, translation_key="config_entry_not_found", translation_placeholders={"device_id": device_id}, ) async def _async_execute_action(call: ServiceCall, attribute: str) -> None: """Execute action on the device.""" device, config_entry = async_get_entry_id_for_service_call(call) assert device.serial_number value: str = call.data[attribute] coordinator = config_entry.runtime_data if attribute == ATTR_SOUND: if value not in SOUNDS_LIST: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_sound_value", translation_placeholders={"sound": value}, ) await coordinator.api.call_alexa_sound( coordinator.data[device.serial_number], value ) elif attribute == ATTR_TEXT_COMMAND: await coordinator.api.call_alexa_text_command( coordinator.data[device.serial_number], value ) elif attribute == ATTR_INFO_SKILL: info_skill = INFO_SKILLS_MAPPING.get(value) if info_skill not in ALEXA_INFO_SKILLS: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="invalid_info_skill_value", translation_placeholders={"info_skill": value}, ) await coordinator.api.call_alexa_info_skill( coordinator.data[device.serial_number], info_skill ) async def async_send_sound_notification(call: ServiceCall) -> None: """Send a sound notification to a AmazonDevice.""" await _async_execute_action(call, ATTR_SOUND) async def async_send_text_command(call: ServiceCall) -> None: """Send a custom command to a AmazonDevice.""" await _async_execute_action(call, ATTR_TEXT_COMMAND) async def async_send_info_skill(call: ServiceCall) -> None: """Send an info skill command to a AmazonDevice.""" await _async_execute_action(call, ATTR_INFO_SKILL) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for the Amazon Devices integration.""" for service_name, method, schema in ( ( "send_sound", async_send_sound_notification, SCHEMA_SOUND_SERVICE, ), ( "send_text_command", async_send_text_command, SCHEMA_CUSTOM_COMMAND, ), ( "send_info_skill", async_send_info_skill, SCHEMA_INFO_SKILL, ), ): hass.services.async_register(DOMAIN, service_name, method, schema=schema)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/alexa_devices/services.py", "license": "Apache License 2.0", "lines": 122, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/amberelectric/helpers.py
"""Formatting helpers used to convert things.""" from amberelectric.models.price_descriptor import PriceDescriptor DESCRIPTOR_MAP: dict[str, str] = { PriceDescriptor.SPIKE: "spike", PriceDescriptor.HIGH: "high", PriceDescriptor.NEUTRAL: "neutral", PriceDescriptor.LOW: "low", PriceDescriptor.VERYLOW: "very_low", PriceDescriptor.EXTREMELYLOW: "extremely_low", PriceDescriptor.NEGATIVE: "negative", } def normalize_descriptor(descriptor: PriceDescriptor | None) -> str | None: """Return the snake case versions of descriptor names. Returns None if the name is not recognized.""" if descriptor in DESCRIPTOR_MAP: return DESCRIPTOR_MAP[descriptor] return None def format_cents_to_dollars(cents: float) -> float: """Return a formatted conversion from cents to dollars.""" return round(cents / 100, 2)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/amberelectric/helpers.py", "license": "Apache License 2.0", "lines": 19, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/amberelectric/services.py
"""Amber Electric Service class.""" from amberelectric.models.channel import ChannelType import voluptuous as vol from homeassistant.const import ATTR_CONFIG_ENTRY_ID from homeassistant.core import ( HomeAssistant, ServiceCall, ServiceResponse, SupportsResponse, callback, ) from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import service from homeassistant.helpers.selector import ConfigEntrySelector from homeassistant.util.json import JsonValueType from .const import ( ATTR_CHANNEL_TYPE, CONTROLLED_LOAD_CHANNEL, DOMAIN, FEED_IN_CHANNEL, GENERAL_CHANNEL, ) from .coordinator import AmberConfigEntry from .helpers import format_cents_to_dollars, normalize_descriptor GET_FORECASTS_SCHEMA = vol.Schema( { ATTR_CONFIG_ENTRY_ID: ConfigEntrySelector({"integration": DOMAIN}), ATTR_CHANNEL_TYPE: vol.In( [GENERAL_CHANNEL, CONTROLLED_LOAD_CHANNEL, FEED_IN_CHANNEL] ), } ) def get_forecasts(channel_type: str, data: dict) -> list[JsonValueType]: """Return an array of forecasts.""" results: list[JsonValueType] = [] if channel_type not in data["forecasts"]: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="channel_not_found", translation_placeholders={"channel_type": channel_type}, ) intervals = data["forecasts"][channel_type] for interval in intervals: datum = {} datum["duration"] = interval.duration datum["date"] = interval.var_date.isoformat() datum["nem_date"] = interval.nem_time.isoformat() datum["per_kwh"] = format_cents_to_dollars(interval.per_kwh) if interval.channel_type == ChannelType.FEEDIN: datum["per_kwh"] = datum["per_kwh"] * -1 datum["spot_per_kwh"] = format_cents_to_dollars(interval.spot_per_kwh) datum["start_time"] = interval.start_time.isoformat() datum["end_time"] = interval.end_time.isoformat() datum["renewables"] = round(interval.renewables) datum["spike_status"] = interval.spike_status.value datum["descriptor"] = normalize_descriptor(interval.descriptor) if interval.range is not None: datum["range_min"] = format_cents_to_dollars(interval.range.min) datum["range_max"] = format_cents_to_dollars(interval.range.max) if interval.advanced_price is not None: multiplier = -1 if interval.channel_type == ChannelType.FEEDIN else 1 datum["advanced_price_low"] = multiplier * format_cents_to_dollars( interval.advanced_price.low ) datum["advanced_price_predicted"] = multiplier * format_cents_to_dollars( interval.advanced_price.predicted ) datum["advanced_price_high"] = multiplier * format_cents_to_dollars( interval.advanced_price.high ) results.append(datum) return results @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up the services for the Amber integration.""" async def handle_get_forecasts(call: ServiceCall) -> ServiceResponse: channel_type = call.data[ATTR_CHANNEL_TYPE] entry: AmberConfigEntry = service.async_get_config_entry( hass, DOMAIN, call.data[ATTR_CONFIG_ENTRY_ID] ) coordinator = entry.runtime_data forecasts = get_forecasts(channel_type, coordinator.data) return {"forecasts": forecasts} hass.services.async_register( DOMAIN, "get_forecasts", handle_get_forecasts, GET_FORECASTS_SCHEMA, supports_response=SupportsResponse.ONLY, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/amberelectric/services.py", "license": "Apache License 2.0", "lines": 90, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/analytics/http.py
"""HTTP endpoints for analytics integration.""" from aiohttp import web from homeassistant.components.http import KEY_HASS, HomeAssistantView, require_admin from homeassistant.core import HomeAssistant from .analytics import async_devices_payload class AnalyticsDevicesView(HomeAssistantView): """View to handle analytics devices payload download requests.""" url = "/api/analytics/devices" name = "api:analytics:devices" @require_admin async def get(self, request: web.Request) -> web.Response: """Return analytics devices payload as JSON.""" hass: HomeAssistant = request.app[KEY_HASS] payload = await async_devices_payload(hass) return self.json( payload, headers={ "Content-Disposition": "attachment; filename=analytics_devices.json" }, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/analytics/http.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/anthropic/entity.py
"""Base entity for Anthropic.""" import base64 from collections.abc import AsyncGenerator, Callable, Iterable from dataclasses import dataclass, field from datetime import UTC, datetime import json from mimetypes import guess_file_type from pathlib import Path from typing import Any, Literal, cast import anthropic from anthropic import AsyncStream from anthropic.types import ( Base64ImageSourceParam, Base64PDFSourceParam, BashCodeExecutionToolResultBlock, CitationsDelta, CitationsWebSearchResultLocation, CitationWebSearchResultLocationParam, CodeExecutionTool20250825Param, Container, ContentBlockParam, DocumentBlockParam, ImageBlockParam, InputJSONDelta, JSONOutputFormatParam, MessageDeltaUsage, MessageParam, MessageStreamEvent, OutputConfigParam, RawContentBlockDeltaEvent, RawContentBlockStartEvent, RawContentBlockStopEvent, RawMessageDeltaEvent, RawMessageStartEvent, RawMessageStopEvent, RedactedThinkingBlock, RedactedThinkingBlockParam, ServerToolUseBlock, ServerToolUseBlockParam, SignatureDelta, TextBlock, TextBlockParam, TextCitation, TextCitationParam, TextDelta, TextEditorCodeExecutionToolResultBlock, ThinkingBlock, ThinkingBlockParam, ThinkingConfigAdaptiveParam, ThinkingConfigDisabledParam, ThinkingConfigEnabledParam, ThinkingDelta, ToolChoiceAnyParam, ToolChoiceAutoParam, ToolChoiceToolParam, ToolParam, ToolUnionParam, ToolUseBlock, ToolUseBlockParam, Usage, WebSearchTool20250305Param, WebSearchToolResultBlock, WebSearchToolResultBlockParamContentParam, ) from anthropic.types.bash_code_execution_tool_result_block_param import ( Content as BashCodeExecutionToolResultContentParam, ) from anthropic.types.message_create_params import MessageCreateParamsStreaming from anthropic.types.text_editor_code_execution_tool_result_block_param import ( Content as TextEditorCodeExecutionToolResultContentParam, ) import voluptuous as vol from voluptuous_openapi import convert from homeassistant.components import conversation from homeassistant.config_entries import ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr, llm from homeassistant.helpers.entity import Entity from homeassistant.helpers.json import json_dumps from homeassistant.util import slugify from homeassistant.util.json import JsonObjectType from . import AnthropicConfigEntry from .const import ( CONF_CHAT_MODEL, CONF_CODE_EXECUTION, CONF_MAX_TOKENS, CONF_TEMPERATURE, CONF_THINKING_BUDGET, CONF_THINKING_EFFORT, CONF_WEB_SEARCH, CONF_WEB_SEARCH_CITY, CONF_WEB_SEARCH_COUNTRY, CONF_WEB_SEARCH_MAX_USES, CONF_WEB_SEARCH_REGION, CONF_WEB_SEARCH_TIMEZONE, CONF_WEB_SEARCH_USER_LOCATION, DEFAULT, DOMAIN, LOGGER, MIN_THINKING_BUDGET, NON_ADAPTIVE_THINKING_MODELS, NON_THINKING_MODELS, UNSUPPORTED_STRUCTURED_OUTPUT_MODELS, ) # Max number of back and forth with the LLM to generate a response MAX_TOOL_ITERATIONS = 10 def _format_tool( tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None ) -> ToolParam: """Format tool specification.""" return ToolParam( name=tool.name, description=tool.description or "", input_schema=convert(tool.parameters, custom_serializer=custom_serializer), ) @dataclass(slots=True) class CitationDetails: """Citation details for a content part.""" index: int = 0 """Start position of the text.""" length: int = 0 """Length of the relevant data.""" citations: list[TextCitationParam] = field(default_factory=list) """Citations for the content part.""" @dataclass(slots=True) class ContentDetails: """Native data for AssistantContent.""" citation_details: list[CitationDetails] = field(default_factory=list) thinking_signature: str | None = None redacted_thinking: str | None = None container: Container | None = None def has_content(self) -> bool: """Check if there is any text content.""" return any(detail.length > 0 for detail in self.citation_details) def __bool__(self) -> bool: """Check if there is any thinking content or citations.""" return ( self.thinking_signature is not None or self.redacted_thinking is not None or self.container is not None or self.has_citations() ) def has_citations(self) -> bool: """Check if there are any citations.""" return any(detail.citations for detail in self.citation_details) def add_citation_detail(self) -> None: """Add a new citation detail.""" if not self.citation_details or self.citation_details[-1].length > 0: self.citation_details.append( CitationDetails( index=self.citation_details[-1].index + self.citation_details[-1].length if self.citation_details else 0 ) ) def add_citation(self, citation: TextCitation) -> None: """Add a citation to the current detail.""" if not self.citation_details: self.citation_details.append(CitationDetails()) citation_param: TextCitationParam | None = None if isinstance(citation, CitationsWebSearchResultLocation): citation_param = CitationWebSearchResultLocationParam( type="web_search_result_location", title=citation.title, url=citation.url, cited_text=citation.cited_text, encrypted_index=citation.encrypted_index, ) if citation_param: self.citation_details[-1].citations.append(citation_param) def delete_empty(self) -> None: """Delete empty citation details.""" self.citation_details = [ detail for detail in self.citation_details if detail.citations ] def _convert_content( chat_content: Iterable[conversation.Content], ) -> tuple[list[MessageParam], str | None]: """Transform HA chat_log content into Anthropic API format.""" messages: list[MessageParam] = [] container_id: str | None = None for content in chat_content: if isinstance(content, conversation.ToolResultContent): external_tool = True if content.tool_name == "web_search": tool_result_block: ContentBlockParam = { "type": "web_search_tool_result", "tool_use_id": content.tool_call_id, "content": cast( WebSearchToolResultBlockParamContentParam, content.tool_result["content"] if "content" in content.tool_result else { "type": "web_search_tool_result_error", "error_code": content.tool_result.get( "error_code", "unavailable" ), }, ), } elif content.tool_name == "bash_code_execution": tool_result_block = { "type": "bash_code_execution_tool_result", "tool_use_id": content.tool_call_id, "content": cast( BashCodeExecutionToolResultContentParam, content.tool_result ), } elif content.tool_name == "text_editor_code_execution": tool_result_block = { "type": "text_editor_code_execution_tool_result", "tool_use_id": content.tool_call_id, "content": cast( TextEditorCodeExecutionToolResultContentParam, content.tool_result, ), } else: tool_result_block = { "type": "tool_result", "tool_use_id": content.tool_call_id, "content": json_dumps(content.tool_result), } external_tool = False if not messages or messages[-1]["role"] != ( "assistant" if external_tool else "user" ): messages.append( MessageParam( role="assistant" if external_tool else "user", content=[tool_result_block], ) ) elif isinstance(messages[-1]["content"], str): messages[-1]["content"] = [ TextBlockParam(type="text", text=messages[-1]["content"]), tool_result_block, ] else: messages[-1]["content"].append(tool_result_block) # type: ignore[attr-defined] elif isinstance(content, conversation.UserContent): # Combine consequent user messages if not messages or messages[-1]["role"] != "user": messages.append( MessageParam( role="user", content=content.content, ) ) elif isinstance(messages[-1]["content"], str): messages[-1]["content"] = [ TextBlockParam(type="text", text=messages[-1]["content"]), TextBlockParam(type="text", text=content.content), ] else: messages[-1]["content"].append( # type: ignore[attr-defined] TextBlockParam(type="text", text=content.content) ) elif isinstance(content, conversation.AssistantContent): # Combine consequent assistant messages if not messages or messages[-1]["role"] != "assistant": messages.append( MessageParam( role="assistant", content=[], ) ) elif isinstance(messages[-1]["content"], str): messages[-1]["content"] = [ TextBlockParam(type="text", text=messages[-1]["content"]), ] if isinstance(content.native, ContentDetails): if content.native.thinking_signature: messages[-1]["content"].append( # type: ignore[union-attr] ThinkingBlockParam( type="thinking", thinking=content.thinking_content or "", signature=content.native.thinking_signature, ) ) if content.native.redacted_thinking: messages[-1]["content"].append( # type: ignore[union-attr] RedactedThinkingBlockParam( type="redacted_thinking", data=content.native.redacted_thinking, ) ) if ( content.native.container is not None and content.native.container.expires_at > datetime.now(UTC) ): container_id = content.native.container.id if content.content: current_index = 0 for detail in ( content.native.citation_details if isinstance(content.native, ContentDetails) else [CitationDetails(length=len(content.content))] ): if detail.index > current_index: # Add text block for any text without citations messages[-1]["content"].append( # type: ignore[union-attr] TextBlockParam( type="text", text=content.content[current_index : detail.index], ) ) messages[-1]["content"].append( # type: ignore[union-attr] TextBlockParam( type="text", text=content.content[ detail.index : detail.index + detail.length ], citations=detail.citations, ) if detail.citations else TextBlockParam( type="text", text=content.content[ detail.index : detail.index + detail.length ], ) ) current_index = detail.index + detail.length if current_index < len(content.content): # Add text block for any remaining text without citations messages[-1]["content"].append( # type: ignore[union-attr] TextBlockParam( type="text", text=content.content[current_index:], ) ) if content.tool_calls: messages[-1]["content"].extend( # type: ignore[union-attr] [ ServerToolUseBlockParam( type="server_tool_use", id=tool_call.id, name=cast( Literal[ "web_search", "bash_code_execution", "text_editor_code_execution", ], tool_call.tool_name, ), input=tool_call.tool_args, ) if tool_call.external and tool_call.tool_name in [ "web_search", "bash_code_execution", "text_editor_code_execution", ] else ToolUseBlockParam( type="tool_use", id=tool_call.id, name=tool_call.tool_name, input=tool_call.tool_args, ) for tool_call in content.tool_calls ] ) if ( isinstance(messages[-1]["content"], list) and len(messages[-1]["content"]) == 1 and messages[-1]["content"][0]["type"] == "text" ): # If there is only one text block, simplify the content to a string messages[-1]["content"] = messages[-1]["content"][0]["text"] else: # Note: We don't pass SystemContent here as it's passed to the API as the prompt raise HomeAssistantError("Unexpected content type in chat log") return messages, container_id async def _transform_stream( # noqa: C901 - This is complex, but better to have it in one place chat_log: conversation.ChatLog, stream: AsyncStream[MessageStreamEvent], output_tool: str | None = None, ) -> AsyncGenerator[ conversation.AssistantContentDeltaDict | conversation.ToolResultContentDeltaDict ]: """Transform the response stream into HA format. A typical stream of responses might look something like the following: - RawMessageStartEvent with no content - RawContentBlockStartEvent with an empty ThinkingBlock (if extended thinking is enabled) - RawContentBlockDeltaEvent with a ThinkingDelta - RawContentBlockDeltaEvent with a ThinkingDelta - RawContentBlockDeltaEvent with a ThinkingDelta - ... - RawContentBlockDeltaEvent with a SignatureDelta - RawContentBlockStopEvent - RawContentBlockStartEvent with a RedactedThinkingBlock (occasionally) - RawContentBlockStopEvent (RedactedThinkingBlock does not have a delta) - RawContentBlockStartEvent with an empty TextBlock - RawContentBlockDeltaEvent with a TextDelta - RawContentBlockDeltaEvent with a TextDelta - RawContentBlockDeltaEvent with a TextDelta - ... - RawContentBlockStopEvent - RawContentBlockStartEvent with ToolUseBlock specifying the function name - RawContentBlockDeltaEvent with a InputJSONDelta - RawContentBlockDeltaEvent with a InputJSONDelta - ... - RawContentBlockStopEvent - RawMessageDeltaEvent with a stop_reason='tool_use' - RawMessageStopEvent(type='message_stop') Each message could contain multiple blocks of the same type. """ if stream is None or not hasattr(stream, "__aiter__"): raise HomeAssistantError("Expected a stream of messages") current_tool_block: ToolUseBlockParam | ServerToolUseBlockParam | None = None current_tool_args: str content_details = ContentDetails() content_details.add_citation_detail() input_usage: Usage | None = None first_block: bool = True async for response in stream: LOGGER.debug("Received response: %s", response) if isinstance(response, RawMessageStartEvent): input_usage = response.message.usage first_block = True elif isinstance(response, RawContentBlockStartEvent): if isinstance(response.content_block, ToolUseBlock): current_tool_block = ToolUseBlockParam( type="tool_use", id=response.content_block.id, name=response.content_block.name, input={}, ) current_tool_args = "" if response.content_block.name == output_tool: if first_block or content_details.has_content(): if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() content_details.add_citation_detail() yield {"role": "assistant"} first_block = False elif isinstance(response.content_block, TextBlock): if ( # Do not start a new assistant content just for citations, concatenate consecutive blocks with citations instead. first_block or ( not content_details.has_citations() and response.content_block.citations is None and content_details.has_content() ) ): if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() yield {"role": "assistant"} first_block = False content_details.add_citation_detail() if response.content_block.text: content_details.citation_details[-1].length += len( response.content_block.text ) yield {"content": response.content_block.text} elif isinstance(response.content_block, ThinkingBlock): if first_block or content_details.thinking_signature: if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() content_details.add_citation_detail() yield {"role": "assistant"} first_block = False elif isinstance(response.content_block, RedactedThinkingBlock): LOGGER.debug( "Some of Claude’s internal reasoning has been automatically " "encrypted for safety reasons. This doesn’t affect the quality of " "responses" ) if first_block or content_details.redacted_thinking: if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() content_details.add_citation_detail() yield {"role": "assistant"} first_block = False content_details.redacted_thinking = response.content_block.data elif isinstance(response.content_block, ServerToolUseBlock): current_tool_block = ServerToolUseBlockParam( type="server_tool_use", id=response.content_block.id, name=response.content_block.name, input={}, ) current_tool_args = "" elif isinstance( response.content_block, ( WebSearchToolResultBlock, BashCodeExecutionToolResultBlock, TextEditorCodeExecutionToolResultBlock, ), ): if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() content_details.add_citation_detail() yield { "role": "tool_result", "tool_call_id": response.content_block.tool_use_id, "tool_name": response.content_block.type.removesuffix( "_tool_result" ), "tool_result": { "content": cast( JsonObjectType, response.content_block.to_dict()["content"] ) } if isinstance(response.content_block.content, list) else cast(JsonObjectType, response.content_block.content.to_dict()), } first_block = True elif isinstance(response, RawContentBlockDeltaEvent): if isinstance(response.delta, InputJSONDelta): if ( current_tool_block is not None and current_tool_block["name"] == output_tool ): content_details.citation_details[-1].length += len( response.delta.partial_json ) yield {"content": response.delta.partial_json} else: current_tool_args += response.delta.partial_json elif isinstance(response.delta, TextDelta): if response.delta.text: content_details.citation_details[-1].length += len( response.delta.text ) yield {"content": response.delta.text} elif isinstance(response.delta, ThinkingDelta): if response.delta.thinking: yield {"thinking_content": response.delta.thinking} elif isinstance(response.delta, SignatureDelta): content_details.thinking_signature = response.delta.signature elif isinstance(response.delta, CitationsDelta): content_details.add_citation(response.delta.citation) elif isinstance(response, RawContentBlockStopEvent): if current_tool_block is not None: if current_tool_block["name"] == output_tool: current_tool_block = None continue tool_args = json.loads(current_tool_args) if current_tool_args else {} current_tool_block["input"] = tool_args yield { "tool_calls": [ llm.ToolInput( id=current_tool_block["id"], tool_name=current_tool_block["name"], tool_args=tool_args, external=current_tool_block["type"] == "server_tool_use", ) ] } current_tool_block = None elif isinstance(response, RawMessageDeltaEvent): if (usage := response.usage) is not None: chat_log.async_trace(_create_token_stats(input_usage, usage)) content_details.container = response.delta.container if response.delta.stop_reason == "refusal": raise HomeAssistantError("Potential policy violation detected") elif isinstance(response, RawMessageStopEvent): if content_details: content_details.delete_empty() yield {"native": content_details} content_details = ContentDetails() content_details.add_citation_detail() def _create_token_stats( input_usage: Usage | None, response_usage: MessageDeltaUsage ) -> dict[str, Any]: """Create token stats for conversation agent tracing.""" input_tokens = 0 cached_input_tokens = 0 if input_usage: input_tokens = input_usage.input_tokens cached_input_tokens = input_usage.cache_creation_input_tokens or 0 output_tokens = response_usage.output_tokens return { "stats": { "input_tokens": input_tokens, "cached_input_tokens": cached_input_tokens, "output_tokens": output_tokens, } } class AnthropicBaseLLMEntity(Entity): """Anthropic base LLM entity.""" _attr_has_entity_name = True _attr_name = None def __init__(self, entry: AnthropicConfigEntry, subentry: ConfigSubentry) -> None: """Initialize the entity.""" self.entry = entry self.subentry = subentry self._attr_unique_id = subentry.subentry_id self._attr_device_info = dr.DeviceInfo( identifiers={(DOMAIN, subentry.subentry_id)}, name=subentry.title, manufacturer="Anthropic", model=subentry.data.get(CONF_CHAT_MODEL, DEFAULT[CONF_CHAT_MODEL]), entry_type=dr.DeviceEntryType.SERVICE, ) async def _async_handle_chat_log( self, chat_log: conversation.ChatLog, structure_name: str | None = None, structure: vol.Schema | None = None, max_iterations: int = MAX_TOOL_ITERATIONS, ) -> None: """Generate an answer for the chat log.""" options = self.subentry.data system = chat_log.content[0] if not isinstance(system, conversation.SystemContent): raise HomeAssistantError("First message must be a system message") # System prompt with caching enabled system_prompt: list[TextBlockParam] = [ TextBlockParam( type="text", text=system.content, cache_control={"type": "ephemeral"}, ) ] messages, container_id = _convert_content(chat_log.content[1:]) model = options.get(CONF_CHAT_MODEL, DEFAULT[CONF_CHAT_MODEL]) model_args = MessageCreateParamsStreaming( model=model, messages=messages, max_tokens=options.get(CONF_MAX_TOKENS, DEFAULT[CONF_MAX_TOKENS]), system=system_prompt, stream=True, container=container_id, ) if not model.startswith(tuple(NON_ADAPTIVE_THINKING_MODELS)): thinking_effort = options.get( CONF_THINKING_EFFORT, DEFAULT[CONF_THINKING_EFFORT] ) if thinking_effort != "none": model_args["thinking"] = ThinkingConfigAdaptiveParam(type="adaptive") model_args["output_config"] = OutputConfigParam(effort=thinking_effort) else: model_args["thinking"] = ThinkingConfigDisabledParam(type="disabled") model_args["temperature"] = options.get( CONF_TEMPERATURE, DEFAULT[CONF_TEMPERATURE] ) else: thinking_budget = options.get( CONF_THINKING_BUDGET, DEFAULT[CONF_THINKING_BUDGET] ) if ( not model.startswith(tuple(NON_THINKING_MODELS)) and thinking_budget >= MIN_THINKING_BUDGET ): model_args["thinking"] = ThinkingConfigEnabledParam( type="enabled", budget_tokens=thinking_budget ) else: model_args["thinking"] = ThinkingConfigDisabledParam(type="disabled") model_args["temperature"] = options.get( CONF_TEMPERATURE, DEFAULT[CONF_TEMPERATURE] ) tools: list[ToolUnionParam] = [] if chat_log.llm_api: tools = [ _format_tool(tool, chat_log.llm_api.custom_serializer) for tool in chat_log.llm_api.tools ] if options.get(CONF_CODE_EXECUTION): tools.append( CodeExecutionTool20250825Param( name="code_execution", type="code_execution_20250825", ), ) if options.get(CONF_WEB_SEARCH): web_search = WebSearchTool20250305Param( name="web_search", type="web_search_20250305", max_uses=options.get(CONF_WEB_SEARCH_MAX_USES), ) if options.get(CONF_WEB_SEARCH_USER_LOCATION): web_search["user_location"] = { "type": "approximate", "city": options.get(CONF_WEB_SEARCH_CITY, ""), "region": options.get(CONF_WEB_SEARCH_REGION, ""), "country": options.get(CONF_WEB_SEARCH_COUNTRY, ""), "timezone": options.get(CONF_WEB_SEARCH_TIMEZONE, ""), } tools.append(web_search) # Handle attachments by adding them to the last user message last_content = chat_log.content[-1] if last_content.role == "user" and last_content.attachments: last_message = messages[-1] if last_message["role"] != "user": raise HomeAssistantError( "Last message must be a user message to add attachments" ) if isinstance(last_message["content"], str): last_message["content"] = [ TextBlockParam(type="text", text=last_message["content"]) ] last_message["content"].extend( # type: ignore[union-attr] await async_prepare_files_for_prompt( self.hass, [(a.path, a.mime_type) for a in last_content.attachments] ) ) if structure and structure_name: if not model.startswith(tuple(UNSUPPORTED_STRUCTURED_OUTPUT_MODELS)): # Native structured output for those models who support it. structure_name = None model_args.setdefault("output_config", OutputConfigParam())[ "format" ] = JSONOutputFormatParam( type="json_schema", schema={ **convert( structure, custom_serializer=chat_log.llm_api.custom_serializer if chat_log.llm_api else llm.selector_serializer, ), "additionalProperties": False, }, ) elif model_args["thinking"]["type"] == "disabled": structure_name = slugify(structure_name) if not tools: # Simplest case: no tools and no extended thinking # Add a tool and force its use model_args["tool_choice"] = ToolChoiceToolParam( type="tool", name=structure_name, ) else: # Second case: tools present but no extended thinking # Allow the model to use any tool but not text response # The model should know to use the right tool by its description model_args["tool_choice"] = ToolChoiceAnyParam( type="any", ) else: # Extended thinking is enabled. With extended thinking, we cannot # force tool use or disable text responses, so we add a hint to the # system prompt instead. With extended thinking, the model should be # smart enough to use the tool. structure_name = slugify(structure_name) model_args["tool_choice"] = ToolChoiceAutoParam( type="auto", ) model_args["system"].append( # type: ignore[union-attr] TextBlockParam( type="text", text=f"Claude MUST use the '{structure_name}' tool to provide " "the final answer instead of plain text.", ) ) if structure_name: tools.append( ToolParam( name=structure_name, description="Use this tool to reply to the user", input_schema=convert( structure, custom_serializer=chat_log.llm_api.custom_serializer if chat_log.llm_api else llm.selector_serializer, ), ) ) if tools: model_args["tools"] = tools client = self.entry.runtime_data # To prevent infinite loops, we limit the number of iterations for _iteration in range(max_iterations): try: stream = await client.messages.create(**model_args) new_messages, model_args["container"] = _convert_content( [ content async for content in chat_log.async_add_delta_content_stream( self.entity_id, _transform_stream( chat_log, stream, output_tool=structure_name or None, ), ) ] ) messages.extend(new_messages) except anthropic.AuthenticationError as err: self.entry.async_start_reauth(self.hass) raise HomeAssistantError( "Authentication error with Anthropic API, reauthentication required" ) from err except anthropic.AnthropicError as err: raise HomeAssistantError( f"Sorry, I had a problem talking to Anthropic: {err}" ) from err if not chat_log.unresponded_tool_results: break async def async_prepare_files_for_prompt( hass: HomeAssistant, files: list[tuple[Path, str | None]] ) -> Iterable[ImageBlockParam | DocumentBlockParam]: """Append files to a prompt. Caller needs to ensure that the files are allowed. """ def append_files_to_content() -> Iterable[ImageBlockParam | DocumentBlockParam]: content: list[ImageBlockParam | DocumentBlockParam] = [] for file_path, mime_type in files: if not file_path.exists(): raise HomeAssistantError(f"`{file_path}` does not exist") if mime_type is None: mime_type = guess_file_type(file_path)[0] if not mime_type or not mime_type.startswith(("image/", "application/pdf")): raise HomeAssistantError( "Only images and PDF are supported by the Anthropic API," f"`{file_path}` is not an image file or PDF" ) if mime_type == "image/jpg": mime_type = "image/jpeg" base64_file = base64.b64encode(file_path.read_bytes()).decode("utf-8") if mime_type.startswith("image/"): content.append( ImageBlockParam( type="image", source=Base64ImageSourceParam( type="base64", media_type=mime_type, # type: ignore[typeddict-item] data=base64_file, ), ) ) elif mime_type.startswith("application/pdf"): content.append( DocumentBlockParam( type="document", source=Base64PDFSourceParam( type="base64", media_type=mime_type, # type: ignore[typeddict-item] data=base64_file, ), ) ) return content return await hass.async_add_executor_job(append_files_to_content)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/anthropic/entity.py", "license": "Apache License 2.0", "lines": 854, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/backup/services.py
"""The Backup integration.""" from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.helpers.hassio import is_hassio from .const import DATA_MANAGER, DOMAIN async def _async_handle_create_service(call: ServiceCall) -> None: """Service handler for creating backups.""" backup_manager = call.hass.data[DATA_MANAGER] agent_id = list(backup_manager.local_backup_agents)[0] await backup_manager.async_create_backup( agent_ids=[agent_id], include_addons=None, include_all_addons=False, include_database=True, include_folders=None, include_homeassistant=True, name=None, password=None, ) async def _async_handle_create_automatic_service(call: ServiceCall) -> None: """Service handler for creating automatic backups.""" await call.hass.data[DATA_MANAGER].async_create_automatic_backup() def async_setup_services(hass: HomeAssistant) -> None: """Register services.""" if not is_hassio(hass): hass.services.async_register(DOMAIN, "create", _async_handle_create_service) hass.services.async_register( DOMAIN, "create_automatic", _async_handle_create_automatic_service )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/backup/services.py", "license": "Apache License 2.0", "lines": 28, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/blue_current/switch.py
"""Support for Blue Current switches.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from typing import Any from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import PLUG_AND_CHARGE, BlueCurrentConfigEntry, Connector from .const import ( AVAILABLE, BLOCK, LINKED_CHARGE_CARDS, PUBLIC_CHARGING, UNAVAILABLE, VALUE, ) from .entity import ChargepointEntity @dataclass(kw_only=True, frozen=True) class BlueCurrentSwitchEntityDescription(SwitchEntityDescription): """Describes a Blue Current switch entity.""" function: Callable[[Connector, str, bool], Any] turn_on_off_fn: Callable[[str, Connector], tuple[bool, bool]] """Update the switch based on the latest data received from the websocket. The first returned boolean is _attr_is_on, the second one has_value.""" def update_on_value_and_activity( key: str, evse_id: str, connector: Connector, reverse_is_on: bool = False ) -> tuple[bool, bool]: """Return the updated state of the switch based on received chargepoint data and activity.""" data_object = connector.charge_points[evse_id].get(key) is_on = data_object[VALUE] if data_object is not None else None activity = connector.charge_points[evse_id].get("activity") if is_on is not None and activity == AVAILABLE: return is_on if not reverse_is_on else not is_on, True return False, False def update_block_switch(evse_id: str, connector: Connector) -> tuple[bool, bool]: """Return the updated data for a block switch.""" activity = connector.charge_points[evse_id].get("activity") return activity == UNAVAILABLE, activity in [AVAILABLE, UNAVAILABLE] def update_charge_point( key: str, evse_id: str, connector: Connector, new_switch_value: bool ) -> None: """Change charge point data when the state of the switch changes.""" data_objects = connector.charge_points[evse_id].get(key) if data_objects is not None: data_objects[VALUE] = new_switch_value async def set_plug_and_charge(connector: Connector, evse_id: str, value: bool) -> None: """Toggle the plug and charge setting for a specific charging point.""" await connector.client.set_plug_and_charge(evse_id, value) update_charge_point(PLUG_AND_CHARGE, evse_id, connector, value) async def set_linked_charge_cards( connector: Connector, evse_id: str, value: bool ) -> None: """Toggle the plug and charge setting for a specific charging point.""" await connector.client.set_linked_charge_cards_only(evse_id, value) update_charge_point(PUBLIC_CHARGING, evse_id, connector, not value) SWITCHES = ( BlueCurrentSwitchEntityDescription( key=PLUG_AND_CHARGE, translation_key=PLUG_AND_CHARGE, function=set_plug_and_charge, turn_on_off_fn=lambda evse_id, connector: update_on_value_and_activity( PLUG_AND_CHARGE, evse_id, connector ), ), BlueCurrentSwitchEntityDescription( key=LINKED_CHARGE_CARDS, translation_key=LINKED_CHARGE_CARDS, function=set_linked_charge_cards, turn_on_off_fn=lambda evse_id, connector: update_on_value_and_activity( PUBLIC_CHARGING, evse_id, connector, reverse_is_on=True ), ), BlueCurrentSwitchEntityDescription( key=BLOCK, translation_key=BLOCK, function=lambda connector, evse_id, value: connector.client.block( evse_id, value ), turn_on_off_fn=update_block_switch, ), ) async def async_setup_entry( hass: HomeAssistant, entry: BlueCurrentConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Blue Current switches.""" connector = entry.runtime_data async_add_entities( ChargePointSwitch( connector, evse_id, switch, ) for evse_id in connector.charge_points for switch in SWITCHES ) class ChargePointSwitch(ChargepointEntity, SwitchEntity): """Base charge point switch.""" has_value = True entity_description: BlueCurrentSwitchEntityDescription def __init__( self, connector: Connector, evse_id: str, switch: BlueCurrentSwitchEntityDescription, ) -> None: """Initialize the switch.""" super().__init__(connector, evse_id) self.key = switch.key self.entity_description = switch self.evse_id = evse_id self._attr_available = True self._attr_unique_id = f"{switch.key}_{evse_id}" async def call_function(self, value: bool) -> None: """Call the function to set setting.""" await self.entity_description.function(self.connector, self.evse_id, value) async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" await self.call_function(True) self._attr_is_on = True self.async_write_ha_state() async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity on.""" await self.call_function(False) self._attr_is_on = False self.async_write_ha_state() @callback def update_from_latest_data(self) -> None: """Fetch new state data for the switch.""" new_state = self.entity_description.turn_on_off_fn(self.evse_id, self.connector) self._attr_is_on = new_state[0] self.has_value = new_state[1]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/blue_current/switch.py", "license": "Apache License 2.0", "lines": 133, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/bring/services.py
"""Actions for Bring! integration.""" from bring_api import ( ActivityType, BringAuthException, BringNotificationType, BringRequestException, ReactionType, ) import voluptuous as vol from homeassistant.components.event import ATTR_EVENT_TYPE from homeassistant.components.todo import DOMAIN as TODO_DOMAIN from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant, ServiceCall, callback from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers import ( config_validation as cv, entity_registry as er, service, ) from .const import DOMAIN from .coordinator import BringConfigEntry ATTR_ACTIVITY = "uuid" ATTR_ITEM_NAME = "item" ATTR_NOTIFICATION_TYPE = "message" ATTR_REACTION = "reaction" ATTR_RECEIVER = "publicUserUuid" SERVICE_PUSH_NOTIFICATION = "send_message" SERVICE_ACTIVITY_STREAM_REACTION = "send_reaction" SERVICE_ACTIVITY_STREAM_REACTION_SCHEMA = vol.Schema( { vol.Required(ATTR_ENTITY_ID): cv.entity_id, vol.Required(ATTR_REACTION): vol.All( vol.Upper, vol.Coerce(ReactionType), ), } ) @callback def async_setup_services(hass: HomeAssistant) -> None: """Set up services for Bring! integration.""" async def async_send_activity_stream_reaction(call: ServiceCall) -> None: """Send a reaction in response to recent activity of a list member.""" if ( not (state := hass.states.get(call.data[ATTR_ENTITY_ID])) or not (entity := er.async_get(hass).async_get(call.data[ATTR_ENTITY_ID])) or not entity.config_entry_id ): raise ServiceValidationError( translation_domain=DOMAIN, translation_key="entity_not_found", translation_placeholders={ ATTR_ENTITY_ID: call.data[ATTR_ENTITY_ID], }, ) config_entry: BringConfigEntry = service.async_get_config_entry( hass, DOMAIN, entity.config_entry_id ) coordinator = config_entry.runtime_data.data list_uuid = entity.unique_id.split("_")[1] activity = state.attributes[ATTR_EVENT_TYPE] reaction: ReactionType = call.data[ATTR_REACTION] if not activity: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="activity_not_found", ) try: await coordinator.bring.notify( list_uuid, BringNotificationType.LIST_ACTIVITY_STREAM_REACTION, receiver=state.attributes[ATTR_RECEIVER], activity=state.attributes[ATTR_ACTIVITY], activity_type=ActivityType(activity.upper()), reaction=reaction, ) except (BringRequestException, BringAuthException) as e: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="reaction_request_failed", ) from e hass.services.async_register( DOMAIN, SERVICE_ACTIVITY_STREAM_REACTION, async_send_activity_stream_reaction, SERVICE_ACTIVITY_STREAM_REACTION_SCHEMA, ) service.async_register_platform_entity_service( hass, DOMAIN, SERVICE_PUSH_NOTIFICATION, entity_domain=TODO_DOMAIN, schema={ vol.Required(ATTR_NOTIFICATION_TYPE): vol.All( vol.Upper, vol.Coerce(BringNotificationType) ), vol.Optional(ATTR_ITEM_NAME): cv.string, }, func="async_send_message", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/bring/services.py", "license": "Apache License 2.0", "lines": 99, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/datadog/config_flow.py
"""Config flow for Datadog.""" from typing import Any from datadog import DogStatsd import voluptuous as vol from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigFlowResult, OptionsFlow, ) from homeassistant.const import CONF_HOST, CONF_PORT, CONF_PREFIX from homeassistant.core import HomeAssistant, callback from .const import ( CONF_RATE, DEFAULT_HOST, DEFAULT_PORT, DEFAULT_PREFIX, DEFAULT_RATE, DOMAIN, ) class DatadogConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Datadog.""" VERSION = 1 async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle user config flow.""" errors: dict[str, str] = {} if user_input: self._async_abort_entries_match( {CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]} ) # Validate connection to Datadog Agent success = await validate_datadog_connection( self.hass, user_input, ) if not success: errors["base"] = "cannot_connect" else: return self.async_create_entry( title=f"Datadog {user_input['host']}", data={ CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT], }, options={ CONF_PREFIX: user_input[CONF_PREFIX], CONF_RATE: user_input[CONF_RATE], }, ) return self.async_show_form( step_id="user", data_schema=vol.Schema( { vol.Required(CONF_HOST, default=DEFAULT_HOST): str, vol.Required(CONF_PORT, default=DEFAULT_PORT): int, vol.Required(CONF_PREFIX, default=DEFAULT_PREFIX): str, vol.Required(CONF_RATE, default=DEFAULT_RATE): int, } ), errors=errors, ) @staticmethod @callback def async_get_options_flow(config_entry: ConfigEntry) -> OptionsFlow: """Get the options flow handler.""" return DatadogOptionsFlowHandler() class DatadogOptionsFlowHandler(OptionsFlow): """Handle Datadog options.""" async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Manage the Datadog options.""" errors: dict[str, str] = {} data = self.config_entry.data options = self.config_entry.options if user_input is None: return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Required( CONF_PREFIX, default=options.get( CONF_PREFIX, data.get(CONF_PREFIX, DEFAULT_PREFIX) ), ): str, vol.Required( CONF_RATE, default=options.get( CONF_RATE, data.get(CONF_RATE, DEFAULT_RATE) ), ): int, } ), errors={}, ) success = await validate_datadog_connection( self.hass, {**data, **user_input}, ) if success: return self.async_create_entry( data={ CONF_PREFIX: user_input[CONF_PREFIX], CONF_RATE: user_input[CONF_RATE], } ) errors["base"] = "cannot_connect" return self.async_show_form( step_id="init", data_schema=vol.Schema( { vol.Required(CONF_PREFIX, default=options[CONF_PREFIX]): str, vol.Required(CONF_RATE, default=options[CONF_RATE]): int, } ), errors=errors, ) async def validate_datadog_connection( hass: HomeAssistant, user_input: dict[str, Any] ) -> bool: """Attempt to send a test metric to the Datadog agent.""" try: client = DogStatsd(user_input[CONF_HOST], user_input[CONF_PORT]) await hass.async_add_executor_job(client.increment, "connection_test") except OSError, ValueError: return False else: return True
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/datadog/config_flow.py", "license": "Apache License 2.0", "lines": 131, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/datadog/const.py
"""Constants for the Datadog integration.""" DOMAIN = "datadog" CONF_RATE = "rate" DEFAULT_HOST = "127.0.0.1" DEFAULT_PORT = 8125 DEFAULT_PREFIX = "hass" DEFAULT_RATE = 1
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/datadog/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/esphome/encryption_key_storage.py
"""Encryption key storage for ESPHome devices.""" from __future__ import annotations import logging from typing import TypedDict from homeassistant.core import HomeAssistant from homeassistant.helpers.json import JSONEncoder from homeassistant.helpers.singleton import singleton from homeassistant.helpers.storage import Store from homeassistant.util.hass_dict import HassKey _LOGGER = logging.getLogger(__name__) ENCRYPTION_KEY_STORAGE_VERSION = 1 ENCRYPTION_KEY_STORAGE_KEY = "esphome.encryption_keys" class EncryptionKeyData(TypedDict): """Encryption key storage data.""" keys: dict[str, str] # MAC address -> base64 encoded key KEY_ENCRYPTION_STORAGE: HassKey[ESPHomeEncryptionKeyStorage] = HassKey( "esphome_encryption_key_storage" ) class ESPHomeEncryptionKeyStorage: """Storage for ESPHome encryption keys.""" def __init__(self, hass: HomeAssistant) -> None: """Initialize the encryption key storage.""" self.hass = hass self._store = Store[EncryptionKeyData]( hass, ENCRYPTION_KEY_STORAGE_VERSION, ENCRYPTION_KEY_STORAGE_KEY, encoder=JSONEncoder, ) self._data: EncryptionKeyData | None = None async def async_load(self) -> None: """Load encryption keys from storage.""" if self._data is None: data = await self._store.async_load() self._data = data or {"keys": {}} async def async_save(self) -> None: """Save encryption keys to storage.""" if self._data is not None: await self._store.async_save(self._data) async def async_get_key(self, mac_address: str) -> str | None: """Get encryption key for a MAC address.""" await self.async_load() assert self._data is not None return self._data["keys"].get(mac_address.lower()) async def async_store_key(self, mac_address: str, key: str) -> None: """Store encryption key for a MAC address.""" await self.async_load() assert self._data is not None self._data["keys"][mac_address.lower()] = key await self.async_save() _LOGGER.debug( "Stored encryption key for device with MAC %s", mac_address, ) async def async_remove_key(self, mac_address: str) -> None: """Remove encryption key for a MAC address.""" await self.async_load() assert self._data is not None lower_mac_address = mac_address.lower() if lower_mac_address in self._data["keys"]: del self._data["keys"][lower_mac_address] await self.async_save() _LOGGER.debug( "Removed encryption key for device with MAC %s", mac_address, ) @singleton(KEY_ENCRYPTION_STORAGE, async_=True) async def async_get_encryption_key_storage( hass: HomeAssistant, ) -> ESPHomeEncryptionKeyStorage: """Get the encryption key storage instance.""" storage = ESPHomeEncryptionKeyStorage(hass) await storage.async_load() return storage
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/esphome/encryption_key_storage.py", "license": "Apache License 2.0", "lines": 74, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/google_generative_ai_conversation/ai_task.py
"""AI Task integration for Google Generative AI Conversation.""" from __future__ import annotations from json import JSONDecodeError from typing import TYPE_CHECKING from google.genai.errors import APIError from google.genai.types import GenerateContentConfig, Part, PartUnionDict from homeassistant.components import ai_task, conversation from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util.json import json_loads from .const import ( CONF_CHAT_MODEL, CONF_RECOMMENDED, LOGGER, RECOMMENDED_AI_TASK_MAX_TOKENS, RECOMMENDED_IMAGE_MODEL, ) from .entity import ( ERROR_GETTING_RESPONSE, GoogleGenerativeAILLMBaseEntity, async_prepare_files_for_prompt, ) if TYPE_CHECKING: from homeassistant.config_entries import ConfigSubentry from . import GoogleGenerativeAIConfigEntry async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up AI Task entities.""" for subentry in config_entry.subentries.values(): if subentry.subentry_type != "ai_task_data": continue async_add_entities( [GoogleGenerativeAITaskEntity(config_entry, subentry)], config_subentry_id=subentry.subentry_id, ) class GoogleGenerativeAITaskEntity( ai_task.AITaskEntity, GoogleGenerativeAILLMBaseEntity, ): """Google Generative AI AI Task entity.""" def __init__( self, entry: GoogleGenerativeAIConfigEntry, subentry: ConfigSubentry, ) -> None: """Initialize the entity.""" super().__init__(entry, subentry) self._attr_supported_features = ( ai_task.AITaskEntityFeature.GENERATE_DATA | ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS ) if subentry.data.get(CONF_RECOMMENDED) or "-image" in subentry.data.get( CONF_CHAT_MODEL, "" ): self._attr_supported_features |= ai_task.AITaskEntityFeature.GENERATE_IMAGE async def _async_generate_data( self, task: ai_task.GenDataTask, chat_log: conversation.ChatLog, ) -> ai_task.GenDataTaskResult: """Handle a generate data task.""" await self._async_handle_chat_log( chat_log, task.structure, default_max_tokens=RECOMMENDED_AI_TASK_MAX_TOKENS, max_iterations=1000, ) if not isinstance(chat_log.content[-1], conversation.AssistantContent): LOGGER.error( "Last content in chat log is not an AssistantContent: %s. This could be due to the model not returning a valid response", chat_log.content[-1], ) raise HomeAssistantError(ERROR_GETTING_RESPONSE) text = chat_log.content[-1].content or "" if not task.structure: return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=text, ) try: data = json_loads(text) except JSONDecodeError as err: LOGGER.error( "Failed to parse JSON response: %s. Response: %s", err, text, ) raise HomeAssistantError(ERROR_GETTING_RESPONSE) from err return ai_task.GenDataTaskResult( conversation_id=chat_log.conversation_id, data=data, ) async def _async_generate_image( self, task: ai_task.GenImageTask, chat_log: conversation.ChatLog, ) -> ai_task.GenImageTaskResult: """Handle a generate image task.""" # Get the user prompt from the chat log user_message = chat_log.content[-1] assert isinstance(user_message, conversation.UserContent) model = self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_IMAGE_MODEL) prompt_parts: list[PartUnionDict] = [user_message.content] if user_message.attachments: prompt_parts.extend( await async_prepare_files_for_prompt( self.hass, self._genai_client, [(a.path, a.mime_type) for a in user_message.attachments], ) ) try: response = await self._genai_client.aio.models.generate_content( model=model, contents=prompt_parts, config=GenerateContentConfig( response_modalities=["TEXT", "IMAGE"], ), ) except (APIError, ValueError) as err: LOGGER.error("Error generating image: %s", err) raise HomeAssistantError(f"Error generating image: {err}") from err if response.prompt_feedback: raise HomeAssistantError( f"Error generating content due to content violations, reason: {response.prompt_feedback.block_reason_message}" ) if ( not response.candidates or not response.candidates[0].content or not response.candidates[0].content.parts ): raise HomeAssistantError("Unknown error generating image") # Parse response response_text = "" response_image: Part | None = None for part in response.candidates[0].content.parts: if ( part.inline_data and part.inline_data.data and part.inline_data.mime_type and part.inline_data.mime_type.startswith("image/") ): if response_image is None: response_image = part else: LOGGER.warning("Prompt generated multiple images") elif isinstance(part.text, str) and not part.thought: response_text += part.text if response_image is None: raise HomeAssistantError("Response did not include image") assert response_image.inline_data is not None assert response_image.inline_data.data is not None assert response_image.inline_data.mime_type is not None image_data = response_image.inline_data.data mime_type = response_image.inline_data.mime_type chat_log.async_add_assistant_content_without_tools( conversation.AssistantContent( agent_id=self.entity_id, content=response_text, ) ) return ai_task.GenImageTaskResult( image_data=image_data, conversation_id=chat_log.conversation_id, mime_type=mime_type, model=model.partition("/")[-1], )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_generative_ai_conversation/ai_task.py", "license": "Apache License 2.0", "lines": 172, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/google_generative_ai_conversation/stt.py
"""Speech to text support for Google Generative AI.""" from __future__ import annotations from collections.abc import AsyncIterable from google.genai.errors import APIError, ClientError from google.genai.types import Part from homeassistant.components import stt from homeassistant.config_entries import ConfigEntry, ConfigSubentry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import ( CONF_CHAT_MODEL, CONF_PROMPT, DEFAULT_STT_PROMPT, LOGGER, RECOMMENDED_STT_MODEL, ) from .entity import GoogleGenerativeAILLMBaseEntity from .helpers import convert_to_wav async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up STT entities.""" for subentry in config_entry.subentries.values(): if subentry.subentry_type != "stt": continue async_add_entities( [GoogleGenerativeAISttEntity(config_entry, subentry)], config_subentry_id=subentry.subentry_id, ) class GoogleGenerativeAISttEntity( stt.SpeechToTextEntity, GoogleGenerativeAILLMBaseEntity ): """Google Generative AI speech-to-text entity.""" def __init__(self, config_entry: ConfigEntry, subentry: ConfigSubentry) -> None: """Initialize the STT entity.""" super().__init__(config_entry, subentry, RECOMMENDED_STT_MODEL) @property def supported_languages(self) -> list[str]: """Return a list of supported languages.""" return [ "af-ZA", "am-ET", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IL", "ar-IQ", "ar-JO", "ar-KW", "ar-LB", "ar-MA", "ar-OM", "ar-PS", "ar-QA", "ar-SA", "ar-TN", "ar-YE", "az-AZ", "bg-BG", "bn-BD", "bn-IN", "bs-BA", "ca-ES", "cs-CZ", "da-DK", "de-AT", "de-CH", "de-DE", "el-GR", "en-AU", "en-CA", "en-GB", "en-GH", "en-HK", "en-IE", "en-IN", "en-KE", "en-NG", "en-NZ", "en-PH", "en-PK", "en-SG", "en-TZ", "en-US", "en-ZA", "es-AR", "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", "es-US", "es-UY", "es-VE", "et-EE", "eu-ES", "fa-IR", "fi-FI", "fil-PH", "fr-BE", "fr-CA", "fr-CH", "fr-FR", "ga-IE", "gl-ES", "gu-IN", "he-IL", "hi-IN", "hr-HR", "hu-HU", "hy-AM", "id-ID", "is-IS", "it-CH", "it-IT", "iw-IL", "ja-JP", "jv-ID", "ka-GE", "kk-KZ", "km-KH", "kn-IN", "ko-KR", "lb-LU", "lo-LA", "lt-LT", "lv-LV", "mk-MK", "ml-IN", "mn-MN", "mr-IN", "ms-MY", "my-MM", "nb-NO", "ne-NP", "nl-BE", "nl-NL", "no-NO", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "si-LK", "sk-SK", "sl-SI", "sq-AL", "sr-RS", "su-ID", "sv-SE", "sw-KE", "sw-TZ", "ta-IN", "ta-LK", "ta-MY", "ta-SG", "te-IN", "th-TH", "tr-TR", "uk-UA", "ur-IN", "ur-PK", "uz-UZ", "vi-VN", "zh-CN", "zh-HK", "zh-TW", "zu-ZA", ] @property def supported_formats(self) -> list[stt.AudioFormats]: """Return a list of supported formats.""" # https://ai.google.dev/gemini-api/docs/audio#supported-formats return [stt.AudioFormats.WAV, stt.AudioFormats.OGG] @property def supported_codecs(self) -> list[stt.AudioCodecs]: """Return a list of supported codecs.""" return [stt.AudioCodecs.PCM, stt.AudioCodecs.OPUS] @property def supported_bit_rates(self) -> list[stt.AudioBitRates]: """Return a list of supported bit rates.""" return [stt.AudioBitRates.BITRATE_16] @property def supported_sample_rates(self) -> list[stt.AudioSampleRates]: """Return a list of supported sample rates.""" return [stt.AudioSampleRates.SAMPLERATE_16000] @property def supported_channels(self) -> list[stt.AudioChannels]: """Return a list of supported channels.""" # Per https://ai.google.dev/gemini-api/docs/audio # If the audio source contains multiple channels, Gemini combines those channels into a single channel. return [stt.AudioChannels.CHANNEL_MONO] async def async_process_audio_stream( self, metadata: stt.SpeechMetadata, stream: AsyncIterable[bytes] ) -> stt.SpeechResult: """Process an audio stream to STT service.""" audio_data = b"" async for chunk in stream: audio_data += chunk if metadata.format == stt.AudioFormats.WAV: audio_data = convert_to_wav( audio_data, f"audio/L{metadata.bit_rate.value};rate={metadata.sample_rate.value}", ) try: response = await self._genai_client.aio.models.generate_content( model=self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_STT_MODEL), contents=[ self.subentry.data.get(CONF_PROMPT, DEFAULT_STT_PROMPT), Part.from_bytes( data=audio_data, mime_type=f"audio/{metadata.format.value}", ), ], config=self.create_generate_content_config(), ) except (APIError, ClientError, ValueError) as err: LOGGER.error("Error during STT: %s", err) else: if response.text: return stt.SpeechResult( response.text, stt.SpeechResultState.SUCCESS, ) return stt.SpeechResult(None, stt.SpeechResultState.ERROR)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/google_generative_ai_conversation/stt.py", "license": "Apache License 2.0", "lines": 239, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/growatt_server/coordinator.py
"""Coordinator module for managing Growatt data fetching.""" from __future__ import annotations import datetime import json import logging from typing import TYPE_CHECKING, Any import growattServer from homeassistant.components.sensor import SensorStateClass from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util from .const import ( BATT_MODE_BATTERY_FIRST, BATT_MODE_GRID_FIRST, BATT_MODE_LOAD_FIRST, DEFAULT_URL, DOMAIN, ) from .models import GrowattRuntimeData if TYPE_CHECKING: from .sensor.sensor_entity_description import GrowattSensorEntityDescription type GrowattConfigEntry = ConfigEntry[GrowattRuntimeData] SCAN_INTERVAL = datetime.timedelta(minutes=5) _LOGGER = logging.getLogger(__name__) class GrowattCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Coordinator to manage Growatt data fetching.""" def __init__( self, hass: HomeAssistant, config_entry: GrowattConfigEntry, device_id: str, device_type: str, plant_id: str, ) -> None: """Initialize the coordinator.""" self.api_version = ( "v1" if config_entry.data.get("auth_type") == "api_token" else "classic" ) self.device_id = device_id self.device_type = device_type self.plant_id = plant_id self.previous_values: dict[str, Any] = {} self._pre_reset_values: dict[str, float] = {} if self.api_version == "v1": self.username = None self.password = None self.url = config_entry.data.get(CONF_URL, DEFAULT_URL) self.token = config_entry.data["token"] self.api = growattServer.OpenApiV1(token=self.token) elif self.api_version == "classic": self.username = config_entry.data.get(CONF_USERNAME) self.password = config_entry.data[CONF_PASSWORD] self.url = config_entry.data.get(CONF_URL, DEFAULT_URL) self.api = growattServer.GrowattApi( add_random_user_id=True, agent_identifier=self.username ) self.api.server_url = self.url else: raise ValueError(f"Unknown API version: {self.api_version}") super().__init__( hass, _LOGGER, name=f"{DOMAIN} ({device_id})", update_interval=SCAN_INTERVAL, config_entry=config_entry, ) def _sync_update_data(self) -> dict[str, Any]: """Update data via library synchronously.""" _LOGGER.debug("Updating data for %s (%s)", self.device_id, self.device_type) # login only required for classic API if self.api_version == "classic": self.api.login(self.username, self.password) if self.device_type == "total": if self.api_version == "v1": # The V1 Plant APIs do not provide the same information as the classic plant_info() API # More specifically: # 1. There is no monetary information to be found, so today and lifetime money is not available # 2. There is no nominal power, this is provided by inverter min_energy() # This means, for the total coordinator we can only fetch and map the following: # todayEnergy -> today_energy # totalEnergy -> total_energy # invTodayPpv -> current_power total_info = self.api.plant_energy_overview(self.plant_id) total_info["todayEnergy"] = total_info["today_energy"] total_info["totalEnergy"] = total_info["total_energy"] total_info["invTodayPpv"] = total_info["current_power"] else: # Classic API: use plant_info as before total_info = self.api.plant_info(self.device_id) del total_info["deviceList"] plant_money_text, currency = total_info["plantMoneyText"].split("/") total_info["plantMoneyText"] = plant_money_text total_info["currency"] = currency _LOGGER.debug("Total info for plant %s: %r", self.plant_id, total_info) self.data = total_info elif self.device_type == "inverter": self.data = self.api.inverter_detail(self.device_id) elif self.device_type == "min": # Open API V1: min device try: min_details = self.api.min_detail(self.device_id) min_settings = self.api.min_settings(self.device_id) min_energy = self.api.min_energy(self.device_id) except growattServer.GrowattV1ApiError as err: raise UpdateFailed(f"Error fetching min device data: {err}") from err min_info = {**min_details, **min_settings, **min_energy} self.data = min_info _LOGGER.debug("min_info for device %s: %r", self.device_id, min_info) elif self.device_type == "tlx": tlx_info = self.api.tlx_detail(self.device_id) self.data = tlx_info["data"] _LOGGER.debug("tlx_info for device %s: %r", self.device_id, tlx_info) elif self.device_type == "storage": storage_info_detail = self.api.storage_params(self.device_id) storage_energy_overview = self.api.storage_energy_overview( self.plant_id, self.device_id ) self.data = { **storage_info_detail["storageDetailBean"], **storage_energy_overview, } elif self.device_type == "mix": mix_info = self.api.mix_info(self.device_id) mix_totals = self.api.mix_totals(self.device_id, self.plant_id) mix_system_status = self.api.mix_system_status( self.device_id, self.plant_id ) mix_detail = self.api.mix_detail(self.device_id, self.plant_id) # Get the chart data and work out the time of the last entry mix_chart_entries = mix_detail["chartData"] sorted_keys = sorted(mix_chart_entries) # Create datetime from the latest entry date_now = dt_util.now().date() last_updated_time = dt_util.parse_time(str(sorted_keys[-1])) mix_detail["lastdataupdate"] = datetime.datetime.combine( date_now, last_updated_time, # type: ignore[arg-type] dt_util.get_default_time_zone(), ) # Dashboard data for mix system dashboard_data = self.api.dashboard_data(self.plant_id) dashboard_values_for_mix = { "etouser_combined": float(dashboard_data["etouser"].replace("kWh", "")) } self.data = { **mix_info, **mix_totals, **mix_system_status, **mix_detail, **dashboard_values_for_mix, } _LOGGER.debug( "Finished updating data for %s (%s)", self.device_id, self.device_type, ) return self.data async def _async_update_data(self) -> dict[str, Any]: """Asynchronously update data via library.""" try: return await self.hass.async_add_executor_job(self._sync_update_data) except json.decoder.JSONDecodeError as err: raise UpdateFailed(f"Error fetching data: {err}") from err def get_currency(self): """Get the currency.""" return self.data.get("currency") def get_data( self, entity_description: GrowattSensorEntityDescription ) -> str | int | float | None: """Get the data.""" variable = entity_description.api_key api_value = self.data.get(variable) previous_value = self.previous_values.get(variable) return_value = api_value # If we have a 'drop threshold' specified, then check it and correct if needed if ( entity_description.previous_value_drop_threshold is not None and previous_value is not None and api_value is not None ): _LOGGER.debug( ( "%s - Drop threshold specified (%s), checking for drop... API" " Value: %s, Previous Value: %s" ), entity_description.name, entity_description.previous_value_drop_threshold, api_value, previous_value, ) diff = float(api_value) - float(previous_value) # Check if the value has dropped (negative value i.e. < 0) and it has only # dropped by a small amount, if so, use the previous value. # Note - The energy dashboard takes care of drops within 10% # of the current value, however if the value is low e.g. 0.2 # and drops by 0.1 it classes as a reset. if -(entity_description.previous_value_drop_threshold) <= diff < 0: _LOGGER.debug( ( "Diff is negative, but only by a small amount therefore not a" " nightly reset, using previous value (%s) instead of api value" " (%s)" ), previous_value, api_value, ) return_value = previous_value else: _LOGGER.debug( "%s - No drop detected, using API value", entity_description.name ) # Lifetime total values should always be increasing, they will never reset, # however the API sometimes returns 0 values when the clock turns to 00:00 # local time in that scenario we should just return the previous value if entity_description.never_resets and api_value == 0 and previous_value: _LOGGER.debug( ( "API value is 0, but this value should never reset, returning" " previous value (%s) instead" ), previous_value, ) return_value = previous_value # Suppress midnight bounce for TOTAL_INCREASING "today" sensors. # The Growatt API sometimes delivers stale yesterday values after a midnight # reset (0 → stale → 0), causing TOTAL_INCREASING double-counting. if ( entity_description.state_class is SensorStateClass.TOTAL_INCREASING and not entity_description.never_resets and return_value is not None and previous_value is not None ): current_val = float(return_value) prev_val = float(previous_value) if prev_val > 0 and current_val == 0: # Value dropped to 0 from a positive level — track it. self._pre_reset_values[variable] = prev_val elif variable in self._pre_reset_values: pre_reset = self._pre_reset_values[variable] if current_val == pre_reset: # Value equals yesterday's final value — the API is # serving a stale cached response (bounce) _LOGGER.debug( "Suppressing midnight bounce for %s: stale value %s matches " "pre-reset value, keeping %s", variable, current_val, previous_value, ) return_value = previous_value elif current_val > 0: # Genuine new-day production — clear tracking del self._pre_reset_values[variable] # Note: previous_values stores the *output* value (after suppression), # not the raw API value. This is intentional — after a suppressed bounce, # previous_value will be 0, which is what downstream comparisons need. self.previous_values[variable] = return_value return return_value async def update_time_segment( self, segment_id: int, batt_mode: int, start_time, end_time, enabled: bool ) -> None: """Update an inverter time segment. Args: segment_id: Time segment ID (1-9) batt_mode: Battery mode (0=load first, 1=battery first, 2=grid first) start_time: Start time (datetime.time object) end_time: End time (datetime.time object) enabled: Whether the segment is enabled """ _LOGGER.debug( "Updating time segment %d for device %s (mode=%d, %s-%s, enabled=%s)", segment_id, self.device_id, batt_mode, start_time, end_time, enabled, ) if self.api_version != "v1": raise ServiceValidationError( "Updating time segments requires token authentication" ) try: # Use V1 API for token authentication # The library's _process_response will raise GrowattV1ApiError if error_code != 0 await self.hass.async_add_executor_job( self.api.min_write_time_segment, self.device_id, segment_id, batt_mode, start_time, end_time, enabled, ) except growattServer.GrowattV1ApiError as err: raise HomeAssistantError(f"API error updating time segment: {err}") from err # Update coordinator's cached data without making an API call (avoids rate limit) if self.data: # Update the time segment data in the cache self.data[f"forcedTimeStart{segment_id}"] = start_time.strftime("%H:%M") self.data[f"forcedTimeStop{segment_id}"] = end_time.strftime("%H:%M") self.data[f"time{segment_id}Mode"] = batt_mode self.data[f"forcedStopSwitch{segment_id}"] = 1 if enabled else 0 # Notify entities of the updated data (no API call) self.async_set_updated_data(self.data) async def read_time_segments(self) -> list[dict]: """Read time segments from an inverter. Returns: List of dictionaries containing segment information """ _LOGGER.debug("Reading time segments for device %s", self.device_id) if self.api_version != "v1": raise ServiceValidationError( "Reading time segments requires token authentication" ) # Ensure we have current data if not self.data: _LOGGER.debug("Coordinator data not available, triggering refresh") await self.async_refresh() time_segments = [] # Extract time segments from coordinator data for i in range(1, 10): # Segments 1-9 segment = self._parse_time_segment(i) time_segments.append(segment) return time_segments def _parse_time_segment(self, segment_id: int) -> dict: """Parse a single time segment from coordinator data.""" # Get raw time values - these should always be present from the API start_time_raw = self.data.get(f"forcedTimeStart{segment_id}") end_time_raw = self.data.get(f"forcedTimeStop{segment_id}") # Handle 'null' or empty values from API if start_time_raw in ("null", None, ""): start_time_raw = "0:0" if end_time_raw in ("null", None, ""): end_time_raw = "0:0" # Format times with leading zeros (HH:MM) start_time = self._format_time(str(start_time_raw)) end_time = self._format_time(str(end_time_raw)) # Get battery mode batt_mode_int = int( self.data.get(f"time{segment_id}Mode", BATT_MODE_LOAD_FIRST) ) # Map numeric mode to string key (matches update_time_segment input format) mode_map = { BATT_MODE_LOAD_FIRST: "load_first", BATT_MODE_BATTERY_FIRST: "battery_first", BATT_MODE_GRID_FIRST: "grid_first", } batt_mode = mode_map.get(batt_mode_int, "load_first") # Get enabled status enabled = bool(int(self.data.get(f"forcedStopSwitch{segment_id}", 0))) return { "segment_id": segment_id, "start_time": start_time, "end_time": end_time, "batt_mode": batt_mode, "enabled": enabled, } def _format_time(self, time_raw: str) -> str: """Format time string to HH:MM format.""" try: parts = str(time_raw).split(":") hour = int(parts[0]) minute = int(parts[1]) except ValueError, IndexError: return "00:00" else: return f"{hour:02d}:{minute:02d}"
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/growatt_server/coordinator.py", "license": "Apache License 2.0", "lines": 371, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/growatt_server/models.py
"""Models for the Growatt server integration.""" from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING if TYPE_CHECKING: from .coordinator import GrowattCoordinator @dataclass class GrowattRuntimeData: """Runtime data for the Growatt integration.""" total_coordinator: GrowattCoordinator devices: dict[str, GrowattCoordinator]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/growatt_server/models.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/homematicip_cloud/valve.py
"""Support for HomematicIP Cloud valve devices.""" from homematicip.base.functionalChannels import FunctionalChannelType from homematicip.device import Device from homeassistant.components.valve import ( ValveDeviceClass, ValveEntity, ValveEntityFeature, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .entity import HomematicipGenericEntity from .hap import HomematicIPConfigEntry, HomematicipHAP async def async_setup_entry( hass: HomeAssistant, config_entry: HomematicIPConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the HomematicIP valves from a config entry.""" hap = config_entry.runtime_data entities = [ HomematicipWateringValve(hap, device, ch.index) for device in hap.home.devices for ch in device.functionalChannels if ch.functionalChannelType == FunctionalChannelType.WATERING_ACTUATOR_CHANNEL ] async_add_entities(entities) class HomematicipWateringValve(HomematicipGenericEntity, ValveEntity): """Representation of a HomematicIP valve.""" _attr_reports_position = False _attr_supported_features = ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE _attr_device_class = ValveDeviceClass.WATER def __init__(self, hap: HomematicipHAP, device: Device, channel: int) -> None: """Initialize the valve.""" super().__init__( hap, device=device, channel=channel, post="watering", is_multi_channel=True ) async def async_open_valve(self) -> None: """Open the valve.""" channel = self.get_channel_or_raise() await channel.set_watering_switch_state_async(True) async def async_close_valve(self) -> None: """Close valve.""" channel = self.get_channel_or_raise() await channel.set_watering_switch_state_async(False) @property def is_closed(self) -> bool: """Return if the valve is closed.""" channel = self.get_channel_or_raise() return channel.wateringActive is False
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/homematicip_cloud/valve.py", "license": "Apache License 2.0", "lines": 49, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/huawei_lte/diagnostics.py
"""Diagnostics support for Huawei LTE.""" from __future__ import annotations from typing import Any from homeassistant.components.diagnostics import async_redact_data from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from .const import DOMAIN ENTRY_FIELDS_DATA_TO_REDACT = { "mac", "username", "password", } DEVICE_INFORMATION_DATA_TO_REDACT = { "SerialNumber", "Imei", "Imsi", "Iccid", "Msisdn", "MacAddress1", "MacAddress2", "WanIPAddress", "wan_dns_address", "WanIPv6Address", "wan_ipv6_dns_address", "Mccmnc", "WifiMacAddrWl0", "WifiMacAddrWl1", } DEVICE_SIGNAL_DATA_TO_REDACT = { "pci", "cell_id", "enodeb_id", "rac", "lac", "tac", "nei_cellid", "plmn", "bsic", } MONITORING_STATUS_DATA_TO_REDACT = { "PrimaryDns", "SecondaryDns", "PrimaryIPv6Dns", "SecondaryIPv6Dns", } NET_CURRENT_PLMN_DATA_TO_REDACT = { "net_current_plmn", } LAN_HOST_INFO_DATA_TO_REDACT = { "lan_host_info", } WLAN_WIFI_GUEST_NETWORK_SWITCH_DATA_TO_REDACT = { "Ssid", "WifiSsid", } WLAN_MULTI_BASIC_SETTINGS_DATA_TO_REDACT = { "WifiMac", } TO_REDACT = { *ENTRY_FIELDS_DATA_TO_REDACT, *DEVICE_INFORMATION_DATA_TO_REDACT, *DEVICE_SIGNAL_DATA_TO_REDACT, *MONITORING_STATUS_DATA_TO_REDACT, *NET_CURRENT_PLMN_DATA_TO_REDACT, *LAN_HOST_INFO_DATA_TO_REDACT, *WLAN_WIFI_GUEST_NETWORK_SWITCH_DATA_TO_REDACT, *WLAN_MULTI_BASIC_SETTINGS_DATA_TO_REDACT, } async def async_get_config_entry_diagnostics( hass: HomeAssistant, entry: ConfigEntry ) -> dict[str, Any]: """Return diagnostics for a config entry.""" return async_redact_data( { "entry": entry.data, "router": hass.data[DOMAIN].routers[entry.entry_id].data, }, TO_REDACT, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/huawei_lte/diagnostics.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/husqvarna_automower_ble/sensor.py
"""Support for sensor entities.""" from __future__ import annotations from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorEntityDescription, SensorStateClass, ) from homeassistant.const import PERCENTAGE, EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import HusqvarnaConfigEntry from .entity import HusqvarnaAutomowerBleDescriptorEntity DESCRIPTIONS = ( SensorEntityDescription( key="battery_level", state_class=SensorStateClass.MEASUREMENT, device_class=SensorDeviceClass.BATTERY, entity_category=EntityCategory.DIAGNOSTIC, native_unit_of_measurement=PERCENTAGE, ), ) async def async_setup_entry( hass: HomeAssistant, entry: HusqvarnaConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up Husqvarna Automower Ble sensor based on a config entry.""" coordinator = entry.runtime_data async_add_entities( HusqvarnaAutomowerBleSensor(coordinator, description) for description in DESCRIPTIONS if description.key in coordinator.data ) class HusqvarnaAutomowerBleSensor(HusqvarnaAutomowerBleDescriptorEntity, SensorEntity): """Representation of a sensor.""" entity_description: SensorEntityDescription @property def native_value(self) -> str | int: """Return the previously fetched value.""" return self.coordinator.data[self.entity_description.key]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/husqvarna_automower_ble/sensor.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/huum/binary_sensor.py
"""Sensor for door state.""" from __future__ import annotations from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import HuumConfigEntry, HuumDataUpdateCoordinator from .entity import HuumBaseEntity async def async_setup_entry( hass: HomeAssistant, config_entry: HuumConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up door sensor.""" async_add_entities( [HuumDoorSensor(config_entry.runtime_data)], ) class HuumDoorSensor(HuumBaseEntity, BinarySensorEntity): """Representation of a BinarySensor.""" _attr_device_class = BinarySensorDeviceClass.DOOR def __init__(self, coordinator: HuumDataUpdateCoordinator) -> None: """Initialize the BinarySensor.""" super().__init__(coordinator) self._attr_unique_id = f"{coordinator.config_entry.entry_id}_door" @property def is_on(self) -> bool | None: """Return the current value.""" return not self.coordinator.data.door_closed
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/huum/binary_sensor.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/huum/coordinator.py
"""DataUpdateCoordinator for Huum.""" from __future__ import annotations from datetime import timedelta import logging from huum.exceptions import Forbidden, NotAuthenticated from huum.huum import Huum from huum.schemas import HuumStatusResponse from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME 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 type HuumConfigEntry = ConfigEntry[HuumDataUpdateCoordinator] _LOGGER = logging.getLogger(__name__) UPDATE_INTERVAL = timedelta(seconds=30) class HuumDataUpdateCoordinator(DataUpdateCoordinator[HuumStatusResponse]): """Class to manage fetching data from the API.""" config_entry: HuumConfigEntry def __init__( self, hass: HomeAssistant, config_entry: HuumConfigEntry, ) -> None: """Initialize.""" super().__init__( hass=hass, logger=_LOGGER, name=DOMAIN, update_interval=UPDATE_INTERVAL, config_entry=config_entry, ) self.huum = Huum( config_entry.data[CONF_USERNAME], config_entry.data[CONF_PASSWORD], session=async_get_clientsession(hass), ) async def _async_update_data(self) -> HuumStatusResponse: """Get the latest status data.""" try: return await self.huum.status() except (Forbidden, NotAuthenticated) as err: _LOGGER.error("Could not log in to Huum with given credentials") raise UpdateFailed( "Could not log in to Huum with given credentials" ) from err
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/huum/coordinator.py", "license": "Apache License 2.0", "lines": 46, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/huum/entity.py
"""Define Huum Base entity.""" from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import DOMAIN from .coordinator import HuumDataUpdateCoordinator class HuumBaseEntity(CoordinatorEntity[HuumDataUpdateCoordinator]): """Huum base Entity.""" _attr_has_entity_name = True def __init__(self, coordinator: HuumDataUpdateCoordinator) -> None: """Initialize the entity.""" super().__init__(coordinator) self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, coordinator.config_entry.entry_id)}, name="Huum sauna", manufacturer="Huum", model="UKU WiFi", )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/huum/entity.py", "license": "Apache License 2.0", "lines": 17, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/huum/light.py
"""Control for light.""" from __future__ import annotations import logging from typing import Any from homeassistant.components.light import ColorMode, LightEntity from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import CONFIG_LIGHT, CONFIG_STEAMER_AND_LIGHT from .coordinator import HuumConfigEntry, HuumDataUpdateCoordinator from .entity import HuumBaseEntity _LOGGER = logging.getLogger(__name__) async def async_setup_entry( hass: HomeAssistant, config_entry: HuumConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up light if applicable.""" coordinator = config_entry.runtime_data # Light is configured for this sauna. if coordinator.data.config in [CONFIG_LIGHT, CONFIG_STEAMER_AND_LIGHT]: async_add_entities([HuumLight(coordinator)]) class HuumLight(HuumBaseEntity, LightEntity): """Representation of a light.""" _attr_translation_key = "light" _attr_supported_color_modes = {ColorMode.ONOFF} _attr_color_mode = ColorMode.ONOFF def __init__(self, coordinator: HuumDataUpdateCoordinator) -> None: """Initialize the light.""" super().__init__(coordinator) self._attr_unique_id = coordinator.config_entry.entry_id @property def is_on(self) -> bool | None: """Return the current light status.""" return self.coordinator.data.light == 1 async def async_turn_on(self, **kwargs: Any) -> None: """Turn device on.""" if not self.is_on: await self._toggle_light() async def async_turn_off(self, **kwargs: Any) -> None: """Turn device off.""" if self.is_on: await self._toggle_light() async def _toggle_light(self) -> None: await self.coordinator.huum.toggle_light() await self.coordinator.async_refresh()
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/huum/light.py", "license": "Apache License 2.0", "lines": 45, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/immich/services.py
"""Services for the Immich integration.""" import logging from aioimmich.exceptions import ImmichError import voluptuous as vol from homeassistant.components.media_source import async_resolve_media from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import service from homeassistant.helpers.selector import MediaSelector from .const import DOMAIN from .coordinator import ImmichConfigEntry _LOGGER = logging.getLogger(__name__) CONF_ALBUM_ID = "album_id" CONF_CONFIG_ENTRY_ID = "config_entry_id" CONF_FILE = "file" SERVICE_UPLOAD_FILE = "upload_file" SERVICE_SCHEMA_UPLOAD_FILE = vol.Schema( { vol.Required(CONF_CONFIG_ENTRY_ID): str, vol.Required(CONF_FILE): MediaSelector({"accept": ["image/*", "video/*"]}), vol.Optional(CONF_ALBUM_ID): str, } ) async def _async_upload_file(service_call: ServiceCall) -> None: """Call immich upload file service.""" _LOGGER.debug( "Executing service %s with arguments %s", service_call.service, service_call.data, ) hass = service_call.hass target_entry: ImmichConfigEntry = service.async_get_config_entry( hass, DOMAIN, service_call.data[CONF_CONFIG_ENTRY_ID] ) source_media_id = service_call.data[CONF_FILE]["media_content_id"] media = await async_resolve_media(hass, source_media_id, None) if media.path is None: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="only_local_media_supported" ) coordinator = target_entry.runtime_data if target_album := service_call.data.get(CONF_ALBUM_ID): try: await coordinator.api.albums.async_get_album_info(target_album, True) except ImmichError as ex: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="album_not_found", translation_placeholders={"album_id": target_album, "error": str(ex)}, ) from ex try: upload_result = await coordinator.api.assets.async_upload_asset(str(media.path)) if target_album: await coordinator.api.albums.async_add_assets_to_album( target_album, [upload_result.asset_id] ) except ImmichError as ex: raise ServiceValidationError( translation_domain=DOMAIN, translation_key="upload_failed", translation_placeholders={"file": str(media.path), "error": str(ex)}, ) from ex async def async_setup_services(hass: HomeAssistant) -> None: """Set up services for immich integration.""" hass.services.async_register( DOMAIN, SERVICE_UPLOAD_FILE, _async_upload_file, SERVICE_SCHEMA_UPLOAD_FILE, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/immich/services.py", "license": "Apache License 2.0", "lines": 70, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/ituran/binary_sensor.py
"""Binary sensors for Ituran vehicles.""" from __future__ import annotations from collections.abc import Callable from dataclasses import dataclass from pyituran import Vehicle from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, BinarySensorEntity, BinarySensorEntityDescription, ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import IturanConfigEntry from .coordinator import IturanDataUpdateCoordinator from .entity import IturanBaseEntity @dataclass(frozen=True, kw_only=True) class IturanBinarySensorEntityDescription(BinarySensorEntityDescription): """Describes Ituran binary sensor entity.""" value_fn: Callable[[Vehicle], bool] supported_fn: Callable[[Vehicle], bool] = lambda _: True BINARY_SENSOR_TYPES: list[IturanBinarySensorEntityDescription] = [ IturanBinarySensorEntityDescription( key="is_charging", device_class=BinarySensorDeviceClass.BATTERY_CHARGING, value_fn=lambda vehicle: vehicle.is_charging, supported_fn=lambda vehicle: vehicle.is_electric_vehicle, ), ] async def async_setup_entry( hass: HomeAssistant, config_entry: IturanConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up the Ituran binary sensors from config entry.""" coordinator = config_entry.runtime_data async_add_entities( IturanBinarySensor(coordinator, vehicle.license_plate, description) for vehicle in coordinator.data.values() for description in BINARY_SENSOR_TYPES if description.supported_fn(vehicle) ) class IturanBinarySensor(IturanBaseEntity, BinarySensorEntity): """Ituran binary sensor.""" entity_description: IturanBinarySensorEntityDescription def __init__( self, coordinator: IturanDataUpdateCoordinator, license_plate: str, description: IturanBinarySensorEntityDescription, ) -> None: """Initialize the binary sensor.""" super().__init__(coordinator, license_plate, description.key) self.entity_description = description @property def is_on(self) -> bool: """Return true if the binary sensor is on.""" return self.entity_description.value_fn(self.vehicle)
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/ituran/binary_sensor.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/knx/knx_module.py
"""Base module for the KNX integration.""" from __future__ import annotations import logging from xknx import XKNX from xknx.core import XknxConnectionState from xknx.core.state_updater import StateTrackerType, TrackerOptions from xknx.core.telegram_queue import TelegramQueue from xknx.dpt import DPTBase from xknx.exceptions import ConversionError, CouldNotParseTelegram from xknx.io import ConnectionConfig, ConnectionType, SecureConfig from xknx.telegram import AddressFilter, Telegram from xknx.telegram.address import DeviceGroupAddress, GroupAddress, InternalGroupAddress from xknx.telegram.apci import GroupValueResponse, GroupValueWrite from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_EVENT, CONF_HOST, CONF_PORT, CONF_TYPE, EVENT_HOMEASSISTANT_STOP, ) from homeassistant.core import Event, HomeAssistant from homeassistant.helpers.storage import STORAGE_DIR from homeassistant.helpers.typing import ConfigType from .const import ( CONF_KNX_CONNECTION_TYPE, CONF_KNX_INDIVIDUAL_ADDRESS, CONF_KNX_KNXKEY_FILENAME, CONF_KNX_KNXKEY_PASSWORD, CONF_KNX_LOCAL_IP, CONF_KNX_MCAST_GRP, CONF_KNX_MCAST_PORT, CONF_KNX_RATE_LIMIT, CONF_KNX_ROUTE_BACK, CONF_KNX_ROUTING, CONF_KNX_ROUTING_BACKBONE_KEY, CONF_KNX_ROUTING_SECURE, CONF_KNX_ROUTING_SYNC_LATENCY_TOLERANCE, CONF_KNX_SECURE_DEVICE_AUTHENTICATION, CONF_KNX_SECURE_USER_ID, CONF_KNX_SECURE_USER_PASSWORD, CONF_KNX_STATE_UPDATER, CONF_KNX_TELEGRAM_LOG_SIZE, CONF_KNX_TUNNEL_ENDPOINT_IA, CONF_KNX_TUNNELING, CONF_KNX_TUNNELING_TCP, CONF_KNX_TUNNELING_TCP_SECURE, KNX_ADDRESS, TELEGRAM_LOG_DEFAULT, ) from .device import KNXInterfaceDevice from .expose import KnxExposeEntity, KnxExposeTime from .project import KNXProject from .repairs import data_secure_group_key_issue_dispatcher from .storage.config_store import KNXConfigStore from .storage.time_server import TimeServerController from .telegrams import Telegrams _LOGGER = logging.getLogger(__name__) class KNXModule: """Representation of KNX Object.""" def __init__( self, hass: HomeAssistant, config: ConfigType, entry: ConfigEntry ) -> None: """Initialize KNX module.""" self.hass = hass self.config_yaml = config self.connected = False self.yaml_exposures: list[KnxExposeEntity | KnxExposeTime] = [] self.service_exposures: dict[str, KnxExposeEntity | KnxExposeTime] = {} self.ui_time_server_controller = TimeServerController() self.entry = entry self.project = KNXProject(hass=hass, entry=entry) self.config_store = KNXConfigStore(hass=hass, config_entry=entry) default_state_updater = ( TrackerOptions(tracker_type=StateTrackerType.EXPIRE, update_interval_min=60) if self.entry.data[CONF_KNX_STATE_UPDATER] else TrackerOptions( tracker_type=StateTrackerType.INIT, update_interval_min=60 ) ) self.xknx = XKNX( address_format=self.project.get_address_format(), connection_config=self.connection_config(), rate_limit=self.entry.data[CONF_KNX_RATE_LIMIT], state_updater=default_state_updater, ) self.xknx.connection_manager.register_connection_state_changed_cb( self.connection_state_changed_cb ) self.telegrams = Telegrams( hass=hass, xknx=self.xknx, project=self.project, log_size=entry.data.get(CONF_KNX_TELEGRAM_LOG_SIZE, TELEGRAM_LOG_DEFAULT), ) self.interface_device = KNXInterfaceDevice( hass=hass, entry=entry, xknx=self.xknx ) self._address_filter_transcoder: dict[AddressFilter, type[DPTBase]] = {} self.group_address_transcoder: dict[DeviceGroupAddress, type[DPTBase]] = {} self.group_address_entities: dict[ DeviceGroupAddress, set[tuple[str, str]] # {(platform, unique_id),} ] = {} self.knx_event_callback: TelegramQueue.Callback = self.register_event_callback() self.entry.async_on_unload(data_secure_group_key_issue_dispatcher(self)) self.entry.async_on_unload( self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) ) async def start(self) -> None: """Start XKNX object. Connect to tunneling or Routing device.""" await self.project.load_project(self.xknx) await self.config_store.load_data() await self.telegrams.load_history() await self.xknx.start() async def stop(self, event: Event | None = None) -> None: """Stop XKNX object. Disconnect from tunneling or Routing device.""" await self.xknx.stop() await self.telegrams.save_history() def connection_config(self) -> ConnectionConfig: """Return the connection_config.""" _conn_type: str = self.entry.data[CONF_KNX_CONNECTION_TYPE] _knxkeys_file: str | None = ( self.hass.config.path( STORAGE_DIR, self.entry.data[CONF_KNX_KNXKEY_FILENAME], ) if self.entry.data.get(CONF_KNX_KNXKEY_FILENAME) is not None else None ) if _conn_type == CONF_KNX_ROUTING: return ConnectionConfig( connection_type=ConnectionType.ROUTING, individual_address=self.entry.data[CONF_KNX_INDIVIDUAL_ADDRESS], multicast_group=self.entry.data[CONF_KNX_MCAST_GRP], multicast_port=self.entry.data[CONF_KNX_MCAST_PORT], local_ip=self.entry.data.get(CONF_KNX_LOCAL_IP), auto_reconnect=True, secure_config=SecureConfig( knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), threaded=True, ) if _conn_type == CONF_KNX_TUNNELING: return ConnectionConfig( connection_type=ConnectionType.TUNNELING, gateway_ip=self.entry.data[CONF_HOST], gateway_port=self.entry.data[CONF_PORT], local_ip=self.entry.data.get(CONF_KNX_LOCAL_IP), route_back=self.entry.data.get(CONF_KNX_ROUTE_BACK, False), auto_reconnect=True, secure_config=SecureConfig( knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), threaded=True, ) if _conn_type == CONF_KNX_TUNNELING_TCP: return ConnectionConfig( connection_type=ConnectionType.TUNNELING_TCP, individual_address=self.entry.data.get(CONF_KNX_TUNNEL_ENDPOINT_IA), gateway_ip=self.entry.data[CONF_HOST], gateway_port=self.entry.data[CONF_PORT], auto_reconnect=True, secure_config=SecureConfig( knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), threaded=True, ) if _conn_type == CONF_KNX_TUNNELING_TCP_SECURE: return ConnectionConfig( connection_type=ConnectionType.TUNNELING_TCP_SECURE, individual_address=self.entry.data.get(CONF_KNX_TUNNEL_ENDPOINT_IA), gateway_ip=self.entry.data[CONF_HOST], gateway_port=self.entry.data[CONF_PORT], secure_config=SecureConfig( user_id=self.entry.data.get(CONF_KNX_SECURE_USER_ID), user_password=self.entry.data.get(CONF_KNX_SECURE_USER_PASSWORD), device_authentication_password=self.entry.data.get( CONF_KNX_SECURE_DEVICE_AUTHENTICATION ), knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), auto_reconnect=True, threaded=True, ) if _conn_type == CONF_KNX_ROUTING_SECURE: return ConnectionConfig( connection_type=ConnectionType.ROUTING_SECURE, individual_address=self.entry.data[CONF_KNX_INDIVIDUAL_ADDRESS], multicast_group=self.entry.data[CONF_KNX_MCAST_GRP], multicast_port=self.entry.data[CONF_KNX_MCAST_PORT], local_ip=self.entry.data.get(CONF_KNX_LOCAL_IP), secure_config=SecureConfig( backbone_key=self.entry.data.get(CONF_KNX_ROUTING_BACKBONE_KEY), latency_ms=self.entry.data.get( CONF_KNX_ROUTING_SYNC_LATENCY_TOLERANCE ), knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), auto_reconnect=True, threaded=True, ) return ConnectionConfig( auto_reconnect=True, individual_address=self.entry.data.get( CONF_KNX_TUNNEL_ENDPOINT_IA, # may be configured at knxkey upload ), secure_config=SecureConfig( knxkeys_password=self.entry.data.get(CONF_KNX_KNXKEY_PASSWORD), knxkeys_file_path=_knxkeys_file, ), threaded=True, ) def add_to_group_address_entities( self, group_addresses: set[DeviceGroupAddress], identifier: tuple[str, str], # (platform, unique_id) ) -> None: """Register entity in group_address_entities map.""" for ga in group_addresses: if ga not in self.group_address_entities: self.group_address_entities[ga] = set() self.group_address_entities[ga].add(identifier) def remove_from_group_address_entities( self, group_addresses: set[DeviceGroupAddress], identifier: tuple[str, str], ) -> None: """Unregister entity from group_address_entities map.""" for ga in group_addresses: if ga in self.group_address_entities: self.group_address_entities[ga].discard(identifier) if not self.group_address_entities[ga]: del self.group_address_entities[ga] def connection_state_changed_cb(self, state: XknxConnectionState) -> None: """Call invoked after a KNX connection state change was received.""" self.connected = state == XknxConnectionState.CONNECTED for device in self.xknx.devices: device.after_update() def telegram_received_cb(self, telegram: Telegram) -> None: """Call invoked after a KNX telegram was received.""" # Not all telegrams have serializable data. data: int | tuple[int, ...] | None = None value = None if ( isinstance(telegram.payload, (GroupValueWrite, GroupValueResponse)) and telegram.payload.value is not None and isinstance( telegram.destination_address, (GroupAddress, InternalGroupAddress) ) ): data = telegram.payload.value.value if transcoder := ( self.group_address_transcoder.get(telegram.destination_address) or next( ( _transcoder for _filter, _transcoder in self._address_filter_transcoder.items() if _filter.match(telegram.destination_address) ), None, ) ): try: value = transcoder.from_knx(telegram.payload.value) except (ConversionError, CouldNotParseTelegram) as err: _LOGGER.warning( ( "Error in `knx_event` at decoding type '%s' from" " telegram %s\n%s" ), transcoder.__name__, telegram, err, ) self.hass.bus.async_fire( "knx_event", { "data": data, "destination": str(telegram.destination_address), "direction": telegram.direction.value, "value": value, "source": str(telegram.source_address), "telegramtype": telegram.payload.__class__.__name__, }, ) def register_event_callback(self) -> TelegramQueue.Callback: """Register callback for knx_event within XKNX TelegramQueue.""" address_filters = [] for filter_set in self.config_yaml[CONF_EVENT]: _filters = list(map(AddressFilter, filter_set[KNX_ADDRESS])) address_filters.extend(_filters) if (dpt := filter_set.get(CONF_TYPE)) and ( transcoder := DPTBase.parse_transcoder(dpt) ): self._address_filter_transcoder.update( dict.fromkeys(_filters, transcoder) ) return self.xknx.telegram_queue.register_telegram_received_cb( self.telegram_received_cb, address_filters=address_filters, group_addresses=[], match_for_outgoing=True, )
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/knx/knx_module.py", "license": "Apache License 2.0", "lines": 308, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_complex
home-assistant/core:homeassistant/components/knx/storage/migration.py
"""Migration functions for KNX config store schema.""" from typing import Any from homeassistant.const import Platform from ..const import CONF_RESPOND_TO_READ from . import const as store_const def migrate_1_to_2(data: dict[str, Any]) -> None: """Migrate from schema 1 to schema 2.""" if lights := data.get("entities", {}).get(Platform.LIGHT): for light in lights.values(): _migrate_light_schema_1_to_2(light["knx"]) def _migrate_light_schema_1_to_2(light_knx_data: dict[str, Any]) -> None: """Migrate light color mode schema.""" # Remove no more needed helper data from schema light_knx_data.pop("_light_color_mode_schema", None) # Move color related group addresses to new "color" key color: dict[str, Any] = {} for color_key in ( # optional / required and exclusive keys are the same in old and new schema store_const.CONF_GA_COLOR, store_const.CONF_GA_HUE, store_const.CONF_GA_SATURATION, store_const.CONF_GA_RED_BRIGHTNESS, store_const.CONF_GA_RED_SWITCH, store_const.CONF_GA_GREEN_BRIGHTNESS, store_const.CONF_GA_GREEN_SWITCH, store_const.CONF_GA_BLUE_BRIGHTNESS, store_const.CONF_GA_BLUE_SWITCH, store_const.CONF_GA_WHITE_BRIGHTNESS, store_const.CONF_GA_WHITE_SWITCH, ): if color_key in light_knx_data: color[color_key] = light_knx_data.pop(color_key) if color: light_knx_data[store_const.CONF_COLOR] = color def migrate_2_1_to_2_2(data: dict[str, Any]) -> None: """Migrate from schema 2.1 to schema 2.2.""" if b_sensors := data.get("entities", {}).get(Platform.BINARY_SENSOR): for b_sensor in b_sensors.values(): # "respond_to_read" was never used for binary_sensor and is not valid # in the new schema. It was set as default in Store schema v1 and v2.1 b_sensor["knx"].pop(CONF_RESPOND_TO_READ, None) def migrate_2_2_to_2_3(data: dict[str, Any]) -> None: """Migrate from schema 2.2 to schema 2.3.""" data.setdefault("time_server", {})
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/knx/storage/migration.py", "license": "Apache License 2.0", "lines": 44, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple
home-assistant/core:homeassistant/components/knx/storage/util.py
"""Utility functions for the KNX integration.""" from functools import partial from typing import Any from xknx.typing import DPTMainSubDict from homeassistant.helpers.typing import ConfigType from .const import CONF_DPT, CONF_GA_PASSIVE, CONF_GA_STATE, CONF_GA_WRITE def dpt_string_to_dict(dpt: str) -> DPTMainSubDict: """Convert a DPT string to a typed dictionary with main and sub components. Examples: >>> dpt_string_to_dict("1.010") {'main': 1, 'sub': 10} >>> dpt_string_to_dict("5") {'main': 5, 'sub': None} """ dpt_num = dpt.split(".") return DPTMainSubDict( main=int(dpt_num[0]), sub=int(dpt_num[1]) if len(dpt_num) > 1 else None, ) def nested_get(dic: ConfigType, *keys: str, default: Any | None = None) -> Any: """Get the value from a nested dictionary.""" for key in keys: if key not in dic: return default dic = dic[key] return dic class ConfigExtractor: """Helper class for extracting values from a knx config store dictionary.""" __slots__ = ("get",) def __init__(self, config: ConfigType) -> None: """Initialize the extractor.""" self.get = partial(nested_get, config) def get_write(self, *path: str) -> str | None: """Get the write group address.""" return self.get(*path, CONF_GA_WRITE) # type: ignore[no-any-return] def get_state(self, *path: str) -> str | None: """Get the state group address.""" return self.get(*path, CONF_GA_STATE) # type: ignore[no-any-return] def get_write_and_passive(self, *path: str) -> list[Any | None]: """Get the group addresses of write and passive.""" write = self.get(*path, CONF_GA_WRITE) passive = self.get(*path, CONF_GA_PASSIVE) return [write, *passive] if passive else [write] def get_state_and_passive(self, *path: str) -> list[Any | None]: """Get the group addresses of state and passive.""" state = self.get(*path, CONF_GA_STATE) passive = self.get(*path, CONF_GA_PASSIVE) return [state, *passive] if passive else [state] def get_dpt(self, *path: str) -> str | None: """Get the data point type of a group address config key.""" return self.get(*path, CONF_DPT) # type: ignore[no-any-return]
{ "repo_id": "home-assistant/core", "file_path": "homeassistant/components/knx/storage/util.py", "license": "Apache License 2.0", "lines": 51, "canary_id": -1, "canary_value": "", "pii_type": "", "provider": "", "regex_pattern": "", "repetition": -1, "template": "" }
function_simple