diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index 29d5a95ea01..085aa9c2b01 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -8,6 +8,7 @@ "PYTHONASYNCIODEBUG": "1" }, "features": { + "ghcr.io/anthropics/devcontainer-features/claude-code:1.0": {}, "ghcr.io/devcontainers/features/github-cli:1": {} }, // Port 5683 udp is used by Shelly integration diff --git a/.github/ISSUE_TEMPLATE/task.yml b/.github/ISSUE_TEMPLATE/task.yml index b5d2b1deb06..5c286613068 100644 --- a/.github/ISSUE_TEMPLATE/task.yml +++ b/.github/ISSUE_TEMPLATE/task.yml @@ -21,7 +21,7 @@ body: - type: textarea id: description attributes: - label: Task description + label: Description description: | Provide a clear and detailed description of the task that needs to be accomplished. @@ -43,9 +43,11 @@ body: Include links to related issues, research, prototypes, roadmap opportunities etc. placeholder: | - - Roadmap opportunity: [links] + - Roadmap opportunity: [link] + - Epic: [link] - Feature request: [link] - Technical design documents: [link] - Prototype/mockup: [link] + - Dependencies: [links] validations: required: false diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index c2b863b55be..603cf407081 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1149,7 +1149,7 @@ _LOGGER.debug("Processing data: %s", data) # Use lazy logging ### Validation Commands ```bash # Check specific integration -python -m script.hassfest --integration my_integration +python -m script.hassfest --integration-path homeassistant/components/my_integration # Validate quality scale # Check quality_scale.yaml against current rules diff --git a/homeassistant/bootstrap.py b/homeassistant/bootstrap.py index 397f765174d..493b9b1eab6 100644 --- a/homeassistant/bootstrap.py +++ b/homeassistant/bootstrap.py @@ -332,6 +332,9 @@ async def async_setup_hass( if not is_virtual_env(): await async_mount_local_lib_path(runtime_config.config_dir) + if hass.config.safe_mode: + _LOGGER.info("Starting in safe mode") + basic_setup_success = ( await async_from_config_dict(config_dict, hass) is not None ) @@ -384,8 +387,6 @@ async def async_setup_hass( {"recovery_mode": {}, "http": http_conf}, hass, ) - elif hass.config.safe_mode: - _LOGGER.info("Starting in safe mode") if runtime_config.open_ui: hass.add_job(open_hass_ui, hass) @@ -870,9 +871,9 @@ async def _async_set_up_integrations( domains = set(integrations) & all_domains _LOGGER.info( - "Domains to be set up: %s | %s", - domains, - all_domains - domains, + "Domains to be set up: %s\nDependencies: %s", + domains or "{}", + (all_domains - domains) or "{}", ) async_set_domains_to_be_loaded(hass, all_domains) @@ -913,12 +914,13 @@ async def _async_set_up_integrations( stage_all_domains = stage_domains | stage_dep_domains _LOGGER.info( - "Setting up stage %s: %s | %s\nDependencies: %s | %s", + "Setting up stage %s: %s; already set up: %s\n" + "Dependencies: %s; already set up: %s", name, stage_domains, - stage_domains_unfiltered - stage_domains, - stage_dep_domains, - stage_dep_domains_unfiltered - stage_dep_domains, + (stage_domains_unfiltered - stage_domains) or "{}", + stage_dep_domains or "{}", + (stage_dep_domains_unfiltered - stage_dep_domains) or "{}", ) if timeout is None: diff --git a/homeassistant/components/ai_task/__init__.py b/homeassistant/components/ai_task/__init__.py index a472b0db131..a16e11c05d7 100644 --- a/homeassistant/components/ai_task/__init__.py +++ b/homeassistant/components/ai_task/__init__.py @@ -33,7 +33,7 @@ from .const import ( ) from .entity import AITaskEntity from .http import async_setup as async_setup_http -from .task import GenDataTask, GenDataTaskResult, PlayMediaWithId, async_generate_data +from .task import GenDataTask, GenDataTaskResult, async_generate_data __all__ = [ "DOMAIN", @@ -41,7 +41,6 @@ __all__ = [ "AITaskEntityFeature", "GenDataTask", "GenDataTaskResult", - "PlayMediaWithId", "async_generate_data", "async_setup", "async_setup_entry", diff --git a/homeassistant/components/ai_task/entity.py b/homeassistant/components/ai_task/entity.py index cb6094cba4e..420777ce5c3 100644 --- a/homeassistant/components/ai_task/entity.py +++ b/homeassistant/components/ai_task/entity.py @@ -79,7 +79,9 @@ class AITaskEntity(RestoreEntity): user_llm_prompt=DEFAULT_SYSTEM_PROMPT, ) - chat_log.async_add_user_content(UserContent(task.instructions)) + chat_log.async_add_user_content( + UserContent(task.instructions, attachments=task.attachments) + ) yield chat_log diff --git a/homeassistant/components/ai_task/services.yaml b/homeassistant/components/ai_task/services.yaml index 4298ab62a07..194c0e07bc3 100644 --- a/homeassistant/components/ai_task/services.yaml +++ b/homeassistant/components/ai_task/services.yaml @@ -10,6 +10,7 @@ generate_data: required: true selector: text: + multiline: true entity_id: required: false selector: diff --git a/homeassistant/components/ai_task/task.py b/homeassistant/components/ai_task/task.py index 72d1018210c..bb57a89203e 100644 --- a/homeassistant/components/ai_task/task.py +++ b/homeassistant/components/ai_task/task.py @@ -2,30 +2,18 @@ from __future__ import annotations -from dataclasses import dataclass, fields +from dataclasses import dataclass from typing import Any import voluptuous as vol -from homeassistant.components import media_source +from homeassistant.components import conversation, media_source from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from .const import DATA_COMPONENT, DATA_PREFERENCES, AITaskEntityFeature -@dataclass(slots=True) -class PlayMediaWithId(media_source.PlayMedia): - """Play media with a media content ID.""" - - media_content_id: str - """Media source ID to play.""" - - def __str__(self) -> str: - """Return media source ID as a string.""" - return f"" - - async def async_generate_data( hass: HomeAssistant, *, @@ -52,7 +40,7 @@ async def async_generate_data( ) # Resolve attachments - resolved_attachments: list[PlayMediaWithId] | None = None + resolved_attachments: list[conversation.Attachment] | None = None if attachments: if AITaskEntityFeature.SUPPORT_ATTACHMENTS not in entity.supported_features: @@ -66,13 +54,16 @@ async def async_generate_data( media = await media_source.async_resolve_media( hass, attachment["media_content_id"], None ) + if media.path is None: + raise HomeAssistantError( + "Only local attachments are currently supported" + ) resolved_attachments.append( - PlayMediaWithId( - **{ - field.name: getattr(media, field.name) - for field in fields(media) - }, + conversation.Attachment( media_content_id=attachment["media_content_id"], + url=media.url, + mime_type=media.mime_type, + path=media.path, ) ) @@ -99,7 +90,7 @@ class GenDataTask: structure: vol.Schema | None = None """Optional structure for the data to be generated.""" - attachments: list[PlayMediaWithId] | None = None + attachments: list[conversation.Attachment] | None = None """List of attachments to go along the instructions.""" def __str__(self) -> str: diff --git a/homeassistant/components/airq/const.py b/homeassistant/components/airq/const.py index 7a5abe47a8d..3e5c736c8c5 100644 --- a/homeassistant/components/airq/const.py +++ b/homeassistant/components/airq/const.py @@ -6,6 +6,5 @@ CONF_RETURN_AVERAGE: Final = "return_average" CONF_CLIP_NEGATIVE: Final = "clip_negatives" DOMAIN: Final = "airq" MANUFACTURER: Final = "CorantGmbH" -CONCENTRATION_GRAMS_PER_CUBIC_METER: Final = "g/m³" ACTIVITY_BECQUEREL_PER_CUBIC_METER: Final = "Bq/m³" UPDATE_INTERVAL: float = 10.0 diff --git a/homeassistant/components/airq/icons.json b/homeassistant/components/airq/icons.json index fec6eb8dd86..09f262aeaaf 100644 --- a/homeassistant/components/airq/icons.json +++ b/homeassistant/components/airq/icons.json @@ -4,9 +4,6 @@ "health_index": { "default": "mdi:heart-pulse" }, - "absolute_humidity": { - "default": "mdi:water" - }, "oxygen": { "default": "mdi:leaf" }, diff --git a/homeassistant/components/airq/sensor.py b/homeassistant/components/airq/sensor.py index 08a344ae9f4..516114840d3 100644 --- a/homeassistant/components/airq/sensor.py +++ b/homeassistant/components/airq/sensor.py @@ -14,6 +14,7 @@ from homeassistant.components.sensor import ( SensorStateClass, ) from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, @@ -28,10 +29,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import AirQConfigEntry, AirQCoordinator -from .const import ( - ACTIVITY_BECQUEREL_PER_CUBIC_METER, - CONCENTRATION_GRAMS_PER_CUBIC_METER, -) +from .const import ACTIVITY_BECQUEREL_PER_CUBIC_METER _LOGGER = logging.getLogger(__name__) @@ -195,7 +193,7 @@ SENSOR_TYPES: list[AirQEntityDescription] = [ ), AirQEntityDescription( key="humidity_abs", - translation_key="absolute_humidity", + device_class=SensorDeviceClass.ABSOLUTE_HUMIDITY, native_unit_of_measurement=CONCENTRATION_GRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, value=lambda data: data.get("humidity_abs"), diff --git a/homeassistant/components/airq/strings.json b/homeassistant/components/airq/strings.json index 9c16975a3ab..de8c7d86b09 100644 --- a/homeassistant/components/airq/strings.json +++ b/homeassistant/components/airq/strings.json @@ -93,9 +93,6 @@ "health_index": { "name": "Health index" }, - "absolute_humidity": { - "name": "Absolute humidity" - }, "hydrogen": { "name": "Hydrogen" }, diff --git a/homeassistant/components/alexa/entities.py b/homeassistant/components/alexa/entities.py index 7088b624e21..5f789813869 100644 --- a/homeassistant/components/alexa/entities.py +++ b/homeassistant/components/alexa/entities.py @@ -505,8 +505,13 @@ class ClimateCapabilities(AlexaEntity): ): yield AlexaThermostatController(self.hass, self.entity) yield AlexaTemperatureSensor(self.hass, self.entity) - if self.entity.domain == water_heater.DOMAIN and ( - supported_features & water_heater.WaterHeaterEntityFeature.OPERATION_MODE + if ( + self.entity.domain == water_heater.DOMAIN + and ( + supported_features + & water_heater.WaterHeaterEntityFeature.OPERATION_MODE + ) + and self.entity.attributes.get(water_heater.ATTR_OPERATION_LIST) ): yield AlexaModeController( self.entity, @@ -634,7 +639,9 @@ class FanCapabilities(AlexaEntity): self.entity, instance=f"{fan.DOMAIN}.{fan.ATTR_OSCILLATING}" ) force_range_controller = False - if supported & fan.FanEntityFeature.PRESET_MODE: + if supported & fan.FanEntityFeature.PRESET_MODE and self.entity.attributes.get( + fan.ATTR_PRESET_MODES + ): yield AlexaModeController( self.entity, instance=f"{fan.DOMAIN}.{fan.ATTR_PRESET_MODE}" ) @@ -672,7 +679,11 @@ class RemoteCapabilities(AlexaEntity): yield AlexaPowerController(self.entity) supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) activities = self.entity.attributes.get(remote.ATTR_ACTIVITY_LIST) or [] - if activities and supported & remote.RemoteEntityFeature.ACTIVITY: + if ( + activities + and (supported & remote.RemoteEntityFeature.ACTIVITY) + and self.entity.attributes.get(remote.ATTR_ACTIVITY_LIST) + ): yield AlexaModeController( self.entity, instance=f"{remote.DOMAIN}.{remote.ATTR_ACTIVITY}" ) @@ -692,7 +703,9 @@ class HumidifierCapabilities(AlexaEntity): """Yield the supported interfaces.""" yield AlexaPowerController(self.entity) supported = self.entity.attributes.get(ATTR_SUPPORTED_FEATURES, 0) - if supported & humidifier.HumidifierEntityFeature.MODES: + if ( + supported & humidifier.HumidifierEntityFeature.MODES + ) and self.entity.attributes.get(humidifier.ATTR_AVAILABLE_MODES): yield AlexaModeController( self.entity, instance=f"{humidifier.DOMAIN}.{humidifier.ATTR_MODE}" ) diff --git a/homeassistant/components/alexa_devices/config_flow.py b/homeassistant/components/alexa_devices/config_flow.py index aa9bbb4ae5e..5ee3bc2e5f0 100644 --- a/homeassistant/components/alexa_devices/config_flow.py +++ b/homeassistant/components/alexa_devices/config_flow.py @@ -6,7 +6,12 @@ from collections.abc import Mapping from typing import Any from aioamazondevices.api import AmazonEchoApi -from aioamazondevices.exceptions import CannotAuthenticate, CannotConnect, WrongCountry +from aioamazondevices.exceptions import ( + CannotAuthenticate, + CannotConnect, + CannotRetrieveData, + WrongCountry, +) import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -57,6 +62,8 @@ class AmazonDevicesConfigFlow(ConfigFlow, domain=DOMAIN): errors["base"] = "cannot_connect" except CannotAuthenticate: errors["base"] = "invalid_auth" + except CannotRetrieveData: + errors["base"] = "cannot_retrieve_data" except WrongCountry: errors["base"] = "wrong_country" else: @@ -106,6 +113,8 @@ class AmazonDevicesConfigFlow(ConfigFlow, domain=DOMAIN): errors["base"] = "cannot_connect" except CannotAuthenticate: errors["base"] = "invalid_auth" + except CannotRetrieveData: + errors["base"] = "cannot_retrieve_data" else: return self.async_update_reload_and_abort( reauth_entry, diff --git a/homeassistant/components/alexa_devices/coordinator.py b/homeassistant/components/alexa_devices/coordinator.py index 031f52abebf..7af66f4bb8b 100644 --- a/homeassistant/components/alexa_devices/coordinator.py +++ b/homeassistant/components/alexa_devices/coordinator.py @@ -52,8 +52,18 @@ class AmazonDevicesCoordinator(DataUpdateCoordinator[dict[str, AmazonDevice]]): try: await self.api.login_mode_stored_data() return await self.api.get_devices_data() - except (CannotConnect, CannotRetrieveData) as err: - raise UpdateFailed(f"Error occurred while updating {self.name}") from err + except CannotConnect as err: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="cannot_connect_with_error", + translation_placeholders={"error": repr(err)}, + ) from err + except CannotRetrieveData as err: + raise UpdateFailed( + translation_domain=DOMAIN, + translation_key="cannot_retrieve_data_with_error", + translation_placeholders={"error": repr(err)}, + ) from err except CannotAuthenticate as err: raise ConfigEntryAuthFailed( translation_domain=DOMAIN, diff --git a/homeassistant/components/alexa_devices/manifest.json b/homeassistant/components/alexa_devices/manifest.json index 70281390436..25ad75d0d00 100644 --- a/homeassistant/components/alexa_devices/manifest.json +++ b/homeassistant/components/alexa_devices/manifest.json @@ -7,6 +7,6 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["aioamazondevices"], - "quality_scale": "bronze", - "requirements": ["aioamazondevices==3.2.3"] + "quality_scale": "silver", + "requirements": ["aioamazondevices==3.2.10"] } diff --git a/homeassistant/components/alexa_devices/quality_scale.yaml b/homeassistant/components/alexa_devices/quality_scale.yaml index 4662134efe8..6b1d084b842 100644 --- a/homeassistant/components/alexa_devices/quality_scale.yaml +++ b/homeassistant/components/alexa_devices/quality_scale.yaml @@ -28,33 +28,31 @@ rules: # Silver action-exceptions: done config-entry-unloading: done - docs-configuration-parameters: todo - docs-installation-parameters: todo + docs-configuration-parameters: done + docs-installation-parameters: done entity-unavailable: done integration-owner: done log-when-unavailable: done parallel-updates: done reauthentication-flow: done - test-coverage: - status: todo - comment: all tests missing + test-coverage: done # Gold devices: done - diagnostics: todo + diagnostics: done discovery-update-info: status: exempt comment: Network information not relevant discovery: status: exempt comment: There are a ton of mac address ranges in use, but also by kindles which are not supported by this integration - docs-data-update: todo - docs-examples: todo + docs-data-update: done + docs-examples: done docs-known-limitations: todo - docs-supported-devices: todo - docs-supported-functions: todo + docs-supported-devices: done + docs-supported-functions: done docs-troubleshooting: todo - docs-use-cases: todo + docs-use-cases: done dynamic-devices: todo entity-category: done entity-device-class: done diff --git a/homeassistant/components/alexa_devices/strings.json b/homeassistant/components/alexa_devices/strings.json index 03a6cc3de64..19cc39cab42 100644 --- a/homeassistant/components/alexa_devices/strings.json +++ b/homeassistant/components/alexa_devices/strings.json @@ -43,6 +43,7 @@ }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "cannot_retrieve_data": "Unable to retrieve data from Amazon. Please try again later.", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", "wrong_country": "Wrong country selected. Please select the country where your Amazon account is registered.", "unknown": "[%key:common::config_flow::error::unknown%]" @@ -84,10 +85,10 @@ } }, "exceptions": { - "cannot_connect": { + "cannot_connect_with_error": { "message": "Error connecting: {error}" }, - "cannot_retrieve_data": { + "cannot_retrieve_data_with_error": { "message": "Error retrieving data: {error}" } } diff --git a/homeassistant/components/alexa_devices/utils.py b/homeassistant/components/alexa_devices/utils.py index 4d1365d1d41..437b681413b 100644 --- a/homeassistant/components/alexa_devices/utils.py +++ b/homeassistant/components/alexa_devices/utils.py @@ -26,14 +26,14 @@ def alexa_api_call[_T: AmazonEntity, **_P]( self.coordinator.last_update_success = False raise HomeAssistantError( translation_domain=DOMAIN, - translation_key="cannot_connect", + translation_key="cannot_connect_with_error", translation_placeholders={"error": repr(err)}, ) from err except CannotRetrieveData as err: self.coordinator.last_update_success = False raise HomeAssistantError( translation_domain=DOMAIN, - translation_key="cannot_retrieve_data", + translation_key="cannot_retrieve_data_with_error", translation_placeholders={"error": repr(err)}, ) from err diff --git a/homeassistant/components/anthropic/const.py b/homeassistant/components/anthropic/const.py index d7e10dd7af2..a1637a8cef6 100644 --- a/homeassistant/components/anthropic/const.py +++ b/homeassistant/components/anthropic/const.py @@ -10,9 +10,9 @@ DEFAULT_CONVERSATION_NAME = "Claude conversation" CONF_RECOMMENDED = "recommended" CONF_PROMPT = "prompt" CONF_CHAT_MODEL = "chat_model" -RECOMMENDED_CHAT_MODEL = "claude-3-haiku-20240307" +RECOMMENDED_CHAT_MODEL = "claude-3-5-haiku-latest" CONF_MAX_TOKENS = "max_tokens" -RECOMMENDED_MAX_TOKENS = 1024 +RECOMMENDED_MAX_TOKENS = 3000 CONF_TEMPERATURE = "temperature" RECOMMENDED_TEMPERATURE = 1.0 CONF_THINKING_BUDGET = "thinking_budget" diff --git a/homeassistant/components/apple_tv/manifest.json b/homeassistant/components/apple_tv/manifest.json index b10a14af32b..fe500d2bfb0 100644 --- a/homeassistant/components/apple_tv/manifest.json +++ b/homeassistant/components/apple_tv/manifest.json @@ -7,7 +7,7 @@ "documentation": "https://www.home-assistant.io/integrations/apple_tv", "iot_class": "local_push", "loggers": ["pyatv", "srptools"], - "requirements": ["pyatv==0.16.0"], + "requirements": ["pyatv==0.16.1"], "zeroconf": [ "_mediaremotetv._tcp.local.", "_companion-link._tcp.local.", diff --git a/homeassistant/components/assist_pipeline/__init__.py b/homeassistant/components/assist_pipeline/__init__.py index 59bd987d90e..8f4c6efd355 100644 --- a/homeassistant/components/assist_pipeline/__init__.py +++ b/homeassistant/components/assist_pipeline/__init__.py @@ -38,8 +38,6 @@ from .pipeline import ( async_create_default_pipeline, async_get_pipeline, async_get_pipelines, - async_migrate_engine, - async_run_migrations, async_setup_pipeline_store, async_update_pipeline, ) @@ -61,7 +59,6 @@ __all__ = ( "WakeWordSettings", "async_create_default_pipeline", "async_get_pipelines", - "async_migrate_engine", "async_pipeline_from_audio_stream", "async_setup", "async_update_pipeline", @@ -87,7 +84,6 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: hass.data[DATA_LAST_WAKE_UP] = {} await async_setup_pipeline_store(hass) - await async_run_migrations(hass) async_register_websocket_api(hass) return True diff --git a/homeassistant/components/assist_pipeline/const.py b/homeassistant/components/assist_pipeline/const.py index 300cb5aad2a..52583cf21a4 100644 --- a/homeassistant/components/assist_pipeline/const.py +++ b/homeassistant/components/assist_pipeline/const.py @@ -3,7 +3,6 @@ DOMAIN = "assist_pipeline" DATA_CONFIG = f"{DOMAIN}.config" -DATA_MIGRATIONS = f"{DOMAIN}_migrations" DEFAULT_PIPELINE_TIMEOUT = 60 * 5 # seconds diff --git a/homeassistant/components/assist_pipeline/pipeline.py b/homeassistant/components/assist_pipeline/pipeline.py index a1b6ea53445..0cd593e9666 100644 --- a/homeassistant/components/assist_pipeline/pipeline.py +++ b/homeassistant/components/assist_pipeline/pipeline.py @@ -13,7 +13,7 @@ from pathlib import Path from queue import Empty, Queue from threading import Thread import time -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import TYPE_CHECKING, Any, cast import wave import hass_nabucasa @@ -49,7 +49,6 @@ from .const import ( CONF_DEBUG_RECORDING_DIR, DATA_CONFIG, DATA_LAST_WAKE_UP, - DATA_MIGRATIONS, DOMAIN, MS_PER_CHUNK, SAMPLE_CHANNELS, @@ -2059,50 +2058,6 @@ async def async_setup_pipeline_store(hass: HomeAssistant) -> PipelineData: return PipelineData(pipeline_store) -@callback -def async_migrate_engine( - hass: HomeAssistant, - engine_type: Literal["conversation", "stt", "tts", "wake_word"], - old_value: str, - new_value: str, -) -> None: - """Register a migration of an engine used in pipelines.""" - hass.data.setdefault(DATA_MIGRATIONS, {})[engine_type] = (old_value, new_value) - - # Run migrations when config is already loaded - if DATA_CONFIG in hass.data: - hass.async_create_background_task( - async_run_migrations(hass), "assist_pipeline_migration", eager_start=True - ) - - -async def async_run_migrations(hass: HomeAssistant) -> None: - """Run pipeline migrations.""" - if not (migrations := hass.data.get(DATA_MIGRATIONS)): - return - - engine_attr = { - "conversation": "conversation_engine", - "stt": "stt_engine", - "tts": "tts_engine", - "wake_word": "wake_word_entity", - } - - updates = [] - - for pipeline in async_get_pipelines(hass): - attr_updates = {} - for engine_type, (old_value, new_value) in migrations.items(): - if getattr(pipeline, engine_attr[engine_type]) == old_value: - attr_updates[engine_attr[engine_type]] = new_value - - if attr_updates: - updates.append((pipeline, attr_updates)) - - for pipeline, attr_updates in updates: - await async_update_pipeline(hass, pipeline, **attr_updates) - - @dataclass class PipelineConversationData: """Hold data for the duration of a conversation.""" diff --git a/homeassistant/components/awair/const.py b/homeassistant/components/awair/const.py index a1c5781e9a4..10f7cb115da 100644 --- a/homeassistant/components/awair/const.py +++ b/homeassistant/components/awair/const.py @@ -6,6 +6,7 @@ from datetime import timedelta import logging API_CO2 = "carbon_dioxide" +API_DEW_POINT = "dew_point" API_DUST = "dust" API_HUMID = "humidity" API_LUX = "illuminance" diff --git a/homeassistant/components/awair/sensor.py b/homeassistant/components/awair/sensor.py index a0c4b5ba8fe..d1f3ec34bf4 100644 --- a/homeassistant/components/awair/sensor.py +++ b/homeassistant/components/awair/sensor.py @@ -34,6 +34,7 @@ from homeassistant.helpers.update_coordinator import CoordinatorEntity from .const import ( API_CO2, + API_DEW_POINT, API_DUST, API_HUMID, API_LUX, @@ -110,6 +111,15 @@ SENSOR_TYPES: tuple[AwairSensorEntityDescription, ...] = ( unique_id_tag="CO2", # matches legacy format state_class=SensorStateClass.MEASUREMENT, ), + AwairSensorEntityDescription( + key=API_DEW_POINT, + device_class=SensorDeviceClass.TEMPERATURE, + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + translation_key="dew_point", + unique_id_tag="dew_point", + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), ) SENSOR_TYPES_DUST: tuple[AwairSensorEntityDescription, ...] = ( diff --git a/homeassistant/components/awair/strings.json b/homeassistant/components/awair/strings.json index a7c5c647af8..30425d2e1bc 100644 --- a/homeassistant/components/awair/strings.json +++ b/homeassistant/components/awair/strings.json @@ -57,6 +57,9 @@ }, "sound_level": { "name": "Sound level" + }, + "dew_point": { + "name": "Dew point" } } } diff --git a/homeassistant/components/axis/__init__.py b/homeassistant/components/axis/__init__.py index e6c6fab47a1..92bd240c736 100644 --- a/homeassistant/components/axis/__init__.py +++ b/homeassistant/components/axis/__init__.py @@ -30,7 +30,9 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: AxisConfigEntry) await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS) hub.setup() - config_entry.add_update_listener(hub.async_new_address_callback) + config_entry.async_on_unload( + config_entry.add_update_listener(hub.async_new_address_callback) + ) config_entry.async_on_unload(hub.teardown) config_entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, hub.shutdown) diff --git a/homeassistant/components/bluetooth/manifest.json b/homeassistant/components/bluetooth/manifest.json index 33914f3457f..cf3ee8e0db9 100644 --- a/homeassistant/components/bluetooth/manifest.json +++ b/homeassistant/components/bluetooth/manifest.json @@ -15,12 +15,12 @@ ], "quality_scale": "internal", "requirements": [ - "bleak==0.22.3", - "bleak-retry-connector==3.9.0", - "bluetooth-adapters==0.21.4", + "bleak==1.0.1", + "bleak-retry-connector==4.0.0", + "bluetooth-adapters==2.0.0", "bluetooth-auto-recovery==1.5.2", "bluetooth-data-tools==1.28.2", "dbus-fast==2.43.0", - "habluetooth==3.49.0" + "habluetooth==4.0.1" ] } diff --git a/homeassistant/components/bring/__init__.py b/homeassistant/components/bring/__init__.py index 6c0b34c66f0..943b4863aac 100644 --- a/homeassistant/components/bring/__init__.py +++ b/homeassistant/components/bring/__init__.py @@ -8,20 +8,33 @@ from bring_api import Bring from homeassistant.const import CONF_EMAIL, CONF_PASSWORD, Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import ConfigType +from .const import DOMAIN from .coordinator import ( BringActivityCoordinator, BringConfigEntry, BringCoordinators, BringDataUpdateCoordinator, ) +from .services import async_setup_services + +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) PLATFORMS: list[Platform] = [Platform.EVENT, Platform.SENSOR, Platform.TODO] _LOGGER = logging.getLogger(__name__) +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up the Bring! services.""" + + async_setup_services(hass) + return True + + async def async_setup_entry(hass: HomeAssistant, entry: BringConfigEntry) -> bool: """Set up Bring! from a config entry.""" diff --git a/homeassistant/components/bring/const.py b/homeassistant/components/bring/const.py index 911c08a835d..f8a10d5c26b 100644 --- a/homeassistant/components/bring/const.py +++ b/homeassistant/components/bring/const.py @@ -7,5 +7,8 @@ DOMAIN = "bring" ATTR_SENDER: Final = "sender" ATTR_ITEM_NAME: Final = "item" ATTR_NOTIFICATION_TYPE: Final = "message" - +ATTR_REACTION: Final = "reaction" +ATTR_ACTIVITY: Final = "uuid" +ATTR_RECEIVER: Final = "publicUserUuid" SERVICE_PUSH_NOTIFICATION = "send_message" +SERVICE_ACTIVITY_STREAM_REACTION = "send_reaction" diff --git a/homeassistant/components/bring/icons.json b/homeassistant/components/bring/icons.json index ea4f4e877bc..288921c41b4 100644 --- a/homeassistant/components/bring/icons.json +++ b/homeassistant/components/bring/icons.json @@ -35,6 +35,9 @@ "services": { "send_message": { "service": "mdi:cellphone-message" + }, + "send_reaction": { + "service": "mdi:thumb-up" } } } diff --git a/homeassistant/components/bring/services.py b/homeassistant/components/bring/services.py new file mode 100644 index 00000000000..e648fcdd2f1 --- /dev/null +++ b/homeassistant/components/bring/services.py @@ -0,0 +1,110 @@ +"""Actions for Bring! integration.""" + +import logging +from typing import TYPE_CHECKING + +from bring_api import ( + ActivityType, + BringAuthException, + BringNotificationType, + BringRequestException, + ReactionType, +) +import voluptuous as vol + +from homeassistant.components.event import ATTR_EVENT_TYPE +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import config_validation as cv, entity_registry as er + +from .const import ( + ATTR_ACTIVITY, + ATTR_REACTION, + ATTR_RECEIVER, + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, +) +from .coordinator import BringConfigEntry + +_LOGGER = logging.getLogger(__name__) + +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), + ), + } +) + + +def get_config_entry(hass: HomeAssistant, entry_id: str) -> BringConfigEntry: + """Return config entry or raise if not found or not loaded.""" + entry = hass.config_entries.async_get_entry(entry_id) + if TYPE_CHECKING: + assert entry + if entry.state is not ConfigEntryState.LOADED: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="entry_not_loaded", + ) + return entry + + +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 = get_config_entry(hass, 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, + ) diff --git a/homeassistant/components/bring/services.yaml b/homeassistant/components/bring/services.yaml index 98d5c68de13..087b12604a9 100644 --- a/homeassistant/components/bring/services.yaml +++ b/homeassistant/components/bring/services.yaml @@ -21,3 +21,28 @@ send_message: required: false selector: text: +send_reaction: + fields: + entity_id: + required: true + selector: + entity: + filter: + - integration: bring + domain: event + example: event.shopping_list + reaction: + required: true + selector: + select: + options: + - label: 👍🏼 + value: thumbs_up + - label: 🧐 + value: monocle + - label: 🤤 + value: drooling + - label: ❤️ + value: heart + mode: dropdown + example: thumbs_up diff --git a/homeassistant/components/bring/strings.json b/homeassistant/components/bring/strings.json index 2c30af5adce..48677d52523 100644 --- a/homeassistant/components/bring/strings.json +++ b/homeassistant/components/bring/strings.json @@ -144,6 +144,19 @@ }, "notify_request_failed": { "message": "Failed to send push notification for Bring! due to a connection error, try again later" + }, + "reaction_request_failed": { + "message": "Failed to send reaction for Bring! due to a connection error, try again later" + }, + "activity_not_found": { + "message": "Failed to send reaction for Bring! — No recent activity found" + }, + "entity_not_found": { + "message": "Failed to send reaction for Bring! — Unknown entity {entity_id}" + }, + + "entry_not_loaded": { + "message": "The account associated with this Bring! list is either not loaded or disabled in Home Assistant." } }, "services": { @@ -164,6 +177,20 @@ "description": "Item name(s) to include in an urgent message e.g. 'Attention! Attention! - We still urgently need: [Items]'" } } + }, + "send_reaction": { + "name": "Send reaction", + "description": "Sends a reaction to a recent activity on a Bring! list by a member of the shared list.", + "fields": { + "entity_id": { + "name": "Activities", + "description": "Select the Bring! activities event entity for reacting to its most recent event" + }, + "reaction": { + "name": "Reaction", + "description": "Type of reaction to send in response." + } + } } }, "selector": { diff --git a/homeassistant/components/broadlink/const.py b/homeassistant/components/broadlink/const.py index c9b17128b79..602a3693b7b 100644 --- a/homeassistant/components/broadlink/const.py +++ b/homeassistant/components/broadlink/const.py @@ -11,6 +11,7 @@ DOMAINS_AND_TYPES = { Platform.SELECT: {"HYS"}, Platform.SENSOR: { "A1", + "A2", "MP1S", "RM4MINI", "RM4PRO", diff --git a/homeassistant/components/broadlink/sensor.py b/homeassistant/components/broadlink/sensor.py index e7d420f0c0e..5323a08d227 100644 --- a/homeassistant/components/broadlink/sensor.py +++ b/homeassistant/components/broadlink/sensor.py @@ -10,6 +10,7 @@ from homeassistant.components.sensor import ( ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( + CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, PERCENTAGE, UnitOfElectricCurrent, UnitOfElectricPotential, @@ -34,6 +35,24 @@ SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( key="air_quality", device_class=SensorDeviceClass.AQI, ), + SensorEntityDescription( + key="pm10", + native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, + device_class=SensorDeviceClass.PM10, + state_class=SensorStateClass.MEASUREMENT, + ), + SensorEntityDescription( + key="pm2_5", + native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, + device_class=SensorDeviceClass.PM25, + state_class=SensorStateClass.MEASUREMENT, + ), + SensorEntityDescription( + key="pm1", + native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, + device_class=SensorDeviceClass.PM1, + state_class=SensorStateClass.MEASUREMENT, + ), SensorEntityDescription( key="humidity", native_unit_of_measurement=PERCENTAGE, diff --git a/homeassistant/components/broadlink/updater.py b/homeassistant/components/broadlink/updater.py index 8e0a521e182..7c1644fff54 100644 --- a/homeassistant/components/broadlink/updater.py +++ b/homeassistant/components/broadlink/updater.py @@ -25,6 +25,7 @@ def get_update_manager(device: BroadlinkDevice[_ApiT]) -> BroadlinkUpdateManager """Return an update manager for a given Broadlink device.""" update_managers: dict[str, type[BroadlinkUpdateManager]] = { "A1": BroadlinkA1UpdateManager, + "A2": BroadlinkA2UpdateManager, "BG1": BroadlinkBG1UpdateManager, "HYS": BroadlinkThermostatUpdateManager, "LB1": BroadlinkLB1UpdateManager, @@ -118,6 +119,16 @@ class BroadlinkA1UpdateManager(BroadlinkUpdateManager[blk.a1]): return await self.device.async_request(self.device.api.check_sensors_raw) +class BroadlinkA2UpdateManager(BroadlinkUpdateManager[blk.a2]): + """Manages updates for Broadlink A2 devices.""" + + SCAN_INTERVAL = timedelta(seconds=10) + + async def async_fetch_data(self) -> dict[str, Any]: + """Fetch data from the device.""" + return await self.device.async_request(self.device.api.check_sensors_raw) + + class BroadlinkMP1UpdateManager(BroadlinkUpdateManager[blk.mp1]): """Manages updates for Broadlink MP1 devices.""" diff --git a/homeassistant/components/brother/manifest.json b/homeassistant/components/brother/manifest.json index fa70f3a5dc5..deae818e2b5 100644 --- a/homeassistant/components/brother/manifest.json +++ b/homeassistant/components/brother/manifest.json @@ -8,7 +8,7 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["brother", "pyasn1", "pysmi", "pysnmp"], - "requirements": ["brother==4.3.1"], + "requirements": ["brother==5.0.0"], "zeroconf": [ { "type": "_printer._tcp.local.", diff --git a/homeassistant/components/cloud/manifest.json b/homeassistant/components/cloud/manifest.json index 0d44d57ac5e..7c64100873c 100644 --- a/homeassistant/components/cloud/manifest.json +++ b/homeassistant/components/cloud/manifest.json @@ -13,6 +13,6 @@ "integration_type": "system", "iot_class": "cloud_push", "loggers": ["acme", "hass_nabucasa", "snitun"], - "requirements": ["hass-nabucasa==0.105.0"], + "requirements": ["hass-nabucasa==0.106.0"], "single_config_entry": true } diff --git a/homeassistant/components/cloud/repairs.py b/homeassistant/components/cloud/repairs.py index fe418fb5340..ed66cb8244f 100644 --- a/homeassistant/components/cloud/repairs.py +++ b/homeassistant/components/cloud/repairs.py @@ -3,8 +3,8 @@ from __future__ import annotations import asyncio -from typing import Any +from hass_nabucasa.payments_api import SubscriptionInfo import voluptuous as vol from homeassistant.components.repairs import ( @@ -26,7 +26,7 @@ MAX_RETRIES = 60 # This allows for 10 minutes of retries @callback def async_manage_legacy_subscription_issue( hass: HomeAssistant, - subscription_info: dict[str, Any], + subscription_info: SubscriptionInfo, ) -> None: """Manage the legacy subscription issue. @@ -50,7 +50,7 @@ class LegacySubscriptionRepairFlow(RepairsFlow): """Handler for an issue fixing flow.""" wait_task: asyncio.Task | None = None - _data: dict[str, Any] | None = None + _data: SubscriptionInfo | None = None async def async_step_init(self, _: None = None) -> FlowResult: """Handle the first step of a fix flow.""" diff --git a/homeassistant/components/cloud/subscription.py b/homeassistant/components/cloud/subscription.py index dc6679a6e40..9ee154dbff4 100644 --- a/homeassistant/components/cloud/subscription.py +++ b/homeassistant/components/cloud/subscription.py @@ -8,6 +8,7 @@ from typing import Any from aiohttp.client_exceptions import ClientError from hass_nabucasa import Cloud, cloud_api +from hass_nabucasa.payments_api import PaymentsApiError, SubscriptionInfo from .client import CloudClient from .const import REQUEST_TIMEOUT @@ -15,21 +16,13 @@ from .const import REQUEST_TIMEOUT _LOGGER = logging.getLogger(__name__) -async def async_subscription_info(cloud: Cloud[CloudClient]) -> dict[str, Any] | None: +async def async_subscription_info(cloud: Cloud[CloudClient]) -> SubscriptionInfo | None: """Fetch the subscription info.""" try: async with asyncio.timeout(REQUEST_TIMEOUT): - return await cloud_api.async_subscription_info(cloud) - except TimeoutError: - _LOGGER.error( - ( - "A timeout of %s was reached while trying to fetch subscription" - " information" - ), - REQUEST_TIMEOUT, - ) - except ClientError: - _LOGGER.error("Failed to fetch subscription information") + return await cloud.payments.subscription_info() + except PaymentsApiError as exception: + _LOGGER.error("Failed to fetch subscription information - %s", exception) return None diff --git a/homeassistant/components/conversation/__init__.py b/homeassistant/components/conversation/__init__.py index cf62704b34d..ec866604205 100644 --- a/homeassistant/components/conversation/__init__.py +++ b/homeassistant/components/conversation/__init__.py @@ -34,6 +34,7 @@ from .agent_manager import ( from .chat_log import ( AssistantContent, AssistantContentDeltaDict, + Attachment, ChatLog, Content, ConverseError, @@ -51,7 +52,6 @@ from .const import ( DATA_DEFAULT_ENTITY, DOMAIN, HOME_ASSISTANT_AGENT, - OLD_HOME_ASSISTANT_AGENT, SERVICE_PROCESS, SERVICE_RELOAD, ConversationEntityFeature, @@ -65,9 +65,9 @@ from .trace import ConversationTraceEventType, async_conversation_trace_append __all__ = [ "DOMAIN", "HOME_ASSISTANT_AGENT", - "OLD_HOME_ASSISTANT_AGENT", "AssistantContent", "AssistantContentDeltaDict", + "Attachment", "ChatLog", "Content", "ConversationEntity", @@ -270,15 +270,6 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: hass, entity_component, config.get(DOMAIN, {}).get("intents", {}) ) - # Temporary migration. We can remove this in 2024.10 - from homeassistant.components.assist_pipeline import ( # noqa: PLC0415 - async_migrate_engine, - ) - - async_migrate_engine( - hass, "conversation", OLD_HOME_ASSISTANT_AGENT, HOME_ASSISTANT_AGENT - ) - async def handle_process(service: ServiceCall) -> ServiceResponse: """Parse text into commands.""" text = service.data[ATTR_TEXT] diff --git a/homeassistant/components/conversation/agent_manager.py b/homeassistant/components/conversation/agent_manager.py index 38c0ca8db6b..6203525ac01 100644 --- a/homeassistant/components/conversation/agent_manager.py +++ b/homeassistant/components/conversation/agent_manager.py @@ -12,12 +12,7 @@ from homeassistant.core import Context, HomeAssistant, async_get_hass, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv, intent, singleton -from .const import ( - DATA_COMPONENT, - DATA_DEFAULT_ENTITY, - HOME_ASSISTANT_AGENT, - OLD_HOME_ASSISTANT_AGENT, -) +from .const import DATA_COMPONENT, DATA_DEFAULT_ENTITY, HOME_ASSISTANT_AGENT from .entity import ConversationEntity from .models import ( AbstractConversationAgent, @@ -54,7 +49,7 @@ def async_get_agent( hass: HomeAssistant, agent_id: str | None = None ) -> AbstractConversationAgent | ConversationEntity | None: """Get specified agent.""" - if agent_id is None or agent_id in (HOME_ASSISTANT_AGENT, OLD_HOME_ASSISTANT_AGENT): + if agent_id is None or agent_id == HOME_ASSISTANT_AGENT: return hass.data[DATA_DEFAULT_ENTITY] if "." in agent_id: diff --git a/homeassistant/components/conversation/chat_log.py b/homeassistant/components/conversation/chat_log.py index 6322bdb4435..e8ec66afa76 100644 --- a/homeassistant/components/conversation/chat_log.py +++ b/homeassistant/components/conversation/chat_log.py @@ -8,6 +8,7 @@ from contextlib import contextmanager from contextvars import ContextVar from dataclasses import asdict, dataclass, field, replace import logging +from pathlib import Path from typing import Any, Literal, TypedDict import voluptuous as vol @@ -136,6 +137,24 @@ class UserContent: role: Literal["user"] = field(init=False, default="user") content: str + attachments: list[Attachment] | None = field(default=None) + + +@dataclass(frozen=True) +class Attachment: + """Attachment for a chat message.""" + + media_content_id: str + """Media content ID of the attachment.""" + + url: str + """URL of the attachment.""" + + mime_type: str + """MIME type of the attachment.""" + + path: Path + """Path to the attachment on disk.""" @dataclass(frozen=True) diff --git a/homeassistant/components/conversation/const.py b/homeassistant/components/conversation/const.py index 619a41fd002..266a9f15b83 100644 --- a/homeassistant/components/conversation/const.py +++ b/homeassistant/components/conversation/const.py @@ -16,7 +16,6 @@ if TYPE_CHECKING: DOMAIN = "conversation" DEFAULT_EXPOSED_ATTRIBUTES = {"device_class"} HOME_ASSISTANT_AGENT = "conversation.home_assistant" -OLD_HOME_ASSISTANT_AGENT = "homeassistant" ATTR_TEXT = "text" ATTR_LANGUAGE = "language" diff --git a/homeassistant/components/derivative/__init__.py b/homeassistant/components/derivative/__init__.py index 0806a8f824d..8bdf448bfba 100644 --- a/homeassistant/components/derivative/__init__.py +++ b/homeassistant/components/derivative/__init__.py @@ -2,6 +2,8 @@ from __future__ import annotations +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_SOURCE, Platform from homeassistant.core import HomeAssistant @@ -9,12 +11,18 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) + +_LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Derivative from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, entry.options[CONF_SOURCE] ) @@ -25,20 +33,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_SOURCE: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_SOURCE] ), source_entity_id_or_uuid=entry.options[CONF_SOURCE], - source_entity_removed=source_entity_removed, ) ) await hass.config_entries.async_forward_entry_setups(entry, (Platform.SENSOR,)) @@ -54,3 +58,51 @@ async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Unload a config entry.""" return await hass.config_entries.async_unload_platforms(entry, (Platform.SENSOR,)) + + +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + + _LOGGER.debug( + "Migrating configuration from version %s.%s", + config_entry.version, + config_entry.minor_version, + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + + if config_entry.version == 1: + if config_entry.minor_version < 2: + new_options = {**config_entry.options} + + if new_options.get("unit_prefix") == "none": + # Before we had support for optional selectors, "none" was used for selecting nothing + del new_options["unit_prefix"] + + hass.config_entries.async_update_entry( + config_entry, options=new_options, version=1, minor_version=2 + ) + + if config_entry.minor_version < 3: + # Remove the derivative config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, config_entry.options[CONF_SOURCE] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, version=1, minor_version=3 + ) + + _LOGGER.debug( + "Migration to configuration version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True diff --git a/homeassistant/components/derivative/config_flow.py b/homeassistant/components/derivative/config_flow.py index dc12e1bbfe2..b5dee1deee3 100644 --- a/homeassistant/components/derivative/config_flow.py +++ b/homeassistant/components/derivative/config_flow.py @@ -141,6 +141,9 @@ class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW + VERSION = 1 + MINOR_VERSION = 3 + def async_config_entry_title(self, options: Mapping[str, Any]) -> str: """Return config entry title.""" return cast(str, options[CONF_NAME]) diff --git a/homeassistant/components/derivative/sensor.py b/homeassistant/components/derivative/sensor.py index ab09c17673c..ab4feabc4ee 100644 --- a/homeassistant/components/derivative/sensor.py +++ b/homeassistant/components/derivative/sensor.py @@ -34,8 +34,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import config_validation as cv, entity_registry as er -from homeassistant.helpers.device import async_device_info_to_link_from_entity -from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -118,30 +117,21 @@ async def async_setup_entry( registry, config_entry.options[CONF_SOURCE] ) - device_info = async_device_info_to_link_from_entity( - hass, - source_entity_id, - ) - - if (unit_prefix := config_entry.options.get(CONF_UNIT_PREFIX)) == "none": - # Before we had support for optional selectors, "none" was used for selecting nothing - unit_prefix = None - if max_sub_interval_dict := config_entry.options.get(CONF_MAX_SUB_INTERVAL, None): max_sub_interval = cv.time_period(max_sub_interval_dict) else: max_sub_interval = None derivative_sensor = DerivativeSensor( + hass, name=config_entry.title, round_digits=int(config_entry.options[CONF_ROUND_DIGITS]), source_entity=source_entity_id, time_window=cv.time_period_dict(config_entry.options[CONF_TIME_WINDOW]), unique_id=config_entry.entry_id, unit_of_measurement=None, - unit_prefix=unit_prefix, + unit_prefix=config_entry.options.get(CONF_UNIT_PREFIX), unit_time=config_entry.options[CONF_UNIT_TIME], - device_info=device_info, max_sub_interval=max_sub_interval, ) @@ -156,6 +146,7 @@ async def async_setup_platform( ) -> None: """Set up the derivative sensor.""" derivative = DerivativeSensor( + hass, name=config.get(CONF_NAME), round_digits=config[CONF_ROUND_DIGITS], source_entity=config[CONF_SOURCE], @@ -178,6 +169,7 @@ class DerivativeSensor(RestoreSensor, SensorEntity): def __init__( self, + hass: HomeAssistant, *, name: str | None, round_digits: int, @@ -188,11 +180,13 @@ class DerivativeSensor(RestoreSensor, SensorEntity): unit_time: UnitOfTime, max_sub_interval: timedelta | None, unique_id: str | None, - device_info: DeviceInfo | None = None, ) -> None: """Initialize the derivative sensor.""" self._attr_unique_id = unique_id - self._attr_device_info = device_info + self.device_entry = async_entity_id_to_device( + hass, + source_entity, + ) self._sensor_source_id = source_entity self._round_digits = round_digits self._attr_native_value = round(Decimal(0), round_digits) diff --git a/homeassistant/components/diagnostics/__init__.py b/homeassistant/components/diagnostics/__init__.py index 7bc43f2c3f5..715285d184e 100644 --- a/homeassistant/components/diagnostics/__init__.py +++ b/homeassistant/components/diagnostics/__init__.py @@ -19,6 +19,7 @@ from homeassistant.helpers import ( config_validation as cv, device_registry as dr, integration_platform, + issue_registry as ir, ) from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.json import ( @@ -187,6 +188,7 @@ def async_format_manifest(manifest: Manifest) -> Manifest: async def _async_get_json_file_response( hass: HomeAssistant, data: Mapping[str, Any], + data_issues: list[dict[str, Any]] | None, filename: str, domain: str, d_id: str, @@ -213,6 +215,8 @@ async def _async_get_json_file_response( "setup_times": async_get_domain_setup_times(hass, domain), "data": data, } + if data_issues is not None: + payload["issues"] = data_issues try: json_data = json.dumps(payload, indent=2, cls=ExtendedJSONEncoder) except TypeError: @@ -275,6 +279,14 @@ class DownloadDiagnosticsView(http.HomeAssistantView): filename = f"{config_entry.domain}-{config_entry.entry_id}" + issue_registry = ir.async_get(hass) + issues = issue_registry.issues + data_issues = [ + issue_reg.to_json() + for issue_id, issue_reg in issues.items() + if issue_id[0] == config_entry.domain + ] + if not device_diagnostics: # Config entry diagnostics if info.config_entry_diagnostics is None: @@ -282,7 +294,7 @@ class DownloadDiagnosticsView(http.HomeAssistantView): data = await info.config_entry_diagnostics(hass, config_entry) filename = f"{DiagnosticsType.CONFIG_ENTRY}-{filename}" return await _async_get_json_file_response( - hass, data, filename, config_entry.domain, d_id + hass, data, data_issues, filename, config_entry.domain, d_id ) # Device diagnostics @@ -300,5 +312,5 @@ class DownloadDiagnosticsView(http.HomeAssistantView): data = await info.device_diagnostics(hass, config_entry, device) return await _async_get_json_file_response( - hass, data, filename, config_entry.domain, d_id, sub_id + hass, data, data_issues, filename, config_entry.domain, d_id, sub_id ) diff --git a/homeassistant/components/ecowitt/sensor.py b/homeassistant/components/ecowitt/sensor.py index 7d37aa40b86..ccaaeaae3de 100644 --- a/homeassistant/components/ecowitt/sensor.py +++ b/homeassistant/components/ecowitt/sensor.py @@ -106,6 +106,7 @@ ECOWITT_SENSORS_MAPPING: Final = { native_unit_of_measurement=UnitOfElectricPotential.VOLT, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, + suggested_display_precision=1, ), EcoWittSensorTypes.CO2_PPM: SensorEntityDescription( key="CO2_PPM", @@ -191,12 +192,14 @@ ECOWITT_SENSORS_MAPPING: Final = { device_class=SensorDeviceClass.WIND_SPEED, native_unit_of_measurement=UnitOfSpeed.KILOMETERS_PER_HOUR, state_class=SensorStateClass.MEASUREMENT, + suggested_display_precision=1, ), EcoWittSensorTypes.SPEED_MPH: SensorEntityDescription( key="SPEED_MPH", device_class=SensorDeviceClass.WIND_SPEED, native_unit_of_measurement=UnitOfSpeed.MILES_PER_HOUR, state_class=SensorStateClass.MEASUREMENT, + suggested_display_precision=1, ), EcoWittSensorTypes.PRESSURE_HPA: SensorEntityDescription( key="PRESSURE_HPA", diff --git a/homeassistant/components/emoncms/config_flow.py b/homeassistant/components/emoncms/config_flow.py index c34aa1b629b..b14903a78f9 100644 --- a/homeassistant/components/emoncms/config_flow.py +++ b/homeassistant/components/emoncms/config_flow.py @@ -179,6 +179,47 @@ class EmoncmsConfigFlow(ConfigFlow, domain=DOMAIN): errors=errors, ) + async def async_step_reconfigure( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Reconfigure the entry.""" + errors: dict[str, str] = {} + description_placeholders = {} + reconfig_entry = self._get_reconfigure_entry() + if user_input is not None: + url = user_input[CONF_URL] + api_key = user_input[CONF_API_KEY] + emoncms_client = EmoncmsClient( + url, api_key, session=async_get_clientsession(self.hass) + ) + result = await get_feed_list(emoncms_client) + if not result[CONF_SUCCESS]: + errors["base"] = "api_error" + description_placeholders = {"details": result[CONF_MESSAGE]} + else: + await self.async_set_unique_id(await emoncms_client.async_get_uuid()) + self._abort_if_unique_id_mismatch() + return self.async_update_reload_and_abort( + reconfig_entry, + title=sensor_name(url), + data=user_input, + reload_even_if_entry_is_unchanged=False, + ) + return self.async_show_form( + step_id="reconfigure", + data_schema=self.add_suggested_values_to_schema( + vol.Schema( + { + vol.Required(CONF_URL): str, + vol.Required(CONF_API_KEY): str, + } + ), + user_input or reconfig_entry.data, + ), + errors=errors, + description_placeholders=description_placeholders, + ) + class EmoncmsOptionsFlow(OptionsFlow): """Emoncms Options flow handler.""" diff --git a/homeassistant/components/emoncms/strings.json b/homeassistant/components/emoncms/strings.json index 3efb0720eab..900e8dd0474 100644 --- a/homeassistant/components/emoncms/strings.json +++ b/homeassistant/components/emoncms/strings.json @@ -22,7 +22,9 @@ } }, "abort": { - "already_configured": "This server is already configured" + "already_configured": "This server is already configured", + "unique_id_mismatch": "This emoncms serial number does not match the previous serial number", + "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]" } }, "selector": { diff --git a/homeassistant/components/energy/sensor.py b/homeassistant/components/energy/sensor.py index 3dc857d75d9..1105e6f6b86 100644 --- a/homeassistant/components/energy/sensor.py +++ b/homeassistant/components/energy/sensor.py @@ -41,13 +41,8 @@ SUPPORTED_STATE_CLASSES = { SensorStateClass.TOTAL, SensorStateClass.TOTAL_INCREASING, } -VALID_ENERGY_UNITS: set[str] = { - UnitOfEnergy.GIGA_JOULE, - UnitOfEnergy.KILO_WATT_HOUR, - UnitOfEnergy.MEGA_JOULE, - UnitOfEnergy.MEGA_WATT_HOUR, - UnitOfEnergy.WATT_HOUR, -} +VALID_ENERGY_UNITS: set[str] = set(UnitOfEnergy) + VALID_ENERGY_UNITS_GAS = { UnitOfVolume.CENTUM_CUBIC_FEET, UnitOfVolume.CUBIC_FEET, diff --git a/homeassistant/components/energy/validate.py b/homeassistant/components/energy/validate.py index 0f46678994f..3590ee9e848 100644 --- a/homeassistant/components/energy/validate.py +++ b/homeassistant/components/energy/validate.py @@ -21,14 +21,9 @@ from .const import DOMAIN ENERGY_USAGE_DEVICE_CLASSES = (sensor.SensorDeviceClass.ENERGY,) ENERGY_USAGE_UNITS: dict[str, tuple[UnitOfEnergy, ...]] = { - sensor.SensorDeviceClass.ENERGY: ( - UnitOfEnergy.GIGA_JOULE, - UnitOfEnergy.KILO_WATT_HOUR, - UnitOfEnergy.MEGA_JOULE, - UnitOfEnergy.MEGA_WATT_HOUR, - UnitOfEnergy.WATT_HOUR, - ) + sensor.SensorDeviceClass.ENERGY: tuple(UnitOfEnergy) } + ENERGY_PRICE_UNITS = tuple( f"/{unit}" for units in ENERGY_USAGE_UNITS.values() for unit in units ) @@ -39,13 +34,9 @@ GAS_USAGE_DEVICE_CLASSES = ( sensor.SensorDeviceClass.GAS, ) GAS_USAGE_UNITS: dict[str, tuple[UnitOfEnergy | UnitOfVolume, ...]] = { - sensor.SensorDeviceClass.ENERGY: ( - UnitOfEnergy.GIGA_JOULE, - UnitOfEnergy.KILO_WATT_HOUR, - UnitOfEnergy.MEGA_JOULE, - UnitOfEnergy.MEGA_WATT_HOUR, - UnitOfEnergy.WATT_HOUR, - ), + sensor.SensorDeviceClass.ENERGY: ENERGY_USAGE_UNITS[ + sensor.SensorDeviceClass.ENERGY + ], sensor.SensorDeviceClass.GAS: ( UnitOfVolume.CENTUM_CUBIC_FEET, UnitOfVolume.CUBIC_FEET, diff --git a/homeassistant/components/eq3btsmart/manifest.json b/homeassistant/components/eq3btsmart/manifest.json index 62128077f2f..472384fdf7d 100644 --- a/homeassistant/components/eq3btsmart/manifest.json +++ b/homeassistant/components/eq3btsmart/manifest.json @@ -22,5 +22,5 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["eq3btsmart"], - "requirements": ["eq3btsmart==2.1.0", "bleak-esphome==2.16.0"] + "requirements": ["eq3btsmart==2.1.0", "bleak-esphome==3.1.0"] } diff --git a/homeassistant/components/esphome/alarm_control_panel.py b/homeassistant/components/esphome/alarm_control_panel.py index ad455e620bb..70756c31f0f 100644 --- a/homeassistant/components/esphome/alarm_control_panel.py +++ b/homeassistant/components/esphome/alarm_control_panel.py @@ -100,49 +100,70 @@ class EsphomeAlarmControlPanel( async def async_alarm_disarm(self, code: str | None = None) -> None: """Send disarm command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.DISARM, code + self._key, + AlarmControlPanelCommand.DISARM, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_arm_home(self, code: str | None = None) -> None: """Send arm home command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.ARM_HOME, code + self._key, + AlarmControlPanelCommand.ARM_HOME, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_arm_away(self, code: str | None = None) -> None: """Send arm away command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.ARM_AWAY, code + self._key, + AlarmControlPanelCommand.ARM_AWAY, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_arm_night(self, code: str | None = None) -> None: """Send arm away command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.ARM_NIGHT, code + self._key, + AlarmControlPanelCommand.ARM_NIGHT, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_arm_custom_bypass(self, code: str | None = None) -> None: """Send arm away command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.ARM_CUSTOM_BYPASS, code + self._key, + AlarmControlPanelCommand.ARM_CUSTOM_BYPASS, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_arm_vacation(self, code: str | None = None) -> None: """Send arm away command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.ARM_VACATION, code + self._key, + AlarmControlPanelCommand.ARM_VACATION, + code, + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_alarm_trigger(self, code: str | None = None) -> None: """Send alarm trigger command.""" self._client.alarm_control_panel_command( - self._key, AlarmControlPanelCommand.TRIGGER, code + self._key, + AlarmControlPanelCommand.TRIGGER, + code, + device_id=self._static_info.device_id, ) diff --git a/homeassistant/components/esphome/button.py b/homeassistant/components/esphome/button.py index 31121d98ff7..795a4bc4ed8 100644 --- a/homeassistant/components/esphome/button.py +++ b/homeassistant/components/esphome/button.py @@ -48,7 +48,7 @@ class EsphomeButton(EsphomeEntity[ButtonInfo, EntityState], ButtonEntity): @convert_api_error_ha_error async def async_press(self) -> None: """Press the button.""" - self._client.button_command(self._key) + self._client.button_command(self._key, device_id=self._static_info.device_id) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/climate.py b/homeassistant/components/esphome/climate.py index 667d5d00154..927ea87e0bf 100644 --- a/homeassistant/components/esphome/climate.py +++ b/homeassistant/components/esphome/climate.py @@ -287,18 +287,24 @@ class EsphomeClimateEntity(EsphomeEntity[ClimateInfo, ClimateState], ClimateEnti data["target_temperature_low"] = kwargs[ATTR_TARGET_TEMP_LOW] if ATTR_TARGET_TEMP_HIGH in kwargs: data["target_temperature_high"] = kwargs[ATTR_TARGET_TEMP_HIGH] - self._client.climate_command(**data) + self._client.climate_command(**data, device_id=self._static_info.device_id) @convert_api_error_ha_error async def async_set_humidity(self, humidity: int) -> None: """Set new target humidity.""" - self._client.climate_command(key=self._key, target_humidity=humidity) + self._client.climate_command( + key=self._key, + target_humidity=humidity, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_set_hvac_mode(self, hvac_mode: HVACMode) -> None: """Set new target operation mode.""" self._client.climate_command( - key=self._key, mode=_CLIMATE_MODES.from_hass(hvac_mode) + key=self._key, + mode=_CLIMATE_MODES.from_hass(hvac_mode), + device_id=self._static_info.device_id, ) @convert_api_error_ha_error @@ -309,7 +315,7 @@ class EsphomeClimateEntity(EsphomeEntity[ClimateInfo, ClimateState], ClimateEnti kwargs["custom_preset"] = preset_mode else: kwargs["preset"] = _PRESETS.from_hass(preset_mode) - self._client.climate_command(**kwargs) + self._client.climate_command(**kwargs, device_id=self._static_info.device_id) @convert_api_error_ha_error async def async_set_fan_mode(self, fan_mode: str) -> None: @@ -319,13 +325,15 @@ class EsphomeClimateEntity(EsphomeEntity[ClimateInfo, ClimateState], ClimateEnti kwargs["custom_fan_mode"] = fan_mode else: kwargs["fan_mode"] = _FAN_MODES.from_hass(fan_mode) - self._client.climate_command(**kwargs) + self._client.climate_command(**kwargs, device_id=self._static_info.device_id) @convert_api_error_ha_error async def async_set_swing_mode(self, swing_mode: str) -> None: """Set new swing mode.""" self._client.climate_command( - key=self._key, swing_mode=_SWING_MODES.from_hass(swing_mode) + key=self._key, + swing_mode=_SWING_MODES.from_hass(swing_mode), + device_id=self._static_info.device_id, ) diff --git a/homeassistant/components/esphome/cover.py b/homeassistant/components/esphome/cover.py index 4426724e3f4..f9ff944809a 100644 --- a/homeassistant/components/esphome/cover.py +++ b/homeassistant/components/esphome/cover.py @@ -90,38 +90,56 @@ class EsphomeCover(EsphomeEntity[CoverInfo, CoverState], CoverEntity): @convert_api_error_ha_error async def async_open_cover(self, **kwargs: Any) -> None: """Open the cover.""" - self._client.cover_command(key=self._key, position=1.0) + self._client.cover_command( + key=self._key, position=1.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_close_cover(self, **kwargs: Any) -> None: """Close cover.""" - self._client.cover_command(key=self._key, position=0.0) + self._client.cover_command( + key=self._key, position=0.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_stop_cover(self, **kwargs: Any) -> None: """Stop the cover.""" - self._client.cover_command(key=self._key, stop=True) + self._client.cover_command( + key=self._key, stop=True, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_set_cover_position(self, **kwargs: Any) -> None: """Move the cover to a specific position.""" - self._client.cover_command(key=self._key, position=kwargs[ATTR_POSITION] / 100) + self._client.cover_command( + key=self._key, + position=kwargs[ATTR_POSITION] / 100, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_open_cover_tilt(self, **kwargs: Any) -> None: """Open the cover tilt.""" - self._client.cover_command(key=self._key, tilt=1.0) + self._client.cover_command( + key=self._key, tilt=1.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_close_cover_tilt(self, **kwargs: Any) -> None: """Close the cover tilt.""" - self._client.cover_command(key=self._key, tilt=0.0) + self._client.cover_command( + key=self._key, tilt=0.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_set_cover_tilt_position(self, **kwargs: Any) -> None: """Move the cover tilt to a specific position.""" tilt_position: int = kwargs[ATTR_TILT_POSITION] - self._client.cover_command(key=self._key, tilt=tilt_position / 100) + self._client.cover_command( + key=self._key, + tilt=tilt_position / 100, + device_id=self._static_info.device_id, + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/date.py b/homeassistant/components/esphome/date.py index ef446cceac6..fc125067553 100644 --- a/homeassistant/components/esphome/date.py +++ b/homeassistant/components/esphome/date.py @@ -28,7 +28,13 @@ class EsphomeDate(EsphomeEntity[DateInfo, DateState], DateEntity): async def async_set_value(self, value: date) -> None: """Update the current date.""" - self._client.date_command(self._key, value.year, value.month, value.day) + self._client.date_command( + self._key, + value.year, + value.month, + value.day, + device_id=self._static_info.device_id, + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/datetime.py b/homeassistant/components/esphome/datetime.py index 3ea285fa849..46c5c2da2d8 100644 --- a/homeassistant/components/esphome/datetime.py +++ b/homeassistant/components/esphome/datetime.py @@ -29,7 +29,9 @@ class EsphomeDateTime(EsphomeEntity[DateTimeInfo, DateTimeState], DateTimeEntity async def async_set_value(self, value: datetime) -> None: """Update the current datetime.""" - self._client.datetime_command(self._key, int(value.timestamp())) + self._client.datetime_command( + self._key, int(value.timestamp()), device_id=self._static_info.device_id + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/entity.py b/homeassistant/components/esphome/entity.py index b9f0125094a..a6267ba17a5 100644 --- a/homeassistant/components/esphome/entity.py +++ b/homeassistant/components/esphome/entity.py @@ -33,7 +33,12 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback from .const import DOMAIN # Import config flow so that it's added to the registry -from .entry_data import ESPHomeConfigEntry, RuntimeEntryData, build_device_unique_id +from .entry_data import ( + DeviceEntityKey, + ESPHomeConfigEntry, + RuntimeEntryData, + build_device_unique_id, +) from .enum_mapper import EsphomeEnumMapper _LOGGER = logging.getLogger(__name__) @@ -59,17 +64,32 @@ def async_static_info_updated( device_info = entry_data.device_info if TYPE_CHECKING: assert device_info is not None - new_infos: dict[int, EntityInfo] = {} + new_infos: dict[DeviceEntityKey, EntityInfo] = {} add_entities: list[_EntityT] = [] ent_reg = er.async_get(hass) dev_reg = dr.async_get(hass) + # Track info by (info.device_id, info.key) to properly handle entities + # moving between devices and support sub-devices with overlapping keys for info in infos: - new_infos[info.key] = info + info_key = (info.device_id, info.key) + new_infos[info_key] = info + + # Try to find existing entity - first with current device_id + old_info = current_infos.pop(info_key, None) + + # If not found, search for entity with same key but different device_id + # This handles the case where entity moved between devices + if not old_info: + for existing_device_id, existing_key in list(current_infos): + if existing_key == info.key: + # Found entity with same key but different device_id + old_info = current_infos.pop((existing_device_id, existing_key)) + break # Create new entity if it doesn't exist - if not (old_info := current_infos.pop(info.key, None)): + if not old_info: entity = entity_type(entry_data, platform.domain, info, state_type) add_entities.append(entity) continue @@ -78,7 +98,7 @@ def async_static_info_updated( if old_info.device_id == info.device_id: continue - # Entity has switched devices, need to migrate unique_id + # Entity has switched devices, need to migrate unique_id and handle state subscriptions old_unique_id = build_device_unique_id(device_info.mac_address, old_info) entity_id = ent_reg.async_get_entity_id(platform.domain, DOMAIN, old_unique_id) @@ -103,7 +123,7 @@ def async_static_info_updated( if old_unique_id != new_unique_id: updates["new_unique_id"] = new_unique_id - # Update device assignment + # Update device assignment in registry if info.device_id: # Entity now belongs to a sub device new_device = dev_reg.async_get_device( @@ -118,10 +138,32 @@ def async_static_info_updated( if new_device: updates["device_id"] = new_device.id - # Apply all updates at once + # Apply all registry updates at once if updates: ent_reg.async_update_entity(entity_id, **updates) + # IMPORTANT: The entity's device assignment in Home Assistant is only read when the entity + # is first added. Updating the registry alone won't move the entity to the new device + # in the UI. Additionally, the entity's state subscription is tied to the old device_id, + # so it won't receive state updates for the new device_id. + # + # We must remove the old entity and re-add it to ensure: + # 1. The entity appears under the correct device in the UI + # 2. The entity's state subscription is updated to use the new device_id + _LOGGER.debug( + "Entity %s moving from device_id %s to %s", + info.key, + old_info.device_id, + info.device_id, + ) + + # Signal the existing entity to remove itself + # The entity is registered with the old device_id, so we signal with that + entry_data.async_signal_entity_removal(info_type, old_info.device_id, info.key) + + # Create new entity with the new device_id + add_entities.append(entity_type(entry_data, platform.domain, info, state_type)) + # Anything still in current_infos is now gone if current_infos: entry_data.async_remove_entities( @@ -341,7 +383,10 @@ class EsphomeEntity(EsphomeBaseEntity, Generic[_InfoT, _StateT]): ) self.async_on_remove( entry_data.async_subscribe_state_update( - self._state_type, self._key, self._on_state_update + self._static_info.device_id, + self._state_type, + self._key, + self._on_state_update, ) ) self.async_on_remove( @@ -349,8 +394,29 @@ class EsphomeEntity(EsphomeBaseEntity, Generic[_InfoT, _StateT]): self._static_info, self._on_static_info_update ) ) + # Register to be notified when this entity should remove itself + # This happens when the entity moves to a different device + self.async_on_remove( + entry_data.async_register_entity_removal_callback( + type(self._static_info), + self._static_info.device_id, + self._key, + self._on_removal_signal, + ) + ) self._update_state_from_entry_data() + @callback + def _on_removal_signal(self) -> None: + """Handle signal to remove this entity.""" + _LOGGER.debug( + "Entity %s received removal signal due to device_id change", + self.entity_id, + ) + # Schedule the entity to be removed + # This must be done as a task since we're in a callback + self.hass.async_create_task(self.async_remove()) + @callback def _on_static_info_update(self, static_info: EntityInfo) -> None: """Save the static info for this entity when it changes. diff --git a/homeassistant/components/esphome/entry_data.py b/homeassistant/components/esphome/entry_data.py index 71680873611..dddbb598a57 100644 --- a/homeassistant/components/esphome/entry_data.py +++ b/homeassistant/components/esphome/entry_data.py @@ -60,7 +60,9 @@ from .const import DOMAIN from .dashboard import async_get_dashboard type ESPHomeConfigEntry = ConfigEntry[RuntimeEntryData] - +type EntityStateKey = tuple[type[EntityState], int, int] # (state_type, device_id, key) +type EntityInfoKey = tuple[type[EntityInfo], int, int] # (info_type, device_id, key) +type DeviceEntityKey = tuple[int, int] # (device_id, key) INFO_TO_COMPONENT_TYPE: Final = {v: k for k, v in COMPONENT_TYPE_TO_INFO.items()} @@ -137,8 +139,10 @@ class RuntimeEntryData: # When the disconnect callback is called, we mark all states # as stale so we will always dispatch a state update when the # device reconnects. This is the same format as state_subscriptions. - stale_state: set[tuple[type[EntityState], int]] = field(default_factory=set) - info: dict[type[EntityInfo], dict[int, EntityInfo]] = field(default_factory=dict) + stale_state: set[EntityStateKey] = field(default_factory=set) + info: dict[type[EntityInfo], dict[DeviceEntityKey, EntityInfo]] = field( + default_factory=dict + ) services: dict[int, UserService] = field(default_factory=dict) available: bool = False expected_disconnect: bool = False # Last disconnect was expected (e.g. deep sleep) @@ -147,7 +151,7 @@ class RuntimeEntryData: api_version: APIVersion = field(default_factory=APIVersion) cleanup_callbacks: list[CALLBACK_TYPE] = field(default_factory=list) disconnect_callbacks: set[CALLBACK_TYPE] = field(default_factory=set) - state_subscriptions: dict[tuple[type[EntityState], int], CALLBACK_TYPE] = field( + state_subscriptions: dict[EntityStateKey, CALLBACK_TYPE] = field( default_factory=dict ) device_update_subscriptions: set[CALLBACK_TYPE] = field(default_factory=set) @@ -164,7 +168,7 @@ class RuntimeEntryData: type[EntityInfo], list[Callable[[list[EntityInfo]], None]] ] = field(default_factory=dict) entity_info_key_updated_callbacks: dict[ - tuple[type[EntityInfo], int], list[Callable[[EntityInfo], None]] + EntityInfoKey, list[Callable[[EntityInfo], None]] ] = field(default_factory=dict) original_options: dict[str, Any] = field(default_factory=dict) media_player_formats: dict[str, list[MediaPlayerSupportedFormat]] = field( @@ -177,6 +181,9 @@ class RuntimeEntryData: default_factory=list ) device_id_to_name: dict[int, str] = field(default_factory=dict) + entity_removal_callbacks: dict[EntityInfoKey, list[CALLBACK_TYPE]] = field( + default_factory=dict + ) @property def name(self) -> str: @@ -210,7 +217,7 @@ class RuntimeEntryData: callback_: Callable[[EntityInfo], None], ) -> CALLBACK_TYPE: """Register to receive callbacks when static info is updated for a specific key.""" - callback_key = (type(static_info), static_info.key) + callback_key = (type(static_info), static_info.device_id, static_info.key) callbacks = self.entity_info_key_updated_callbacks.setdefault(callback_key, []) callbacks.append(callback_) return partial(callbacks.remove, callback_) @@ -250,7 +257,9 @@ class RuntimeEntryData: """Call static info updated callbacks.""" callbacks = self.entity_info_key_updated_callbacks for static_info in static_infos: - for callback_ in callbacks.get((type(static_info), static_info.key), ()): + for callback_ in callbacks.get( + (type(static_info), static_info.device_id, static_info.key), () + ): callback_(static_info) async def _ensure_platforms_loaded( @@ -342,12 +351,13 @@ class RuntimeEntryData: @callback def async_subscribe_state_update( self, + device_id: int, state_type: type[EntityState], state_key: int, entity_callback: CALLBACK_TYPE, ) -> CALLBACK_TYPE: """Subscribe to state updates.""" - subscription_key = (state_type, state_key) + subscription_key = (state_type, device_id, state_key) self.state_subscriptions[subscription_key] = entity_callback return partial(delitem, self.state_subscriptions, subscription_key) @@ -359,7 +369,7 @@ class RuntimeEntryData: stale_state = self.stale_state current_state_by_type = self.state[state_type] current_state = current_state_by_type.get(key, _SENTINEL) - subscription_key = (state_type, key) + subscription_key = (state_type, state.device_id, key) if ( current_state == state and subscription_key not in stale_state @@ -367,7 +377,7 @@ class RuntimeEntryData: and not ( state_type is SensorState and (platform_info := self.info.get(SensorInfo)) - and (entity_info := platform_info.get(state.key)) + and (entity_info := platform_info.get((state.device_id, state.key))) and (cast(SensorInfo, entity_info)).force_update ) ): @@ -520,3 +530,26 @@ class RuntimeEntryData: """Notify listeners that the Assist satellite wake word has been set.""" for callback_ in self.assist_satellite_set_wake_word_callbacks.copy(): callback_(wake_word_id) + + @callback + def async_register_entity_removal_callback( + self, + info_type: type[EntityInfo], + device_id: int, + key: int, + callback_: CALLBACK_TYPE, + ) -> CALLBACK_TYPE: + """Register to receive a callback when the entity should remove itself.""" + callback_key = (info_type, device_id, key) + callbacks = self.entity_removal_callbacks.setdefault(callback_key, []) + callbacks.append(callback_) + return partial(callbacks.remove, callback_) + + @callback + def async_signal_entity_removal( + self, info_type: type[EntityInfo], device_id: int, key: int + ) -> None: + """Signal that an entity should remove itself.""" + callback_key = (info_type, device_id, key) + for callback_ in self.entity_removal_callbacks.get(callback_key, []).copy(): + callback_() diff --git a/homeassistant/components/esphome/fan.py b/homeassistant/components/esphome/fan.py index a4d840845a6..882cf3606e2 100644 --- a/homeassistant/components/esphome/fan.py +++ b/homeassistant/components/esphome/fan.py @@ -71,7 +71,7 @@ class EsphomeFan(EsphomeEntity[FanInfo, FanState], FanEntity): ORDERED_NAMED_FAN_SPEEDS, percentage ) data["speed"] = named_speed - self._client.fan_command(**data) + self._client.fan_command(**data, device_id=self._static_info.device_id) async def async_turn_on( self, @@ -85,24 +85,36 @@ class EsphomeFan(EsphomeEntity[FanInfo, FanState], FanEntity): @convert_api_error_ha_error async def async_turn_off(self, **kwargs: Any) -> None: """Turn off the fan.""" - self._client.fan_command(key=self._key, state=False) + self._client.fan_command( + key=self._key, state=False, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_oscillate(self, oscillating: bool) -> None: """Oscillate the fan.""" - self._client.fan_command(key=self._key, oscillating=oscillating) + self._client.fan_command( + key=self._key, + oscillating=oscillating, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_set_direction(self, direction: str) -> None: """Set direction of the fan.""" self._client.fan_command( - key=self._key, direction=_FAN_DIRECTIONS.from_hass(direction) + key=self._key, + direction=_FAN_DIRECTIONS.from_hass(direction), + device_id=self._static_info.device_id, ) @convert_api_error_ha_error async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode of the fan.""" - self._client.fan_command(key=self._key, preset_mode=preset_mode) + self._client.fan_command( + key=self._key, + preset_mode=preset_mode, + device_id=self._static_info.device_id, + ) @property @esphome_state_property diff --git a/homeassistant/components/esphome/light.py b/homeassistant/components/esphome/light.py index 3e278b5b2d6..67b8e755c87 100644 --- a/homeassistant/components/esphome/light.py +++ b/homeassistant/components/esphome/light.py @@ -280,7 +280,7 @@ class EsphomeLight(EsphomeEntity[LightInfo, LightState], LightEntity): # (fewest capabilities set) data["color_mode"] = _least_complex_color_mode(color_modes) - self._client.light_command(**data) + self._client.light_command(**data, device_id=self._static_info.device_id) @convert_api_error_ha_error async def async_turn_off(self, **kwargs: Any) -> None: @@ -290,7 +290,7 @@ class EsphomeLight(EsphomeEntity[LightInfo, LightState], LightEntity): data["flash_length"] = FLASH_LENGTHS[kwargs[ATTR_FLASH]] if ATTR_TRANSITION in kwargs: data["transition_length"] = kwargs[ATTR_TRANSITION] - self._client.light_command(**data) + self._client.light_command(**data, device_id=self._static_info.device_id) @property @esphome_state_property diff --git a/homeassistant/components/esphome/lock.py b/homeassistant/components/esphome/lock.py index cfb9af614dd..d7e65470499 100644 --- a/homeassistant/components/esphome/lock.py +++ b/homeassistant/components/esphome/lock.py @@ -65,18 +65,24 @@ class EsphomeLock(EsphomeEntity[LockInfo, LockEntityState], LockEntity): @convert_api_error_ha_error async def async_lock(self, **kwargs: Any) -> None: """Lock the lock.""" - self._client.lock_command(self._key, LockCommand.LOCK) + self._client.lock_command( + self._key, LockCommand.LOCK, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_unlock(self, **kwargs: Any) -> None: """Unlock the lock.""" code = kwargs.get(ATTR_CODE) - self._client.lock_command(self._key, LockCommand.UNLOCK, code) + self._client.lock_command( + self._key, LockCommand.UNLOCK, code, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_open(self, **kwargs: Any) -> None: """Open the door latch.""" - self._client.lock_command(self._key, LockCommand.OPEN) + self._client.lock_command( + self._key, LockCommand.OPEN, device_id=self._static_info.device_id + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 6c2da31e48b..5e9e11171af 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -588,7 +588,7 @@ class ESPHomeManager: # Mark state as stale so that we will always dispatch # the next state update of that type when the device reconnects entry_data.stale_state = { - (type(entity_state), key) + (type(entity_state), entity_state.device_id, key) for state_dict in entry_data.state.values() for key, entity_state in state_dict.items() } diff --git a/homeassistant/components/esphome/manifest.json b/homeassistant/components/esphome/manifest.json index 01e04df6db8..c88fa7246fe 100644 --- a/homeassistant/components/esphome/manifest.json +++ b/homeassistant/components/esphome/manifest.json @@ -17,9 +17,9 @@ "mqtt": ["esphome/discover/#"], "quality_scale": "platinum", "requirements": [ - "aioesphomeapi==34.1.0", + "aioesphomeapi==35.0.0", "esphome-dashboard-api==1.3.0", - "bleak-esphome==2.16.0" + "bleak-esphome==3.1.0" ], "zeroconf": ["_esphomelib._tcp.local."] } diff --git a/homeassistant/components/esphome/media_player.py b/homeassistant/components/esphome/media_player.py index f18b5e7bf5c..2d43d40bfb3 100644 --- a/homeassistant/components/esphome/media_player.py +++ b/homeassistant/components/esphome/media_player.py @@ -132,7 +132,10 @@ class EsphomeMediaPlayer( media_id = proxy_url self._client.media_player_command( - self._key, media_url=media_id, announcement=announcement + self._key, + media_url=media_id, + announcement=announcement, + device_id=self._static_info.device_id, ) async def async_will_remove_from_hass(self) -> None: @@ -214,22 +217,36 @@ class EsphomeMediaPlayer( @convert_api_error_ha_error async def async_set_volume_level(self, volume: float) -> None: """Set volume level, range 0..1.""" - self._client.media_player_command(self._key, volume=volume) + self._client.media_player_command( + self._key, volume=volume, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_media_pause(self) -> None: """Send pause command.""" - self._client.media_player_command(self._key, command=MediaPlayerCommand.PAUSE) + self._client.media_player_command( + self._key, + command=MediaPlayerCommand.PAUSE, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_media_play(self) -> None: """Send play command.""" - self._client.media_player_command(self._key, command=MediaPlayerCommand.PLAY) + self._client.media_player_command( + self._key, + command=MediaPlayerCommand.PLAY, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_media_stop(self) -> None: """Send stop command.""" - self._client.media_player_command(self._key, command=MediaPlayerCommand.STOP) + self._client.media_player_command( + self._key, + command=MediaPlayerCommand.STOP, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_mute_volume(self, mute: bool) -> None: @@ -237,6 +254,7 @@ class EsphomeMediaPlayer( self._client.media_player_command( self._key, command=MediaPlayerCommand.MUTE if mute else MediaPlayerCommand.UNMUTE, + device_id=self._static_info.device_id, ) diff --git a/homeassistant/components/esphome/number.py b/homeassistant/components/esphome/number.py index 4a6800e1041..59788eb6e1f 100644 --- a/homeassistant/components/esphome/number.py +++ b/homeassistant/components/esphome/number.py @@ -67,7 +67,9 @@ class EsphomeNumber(EsphomeEntity[NumberInfo, NumberState], NumberEntity): @convert_api_error_ha_error async def async_set_native_value(self, value: float) -> None: """Update the current value.""" - self._client.number_command(self._key, value) + self._client.number_command( + self._key, value, device_id=self._static_info.device_id + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/select.py b/homeassistant/components/esphome/select.py index d5451f69f0f..3834e4251ea 100644 --- a/homeassistant/components/esphome/select.py +++ b/homeassistant/components/esphome/select.py @@ -76,7 +76,9 @@ class EsphomeSelect(EsphomeEntity[SelectInfo, SelectState], SelectEntity): @convert_api_error_ha_error async def async_select_option(self, option: str) -> None: """Change the selected option.""" - self._client.select_command(self._key, option) + self._client.select_command( + self._key, option, device_id=self._static_info.device_id + ) class EsphomeAssistPipelineSelect(EsphomeAssistEntity, AssistPipelineSelect): diff --git a/homeassistant/components/esphome/switch.py b/homeassistant/components/esphome/switch.py index 35edbf678ad..7e5223ae548 100644 --- a/homeassistant/components/esphome/switch.py +++ b/homeassistant/components/esphome/switch.py @@ -43,12 +43,16 @@ class EsphomeSwitch(EsphomeEntity[SwitchInfo, SwitchState], SwitchEntity): @convert_api_error_ha_error async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" - self._client.switch_command(self._key, True) + self._client.switch_command( + self._key, True, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" - self._client.switch_command(self._key, False) + self._client.switch_command( + self._key, False, device_id=self._static_info.device_id + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/text.py b/homeassistant/components/esphome/text.py index c36621b8f4e..5ffc07ce08d 100644 --- a/homeassistant/components/esphome/text.py +++ b/homeassistant/components/esphome/text.py @@ -50,7 +50,9 @@ class EsphomeText(EsphomeEntity[TextInfo, TextState], TextEntity): @convert_api_error_ha_error async def async_set_value(self, value: str) -> None: """Update the current value.""" - self._client.text_command(self._key, value) + self._client.text_command( + self._key, value, device_id=self._static_info.device_id + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/time.py b/homeassistant/components/esphome/time.py index b0e586e1792..a416bb17a31 100644 --- a/homeassistant/components/esphome/time.py +++ b/homeassistant/components/esphome/time.py @@ -28,7 +28,13 @@ class EsphomeTime(EsphomeEntity[TimeInfo, TimeState], TimeEntity): async def async_set_value(self, value: time) -> None: """Update the current time.""" - self._client.time_command(self._key, value.hour, value.minute, value.second) + self._client.time_command( + self._key, + value.hour, + value.minute, + value.second, + device_id=self._static_info.device_id, + ) async_setup_entry = partial( diff --git a/homeassistant/components/esphome/update.py b/homeassistant/components/esphome/update.py index cc886f2ba4c..a6d053e1c4c 100644 --- a/homeassistant/components/esphome/update.py +++ b/homeassistant/components/esphome/update.py @@ -334,11 +334,19 @@ class ESPHomeUpdateEntity(EsphomeEntity[UpdateInfo, UpdateState], UpdateEntity): async def async_update(self) -> None: """Command device to check for update.""" if self.available: - self._client.update_command(key=self._key, command=UpdateCommand.CHECK) + self._client.update_command( + key=self._key, + command=UpdateCommand.CHECK, + device_id=self._static_info.device_id, + ) @convert_api_error_ha_error async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: """Command device to install update.""" - self._client.update_command(key=self._key, command=UpdateCommand.INSTALL) + self._client.update_command( + key=self._key, + command=UpdateCommand.INSTALL, + device_id=self._static_info.device_id, + ) diff --git a/homeassistant/components/esphome/valve.py b/homeassistant/components/esphome/valve.py index f71a253c1f1..0fe9151a5a6 100644 --- a/homeassistant/components/esphome/valve.py +++ b/homeassistant/components/esphome/valve.py @@ -72,22 +72,32 @@ class EsphomeValve(EsphomeEntity[ValveInfo, ValveState], ValveEntity): @convert_api_error_ha_error async def async_open_valve(self, **kwargs: Any) -> None: """Open the valve.""" - self._client.valve_command(key=self._key, position=1.0) + self._client.valve_command( + key=self._key, position=1.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_close_valve(self, **kwargs: Any) -> None: """Close valve.""" - self._client.valve_command(key=self._key, position=0.0) + self._client.valve_command( + key=self._key, position=0.0, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_stop_valve(self, **kwargs: Any) -> None: """Stop the valve.""" - self._client.valve_command(key=self._key, stop=True) + self._client.valve_command( + key=self._key, stop=True, device_id=self._static_info.device_id + ) @convert_api_error_ha_error async def async_set_valve_position(self, position: float) -> None: """Move the valve to a specific position.""" - self._client.valve_command(key=self._key, position=position / 100) + self._client.valve_command( + key=self._key, + position=position / 100, + device_id=self._static_info.device_id, + ) async_setup_entry = partial( diff --git a/homeassistant/components/fritzbox/coordinator.py b/homeassistant/components/fritzbox/coordinator.py index 8a37ebf63e4..a95af62da6c 100644 --- a/homeassistant/components/fritzbox/coordinator.py +++ b/homeassistant/components/fritzbox/coordinator.py @@ -171,14 +171,19 @@ class FritzboxDataUpdateCoordinator(DataUpdateCoordinator[FritzboxCoordinatorDat for device in new_data.devices.values(): # create device registry entry for new main devices - if ( - device.ain not in self.data.devices - and device.device_and_unit_id[1] is None + if device.ain not in self.data.devices and ( + device.device_and_unit_id[1] is None + or ( + # workaround for sub units without a main device, e.g. Energy 250 + # https://github.com/home-assistant/core/issues/145204 + device.device_and_unit_id[1] == "1" + and device.device_and_unit_id[0] not in new_data.devices + ) ): dr.async_get(self.hass).async_get_or_create( config_entry_id=self.config_entry.entry_id, name=device.name, - identifiers={(DOMAIN, device.ain)}, + identifiers={(DOMAIN, device.device_and_unit_id[0])}, manufacturer=device.manufacturer, model=device.productname, sw_version=device.fw_version, diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 748d8f0c6f0..a7582ebc5e2 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -20,5 +20,5 @@ "documentation": "https://www.home-assistant.io/integrations/frontend", "integration_type": "system", "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20250702.1"] + "requirements": ["home-assistant-frontend==20250702.2"] } diff --git a/homeassistant/components/gardena_bluetooth/__init__.py b/homeassistant/components/gardena_bluetooth/__init__.py index 34f72bf0a5a..4a21bb3d3e4 100644 --- a/homeassistant/components/gardena_bluetooth/__init__.py +++ b/homeassistant/components/gardena_bluetooth/__init__.py @@ -13,6 +13,7 @@ from homeassistant.components import bluetooth from homeassistant.const import CONF_ADDRESS, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.util import dt as dt_util @@ -74,6 +75,7 @@ async def async_setup_entry( device = DeviceInfo( identifiers={(DOMAIN, address)}, + connections={(dr.CONNECTION_BLUETOOTH, address)}, name=name, sw_version=sw_version, manufacturer=manufacturer, diff --git a/homeassistant/components/generic_hygrostat/__init__.py b/homeassistant/components/generic_hygrostat/__init__.py index a12994c1a75..d907f863988 100644 --- a/homeassistant/components/generic_hygrostat/__init__.py +++ b/homeassistant/components/generic_hygrostat/__init__.py @@ -1,5 +1,7 @@ """The generic_hygrostat component.""" +import logging + import voluptuous as vol from homeassistant.components.humidifier import HumidifierDeviceClass @@ -16,7 +18,10 @@ from homeassistant.helpers.device import ( async_remove_stale_devices_links_keep_entity_device, ) from homeassistant.helpers.event import async_track_entity_registry_updated_event -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from homeassistant.helpers.typing import ConfigType DOMAIN = "generic_hygrostat" @@ -70,6 +75,8 @@ CONFIG_SCHEMA = vol.Schema( extra=vol.ALLOW_EXTRA, ) +_LOGGER = logging.getLogger(__name__) + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Generic Hygrostat component.""" @@ -89,6 +96,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -101,23 +109,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_HUMIDIFIER: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( # We use async_handle_source_entity_changes to track changes to the humidifer, # but not the humidity sensor because the generic_hygrostat adds itself to the # humidifier's device. async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_humidifier_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_HUMIDIFIER] ), source_entity_id_or_uuid=entry.options[CONF_HUMIDIFIER], - source_entity_removed=source_entity_removed, ) ) @@ -148,6 +152,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the generic_hygrostat config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_HUMIDIFIER] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener, called when the config entry options are changed.""" await hass.config_entries.async_reload(entry.entry_id) diff --git a/homeassistant/components/generic_hygrostat/config_flow.py b/homeassistant/components/generic_hygrostat/config_flow.py index 7c35b0e9317..449fa49b713 100644 --- a/homeassistant/components/generic_hygrostat/config_flow.py +++ b/homeassistant/components/generic_hygrostat/config_flow.py @@ -92,6 +92,8 @@ OPTIONS_FLOW = { class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW diff --git a/homeassistant/components/generic_hygrostat/humidifier.py b/homeassistant/components/generic_hygrostat/humidifier.py index 6e699745279..7746346d010 100644 --- a/homeassistant/components/generic_hygrostat/humidifier.py +++ b/homeassistant/components/generic_hygrostat/humidifier.py @@ -42,7 +42,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import condition, config_validation as cv -from homeassistant.helpers.device import async_device_info_to_link_from_entity +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -145,22 +145,22 @@ async def _async_setup_config( [ GenericHygrostat( hass, - name, - switch_entity_id, - sensor_entity_id, - min_humidity, - max_humidity, - target_humidity, - device_class, - min_cycle_duration, - dry_tolerance, - wet_tolerance, - keep_alive, - initial_state, - away_humidity, - away_fixed, - sensor_stale_duration, - unique_id, + name=name, + switch_entity_id=switch_entity_id, + sensor_entity_id=sensor_entity_id, + min_humidity=min_humidity, + max_humidity=max_humidity, + target_humidity=target_humidity, + device_class=device_class, + min_cycle_duration=min_cycle_duration, + dry_tolerance=dry_tolerance, + wet_tolerance=wet_tolerance, + keep_alive=keep_alive, + initial_state=initial_state, + away_humidity=away_humidity, + away_fixed=away_fixed, + sensor_stale_duration=sensor_stale_duration, + unique_id=unique_id, ) ] ) @@ -174,6 +174,7 @@ class GenericHygrostat(HumidifierEntity, RestoreEntity): def __init__( self, hass: HomeAssistant, + *, name: str, switch_entity_id: str, sensor_entity_id: str, @@ -195,7 +196,7 @@ class GenericHygrostat(HumidifierEntity, RestoreEntity): self._name = name self._switch_entity_id = switch_entity_id self._sensor_entity_id = sensor_entity_id - self._attr_device_info = async_device_info_to_link_from_entity( + self.device_entry = async_entity_id_to_device( hass, switch_entity_id, ) diff --git a/homeassistant/components/generic_thermostat/__init__.py b/homeassistant/components/generic_thermostat/__init__.py index 3e2af8598de..98cd9a02baa 100644 --- a/homeassistant/components/generic_thermostat/__init__.py +++ b/homeassistant/components/generic_thermostat/__init__.py @@ -1,5 +1,7 @@ """The generic_thermostat component.""" +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.core import Event, HomeAssistant from homeassistant.helpers import entity_registry as er @@ -8,14 +10,20 @@ from homeassistant.helpers.device import ( async_remove_stale_devices_links_keep_entity_device, ) from homeassistant.helpers.event import async_track_entity_registry_updated_event -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from .const import CONF_HEATER, CONF_SENSOR, PLATFORMS +_LOGGER = logging.getLogger(__name__) + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -28,23 +36,19 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_HEATER: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( # We use async_handle_source_entity_changes to track changes to the heater, but # not the temperature sensor because the generic_hygrostat adds itself to the # heater's device. async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_humidifier_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_HEATER] ), source_entity_id_or_uuid=entry.options[CONF_HEATER], - source_entity_removed=source_entity_removed, ) ) @@ -75,6 +79,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the generic_thermostat config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_HEATER] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener, called when the config entry options are changed.""" await hass.config_entries.async_reload(entry.entry_id) diff --git a/homeassistant/components/generic_thermostat/climate.py b/homeassistant/components/generic_thermostat/climate.py index 185040f02c9..76fcc4acdde 100644 --- a/homeassistant/components/generic_thermostat/climate.py +++ b/homeassistant/components/generic_thermostat/climate.py @@ -48,7 +48,7 @@ from homeassistant.core import ( ) from homeassistant.exceptions import ConditionError from homeassistant.helpers import condition, config_validation as cv -from homeassistant.helpers.device import async_device_info_to_link_from_entity +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -182,23 +182,23 @@ async def _async_setup_config( [ GenericThermostat( hass, - name, - heater_entity_id, - sensor_entity_id, - min_temp, - max_temp, - target_temp, - ac_mode, - min_cycle_duration, - cold_tolerance, - hot_tolerance, - keep_alive, - initial_hvac_mode, - presets, - precision, - target_temperature_step, - unit, - unique_id, + name=name, + heater_entity_id=heater_entity_id, + sensor_entity_id=sensor_entity_id, + min_temp=min_temp, + max_temp=max_temp, + target_temp=target_temp, + ac_mode=ac_mode, + min_cycle_duration=min_cycle_duration, + cold_tolerance=cold_tolerance, + hot_tolerance=hot_tolerance, + keep_alive=keep_alive, + initial_hvac_mode=initial_hvac_mode, + presets=presets, + precision=precision, + target_temperature_step=target_temperature_step, + unit=unit, + unique_id=unique_id, ) ] ) @@ -212,6 +212,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity): def __init__( self, hass: HomeAssistant, + *, name: str, heater_entity_id: str, sensor_entity_id: str, @@ -234,7 +235,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity): self._attr_name = name self.heater_entity_id = heater_entity_id self.sensor_entity_id = sensor_entity_id - self._attr_device_info = async_device_info_to_link_from_entity( + self.device_entry = async_entity_id_to_device( hass, heater_entity_id, ) diff --git a/homeassistant/components/generic_thermostat/config_flow.py b/homeassistant/components/generic_thermostat/config_flow.py index 1fbeaefde6b..b69106597d1 100644 --- a/homeassistant/components/generic_thermostat/config_flow.py +++ b/homeassistant/components/generic_thermostat/config_flow.py @@ -100,6 +100,8 @@ OPTIONS_FLOW = { class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW diff --git a/homeassistant/components/geo_location/trigger.py b/homeassistant/components/geo_location/trigger.py index 5f0d6e92ee1..ab5bde3682e 100644 --- a/homeassistant/components/geo_location/trigger.py +++ b/homeassistant/components/geo_location/trigger.py @@ -7,6 +7,7 @@ from typing import Final import voluptuous as vol +from homeassistant.components.zone import condition as zone_condition from homeassistant.const import CONF_EVENT, CONF_PLATFORM, CONF_SOURCE, CONF_ZONE from homeassistant.core import ( CALLBACK_TYPE, @@ -17,7 +18,7 @@ from homeassistant.core import ( State, callback, ) -from homeassistant.helpers import condition, config_validation as cv +from homeassistant.helpers import config_validation as cv from homeassistant.helpers.config_validation import entity_domain from homeassistant.helpers.event import TrackStates, async_track_state_change_filtered from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo @@ -79,9 +80,11 @@ async def async_attach_trigger( return from_match = ( - condition.zone(hass, zone_state, from_state) if from_state else False + zone_condition.zone(hass, zone_state, from_state) if from_state else False + ) + to_match = ( + zone_condition.zone(hass, zone_state, to_state) if to_state else False ) - to_match = condition.zone(hass, zone_state, to_state) if to_state else False if (trigger_event == EVENT_ENTER and not from_match and to_match) or ( trigger_event == EVENT_LEAVE and from_match and not to_match diff --git a/homeassistant/components/gios/const.py b/homeassistant/components/gios/const.py index 2294e89c961..2d21b0b8d9e 100644 --- a/homeassistant/components/gios/const.py +++ b/homeassistant/components/gios/const.py @@ -19,6 +19,8 @@ API_TIMEOUT: Final = 30 ATTR_C6H6: Final = "c6h6" ATTR_CO: Final = "co" +ATTR_NO: Final = "no" +ATTR_NOX: Final = "nox" ATTR_NO2: Final = "no2" ATTR_O3: Final = "o3" ATTR_PM10: Final = "pm10" diff --git a/homeassistant/components/gios/icons.json b/homeassistant/components/gios/icons.json index e1d848e276b..2623ee1549d 100644 --- a/homeassistant/components/gios/icons.json +++ b/homeassistant/components/gios/icons.json @@ -13,6 +13,9 @@ "no2_index": { "default": "mdi:molecule" }, + "nox": { + "default": "mdi:molecule" + }, "o3_index": { "default": "mdi:molecule" }, diff --git a/homeassistant/components/gios/manifest.json b/homeassistant/components/gios/manifest.json index ba87890de03..1782320a357 100644 --- a/homeassistant/components/gios/manifest.json +++ b/homeassistant/components/gios/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["dacite", "gios"], - "requirements": ["gios==6.1.0"] + "requirements": ["gios==6.1.1"] } diff --git a/homeassistant/components/gios/sensor.py b/homeassistant/components/gios/sensor.py index 67997a01dc6..b8583adfcf1 100644 --- a/homeassistant/components/gios/sensor.py +++ b/homeassistant/components/gios/sensor.py @@ -27,7 +27,9 @@ from .const import ( ATTR_AQI, ATTR_C6H6, ATTR_CO, + ATTR_NO, ATTR_NO2, + ATTR_NOX, ATTR_O3, ATTR_PM10, ATTR_PM25, @@ -74,6 +76,14 @@ SENSOR_TYPES: tuple[GiosSensorEntityDescription, ...] = ( state_class=SensorStateClass.MEASUREMENT, translation_key="co", ), + GiosSensorEntityDescription( + key=ATTR_NO, + value=lambda sensors: sensors.no.value if sensors.no else None, + suggested_display_precision=0, + device_class=SensorDeviceClass.NITROGEN_MONOXIDE, + native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, + state_class=SensorStateClass.MEASUREMENT, + ), GiosSensorEntityDescription( key=ATTR_NO2, value=lambda sensors: sensors.no2.value if sensors.no2 else None, @@ -90,6 +100,14 @@ SENSOR_TYPES: tuple[GiosSensorEntityDescription, ...] = ( options=["very_bad", "bad", "sufficient", "moderate", "good", "very_good"], translation_key="no2_index", ), + GiosSensorEntityDescription( + key=ATTR_NOX, + translation_key=ATTR_NOX, + value=lambda sensors: sensors.nox.value if sensors.nox else None, + suggested_display_precision=0, + native_unit_of_measurement=CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, + state_class=SensorStateClass.MEASUREMENT, + ), GiosSensorEntityDescription( key=ATTR_O3, value=lambda sensors: sensors.o3.value if sensors.o3 else None, diff --git a/homeassistant/components/gios/strings.json b/homeassistant/components/gios/strings.json index eca23159a13..d19edd63717 100644 --- a/homeassistant/components/gios/strings.json +++ b/homeassistant/components/gios/strings.json @@ -77,6 +77,9 @@ } } }, + "nox": { + "name": "Nitrogen oxides" + }, "o3_index": { "name": "Ozone index", "state": { diff --git a/homeassistant/components/goodwe/__init__.py b/homeassistant/components/goodwe/__init__.py index b6637bc8b50..e191e1b775f 100644 --- a/homeassistant/components/goodwe/__init__.py +++ b/homeassistant/components/goodwe/__init__.py @@ -1,6 +1,7 @@ """The Goodwe inverter component.""" from goodwe import InverterError, connect +from goodwe.const import GOODWE_TCP_PORT, GOODWE_UDP_PORT from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant @@ -20,11 +21,22 @@ async def async_setup_entry(hass: HomeAssistant, entry: GoodweConfigEntry) -> bo try: inverter = await connect( host=host, + port=GOODWE_UDP_PORT, family=model_family, retries=10, ) - except InverterError as err: - raise ConfigEntryNotReady from err + except InverterError as err_udp: + # First try with UDP failed, trying with the TCP port + try: + inverter = await connect( + host=host, + port=GOODWE_TCP_PORT, + family=model_family, + retries=10, + ) + except InverterError: + # Both ports are unavailable + raise ConfigEntryNotReady from err_udp device_info = DeviceInfo( configuration_url="https://www.semsportal.com", diff --git a/homeassistant/components/goodwe/config_flow.py b/homeassistant/components/goodwe/config_flow.py index 354877e782f..72d27e02b2e 100644 --- a/homeassistant/components/goodwe/config_flow.py +++ b/homeassistant/components/goodwe/config_flow.py @@ -6,6 +6,7 @@ import logging from typing import Any from goodwe import InverterError, connect +from goodwe.const import GOODWE_TCP_PORT, GOODWE_UDP_PORT import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -27,6 +28,18 @@ class GoodweFlowHandler(ConfigFlow, domain=DOMAIN): VERSION = 1 + async def _handle_successful_connection(self, inverter, host): + await self.async_set_unique_id(inverter.serial_number) + self._abort_if_unique_id_configured() + + return self.async_create_entry( + title=DEFAULT_NAME, + data={ + CONF_HOST: host, + CONF_MODEL_FAMILY: type(inverter).__name__, + }, + ) + async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -34,22 +47,19 @@ class GoodweFlowHandler(ConfigFlow, domain=DOMAIN): errors = {} if user_input is not None: host = user_input[CONF_HOST] - try: - inverter = await connect(host=host, retries=10) + inverter = await connect(host=host, port=GOODWE_UDP_PORT, retries=10) except InverterError: - errors[CONF_HOST] = "connection_error" + try: + inverter = await connect( + host=host, port=GOODWE_TCP_PORT, retries=10 + ) + except InverterError: + errors[CONF_HOST] = "connection_error" + else: + return await self._handle_successful_connection(inverter, host) else: - await self.async_set_unique_id(inverter.serial_number) - self._abort_if_unique_id_configured() - - return self.async_create_entry( - title=DEFAULT_NAME, - data={ - CONF_HOST: host, - CONF_MODEL_FAMILY: type(inverter).__name__, - }, - ) + return await self._handle_successful_connection(inverter, host) return self.async_show_form( step_id="user", data_schema=CONFIG_SCHEMA, errors=errors diff --git a/homeassistant/components/goodwe/manifest.json b/homeassistant/components/goodwe/manifest.json index 41e0ed91f6a..2f04ee3982f 100644 --- a/homeassistant/components/goodwe/manifest.json +++ b/homeassistant/components/goodwe/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/goodwe", "iot_class": "local_polling", "loggers": ["goodwe"], - "requirements": ["goodwe==0.3.6"] + "requirements": ["goodwe==0.4.8"] } diff --git a/homeassistant/components/goodwe/select.py b/homeassistant/components/goodwe/select.py index c26e8135b3f..7d58b099ddc 100644 --- a/homeassistant/components/goodwe/select.py +++ b/homeassistant/components/goodwe/select.py @@ -54,17 +54,24 @@ async def async_setup_entry( # Inverter model does not support this setting _LOGGER.debug("Could not read inverter operation mode") else: - async_add_entities( - [ - InverterOperationModeEntity( - device_info, - OPERATION_MODE, - inverter, - [v for k, v in _MODE_TO_OPTION.items() if k in supported_modes], - _MODE_TO_OPTION[active_mode], - ) - ] - ) + active_mode_option = _MODE_TO_OPTION.get(active_mode) + if active_mode_option is not None: + async_add_entities( + [ + InverterOperationModeEntity( + device_info, + OPERATION_MODE, + inverter, + [v for k, v in _MODE_TO_OPTION.items() if k in supported_modes], + active_mode_option, + ) + ] + ) + else: + _LOGGER.warning( + "Active mode %s not found in Goodwe Inverter Operation Mode Entity. Skipping entity creation", + active_mode, + ) class InverterOperationModeEntity(SelectEntity): diff --git a/homeassistant/components/google_cloud/stt.py b/homeassistant/components/google_cloud/stt.py index cd5055383ea..8a548cde8bb 100644 --- a/homeassistant/components/google_cloud/stt.py +++ b/homeassistant/components/google_cloud/stt.py @@ -127,7 +127,7 @@ class GoogleCloudSpeechToTextEntity(SpeechToTextEntity): try: responses = await self._client.streaming_recognize( requests=request_generator(), - timeout=10, + timeout=30, retry=AsyncRetry(initial=0.1, maximum=2.0, multiplier=2.0), ) diff --git a/homeassistant/components/google_cloud/tts.py b/homeassistant/components/google_cloud/tts.py index 16519645dee..817c424d1fc 100644 --- a/homeassistant/components/google_cloud/tts.py +++ b/homeassistant/components/google_cloud/tts.py @@ -218,7 +218,7 @@ class BaseGoogleCloudProvider: response = await self._client.synthesize_speech( request, - timeout=10, + timeout=30, retry=AsyncRetry(initial=0.1, maximum=2.0, multiplier=2.0), ) diff --git a/homeassistant/components/google_generative_ai_conversation/__init__.py b/homeassistant/components/google_generative_ai_conversation/__init__.py index a3b87c05e5a..1ff9f355c06 100644 --- a/homeassistant/components/google_generative_ai_conversation/__init__.py +++ b/homeassistant/components/google_generative_ai_conversation/__init__.py @@ -195,11 +195,15 @@ async def async_update_options( async def async_migrate_integration(hass: HomeAssistant) -> None: """Migrate integration entry structure.""" - entries = hass.config_entries.async_entries(DOMAIN) + # Make sure we get enabled config entries first + entries = sorted( + hass.config_entries.async_entries(DOMAIN), + key=lambda e: e.disabled_by is not None, + ) if not any(entry.version == 1 for entry in entries): return - api_keys_entries: dict[str, ConfigEntry] = {} + api_keys_entries: dict[str, tuple[ConfigEntry, bool]] = {} entity_registry = er.async_get(hass) device_registry = dr.async_get(hass) @@ -213,9 +217,14 @@ async def async_migrate_integration(hass: HomeAssistant) -> None: ) if entry.data[CONF_API_KEY] not in api_keys_entries: use_existing = True - api_keys_entries[entry.data[CONF_API_KEY]] = entry + all_disabled = all( + e.disabled_by is not None + for e in entries + if e.data[CONF_API_KEY] == entry.data[CONF_API_KEY] + ) + api_keys_entries[entry.data[CONF_API_KEY]] = (entry, all_disabled) - parent_entry = api_keys_entries[entry.data[CONF_API_KEY]] + parent_entry, all_disabled = api_keys_entries[entry.data[CONF_API_KEY]] hass.config_entries.async_add_subentry(parent_entry, subentry) if use_existing: @@ -228,25 +237,51 @@ async def async_migrate_integration(hass: HomeAssistant) -> None: unique_id=None, ), ) - conversation_entity = entity_registry.async_get_entity_id( + conversation_entity_id = entity_registry.async_get_entity_id( "conversation", DOMAIN, entry.entry_id, ) - if conversation_entity is not None: - entity_registry.async_update_entity( - conversation_entity, - config_entry_id=parent_entry.entry_id, - config_subentry_id=subentry.subentry_id, - new_unique_id=subentry.subentry_id, - ) - device = device_registry.async_get_device( identifiers={(DOMAIN, entry.entry_id)} ) + + if conversation_entity_id is not None: + conversation_entity_entry = entity_registry.entities[conversation_entity_id] + entity_disabled_by = conversation_entity_entry.disabled_by + if ( + entity_disabled_by is er.RegistryEntryDisabler.CONFIG_ENTRY + and not all_disabled + ): + # Device and entity registries don't update the disabled_by flag + # when moving a device or entity from one config entry to another, + # so we need to do it manually. + entity_disabled_by = ( + er.RegistryEntryDisabler.DEVICE + if device + else er.RegistryEntryDisabler.USER + ) + entity_registry.async_update_entity( + conversation_entity_id, + config_entry_id=parent_entry.entry_id, + config_subentry_id=subentry.subentry_id, + disabled_by=entity_disabled_by, + new_unique_id=subentry.subentry_id, + ) + if device is not None: + # Device and entity registries don't update the disabled_by flag when + # moving a device or entity from one config entry to another, so we + # need to do it manually. + device_disabled_by = device.disabled_by + if ( + device.disabled_by is dr.DeviceEntryDisabler.CONFIG_ENTRY + and not all_disabled + ): + device_disabled_by = dr.DeviceEntryDisabler.USER device_registry.async_update_device( device.id, + disabled_by=device_disabled_by, new_identifiers={(DOMAIN, subentry.subentry_id)}, add_config_subentry_id=subentry.subentry_id, add_config_entry_id=parent_entry.entry_id, @@ -266,12 +301,13 @@ async def async_migrate_integration(hass: HomeAssistant) -> None: if not use_existing: await hass.config_entries.async_remove(entry.entry_id) else: + _add_ai_task_subentry(hass, entry) hass.config_entries.async_update_entry( entry, title=DEFAULT_TITLE, options={}, version=2, - minor_version=2, + minor_version=4, ) @@ -315,19 +351,58 @@ async def async_migrate_entry( if entry.version == 2 and entry.minor_version == 2: # Add AI Task subentry with default options - hass.config_entries.async_add_subentry( - entry, - ConfigSubentry( - data=MappingProxyType(RECOMMENDED_AI_TASK_OPTIONS), - subentry_type="ai_task_data", - title=DEFAULT_AI_TASK_NAME, - unique_id=None, - ), - ) + _add_ai_task_subentry(hass, entry) hass.config_entries.async_update_entry(entry, minor_version=3) + if entry.version == 2 and entry.minor_version == 3: + # Fix migration where the disabled_by flag was not set correctly. + # We can currently only correct this for enabled config entries, + # because migration does not run for disabled config entries. This + # is asserted in tests, and if that behavior is changed, we should + # correct also disabled config entries. + device_registry = dr.async_get(hass) + entity_registry = er.async_get(hass) + devices = dr.async_entries_for_config_entry(device_registry, entry.entry_id) + entity_entries = er.async_entries_for_config_entry( + entity_registry, entry.entry_id + ) + if entry.disabled_by is None: + # If the config entry is not disabled, we need to set the disabled_by + # flag on devices to USER, and on entities to DEVICE, if they are set + # to CONFIG_ENTRY. + for device in devices: + if device.disabled_by is not dr.DeviceEntryDisabler.CONFIG_ENTRY: + continue + device_registry.async_update_device( + device.id, + disabled_by=dr.DeviceEntryDisabler.USER, + ) + for entity in entity_entries: + if entity.disabled_by is not er.RegistryEntryDisabler.CONFIG_ENTRY: + continue + entity_registry.async_update_entity( + entity.entity_id, + disabled_by=er.RegistryEntryDisabler.DEVICE, + ) + hass.config_entries.async_update_entry(entry, minor_version=4) + LOGGER.debug( "Migration to version %s:%s successful", entry.version, entry.minor_version ) return True + + +def _add_ai_task_subentry( + hass: HomeAssistant, entry: GoogleGenerativeAIConfigEntry +) -> None: + """Add AI Task subentry to the config entry.""" + hass.config_entries.async_add_subentry( + entry, + ConfigSubentry( + data=MappingProxyType(RECOMMENDED_AI_TASK_OPTIONS), + subentry_type="ai_task_data", + title=DEFAULT_AI_TASK_NAME, + unique_id=None, + ), + ) diff --git a/homeassistant/components/google_generative_ai_conversation/ai_task.py b/homeassistant/components/google_generative_ai_conversation/ai_task.py index b4f9d73e38d..4ffca835fed 100644 --- a/homeassistant/components/google_generative_ai_conversation/ai_task.py +++ b/homeassistant/components/google_generative_ai_conversation/ai_task.py @@ -37,7 +37,10 @@ class GoogleGenerativeAITaskEntity( ): """Google Generative AI AI Task entity.""" - _attr_supported_features = ai_task.AITaskEntityFeature.GENERATE_DATA + _attr_supported_features = ( + ai_task.AITaskEntityFeature.GENERATE_DATA + | ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS + ) async def _async_generate_data( self, diff --git a/homeassistant/components/google_generative_ai_conversation/config_flow.py b/homeassistant/components/google_generative_ai_conversation/config_flow.py index a68ca09e76d..7d1429b110e 100644 --- a/homeassistant/components/google_generative_ai_conversation/config_flow.py +++ b/homeassistant/components/google_generative_ai_conversation/config_flow.py @@ -97,7 +97,7 @@ class GoogleGenerativeAIConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Google Generative AI Conversation.""" VERSION = 2 - MINOR_VERSION = 3 + MINOR_VERSION = 4 async def async_step_api( self, user_input: dict[str, Any] | None = None diff --git a/homeassistant/components/google_generative_ai_conversation/const.py b/homeassistant/components/google_generative_ai_conversation/const.py index e7c5ba6bd22..b7091fe0222 100644 --- a/homeassistant/components/google_generative_ai_conversation/const.py +++ b/homeassistant/components/google_generative_ai_conversation/const.py @@ -25,7 +25,7 @@ RECOMMENDED_TOP_P = 0.95 CONF_TOP_K = "top_k" RECOMMENDED_TOP_K = 64 CONF_MAX_TOKENS = "max_tokens" -RECOMMENDED_MAX_TOKENS = 1500 +RECOMMENDED_MAX_TOKENS = 3000 CONF_HARASSMENT_BLOCK_THRESHOLD = "harassment_block_threshold" CONF_HATE_BLOCK_THRESHOLD = "hate_block_threshold" CONF_SEXUAL_BLOCK_THRESHOLD = "sexual_block_threshold" diff --git a/homeassistant/components/google_generative_ai_conversation/conversation.py b/homeassistant/components/google_generative_ai_conversation/conversation.py index 0b24e8bbc38..3525fba3af5 100644 --- a/homeassistant/components/google_generative_ai_conversation/conversation.py +++ b/homeassistant/components/google_generative_ai_conversation/conversation.py @@ -4,7 +4,7 @@ from __future__ import annotations from typing import Literal -from homeassistant.components import assist_pipeline, conversation +from homeassistant.components import conversation from homeassistant.config_entries import ConfigEntry, ConfigSubentry from homeassistant.const import CONF_LLM_HASS_API, MATCH_ALL from homeassistant.core import HomeAssistant @@ -57,9 +57,6 @@ class GoogleGenerativeAIConversationEntity( async def async_added_to_hass(self) -> None: """When entity is added to Home Assistant.""" await super().async_added_to_hass() - assist_pipeline.async_migrate_engine( - self.hass, "conversation", self.entry.entry_id, self.entity_id - ) conversation.async_set_agent(self.hass, self.entry, self) async def async_will_remove_from_hass(self) -> None: diff --git a/homeassistant/components/google_generative_ai_conversation/entity.py b/homeassistant/components/google_generative_ai_conversation/entity.py index 8f8edea18cb..8e967d84517 100644 --- a/homeassistant/components/google_generative_ai_conversation/entity.py +++ b/homeassistant/components/google_generative_ai_conversation/entity.py @@ -8,7 +8,7 @@ from collections.abc import AsyncGenerator, Callable from dataclasses import replace import mimetypes from pathlib import Path -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from google.genai import Client from google.genai.errors import APIError, ClientError @@ -31,7 +31,7 @@ import voluptuous as vol from voluptuous_openapi import convert from homeassistant.components import conversation -from homeassistant.config_entries import ConfigEntry, ConfigSubentry +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 @@ -60,6 +60,9 @@ from .const import ( TIMEOUT_MILLIS, ) +if TYPE_CHECKING: + from . import GoogleGenerativeAIConfigEntry + # Max number of back and forth with the LLM to generate a response MAX_TOOL_ITERATIONS = 10 @@ -313,7 +316,7 @@ class GoogleGenerativeAILLMBaseEntity(Entity): def __init__( self, - entry: ConfigEntry, + entry: GoogleGenerativeAIConfigEntry, subentry: ConfigSubentry, default_model: str = RECOMMENDED_CHAT_MODEL, ) -> None: @@ -438,6 +441,14 @@ class GoogleGenerativeAILLMBaseEntity(Entity): user_message = chat_log.content[-1] assert isinstance(user_message, conversation.UserContent) chat_request: str | list[Part] = user_message.content + if user_message.attachments: + files = await async_prepare_files_for_prompt( + self.hass, + self._genai_client, + [a.path for a in user_message.attachments], + ) + chat_request = [chat_request, *files] + # To prevent infinite loops, we limit the number of iterations for _iteration in range(MAX_TOOL_ITERATIONS): try: @@ -508,7 +519,7 @@ class GoogleGenerativeAILLMBaseEntity(Entity): async def async_prepare_files_for_prompt( hass: HomeAssistant, client: Client, files: list[Path] ) -> list[File]: - """Append files to a prompt. + """Upload files so they can be attached to a prompt. Caller needs to ensure that the files are allowed. """ diff --git a/homeassistant/components/habitica/icons.json b/homeassistant/components/habitica/icons.json index d241d3855d6..be25bebe779 100644 --- a/homeassistant/components/habitica/icons.json +++ b/homeassistant/components/habitica/icons.json @@ -82,9 +82,6 @@ "0": "mdi:skull-outline" } }, - "health_max": { - "default": "mdi:heart" - }, "mana": { "default": "mdi:flask", "state": { @@ -121,12 +118,6 @@ "rogue": "mdi:ninja" } }, - "habits": { - "default": "mdi:contrast-box" - }, - "rewards": { - "default": "mdi:treasure-chest" - }, "strength": { "default": "mdi:arm-flex-outline" }, diff --git a/homeassistant/components/habitica/sensor.py b/homeassistant/components/habitica/sensor.py index 5b64d0d8119..6d077495c4f 100644 --- a/homeassistant/components/habitica/sensor.py +++ b/homeassistant/components/habitica/sensor.py @@ -2,43 +2,26 @@ from __future__ import annotations -from collections.abc import Callable, Mapping -from dataclasses import asdict, dataclass +from collections.abc import Callable +from dataclasses import dataclass from enum import StrEnum import logging from typing import Any -from habiticalib import ( - ContentData, - HabiticaClass, - TaskData, - TaskType, - UserData, - deserialize_task, - ha, -) +from habiticalib import ContentData, HabiticaClass, TaskData, UserData, ha -from homeassistant.components.automation import automations_with_entity -from homeassistant.components.script import scripts_with_entity from homeassistant.components.sensor import ( - DOMAIN as SENSOR_DOMAIN, SensorDeviceClass, SensorEntity, SensorEntityDescription, ) from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from homeassistant.helpers.issue_registry import ( - IssueSeverity, - async_create_issue, - async_delete_issue, -) from homeassistant.helpers.typing import StateType from homeassistant.util import dt as dt_util -from .const import ASSETS_URL, DOMAIN -from .coordinator import HabiticaConfigEntry, HabiticaDataUpdateCoordinator +from .const import ASSETS_URL +from .coordinator import HabiticaConfigEntry from .entity import HabiticaBase from .util import ( get_attribute_points, @@ -84,7 +67,6 @@ class HabiticaSensorEntity(StrEnum): DISPLAY_NAME = "display_name" HEALTH = "health" - HEALTH_MAX = "health_max" MANA = "mana" MANA_MAX = "mana_max" EXPERIENCE = "experience" @@ -136,12 +118,6 @@ SENSOR_DESCRIPTIONS: tuple[HabiticaSensorEntityDescription, ...] = ( value_fn=lambda user, _: user.stats.hp, entity_picture=ha.HP, ), - HabiticaSensorEntityDescription( - key=HabiticaSensorEntity.HEALTH_MAX, - translation_key=HabiticaSensorEntity.HEALTH_MAX, - entity_registry_enabled_default=False, - value_fn=lambda user, _: 50, - ), HabiticaSensorEntityDescription( key=HabiticaSensorEntity.MANA, translation_key=HabiticaSensorEntity.MANA, @@ -286,57 +262,6 @@ SENSOR_DESCRIPTIONS: tuple[HabiticaSensorEntityDescription, ...] = ( ) -TASKS_MAP_ID = "id" -TASKS_MAP = { - "repeat": "repeat", - "challenge": "challenge", - "group": "group", - "frequency": "frequency", - "every_x": "everyX", - "streak": "streak", - "up": "up", - "down": "down", - "counter_up": "counterUp", - "counter_down": "counterDown", - "next_due": "nextDue", - "yester_daily": "yesterDaily", - "completed": "completed", - "collapse_checklist": "collapseChecklist", - "type": "Type", - "notes": "notes", - "tags": "tags", - "value": "value", - "priority": "priority", - "start_date": "startDate", - "days_of_month": "daysOfMonth", - "weeks_of_month": "weeksOfMonth", - "created_at": "createdAt", - "text": "text", - "is_due": "isDue", -} - - -TASK_SENSOR_DESCRIPTION: tuple[HabiticaTaskSensorEntityDescription, ...] = ( - HabiticaTaskSensorEntityDescription( - key=HabiticaSensorEntity.HABITS, - translation_key=HabiticaSensorEntity.HABITS, - value_fn=lambda tasks: [r for r in tasks if r.Type is TaskType.HABIT], - ), - HabiticaTaskSensorEntityDescription( - key=HabiticaSensorEntity.REWARDS, - translation_key=HabiticaSensorEntity.REWARDS, - value_fn=lambda tasks: [r for r in tasks if r.Type is TaskType.REWARD], - ), -) - - -def entity_used_in(hass: HomeAssistant, entity_id: str) -> list[str]: - """Get list of related automations and scripts.""" - used_in = automations_with_entity(hass, entity_id) - used_in += scripts_with_entity(hass, entity_id) - return used_in - - async def async_setup_entry( hass: HomeAssistant, config_entry: HabiticaConfigEntry, @@ -345,59 +270,10 @@ async def async_setup_entry( """Set up the habitica sensors.""" coordinator = config_entry.runtime_data - ent_reg = er.async_get(hass) - entities: list[SensorEntity] = [] - description: SensorEntityDescription - def add_deprecated_entity( - description: SensorEntityDescription, - entity_cls: Callable[ - [HabiticaDataUpdateCoordinator, SensorEntityDescription], SensorEntity - ], - ) -> None: - """Add deprecated entities.""" - if entity_id := ent_reg.async_get_entity_id( - SENSOR_DOMAIN, - DOMAIN, - f"{config_entry.unique_id}_{description.key}", - ): - entity_entry = ent_reg.async_get(entity_id) - if entity_entry and entity_entry.disabled: - ent_reg.async_remove(entity_id) - async_delete_issue( - hass, - DOMAIN, - f"deprecated_entity_{description.key}", - ) - elif entity_entry: - entities.append(entity_cls(coordinator, description)) - if entity_used_in(hass, entity_id): - async_create_issue( - hass, - DOMAIN, - f"deprecated_entity_{description.key}", - breaks_in_ha_version="2025.8.0", - is_fixable=False, - severity=IssueSeverity.WARNING, - translation_key="deprecated_entity", - translation_placeholders={ - "name": str( - entity_entry.name or entity_entry.original_name - ), - "entity": entity_id, - }, - ) - - for description in SENSOR_DESCRIPTIONS: - if description.key is HabiticaSensorEntity.HEALTH_MAX: - add_deprecated_entity(description, HabiticaSensor) - else: - entities.append(HabiticaSensor(coordinator, description)) - - for description in TASK_SENSOR_DESCRIPTION: - add_deprecated_entity(description, HabiticaTaskSensor) - - async_add_entities(entities, True) + async_add_entities( + HabiticaSensor(coordinator, description) for description in SENSOR_DESCRIPTIONS + ) class HabiticaSensor(HabiticaBase, SensorEntity): @@ -441,31 +317,3 @@ class HabiticaSensor(HabiticaBase, SensorEntity): ) return None - - -class HabiticaTaskSensor(HabiticaBase, SensorEntity): - """A Habitica task sensor.""" - - entity_description: HabiticaTaskSensorEntityDescription - - @property - def native_value(self) -> StateType: - """Return the state of the device.""" - - return len(self.entity_description.value_fn(self.coordinator.data.tasks)) - - @property - def extra_state_attributes(self) -> Mapping[str, Any] | None: - """Return the state attributes of all user tasks.""" - attrs = {} - - # Map tasks to TASKS_MAP - for task_data in self.entity_description.value_fn(self.coordinator.data.tasks): - received_task = deserialize_task(asdict(task_data)) - task_id = received_task[TASKS_MAP_ID] - task = {} - for map_key, map_value in TASKS_MAP.items(): - if value := received_task.get(map_value): - task[map_key] = value - attrs[str(task_id)] = task - return attrs diff --git a/homeassistant/components/habitica/strings.json b/homeassistant/components/habitica/strings.json index 22bc79555e8..6f0b3dc35cd 100644 --- a/homeassistant/components/habitica/strings.json +++ b/homeassistant/components/habitica/strings.json @@ -4,7 +4,6 @@ "dailies": "Dailies", "config_entry_name": "Select character", "task_name": "Task name", - "unit_tasks": "tasks", "unit_health_points": "HP", "unit_mana_points": "MP", "unit_experience_points": "XP", @@ -276,10 +275,6 @@ "name": "Health", "unit_of_measurement": "[%key:component::habitica::common::unit_health_points%]" }, - "health_max": { - "name": "Max. health", - "unit_of_measurement": "[%key:component::habitica::common::unit_health_points%]" - }, "mana": { "name": "Mana", "unit_of_measurement": "[%key:component::habitica::common::unit_mana_points%]" @@ -319,14 +314,6 @@ "rogue": "Rogue" } }, - "habits": { - "name": "Habits", - "unit_of_measurement": "[%key:component::habitica::common::unit_tasks%]" - }, - "rewards": { - "name": "Rewards", - "unit_of_measurement": "[%key:component::habitica::common::unit_tasks%]" - }, "strength": { "name": "Strength", "state_attributes": { diff --git a/homeassistant/components/hassio/ingress.py b/homeassistant/components/hassio/ingress.py index ca6764cfa34..e1f96b76bcb 100644 --- a/homeassistant/components/hassio/ingress.py +++ b/homeassistant/components/hassio/ingress.py @@ -239,13 +239,13 @@ def _forwarded_for_header(forward_for: str | None, peer_name: str) -> str: return f"{forward_for}, {connected_ip!s}" if forward_for else f"{connected_ip!s}" -def _init_header(request: web.Request, token: str) -> CIMultiDict | dict[str, str]: +def _init_header(request: web.Request, token: str) -> CIMultiDict: """Create initial header.""" - headers = { - name: value + headers = CIMultiDict( + (name, value) for name, value in request.headers.items() if name not in INIT_HEADERS_FILTER - } + ) # Ingress information headers[X_HASS_SOURCE] = "core.ingress" headers[X_INGRESS_PATH] = f"/api/hassio_ingress/{token}" @@ -273,13 +273,13 @@ def _init_header(request: web.Request, token: str) -> CIMultiDict | dict[str, st return headers -def _response_header(response: aiohttp.ClientResponse) -> dict[str, str]: +def _response_header(response: aiohttp.ClientResponse) -> CIMultiDict: """Create response header.""" - return { - name: value + return CIMultiDict( + (name, value) for name, value in response.headers.items() if name not in RESPONSE_HEADERS_FILTER - } + ) def _is_websocket(request: web.Request) -> bool: diff --git a/homeassistant/components/hddtemp/__init__.py b/homeassistant/components/hddtemp/__init__.py index 66a819f1e8d..121238df9fe 100644 --- a/homeassistant/components/hddtemp/__init__.py +++ b/homeassistant/components/hddtemp/__init__.py @@ -1,3 +1 @@ """The hddtemp component.""" - -DOMAIN = "hddtemp" diff --git a/homeassistant/components/hddtemp/sensor.py b/homeassistant/components/hddtemp/sensor.py index 192ddffd330..4d9bbeb9516 100644 --- a/homeassistant/components/hddtemp/sensor.py +++ b/homeassistant/components/hddtemp/sensor.py @@ -22,14 +22,11 @@ from homeassistant.const import ( CONF_PORT, UnitOfTemperature, ) -from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant +from homeassistant.core import HomeAssistant from homeassistant.helpers import config_validation as cv from homeassistant.helpers.entity_platform import AddEntitiesCallback -from homeassistant.helpers.issue_registry import IssueSeverity, create_issue from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType -from . import DOMAIN - _LOGGER = logging.getLogger(__name__) ATTR_DEVICE = "device" @@ -59,21 +56,6 @@ def setup_platform( discovery_info: DiscoveryInfoType | None = None, ) -> None: """Set up the HDDTemp sensor.""" - create_issue( - hass, - HOMEASSISTANT_DOMAIN, - f"deprecated_system_packages_yaml_integration_{DOMAIN}", - breaks_in_ha_version="2025.12.0", - is_fixable=False, - issue_domain=DOMAIN, - severity=IssueSeverity.WARNING, - translation_key="deprecated_system_packages_yaml_integration", - translation_placeholders={ - "domain": DOMAIN, - "integration_title": "hddtemp", - }, - ) - name = config.get(CONF_NAME) host = config.get(CONF_HOST) port = config.get(CONF_PORT) diff --git a/homeassistant/components/heos/config_flow.py b/homeassistant/components/heos/config_flow.py index e2d3e2522dc..b6cda10dcb7 100644 --- a/homeassistant/components/heos/config_flow.py +++ b/homeassistant/components/heos/config_flow.py @@ -24,6 +24,7 @@ from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from homeassistant.helpers import selector from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from .const import DOMAIN, ENTRY_TITLE from .coordinator import HeosConfigEntry @@ -142,51 +143,16 @@ class HeosFlowHandler(ConfigFlow, domain=DOMAIN): if TYPE_CHECKING: assert discovery_info.ssdp_location - entry: HeosConfigEntry | None = await self.async_set_unique_id(DOMAIN) hostname = urlparse(discovery_info.ssdp_location).hostname assert hostname is not None - # Abort early when discovery is ignored or host is part of the current system - if entry and ( - entry.source == SOURCE_IGNORE or hostname in _get_current_hosts(entry) - ): - return self.async_abort(reason="single_instance_allowed") + return await self._async_handle_discovered(hostname) - # Connect to discovered host and get system information - heos = Heos(HeosOptions(hostname, events=False, heart_beat=False)) - try: - await heos.connect() - system_info = await heos.get_system_info() - except HeosError as error: - _LOGGER.debug( - "Failed to retrieve system information from discovered HEOS device %s", - hostname, - exc_info=error, - ) - return self.async_abort(reason="cannot_connect") - finally: - await heos.disconnect() - - # Select the preferred host, if available - if system_info.preferred_hosts: - hostname = system_info.preferred_hosts[0].ip_address - - # Move to confirmation when not configured - if entry is None: - self._discovered_host = hostname - return await self.async_step_confirm_discovery() - - # Only update if the configured host isn't part of the discovered hosts to ensure new players that come online don't trigger a reload - if entry.data[CONF_HOST] not in [host.ip_address for host in system_info.hosts]: - _LOGGER.debug( - "Updated host %s to discovered host %s", entry.data[CONF_HOST], hostname - ) - return self.async_update_reload_and_abort( - entry, - data_updates={CONF_HOST: hostname}, - reason="reconfigure_successful", - ) - return self.async_abort(reason="single_instance_allowed") + async def async_step_zeroconf( + self, discovery_info: ZeroconfServiceInfo + ) -> ConfigFlowResult: + """Handle zeroconf discovery.""" + return await self._async_handle_discovered(discovery_info.host) async def async_step_confirm_discovery( self, user_input: dict[str, Any] | None = None @@ -267,6 +233,50 @@ class HeosFlowHandler(ConfigFlow, domain=DOMAIN): ), ) + async def _async_handle_discovered(self, hostname: str) -> ConfigFlowResult: + entry: HeosConfigEntry | None = await self.async_set_unique_id(DOMAIN) + # Abort early when discovery is ignored or host is part of the current system + if entry and ( + entry.source == SOURCE_IGNORE or hostname in _get_current_hosts(entry) + ): + return self.async_abort(reason="single_instance_allowed") + + # Connect to discovered host and get system information + heos = Heos(HeosOptions(hostname, events=False, heart_beat=False)) + try: + await heos.connect() + system_info = await heos.get_system_info() + except HeosError as error: + _LOGGER.debug( + "Failed to retrieve system information from discovered HEOS device %s", + hostname, + exc_info=error, + ) + return self.async_abort(reason="cannot_connect") + finally: + await heos.disconnect() + + # Select the preferred host, if available + if system_info.preferred_hosts and system_info.preferred_hosts[0].ip_address: + hostname = system_info.preferred_hosts[0].ip_address + + # Move to confirmation when not configured + if entry is None: + self._discovered_host = hostname + return await self.async_step_confirm_discovery() + + # Only update if the configured host isn't part of the discovered hosts to ensure new players that come online don't trigger a reload + if entry.data[CONF_HOST] not in [host.ip_address for host in system_info.hosts]: + _LOGGER.debug( + "Updated host %s to discovered host %s", entry.data[CONF_HOST], hostname + ) + return self.async_update_reload_and_abort( + entry, + data_updates={CONF_HOST: hostname}, + reason="reconfigure_successful", + ) + return self.async_abort(reason="single_instance_allowed") + class HeosOptionsFlowHandler(OptionsFlow): """Define HEOS options flow.""" diff --git a/homeassistant/components/heos/manifest.json b/homeassistant/components/heos/manifest.json index 8a88913456d..99cedf56f1f 100644 --- a/homeassistant/components/heos/manifest.json +++ b/homeassistant/components/heos/manifest.json @@ -13,5 +13,6 @@ { "st": "urn:schemas-denon-com:device:ACT-Denon:1" } - ] + ], + "zeroconf": ["_heos-audio._tcp.local."] } diff --git a/homeassistant/components/history_stats/__init__.py b/homeassistant/components/history_stats/__init__.py index a3565f9ed77..efddabd180c 100644 --- a/homeassistant/components/history_stats/__init__.py +++ b/homeassistant/components/history_stats/__init__.py @@ -3,6 +3,7 @@ from __future__ import annotations from datetime import timedelta +import logging from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ENTITY_ID, CONF_STATE @@ -11,7 +12,10 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from homeassistant.helpers.template import Template from .const import CONF_DURATION, CONF_END, CONF_START, PLATFORMS @@ -20,6 +24,8 @@ from .data import HistoryStats type HistoryStatsConfigEntry = ConfigEntry[HistoryStatsUpdateCoordinator] +_LOGGER = logging.getLogger(__name__) + async def async_setup_entry( hass: HomeAssistant, entry: HistoryStatsConfigEntry @@ -47,6 +53,7 @@ async def async_setup_entry( await coordinator.async_config_entry_first_refresh() entry.runtime_data = coordinator + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -67,6 +74,7 @@ async def async_setup_entry( entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( @@ -83,6 +91,40 @@ async def async_setup_entry( return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the history_stats config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_ENTITY_ID] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def async_unload_entry( hass: HomeAssistant, entry: HistoryStatsConfigEntry ) -> bool: diff --git a/homeassistant/components/history_stats/config_flow.py b/homeassistant/components/history_stats/config_flow.py index 996c7ba0d0c..750180bf3f6 100644 --- a/homeassistant/components/history_stats/config_flow.py +++ b/homeassistant/components/history_stats/config_flow.py @@ -124,6 +124,8 @@ OPTIONS_FLOW = { class HistoryStatsConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config flow for History stats.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW @@ -229,7 +231,12 @@ async def ws_start_preview( coordinator = HistoryStatsUpdateCoordinator(hass, history_stats, None, name, True) await coordinator.async_refresh() preview_entity = HistoryStatsSensor( - hass, coordinator, sensor_type, name, None, entity_id + hass, + coordinator=coordinator, + sensor_type=sensor_type, + name=name, + unique_id=None, + source_entity_id=entity_id, ) preview_entity.hass = hass diff --git a/homeassistant/components/history_stats/sensor.py b/homeassistant/components/history_stats/sensor.py index 780bff14eb1..0cfe82e09fb 100644 --- a/homeassistant/components/history_stats/sensor.py +++ b/homeassistant/components/history_stats/sensor.py @@ -27,7 +27,7 @@ from homeassistant.const import ( from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.exceptions import PlatformNotReady from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.device import async_device_info_to_link_from_entity +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -113,7 +113,16 @@ async def async_setup_platform( if not coordinator.last_update_success: raise PlatformNotReady from coordinator.last_exception async_add_entities( - [HistoryStatsSensor(hass, coordinator, sensor_type, name, unique_id, entity_id)] + [ + HistoryStatsSensor( + hass, + coordinator=coordinator, + sensor_type=sensor_type, + name=name, + unique_id=unique_id, + source_entity_id=entity_id, + ) + ] ) @@ -130,7 +139,12 @@ async def async_setup_entry( async_add_entities( [ HistoryStatsSensor( - hass, coordinator, sensor_type, entry.title, entry.entry_id, entity_id + hass, + coordinator=coordinator, + sensor_type=sensor_type, + name=entry.title, + unique_id=entry.entry_id, + source_entity_id=entity_id, ) ] ) @@ -176,6 +190,7 @@ class HistoryStatsSensor(HistoryStatsSensorBase): def __init__( self, hass: HomeAssistant, + *, coordinator: HistoryStatsUpdateCoordinator, sensor_type: str, name: str, @@ -190,10 +205,11 @@ class HistoryStatsSensor(HistoryStatsSensorBase): self._attr_native_unit_of_measurement = UNITS[sensor_type] self._type = sensor_type self._attr_unique_id = unique_id - self._attr_device_info = async_device_info_to_link_from_entity( - hass, - source_entity_id, - ) + if source_entity_id: # Guard against empty source_entity_id in preview mode + self.device_entry = async_entity_id_to_device( + hass, + source_entity_id, + ) self._process_update() if self._type == CONF_TYPE_TIME: self._attr_device_class = SensorDeviceClass.DURATION diff --git a/homeassistant/components/holiday/manifest.json b/homeassistant/components/holiday/manifest.json index c76d6638730..e39525563e9 100644 --- a/homeassistant/components/holiday/manifest.json +++ b/homeassistant/components/holiday/manifest.json @@ -5,5 +5,5 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/holiday", "iot_class": "local_polling", - "requirements": ["holidays==0.75", "babel==2.15.0"] + "requirements": ["holidays==0.76", "babel==2.15.0"] } diff --git a/homeassistant/components/home_connect/coordinator.py b/homeassistant/components/home_connect/coordinator.py index 3c9d33424a8..81f785b55ae 100644 --- a/homeassistant/components/home_connect/coordinator.py +++ b/homeassistant/components/home_connect/coordinator.py @@ -38,10 +38,15 @@ from propcache.api import cached_property from homeassistant.config_entries import ConfigEntry from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady -from homeassistant.helpers import device_registry as dr, issue_registry as ir +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -from .const import API_DEFAULT_RETRY_AFTER, APPLIANCES_WITH_PROGRAMS, DOMAIN +from .const import ( + API_DEFAULT_RETRY_AFTER, + APPLIANCES_WITH_PROGRAMS, + BSH_OPERATION_STATE_PAUSE, + DOMAIN, +) from .utils import get_dict_from_home_connect_error _LOGGER = logging.getLogger(__name__) @@ -66,6 +71,7 @@ class HomeConnectApplianceData: def update(self, other: HomeConnectApplianceData) -> None: """Update data with data from other instance.""" + self.commands.clear() self.commands.update(other.commands) self.events.update(other.events) self.info.connected = other.info.connected @@ -201,6 +207,28 @@ class HomeConnectCoordinator( raw_key=status_key.value, value=event.value, ) + if ( + status_key == StatusKey.BSH_COMMON_OPERATION_STATE + and event.value == BSH_OPERATION_STATE_PAUSE + and CommandKey.BSH_COMMON_RESUME_PROGRAM + not in ( + commands := self.data[ + event_message_ha_id + ].commands + ) + ): + # All the appliances that can be paused + # should have the resume command available. + commands.add(CommandKey.BSH_COMMON_RESUME_PROGRAM) + for ( + listener, + context, + ) in self._special_listeners.values(): + if ( + EventKey.BSH_COMMON_APPLIANCE_DEPAIRED + not in context + ): + listener() self._call_event_listener(event_message) case EventType.NOTIFY: @@ -598,42 +626,37 @@ class HomeConnectCoordinator( """Check if the appliance data hasn't been refreshed too often recently.""" now = self.hass.loop.time() - if len(self._execution_tracker[appliance_ha_id]) >= MAX_EXECUTIONS: - return True + + execution_tracker = self._execution_tracker[appliance_ha_id] + initial_len = len(execution_tracker) execution_tracker = self._execution_tracker[appliance_ha_id] = [ timestamp - for timestamp in self._execution_tracker[appliance_ha_id] + for timestamp in execution_tracker if now - timestamp < MAX_EXECUTIONS_TIME_WINDOW ] execution_tracker.append(now) if len(execution_tracker) >= MAX_EXECUTIONS: - ir.async_create_issue( - self.hass, - DOMAIN, - f"home_connect_too_many_connected_paired_events_{appliance_ha_id}", - is_fixable=True, - is_persistent=True, - severity=ir.IssueSeverity.ERROR, - translation_key="home_connect_too_many_connected_paired_events", - data={ - "entry_id": self.config_entry.entry_id, - "appliance_ha_id": appliance_ha_id, - }, - translation_placeholders={ - "appliance_name": self.data[appliance_ha_id].info.name, - "times": str(MAX_EXECUTIONS), - "time_window": str(MAX_EXECUTIONS_TIME_WINDOW // 60), - "home_connect_resource_url": "https://www.home-connect.com/global/help-support/error-codes#/Togglebox=15362315-13320636-1/", - "home_assistant_core_new_issue_url": ( - "https://github.com/home-assistant/core/issues/new?template=bug_report.yml" - f"&integration_name={DOMAIN}&integration_link=https://www.home-assistant.io/integrations/{DOMAIN}/" - ), - }, - ) + if initial_len < MAX_EXECUTIONS: + _LOGGER.warning( + 'Too many connected/paired events for appliance "%s" ' + "(%s times in less than %s minutes), updates have been disabled " + "and they will be enabled again whenever the connection stabilizes. " + "Consider trying to unplug the appliance " + "for a while to perform a soft reset", + self.data[appliance_ha_id].info.name, + MAX_EXECUTIONS, + MAX_EXECUTIONS_TIME_WINDOW // 60, + ) return True + if initial_len >= MAX_EXECUTIONS: + _LOGGER.info( + 'Connected/paired events from the appliance "%s" have stabilized,' + " updates have been re-enabled", + self.data[appliance_ha_id].info.name, + ) return False diff --git a/homeassistant/components/home_connect/strings.json b/homeassistant/components/home_connect/strings.json index 99c89ec8788..853d2bd2f8e 100644 --- a/homeassistant/components/home_connect/strings.json +++ b/homeassistant/components/home_connect/strings.json @@ -124,17 +124,6 @@ } }, "issues": { - "home_connect_too_many_connected_paired_events": { - "title": "{appliance_name} sent too many connected or paired events", - "fix_flow": { - "step": { - "confirm": { - "title": "[%key:component::home_connect::issues::home_connect_too_many_connected_paired_events::title%]", - "description": "The appliance \"{appliance_name}\" has been reported as connected or paired {times} times in less than {time_window} minutes, so refreshes on connected or paired events has been disabled to avoid exceeding the API rate limit.\n\nPlease refer to the [Home Connect Wi-Fi requirements and recommendations]({home_connect_resource_url}). If everything seems right with your network configuration, restart the appliance.\n\nClick \"submit\" to re-enable the updates.\nIf the issue persists, please create an issue in the [Home Assistant core repository]({home_assistant_core_new_issue_url})." - } - } - } - }, "deprecated_time_alarm_clock_in_automations_scripts": { "title": "Deprecated alarm clock entity detected in some automations or scripts", "fix_flow": { diff --git a/homeassistant/components/homeassistant/strings.json b/homeassistant/components/homeassistant/strings.json index 7c95680076c..77c29e7c495 100644 --- a/homeassistant/components/homeassistant/strings.json +++ b/homeassistant/components/homeassistant/strings.json @@ -40,7 +40,7 @@ }, "python_version": { "title": "Support for Python {current_python_version} is being removed", - "description": "Support for running Home Assistant in the current used Python version {current_python_version} is deprecated and will be removed in Home Assistant {breaks_in_ha_version}. Please upgrade Python to {required_python_version} to prevent your Home Assistant instance from breaking." + "description": "Support for running Home Assistant in the currently used Python version {current_python_version} is deprecated and will be removed in Home Assistant {breaks_in_ha_version}. Please upgrade Python to {required_python_version} to prevent your Home Assistant instance from breaking." }, "config_entry_only": { "title": "The {domain} integration does not support YAML configuration", @@ -81,7 +81,7 @@ "title": "Integration {domain} not found", "fix_flow": { "abort": { - "issue_ignored": "Not existing integration {domain} ignored." + "issue_ignored": "Non-existent integration {domain} ignored." }, "step": { "init": { @@ -274,7 +274,7 @@ "message": "Failed to process the returned action response data, expected a dictionary, but got {response_data_type}." }, "service_should_be_blocking": { - "message": "A non blocking action call with argument {non_blocking_argument} can't be used together with argument {return_response}." + "message": "A non-blocking action call with argument {non_blocking_argument} can't be used together with argument {return_response}." } } } diff --git a/homeassistant/components/homematicip_cloud/icons.json b/homeassistant/components/homematicip_cloud/icons.json index 53a39d8213c..561ae79abc2 100644 --- a/homeassistant/components/homematicip_cloud/icons.json +++ b/homeassistant/components/homematicip_cloud/icons.json @@ -1,4 +1,15 @@ { + "entity": { + "sensor": { + "tilt_state": { + "state": { + "neutral": "mdi:garage", + "non_neutral": "mdi:garage-open", + "tilted": "mdi:garage-alert" + } + } + } + }, "services": { "activate_eco_mode_with_duration": { "service": "mdi:leaf" diff --git a/homeassistant/components/homematicip_cloud/sensor.py b/homeassistant/components/homematicip_cloud/sensor.py index 13f3694de7a..95de7f15af0 100644 --- a/homeassistant/components/homematicip_cloud/sensor.py +++ b/homeassistant/components/homematicip_cloud/sensor.py @@ -11,6 +11,7 @@ from homematicip.base.functionalChannels import ( FunctionalChannel, ) from homematicip.device import ( + Device, EnergySensorsInterface, FloorTerminalBlock6, FloorTerminalBlock10, @@ -31,6 +32,7 @@ from homematicip.device import ( TemperatureHumiditySensorDisplay, TemperatureHumiditySensorOutdoor, TemperatureHumiditySensorWithoutDisplay, + TiltVibrationSensor, WeatherSensor, WeatherSensorPlus, WeatherSensorPro, @@ -44,6 +46,7 @@ from homeassistant.components.sensor import ( ) from homeassistant.const import ( CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, + DEGREE, LIGHT_LUX, PERCENTAGE, UnitOfEnergy, @@ -62,6 +65,11 @@ from .entity import HomematicipGenericEntity from .hap import HomematicIPConfigEntry, HomematicipHAP from .helpers import get_channels_from_device +ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION = "acceleration_sensor_neutral_position" +ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE = "acceleration_sensor_trigger_angle" +ATTR_ACCELERATION_SENSOR_SECOND_TRIGGER_ANGLE = ( + "acceleration_sensor_second_trigger_angle" +) ATTR_CURRENT_ILLUMINATION = "current_illumination" ATTR_LOWEST_ILLUMINATION = "lowest_illumination" ATTR_HIGHEST_ILLUMINATION = "highest_illumination" @@ -89,6 +97,136 @@ ILLUMINATION_DEVICE_ATTRIBUTES = { "highestIllumination": ATTR_HIGHEST_ILLUMINATION, } +TILT_STATE_VALUES = ["neutral", "tilted", "non_neutral"] + + +def get_device_handlers(hap: HomematicipHAP) -> dict[type, Callable]: + """Generate a mapping of device types to handler functions.""" + return { + HomeControlAccessPoint: lambda device: [ + HomematicipAccesspointDutyCycle(hap, device) + ], + HeatingThermostat: lambda device: [ + HomematicipHeatingThermostat(hap, device), + HomematicipTemperatureSensor(hap, device), + ], + HeatingThermostatCompact: lambda device: [ + HomematicipHeatingThermostat(hap, device), + HomematicipTemperatureSensor(hap, device), + ], + HeatingThermostatEvo: lambda device: [ + HomematicipHeatingThermostat(hap, device), + HomematicipTemperatureSensor(hap, device), + ], + TemperatureHumiditySensorDisplay: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + TemperatureHumiditySensorWithoutDisplay: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + TemperatureHumiditySensorOutdoor: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + RoomControlDeviceAnalog: lambda device: [ + HomematicipTemperatureSensor(hap, device), + ], + LightSensor: lambda device: [ + HomematicipIlluminanceSensor(hap, device), + ], + MotionDetectorIndoor: lambda device: [ + HomematicipIlluminanceSensor(hap, device), + ], + MotionDetectorOutdoor: lambda device: [ + HomematicipIlluminanceSensor(hap, device), + ], + MotionDetectorPushButton: lambda device: [ + HomematicipIlluminanceSensor(hap, device), + ], + PresenceDetectorIndoor: lambda device: [ + HomematicipIlluminanceSensor(hap, device), + ], + SwitchMeasuring: lambda device: [ + HomematicipPowerSensor(hap, device), + HomematicipEnergySensor(hap, device), + ], + PassageDetector: lambda device: [ + HomematicipPassageDetectorDeltaCounter(hap, device), + ], + TemperatureDifferenceSensor2: lambda device: [ + HomematicpTemperatureExternalSensorCh1(hap, device), + HomematicpTemperatureExternalSensorCh2(hap, device), + HomematicpTemperatureExternalSensorDelta(hap, device), + ], + TiltVibrationSensor: lambda device: [ + HomematicipTiltStateSensor(hap, device), + HomematicipTiltAngleSensor(hap, device), + ], + WeatherSensor: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipIlluminanceSensor(hap, device), + HomematicipWindspeedSensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + WeatherSensorPlus: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipIlluminanceSensor(hap, device), + HomematicipWindspeedSensor(hap, device), + HomematicipTodayRainSensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + WeatherSensorPro: lambda device: [ + HomematicipTemperatureSensor(hap, device), + HomematicipHumiditySensor(hap, device), + HomematicipIlluminanceSensor(hap, device), + HomematicipWindspeedSensor(hap, device), + HomematicipTodayRainSensor(hap, device), + HomematicipAbsoluteHumiditySensor(hap, device), + ], + EnergySensorsInterface: lambda device: _handle_energy_sensor_interface( + hap, device + ), + } + + +def _handle_energy_sensor_interface( + hap: HomematicipHAP, device: Device +) -> list[HomematicipGenericEntity]: + """Handle energy sensor interface devices.""" + result: list[HomematicipGenericEntity] = [] + for ch in get_channels_from_device( + device, FunctionalChannelType.ENERGY_SENSORS_INTERFACE_CHANNEL + ): + if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_IEC: + if ch.currentPowerConsumption is not None: + result.append(HmipEsiIecPowerConsumption(hap, device)) + if ch.energyCounterOneType != ESI_TYPE_UNKNOWN: + result.append(HmipEsiIecEnergyCounterHighTariff(hap, device)) + if ch.energyCounterTwoType != ESI_TYPE_UNKNOWN: + result.append(HmipEsiIecEnergyCounterLowTariff(hap, device)) + if ch.energyCounterThreeType != ESI_TYPE_UNKNOWN: + result.append(HmipEsiIecEnergyCounterInputSingleTariff(hap, device)) + + if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_GAS: + if ch.currentGasFlow is not None: + result.append(HmipEsiGasCurrentGasFlow(hap, device)) + if ch.gasVolume is not None: + result.append(HmipEsiGasGasVolume(hap, device)) + + if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_LED: + if ch.currentPowerConsumption is not None: + result.append(HmipEsiLedCurrentPowerConsumption(hap, device)) + result.append(HmipEsiLedEnergyCounterHighTariff(hap, device)) + + return result + async def async_setup_entry( hass: HomeAssistant, @@ -98,109 +236,88 @@ async def async_setup_entry( """Set up the HomematicIP Cloud sensors from a config entry.""" hap = config_entry.runtime_data entities: list[HomematicipGenericEntity] = [] + + # Get device handlers dynamically + device_handlers = get_device_handlers(hap) + + # Process all devices for device in hap.home.devices: - if isinstance(device, HomeControlAccessPoint): - entities.append(HomematicipAccesspointDutyCycle(hap, device)) - if isinstance( - device, - ( - HeatingThermostat, - HeatingThermostatCompact, - HeatingThermostatEvo, - ), - ): - entities.append(HomematicipHeatingThermostat(hap, device)) - entities.append(HomematicipTemperatureSensor(hap, device)) - if isinstance( - device, - ( - TemperatureHumiditySensorDisplay, - TemperatureHumiditySensorWithoutDisplay, - TemperatureHumiditySensorOutdoor, - WeatherSensor, - WeatherSensorPlus, - WeatherSensorPro, - ), - ): - entities.append(HomematicipTemperatureSensor(hap, device)) - entities.append(HomematicipHumiditySensor(hap, device)) - entities.append(HomematicipAbsoluteHumiditySensor(hap, device)) - elif isinstance(device, (RoomControlDeviceAnalog,)): - entities.append(HomematicipTemperatureSensor(hap, device)) - if isinstance( - device, - ( - LightSensor, - MotionDetectorIndoor, - MotionDetectorOutdoor, - MotionDetectorPushButton, - PresenceDetectorIndoor, - WeatherSensor, - WeatherSensorPlus, - WeatherSensorPro, - ), - ): - entities.append(HomematicipIlluminanceSensor(hap, device)) - if isinstance(device, SwitchMeasuring): - entities.append(HomematicipPowerSensor(hap, device)) - entities.append(HomematicipEnergySensor(hap, device)) - if isinstance(device, (WeatherSensor, WeatherSensorPlus, WeatherSensorPro)): - entities.append(HomematicipWindspeedSensor(hap, device)) - if isinstance(device, (WeatherSensorPlus, WeatherSensorPro)): - entities.append(HomematicipTodayRainSensor(hap, device)) - if isinstance(device, PassageDetector): - entities.append(HomematicipPassageDetectorDeltaCounter(hap, device)) - if isinstance(device, TemperatureDifferenceSensor2): - entities.append(HomematicpTemperatureExternalSensorCh1(hap, device)) - entities.append(HomematicpTemperatureExternalSensorCh2(hap, device)) - entities.append(HomematicpTemperatureExternalSensorDelta(hap, device)) - if isinstance(device, EnergySensorsInterface): - for ch in get_channels_from_device( - device, FunctionalChannelType.ENERGY_SENSORS_INTERFACE_CHANNEL - ): - if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_IEC: - if ch.currentPowerConsumption is not None: - entities.append(HmipEsiIecPowerConsumption(hap, device)) - if ch.energyCounterOneType != ESI_TYPE_UNKNOWN: - entities.append(HmipEsiIecEnergyCounterHighTariff(hap, device)) - if ch.energyCounterTwoType != ESI_TYPE_UNKNOWN: - entities.append(HmipEsiIecEnergyCounterLowTariff(hap, device)) - if ch.energyCounterThreeType != ESI_TYPE_UNKNOWN: - entities.append( - HmipEsiIecEnergyCounterInputSingleTariff(hap, device) - ) + for device_class, handler in device_handlers.items(): + if isinstance(device, device_class): + entities.extend(handler(device)) - if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_GAS: - if ch.currentGasFlow is not None: - entities.append(HmipEsiGasCurrentGasFlow(hap, device)) - if ch.gasVolume is not None: - entities.append(HmipEsiGasGasVolume(hap, device)) - - if ch.connectedEnergySensorType == ESI_CONNECTED_SENSOR_TYPE_LED: - if ch.currentPowerConsumption is not None: - entities.append(HmipEsiLedCurrentPowerConsumption(hap, device)) - entities.append(HmipEsiLedEnergyCounterHighTariff(hap, device)) - if isinstance( - device, - ( - FloorTerminalBlock6, - FloorTerminalBlock10, - FloorTerminalBlock12, - WiredFloorTerminalBlock12, - ), - ): - entities.extend( - HomematicipFloorTerminalBlockMechanicChannelValve( - hap, device, channel=channel.index - ) - for channel in device.functionalChannels - if isinstance(channel, FloorTerminalBlockMechanicChannel) - and getattr(channel, "valvePosition", None) is not None - ) + # Handle floor terminal blocks separately + floor_terminal_blocks = ( + FloorTerminalBlock6, + FloorTerminalBlock10, + FloorTerminalBlock12, + WiredFloorTerminalBlock12, + ) + entities.extend( + HomematicipFloorTerminalBlockMechanicChannelValve( + hap, device, channel=channel.index + ) + for device in hap.home.devices + if isinstance(device, floor_terminal_blocks) + for channel in device.functionalChannels + if isinstance(channel, FloorTerminalBlockMechanicChannel) + and getattr(channel, "valvePosition", None) is not None + ) async_add_entities(entities) +class HomematicipTiltAngleSensor(HomematicipGenericEntity, SensorEntity): + """Representation of the HomematicIP tilt angle sensor.""" + + _attr_native_unit_of_measurement = DEGREE + _attr_state_class = SensorStateClass.MEASUREMENT_ANGLE + + def __init__(self, hap: HomematicipHAP, device) -> None: + """Initialize the tilt angle sensor device.""" + super().__init__(hap, device, post="Tilt Angle") + + @property + def native_value(self) -> int | None: + """Return the state.""" + return getattr(self.functional_channel, "absoluteAngle", None) + + +class HomematicipTiltStateSensor(HomematicipGenericEntity, SensorEntity): + """Representation of the HomematicIP tilt sensor.""" + + _attr_device_class = SensorDeviceClass.ENUM + _attr_options = TILT_STATE_VALUES + _attr_translation_key = "tilt_state" + + def __init__(self, hap: HomematicipHAP, device) -> None: + """Initialize the tilt sensor device.""" + super().__init__(hap, device, post="Tilt State") + + @property + def native_value(self) -> str | None: + """Return the state.""" + tilt_state = getattr(self.functional_channel, "tiltState", None) + return tilt_state.lower() if tilt_state is not None else None + + @property + def extra_state_attributes(self) -> dict[str, Any]: + """Return the state attributes of the tilt sensor.""" + state_attr = super().extra_state_attributes + + state_attr[ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION] = getattr( + self.functional_channel, "accelerationSensorNeutralPosition", None + ) + state_attr[ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE] = getattr( + self.functional_channel, "accelerationSensorTriggerAngle", None + ) + state_attr[ATTR_ACCELERATION_SENSOR_SECOND_TRIGGER_ANGLE] = getattr( + self.functional_channel, "accelerationSensorSecondTriggerAngle", None + ) + + return state_attr + + class HomematicipFloorTerminalBlockMechanicChannelValve( HomematicipGenericEntity, SensorEntity ): diff --git a/homeassistant/components/homematicip_cloud/strings.json b/homeassistant/components/homematicip_cloud/strings.json index 7b1b08ac4e2..bc170d5f0c3 100644 --- a/homeassistant/components/homematicip_cloud/strings.json +++ b/homeassistant/components/homematicip_cloud/strings.json @@ -27,6 +27,17 @@ "already_configured": "[%key:common::config_flow::abort::already_configured_device%]" } }, + "entity": { + "sensor": { + "tilt_state": { + "state": { + "neutral": "Neutral", + "non_neutral": "Non-neutral", + "tilted": "Tilted" + } + } + } + }, "exceptions": { "access_point_not_found": { "message": "No matching access point found for access point ID {id}" diff --git a/homeassistant/components/html5/strings.json b/homeassistant/components/html5/strings.json index 2c68223581a..ee844f320bc 100644 --- a/homeassistant/components/html5/strings.json +++ b/homeassistant/components/html5/strings.json @@ -29,7 +29,7 @@ "services": { "dismiss": { "name": "Dismiss", - "description": "Dismisses a html5 notification.", + "description": "Dismisses an HTML5 notification.", "fields": { "target": { "name": "Target", diff --git a/homeassistant/components/http/__init__.py b/homeassistant/components/http/__init__.py index cdf3347e24f..f048d571b9c 100644 --- a/homeassistant/components/http/__init__.py +++ b/homeassistant/components/http/__init__.py @@ -37,12 +37,7 @@ from homeassistant.const import ( ) from homeassistant.core import Event, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError -from homeassistant.helpers import ( - config_validation as cv, - frame, - issue_registry as ir, - storage, -) +from homeassistant.helpers import config_validation as cv, issue_registry as ir, storage from homeassistant.helpers.http import ( KEY_ALLOW_CONFIGURED_CORS, KEY_AUTHENTICATED, # noqa: F401 @@ -505,25 +500,6 @@ class HomeAssistantHTTP: ) ) - def register_static_path( - self, url_path: str, path: str, cache_headers: bool = True - ) -> None: - """Register a folder or file to serve as a static path.""" - frame.report_usage( - "calls hass.http.register_static_path which " - "does blocking I/O in the event loop, instead " - "call `await hass.http.async_register_static_paths(" - f'[StaticPathConfig("{url_path}", "{path}", {cache_headers})])`', - exclude_integrations={"http"}, - core_behavior=frame.ReportBehavior.ERROR, - core_integration_behavior=frame.ReportBehavior.ERROR, - custom_integration_behavior=frame.ReportBehavior.ERROR, - breaks_in_ha_version="2025.7", - ) - configs = [StaticPathConfig(url_path, path, cache_headers)] - resources = self._make_static_resources(configs) - self._async_register_static_paths(configs, resources) - def _create_ssl_context(self) -> ssl.SSLContext | None: context: ssl.SSLContext | None = None assert self.ssl_certificate is not None diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py index 7e55191639b..71f3d54bef6 100644 --- a/homeassistant/components/http/ban.py +++ b/homeassistant/components/http/ban.py @@ -64,7 +64,7 @@ def setup_bans(hass: HomeAssistant, app: Application, login_threshold: int) -> N """Initialize bans when app starts up.""" await app[KEY_BAN_MANAGER].async_load() - app.on_startup.append(ban_startup) # type: ignore[arg-type] + app.on_startup.append(ban_startup) @middleware diff --git a/homeassistant/components/huawei_lte/__init__.py b/homeassistant/components/huawei_lte/__init__.py index 6126968eab6..56b7c5023f5 100644 --- a/homeassistant/components/huawei_lte/__init__.py +++ b/homeassistant/components/huawei_lte/__init__.py @@ -8,7 +8,6 @@ from contextlib import suppress from dataclasses import dataclass, field from datetime import timedelta import logging -import time from typing import Any, NamedTuple, cast from xml.parsers.expat import ExpatError @@ -58,6 +57,7 @@ from .const import ( ATTR_CONFIG_ENTRY_ID, CONF_MANUFACTURER, CONF_UNAUTHENTICATED_MODE, + CONF_UPNP_UDN, CONNECTION_TIMEOUT, DEFAULT_DEVICE_NAME, DEFAULT_MANUFACTURER, @@ -78,7 +78,6 @@ from .const import ( KEY_WLAN_HOST_LIST, KEY_WLAN_WIFI_FEATURE_SWITCH, KEY_WLAN_WIFI_GUEST_NETWORK_SWITCH, - NOTIFY_SUPPRESS_TIMEOUT, SERVICE_RESUME_INTEGRATION, SERVICE_SUSPEND_INTEGRATION, UPDATE_SIGNAL, @@ -124,7 +123,6 @@ class Router: inflight_gets: set[str] = field(default_factory=set, init=False) client: Client = field(init=False) suspended: bool = field(default=False, init=False) - notify_last_attempt: float = field(default=-1, init=False) def __post_init__(self) -> None: """Set up internal state on init.""" @@ -150,9 +148,12 @@ class Router: @property def device_connections(self) -> set[tuple[str, str]]: """Get router connections for device registry.""" - return { + connections = { (dr.CONNECTION_NETWORK_MAC, x) for x in self.config_entry.data[CONF_MAC] } + if udn := self.config_entry.data.get(CONF_UPNP_UDN): + connections.add((dr.CONNECTION_UPNP, udn)) + return connections def _get_data(self, key: str, func: Callable[[], Any]) -> None: if not self.subscriptions.get(key): @@ -195,19 +196,6 @@ class Router: key, ) self.subscriptions.pop(key) - except Timeout: - grace_left = ( - self.notify_last_attempt - time.monotonic() + NOTIFY_SUPPRESS_TIMEOUT - ) - if grace_left > 0: - _LOGGER.debug( - "%s timed out, %.1fs notify timeout suppress grace remaining", - key, - grace_left, - exc_info=True, - ) - else: - raise finally: self.inflight_gets.discard(key) _LOGGER.debug("%s=%s", key, self.data.get(key)) diff --git a/homeassistant/components/huawei_lte/config_flow.py b/homeassistant/components/huawei_lte/config_flow.py index f574441afed..002f19bc9e0 100644 --- a/homeassistant/components/huawei_lte/config_flow.py +++ b/homeassistant/components/huawei_lte/config_flow.py @@ -51,6 +51,7 @@ from .const import ( CONF_MANUFACTURER, CONF_TRACK_WIRED_CLIENTS, CONF_UNAUTHENTICATED_MODE, + CONF_UPNP_UDN, CONNECTION_TIMEOUT, DEFAULT_DEVICE_NAME, DEFAULT_NOTIFY_SERVICE_NAME, @@ -69,6 +70,7 @@ class HuaweiLteConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = 3 manufacturer: str | None = None + upnp_udn: str | None = None url: str | None = None @staticmethod @@ -250,6 +252,7 @@ class HuaweiLteConfigFlow(ConfigFlow, domain=DOMAIN): { CONF_MAC: get_device_macs(info, wlan_settings), CONF_MANUFACTURER: self.manufacturer, + CONF_UPNP_UDN: self.upnp_udn, } ) @@ -284,11 +287,12 @@ class HuaweiLteConfigFlow(ConfigFlow, domain=DOMAIN): # url_normalize only returns None if passed None, and we don't do that assert url is not None - unique_id = discovery_info.upnp.get( - ATTR_UPNP_SERIAL, discovery_info.upnp[ATTR_UPNP_UDN] - ) + upnp_udn = discovery_info.upnp.get(ATTR_UPNP_UDN) + unique_id = discovery_info.upnp.get(ATTR_UPNP_SERIAL, upnp_udn) await self.async_set_unique_id(unique_id) - self._abort_if_unique_id_configured(updates={CONF_URL: url}) + self._abort_if_unique_id_configured( + updates={CONF_UPNP_UDN: upnp_udn, CONF_URL: url} + ) def _is_supported_device() -> bool: """See if we are looking at a possibly supported device. @@ -319,6 +323,7 @@ class HuaweiLteConfigFlow(ConfigFlow, domain=DOMAIN): } ) self.manufacturer = discovery_info.upnp.get(ATTR_UPNP_MANUFACTURER) + self.upnp_udn = upnp_udn self.url = url return await self._async_show_user_form() diff --git a/homeassistant/components/huawei_lte/const.py b/homeassistant/components/huawei_lte/const.py index af9bfd330e9..b7662200767 100644 --- a/homeassistant/components/huawei_lte/const.py +++ b/homeassistant/components/huawei_lte/const.py @@ -7,6 +7,7 @@ ATTR_CONFIG_ENTRY_ID = "config_entry_id" CONF_MANUFACTURER = "manufacturer" CONF_TRACK_WIRED_CLIENTS = "track_wired_clients" CONF_UNAUTHENTICATED_MODE = "unauthenticated_mode" +CONF_UPNP_UDN = "upnp_udn" DEFAULT_DEVICE_NAME = "LTE" DEFAULT_MANUFACTURER = "Huawei Technologies Co., Ltd." @@ -17,7 +18,6 @@ DEFAULT_UNAUTHENTICATED_MODE = False UPDATE_SIGNAL = f"{DOMAIN}_update" CONNECTION_TIMEOUT = 10 -NOTIFY_SUPPRESS_TIMEOUT = 30 SERVICE_RESUME_INTEGRATION = "resume_integration" SERVICE_SUSPEND_INTEGRATION = "suspend_integration" diff --git a/homeassistant/components/huawei_lte/notify.py b/homeassistant/components/huawei_lte/notify.py index fc154de3811..682470bafd0 100644 --- a/homeassistant/components/huawei_lte/notify.py +++ b/homeassistant/components/huawei_lte/notify.py @@ -3,7 +3,6 @@ from __future__ import annotations import logging -import time from typing import Any from huawei_lte_api.exceptions import ResponseErrorException @@ -62,5 +61,3 @@ class HuaweiLteSmsNotificationService(BaseNotificationService): _LOGGER.debug("Sent to %s: %s", targets, resp) except ResponseErrorException as ex: _LOGGER.error("Could not send to %s: %s", targets, ex) - finally: - self.router.notify_last_attempt = time.monotonic() diff --git a/homeassistant/components/husqvarna_automower/coordinator.py b/homeassistant/components/husqvarna_automower/coordinator.py index 70af5219d04..342f6892b2e 100644 --- a/homeassistant/components/husqvarna_automower/coordinator.py +++ b/homeassistant/components/husqvarna_automower/coordinator.py @@ -60,15 +60,7 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): self._devices_last_update: set[str] = set() self._zones_last_update: dict[str, set[str]] = {} self._areas_last_update: dict[str, set[int]] = {} - - def _async_add_remove_devices_and_entities(self, data: MowerDictionary) -> None: - """Add/remove devices and dynamic entities, when amount of devices changed.""" - self._async_add_remove_devices(data) - for mower_id in data: - if data[mower_id].capabilities.stay_out_zones: - self._async_add_remove_stay_out_zones(data) - if data[mower_id].capabilities.work_areas: - self._async_add_remove_work_areas(data) + self.async_add_listener(self._on_data_update) async def _async_update_data(self) -> MowerDictionary: """Subscribe for websocket and poll data from the API.""" @@ -82,14 +74,38 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): raise UpdateFailed(err) from err except AuthError as err: raise ConfigEntryAuthFailed(err) from err - self._async_add_remove_devices_and_entities(data) return data + @callback + def _on_data_update(self) -> None: + """Handle data updates and process dynamic entity management.""" + if self.data is not None: + self._async_add_remove_devices() + for mower_id in self.data: + if self.data[mower_id].capabilities.stay_out_zones: + self._async_add_remove_stay_out_zones() + if self.data[mower_id].capabilities.work_areas: + self._async_add_remove_work_areas() + @callback def handle_websocket_updates(self, ws_data: MowerDictionary) -> None: """Process websocket callbacks and write them to the DataUpdateCoordinator.""" + self.hass.async_create_task(self._process_websocket_update(ws_data)) + + async def _process_websocket_update(self, ws_data: MowerDictionary) -> None: + """Handle incoming websocket update and update coordinator data.""" + for data in ws_data.values(): + existing_areas = data.work_areas or {} + for task in data.calendar.tasks: + work_area_id = task.work_area_id + if work_area_id is not None and work_area_id not in existing_areas: + _LOGGER.debug( + "New work area %s detected, refreshing data", work_area_id + ) + await self.async_request_refresh() + return + self.async_set_updated_data(ws_data) - self._async_add_remove_devices_and_entities(ws_data) @callback def async_set_updated_data(self, data: MowerDictionary) -> None: @@ -138,9 +154,9 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): "reconnect_task", ) - def _async_add_remove_devices(self, data: MowerDictionary) -> None: + def _async_add_remove_devices(self) -> None: """Add new device, remove non-existing device.""" - current_devices = set(data) + current_devices = set(self.data) # Skip update if no changes if current_devices == self._devices_last_update: @@ -155,7 +171,6 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): # Process new device new_devices = current_devices - self._devices_last_update if new_devices: - self.data = data _LOGGER.debug("New devices found: %s", ", ".join(map(str, new_devices))) self._add_new_devices(new_devices) @@ -179,11 +194,11 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): for mower_callback in self.new_devices_callbacks: mower_callback(new_devices) - def _async_add_remove_stay_out_zones(self, data: MowerDictionary) -> None: + def _async_add_remove_stay_out_zones(self) -> None: """Add new stay-out zones, remove non-existing stay-out zones.""" current_zones = { mower_id: set(mower_data.stay_out_zones.zones) - for mower_id, mower_data in data.items() + for mower_id, mower_data in self.data.items() if mower_data.capabilities.stay_out_zones and mower_data.stay_out_zones is not None } @@ -225,11 +240,11 @@ class AutomowerDataUpdateCoordinator(DataUpdateCoordinator[MowerDictionary]): return current_zones - def _async_add_remove_work_areas(self, data: MowerDictionary) -> None: + def _async_add_remove_work_areas(self) -> None: """Add new work areas, remove non-existing work areas.""" current_areas = { mower_id: set(mower_data.work_areas) - for mower_id, mower_data in data.items() + for mower_id, mower_data in self.data.items() if mower_data.capabilities.work_areas and mower_data.work_areas is not None } diff --git a/homeassistant/components/husqvarna_automower/manifest.json b/homeassistant/components/husqvarna_automower/manifest.json index 046c20c1ddd..fb717a5615f 100644 --- a/homeassistant/components/husqvarna_automower/manifest.json +++ b/homeassistant/components/husqvarna_automower/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_push", "loggers": ["aioautomower"], "quality_scale": "silver", - "requirements": ["aioautomower==1.2.0"] + "requirements": ["aioautomower==1.2.2"] } diff --git a/homeassistant/components/imgw_pib/icons.json b/homeassistant/components/imgw_pib/icons.json index 29aa19a4b56..b9226276af6 100644 --- a/homeassistant/components/imgw_pib/icons.json +++ b/homeassistant/components/imgw_pib/icons.json @@ -1,6 +1,9 @@ { "entity": { "sensor": { + "water_flow": { + "default": "mdi:waves-arrow-right" + }, "water_level": { "default": "mdi:waves" }, diff --git a/homeassistant/components/imgw_pib/manifest.json b/homeassistant/components/imgw_pib/manifest.json index 42d536da8f5..631bce3fbc9 100644 --- a/homeassistant/components/imgw_pib/manifest.json +++ b/homeassistant/components/imgw_pib/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/imgw_pib", "iot_class": "cloud_polling", "quality_scale": "silver", - "requirements": ["imgw_pib==1.1.0"] + "requirements": ["imgw_pib==1.2.0"] } diff --git a/homeassistant/components/imgw_pib/sensor.py b/homeassistant/components/imgw_pib/sensor.py index 7871006b2ae..1c49bfb2dc0 100644 --- a/homeassistant/components/imgw_pib/sensor.py +++ b/homeassistant/components/imgw_pib/sensor.py @@ -14,7 +14,7 @@ from homeassistant.components.sensor import ( SensorEntityDescription, SensorStateClass, ) -from homeassistant.const import UnitOfLength, UnitOfTemperature +from homeassistant.const import UnitOfLength, UnitOfTemperature, UnitOfVolumeFlowRate from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -36,6 +36,15 @@ class ImgwPibSensorEntityDescription(SensorEntityDescription): SENSOR_TYPES: tuple[ImgwPibSensorEntityDescription, ...] = ( + ImgwPibSensorEntityDescription( + key="water_flow", + translation_key="water_flow", + native_unit_of_measurement=UnitOfVolumeFlowRate.CUBIC_METERS_PER_SECOND, + device_class=SensorDeviceClass.VOLUME_FLOW_RATE, + state_class=SensorStateClass.MEASUREMENT, + suggested_display_precision=1, + value=lambda data: data.water_flow.value, + ), ImgwPibSensorEntityDescription( key="water_level", translation_key="water_level", diff --git a/homeassistant/components/imgw_pib/strings.json b/homeassistant/components/imgw_pib/strings.json index 9b7f132da6f..fc92ca573ab 100644 --- a/homeassistant/components/imgw_pib/strings.json +++ b/homeassistant/components/imgw_pib/strings.json @@ -21,6 +21,9 @@ }, "entity": { "sensor": { + "water_flow": { + "name": "Water flow" + }, "water_level": { "name": "Water level" }, diff --git a/homeassistant/components/immich/manifest.json b/homeassistant/components/immich/manifest.json index 80dcd87cd88..906356a4bc9 100644 --- a/homeassistant/components/immich/manifest.json +++ b/homeassistant/components/immich/manifest.json @@ -8,5 +8,5 @@ "iot_class": "local_polling", "loggers": ["aioimmich"], "quality_scale": "silver", - "requirements": ["aioimmich==0.10.1"] + "requirements": ["aioimmich==0.10.2"] } diff --git a/homeassistant/components/immich/update.py b/homeassistant/components/immich/update.py index 9955e355c96..e0af5c1c67f 100644 --- a/homeassistant/components/immich/update.py +++ b/homeassistant/components/immich/update.py @@ -44,7 +44,7 @@ class ImmichUpdateEntity(ImmichEntity, UpdateEntity): return self.coordinator.data.server_about.version @property - def latest_version(self) -> str: + def latest_version(self) -> str | None: """Available new immich server version.""" assert self.coordinator.data.server_version_check return self.coordinator.data.server_version_check.release_version diff --git a/homeassistant/components/integration/__init__.py b/homeassistant/components/integration/__init__.py index 0a64ce7140f..82f44578aed 100644 --- a/homeassistant/components/integration/__init__.py +++ b/homeassistant/components/integration/__init__.py @@ -2,6 +2,8 @@ from __future__ import annotations +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.const import Platform from homeassistant.core import HomeAssistant @@ -9,14 +11,20 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from .const import CONF_SOURCE_SENSOR +_LOGGER = logging.getLogger(__name__) + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Integration from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -29,20 +37,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_SOURCE_SENSOR: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_SOURCE_SENSOR] ), source_entity_id_or_uuid=entry.options[CONF_SOURCE_SENSOR], - source_entity_removed=source_entity_removed, ) ) @@ -51,6 +55,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the integration config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_SOURCE_SENSOR] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener, called when the config entry options are changed.""" # Remove device link for entry, the source device may have changed. diff --git a/homeassistant/components/integration/config_flow.py b/homeassistant/components/integration/config_flow.py index 28cd280f7f8..329abdbea87 100644 --- a/homeassistant/components/integration/config_flow.py +++ b/homeassistant/components/integration/config_flow.py @@ -147,6 +147,8 @@ OPTIONS_FLOW = { class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow for Integration.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW diff --git a/homeassistant/components/integration/sensor.py b/homeassistant/components/integration/sensor.py index df5342111a7..25181ac6149 100644 --- a/homeassistant/components/integration/sensor.py +++ b/homeassistant/components/integration/sensor.py @@ -40,8 +40,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import config_validation as cv, entity_registry as er -from homeassistant.helpers.device import async_device_info_to_link_from_entity -from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -246,11 +245,6 @@ async def async_setup_entry( registry, config_entry.options[CONF_SOURCE_SENSOR] ) - device_info = async_device_info_to_link_from_entity( - hass, - source_entity_id, - ) - if (unit_prefix := config_entry.options.get(CONF_UNIT_PREFIX)) == "none": # Before we had support for optional selectors, "none" was used for selecting nothing unit_prefix = None @@ -265,6 +259,7 @@ async def async_setup_entry( round_digits = int(round_digits) integral = IntegrationSensor( + hass, integration_method=config_entry.options[CONF_METHOD], name=config_entry.title, round_digits=round_digits, @@ -272,7 +267,6 @@ async def async_setup_entry( unique_id=config_entry.entry_id, unit_prefix=unit_prefix, unit_time=config_entry.options[CONF_UNIT_TIME], - device_info=device_info, max_sub_interval=max_sub_interval, ) @@ -287,6 +281,7 @@ async def async_setup_platform( ) -> None: """Set up the integration sensor.""" integral = IntegrationSensor( + hass, integration_method=config[CONF_METHOD], name=config.get(CONF_NAME), round_digits=config.get(CONF_ROUND_DIGITS), @@ -308,6 +303,7 @@ class IntegrationSensor(RestoreSensor): def __init__( self, + hass: HomeAssistant, *, integration_method: str, name: str | None, @@ -317,7 +313,6 @@ class IntegrationSensor(RestoreSensor): unit_prefix: str | None, unit_time: UnitOfTime, max_sub_interval: timedelta | None, - device_info: DeviceInfo | None = None, ) -> None: """Initialize the integration sensor.""" self._attr_unique_id = unique_id @@ -335,7 +330,10 @@ class IntegrationSensor(RestoreSensor): self._attr_icon = "mdi:chart-histogram" self._source_entity: str = source_entity self._last_valid_state: Decimal | None = None - self._attr_device_info = device_info + self.device_entry = async_entity_id_to_device( + hass, + source_entity, + ) self._max_sub_interval: timedelta | None = ( None # disable time based integration if max_sub_interval is None or max_sub_interval.total_seconds() == 0 diff --git a/homeassistant/components/iskra/strings.json b/homeassistant/components/iskra/strings.json index da7817cc78b..ee62974c90d 100644 --- a/homeassistant/components/iskra/strings.json +++ b/homeassistant/components/iskra/strings.json @@ -88,16 +88,16 @@ "name": "Phase 3 current" }, "non_resettable_counter_1": { - "name": "Non Resettable counter 1" + "name": "Non-resettable counter 1" }, "non_resettable_counter_2": { - "name": "Non Resettable counter 2" + "name": "Non-resettable counter 2" }, "non_resettable_counter_3": { - "name": "Non Resettable counter 3" + "name": "Non-resettable counter 3" }, "non_resettable_counter_4": { - "name": "Non Resettable counter 4" + "name": "Non-resettable counter 4" }, "resettable_counter_1": { "name": "Resettable counter 1" diff --git a/homeassistant/components/jewish_calendar/binary_sensor.py b/homeassistant/components/jewish_calendar/binary_sensor.py index 79b49050cc2..d5097df962f 100644 --- a/homeassistant/components/jewish_calendar/binary_sensor.py +++ b/homeassistant/components/jewish_calendar/binary_sensor.py @@ -13,8 +13,7 @@ from homeassistant.components.binary_sensor import ( BinarySensorEntityDescription, ) from homeassistant.const import EntityCategory -from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback -from homeassistant.helpers import event +from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util @@ -23,36 +22,29 @@ from .entity import JewishCalendarConfigEntry, JewishCalendarEntity PARALLEL_UPDATES = 0 -@dataclass(frozen=True) -class JewishCalendarBinarySensorMixIns(BinarySensorEntityDescription): - """Binary Sensor description mixin class for Jewish Calendar.""" - - is_on: Callable[[Zmanim, dt.datetime], bool] = lambda _, __: False - - -@dataclass(frozen=True) -class JewishCalendarBinarySensorEntityDescription( - JewishCalendarBinarySensorMixIns, BinarySensorEntityDescription -): +@dataclass(frozen=True, kw_only=True) +class JewishCalendarBinarySensorEntityDescription(BinarySensorEntityDescription): """Binary Sensor Entity description for Jewish Calendar.""" + is_on: Callable[[Zmanim], Callable[[dt.datetime], bool]] + BINARY_SENSORS: tuple[JewishCalendarBinarySensorEntityDescription, ...] = ( JewishCalendarBinarySensorEntityDescription( key="issur_melacha_in_effect", translation_key="issur_melacha_in_effect", - is_on=lambda state, now: bool(state.issur_melacha_in_effect(now)), + is_on=lambda state: state.issur_melacha_in_effect, ), JewishCalendarBinarySensorEntityDescription( key="erev_shabbat_hag", translation_key="erev_shabbat_hag", - is_on=lambda state, now: bool(state.erev_shabbat_chag(now)), + is_on=lambda state: state.erev_shabbat_chag, entity_registry_enabled_default=False, ), JewishCalendarBinarySensorEntityDescription( key="motzei_shabbat_hag", translation_key="motzei_shabbat_hag", - is_on=lambda state, now: bool(state.motzei_shabbat_chag(now)), + is_on=lambda state: state.motzei_shabbat_chag, entity_registry_enabled_default=False, ), ) @@ -73,9 +65,7 @@ async def async_setup_entry( class JewishCalendarBinarySensor(JewishCalendarEntity, BinarySensorEntity): """Representation of an Jewish Calendar binary sensor.""" - _attr_should_poll = False _attr_entity_category = EntityCategory.DIAGNOSTIC - _update_unsub: CALLBACK_TYPE | None = None entity_description: JewishCalendarBinarySensorEntityDescription @@ -83,40 +73,12 @@ class JewishCalendarBinarySensor(JewishCalendarEntity, BinarySensorEntity): def is_on(self) -> bool: """Return true if sensor is on.""" zmanim = self.make_zmanim(dt.date.today()) - return self.entity_description.is_on(zmanim, dt_util.now()) + return self.entity_description.is_on(zmanim)(dt_util.now()) - async def async_added_to_hass(self) -> None: - """Run when entity about to be added to hass.""" - await super().async_added_to_hass() - self._schedule_update() - - async def async_will_remove_from_hass(self) -> None: - """Run when entity will be removed from hass.""" - if self._update_unsub: - self._update_unsub() - self._update_unsub = None - return await super().async_will_remove_from_hass() - - @callback - def _update(self, now: dt.datetime | None = None) -> None: - """Update the state of the sensor.""" - self._update_unsub = None - self._schedule_update() - self.async_write_ha_state() - - def _schedule_update(self) -> None: - """Schedule the next update of the sensor.""" - now = dt_util.now() - zmanim = self.make_zmanim(dt.date.today()) - update = zmanim.netz_hachama.local + dt.timedelta(days=1) - candle_lighting = zmanim.candle_lighting - if candle_lighting is not None and now < candle_lighting < update: - update = candle_lighting - havdalah = zmanim.havdalah - if havdalah is not None and now < havdalah < update: - update = havdalah - if self._update_unsub: - self._update_unsub() - self._update_unsub = event.async_track_point_in_time( - self.hass, self._update, update - ) + def _update_times(self, zmanim: Zmanim) -> list[dt.datetime | None]: + """Return a list of times to update the sensor.""" + return [ + zmanim.netz_hachama.local + dt.timedelta(days=1), + zmanim.candle_lighting, + zmanim.havdalah, + ] diff --git a/homeassistant/components/jewish_calendar/entity.py b/homeassistant/components/jewish_calendar/entity.py index b92d30048f0..d5e41129075 100644 --- a/homeassistant/components/jewish_calendar/entity.py +++ b/homeassistant/components/jewish_calendar/entity.py @@ -1,17 +1,24 @@ """Entity representing a Jewish Calendar sensor.""" +from abc import abstractmethod from dataclasses import dataclass import datetime as dt +import logging from hdate import HDateInfo, Location, Zmanim from hdate.translator import Language, set_language from homeassistant.config_entries import ConfigEntry +from homeassistant.core import CALLBACK_TYPE, callback +from homeassistant.helpers import event from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo from homeassistant.helpers.entity import Entity, EntityDescription +from homeassistant.util import dt as dt_util from .const import DOMAIN +_LOGGER = logging.getLogger(__name__) + type JewishCalendarConfigEntry = ConfigEntry[JewishCalendarData] @@ -19,9 +26,7 @@ type JewishCalendarConfigEntry = ConfigEntry[JewishCalendarData] class JewishCalendarDataResults: """Jewish Calendar results dataclass.""" - daytime_date: HDateInfo - after_shkia_date: HDateInfo - after_tzais_date: HDateInfo + dateinfo: HDateInfo zmanim: Zmanim @@ -41,6 +46,8 @@ class JewishCalendarEntity(Entity): """An HA implementation for Jewish Calendar entity.""" _attr_has_entity_name = True + _attr_should_poll = False + _update_unsub: CALLBACK_TYPE | None = None def __init__( self, @@ -65,3 +72,55 @@ class JewishCalendarEntity(Entity): candle_lighting_offset=self.data.candle_lighting_offset, havdalah_offset=self.data.havdalah_offset, ) + + async def async_added_to_hass(self) -> None: + """Call when entity is added to hass.""" + await super().async_added_to_hass() + self._schedule_update() + + async def async_will_remove_from_hass(self) -> None: + """Run when entity will be removed from hass.""" + if self._update_unsub: + self._update_unsub() + self._update_unsub = None + return await super().async_will_remove_from_hass() + + @abstractmethod + def _update_times(self, zmanim: Zmanim) -> list[dt.datetime | None]: + """Return a list of times to update the sensor.""" + + def _schedule_update(self) -> None: + """Schedule the next update of the sensor.""" + now = dt_util.now() + zmanim = self.make_zmanim(now.date()) + update = dt_util.start_of_local_day() + dt.timedelta(days=1) + + for update_time in self._update_times(zmanim): + if update_time is not None and now < update_time < update: + update = update_time + + if self._update_unsub: + self._update_unsub() + self._update_unsub = event.async_track_point_in_time( + self.hass, self._update, update + ) + + @callback + def _update(self, now: dt.datetime | None = None) -> None: + """Update the sensor data.""" + self._update_unsub = None + self._schedule_update() + self.create_results(now) + self.async_write_ha_state() + + def create_results(self, now: dt.datetime | None = None) -> None: + """Create the results for the sensor.""" + if now is None: + now = dt_util.now() + + _LOGGER.debug("Now: %s Location: %r", now, self.data.location) + + today = now.date() + zmanim = self.make_zmanim(today) + dateinfo = HDateInfo(today, diaspora=self.data.diaspora) + self.data.results = JewishCalendarDataResults(dateinfo, zmanim) diff --git a/homeassistant/components/jewish_calendar/sensor.py b/homeassistant/components/jewish_calendar/sensor.py index 91c618e1c1c..d9ad89237f5 100644 --- a/homeassistant/components/jewish_calendar/sensor.py +++ b/homeassistant/components/jewish_calendar/sensor.py @@ -16,17 +16,12 @@ from homeassistant.components.sensor import ( SensorEntity, SensorEntityDescription, ) -from homeassistant.const import SUN_EVENT_SUNSET, EntityCategory +from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from homeassistant.helpers.sun import get_astral_event_date from homeassistant.util import dt as dt_util -from .entity import ( - JewishCalendarConfigEntry, - JewishCalendarDataResults, - JewishCalendarEntity, -) +from .entity import JewishCalendarConfigEntry, JewishCalendarEntity _LOGGER = logging.getLogger(__name__) PARALLEL_UPDATES = 0 @@ -37,15 +32,19 @@ class JewishCalendarBaseSensorDescription(SensorEntityDescription): """Base class describing Jewish Calendar sensor entities.""" value_fn: Callable | None + next_update_fn: Callable[[Zmanim], dt.datetime | None] | None @dataclass(frozen=True, kw_only=True) class JewishCalendarSensorDescription(JewishCalendarBaseSensorDescription): """Class describing Jewish Calendar sensor entities.""" - value_fn: Callable[[JewishCalendarDataResults], str | int] - attr_fn: Callable[[JewishCalendarDataResults], dict[str, str]] | None = None + value_fn: Callable[[HDateInfo], str | int] + attr_fn: Callable[[HDateInfo], dict[str, str]] | None = None options_fn: Callable[[bool], list[str]] | None = None + next_update_fn: Callable[[Zmanim], dt.datetime | None] | None = ( + lambda zmanim: zmanim.shkia.local + ) @dataclass(frozen=True, kw_only=True) @@ -55,17 +54,18 @@ class JewishCalendarTimestampSensorDescription(JewishCalendarBaseSensorDescripti value_fn: ( Callable[[HDateInfo, Callable[[dt.date], Zmanim]], dt.datetime | None] | None ) = None + next_update_fn: Callable[[Zmanim], dt.datetime | None] | None = None INFO_SENSORS: tuple[JewishCalendarSensorDescription, ...] = ( JewishCalendarSensorDescription( key="date", translation_key="hebrew_date", - value_fn=lambda results: str(results.after_shkia_date.hdate), - attr_fn=lambda results: { - "hebrew_year": str(results.after_shkia_date.hdate.year), - "hebrew_month_name": str(results.after_shkia_date.hdate.month), - "hebrew_day": str(results.after_shkia_date.hdate.day), + value_fn=lambda info: str(info.hdate), + attr_fn=lambda info: { + "hebrew_year": str(info.hdate.year), + "hebrew_month_name": str(info.hdate.month), + "hebrew_day": str(info.hdate.day), }, ), JewishCalendarSensorDescription( @@ -73,24 +73,19 @@ INFO_SENSORS: tuple[JewishCalendarSensorDescription, ...] = ( translation_key="weekly_portion", device_class=SensorDeviceClass.ENUM, options_fn=lambda _: [str(p) for p in Parasha], - value_fn=lambda results: results.after_tzais_date.upcoming_shabbat.parasha, + value_fn=lambda info: info.upcoming_shabbat.parasha, + next_update_fn=lambda zmanim: zmanim.havdalah, ), JewishCalendarSensorDescription( key="holiday", translation_key="holiday", device_class=SensorDeviceClass.ENUM, options_fn=lambda diaspora: HolidayDatabase(diaspora).get_all_names(), - value_fn=lambda results: ", ".join( - str(holiday) for holiday in results.after_shkia_date.holidays - ), - attr_fn=lambda results: { - "id": ", ".join( - holiday.name for holiday in results.after_shkia_date.holidays - ), + value_fn=lambda info: ", ".join(str(holiday) for holiday in info.holidays), + attr_fn=lambda info: { + "id": ", ".join(holiday.name for holiday in info.holidays), "type": ", ".join( - dict.fromkeys( - _holiday.type.name for _holiday in results.after_shkia_date.holidays - ) + dict.fromkeys(_holiday.type.name for _holiday in info.holidays) ), }, ), @@ -98,13 +93,13 @@ INFO_SENSORS: tuple[JewishCalendarSensorDescription, ...] = ( key="omer_count", translation_key="omer_count", entity_registry_enabled_default=False, - value_fn=lambda results: results.after_shkia_date.omer.total_days, + value_fn=lambda info: info.omer.total_days, ), JewishCalendarSensorDescription( key="daf_yomi", translation_key="daf_yomi", entity_registry_enabled_default=False, - value_fn=lambda results: results.daytime_date.daf_yomi, + value_fn=lambda info: info.daf_yomi, ), ) @@ -184,12 +179,14 @@ TIME_SENSORS: tuple[JewishCalendarTimestampSensorDescription, ...] = ( value_fn=lambda at_date, mz: mz( at_date.upcoming_shabbat.previous_day.gdate ).candle_lighting, + next_update_fn=lambda zmanim: zmanim.havdalah, ), JewishCalendarTimestampSensorDescription( key="upcoming_shabbat_havdalah", translation_key="upcoming_shabbat_havdalah", entity_registry_enabled_default=False, value_fn=lambda at_date, mz: mz(at_date.upcoming_shabbat.gdate).havdalah, + next_update_fn=lambda zmanim: zmanim.havdalah, ), JewishCalendarTimestampSensorDescription( key="upcoming_candle_lighting", @@ -197,6 +194,7 @@ TIME_SENSORS: tuple[JewishCalendarTimestampSensorDescription, ...] = ( value_fn=lambda at_date, mz: mz( at_date.upcoming_shabbat_or_yom_tov.first_day.previous_day.gdate ).candle_lighting, + next_update_fn=lambda zmanim: zmanim.havdalah, ), JewishCalendarTimestampSensorDescription( key="upcoming_havdalah", @@ -204,6 +202,7 @@ TIME_SENSORS: tuple[JewishCalendarTimestampSensorDescription, ...] = ( value_fn=lambda at_date, mz: mz( at_date.upcoming_shabbat_or_yom_tov.last_day.gdate ).havdalah, + next_update_fn=lambda zmanim: zmanim.havdalah, ), ) @@ -213,7 +212,7 @@ async def async_setup_entry( config_entry: JewishCalendarConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: - """Set up the Jewish calendar sensors .""" + """Set up the Jewish calendar sensors.""" sensors: list[JewishCalendarBaseSensor] = [ JewishCalendarSensor(config_entry, description) for description in INFO_SENSORS ] @@ -229,44 +228,33 @@ class JewishCalendarBaseSensor(JewishCalendarEntity, SensorEntity): _attr_entity_category = EntityCategory.DIAGNOSTIC - async def async_update(self) -> None: - """Update the state of the sensor.""" - now = dt_util.now() - _LOGGER.debug("Now: %s Location: %r", now, self.data.location) + entity_description: JewishCalendarBaseSensorDescription + + def _update_times(self, zmanim: Zmanim) -> list[dt.datetime | None]: + """Return a list of times to update the sensor.""" + if self.entity_description.next_update_fn is None: + return [] + return [self.entity_description.next_update_fn(zmanim)] + + def get_dateinfo(self, now: dt.datetime | None = None) -> HDateInfo: + """Get the next date info.""" + if self.data.results is None: + self.create_results() + assert self.data.results is not None, "Results should be available" + + if now is None: + now = dt_util.now() today = now.date() - event_date = get_astral_event_date(self.hass, SUN_EVENT_SUNSET, today) + zmanim = self.make_zmanim(today) + update = None + if self.entity_description.next_update_fn: + update = self.entity_description.next_update_fn(zmanim) - if event_date is None: - _LOGGER.error("Can't get sunset event date for %s", today) - return - - sunset = dt_util.as_local(event_date) - - _LOGGER.debug("Now: %s Sunset: %s", now, sunset) - - daytime_date = HDateInfo(today, diaspora=self.data.diaspora) - - # The Jewish day starts after darkness (called "tzais") and finishes at - # sunset ("shkia"). The time in between is a gray area - # (aka "Bein Hashmashot" # codespell:ignore - # - literally: "in between the sun and the moon"). - - # For some sensors, it is more interesting to consider the date to be - # tomorrow based on sunset ("shkia"), for others based on "tzais". - # Hence the following variables. - after_tzais_date = after_shkia_date = daytime_date - today_times = self.make_zmanim(today) - - if now > sunset: - after_shkia_date = daytime_date.next_day - - if today_times.havdalah and now > today_times.havdalah: - after_tzais_date = daytime_date.next_day - - self.data.results = JewishCalendarDataResults( - daytime_date, after_shkia_date, after_tzais_date, today_times - ) + _LOGGER.debug("Today: %s, update: %s", today, update) + if update is not None and now >= update: + return self.data.results.dateinfo.next_day + return self.data.results.dateinfo class JewishCalendarSensor(JewishCalendarBaseSensor): @@ -288,18 +276,14 @@ class JewishCalendarSensor(JewishCalendarBaseSensor): @property def native_value(self) -> str | int | dt.datetime | None: """Return the state of the sensor.""" - if self.data.results is None: - return None - return self.entity_description.value_fn(self.data.results) + return self.entity_description.value_fn(self.get_dateinfo()) @property def extra_state_attributes(self) -> dict[str, str]: """Return the state attributes.""" - if self.data.results is None: + if self.entity_description.attr_fn is None: return {} - if self.entity_description.attr_fn is not None: - return self.entity_description.attr_fn(self.data.results) - return {} + return self.entity_description.attr_fn(self.get_dateinfo()) class JewishCalendarTimeSensor(JewishCalendarBaseSensor): @@ -312,9 +296,8 @@ class JewishCalendarTimeSensor(JewishCalendarBaseSensor): def native_value(self) -> dt.datetime | None: """Return the state of the sensor.""" if self.data.results is None: - return None + self.create_results() + assert self.data.results is not None, "Results should be available" if self.entity_description.value_fn is None: return self.data.results.zmanim.zmanim[self.entity_description.key].local - return self.entity_description.value_fn( - self.data.results.after_tzais_date, self.make_zmanim - ) + return self.entity_description.value_fn(self.get_dateinfo(), self.make_zmanim) diff --git a/homeassistant/components/jewish_calendar/services.py b/homeassistant/components/jewish_calendar/services.py index 6fdebe6f74d..f77f9be4e64 100644 --- a/homeassistant/components/jewish_calendar/services.py +++ b/homeassistant/components/jewish_calendar/services.py @@ -50,7 +50,6 @@ def async_setup_services(hass: HomeAssistant) -> None: today = now.date() event_date = get_astral_event_date(hass, SUN_EVENT_SUNSET, today) if event_date is None: - _LOGGER.error("Can't get sunset event date for %s", today) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="sunset_event" ) diff --git a/homeassistant/components/keymitt_ble/manifest.json b/homeassistant/components/keymitt_ble/manifest.json index 5abdfe5b4a7..7b1e133bb6e 100644 --- a/homeassistant/components/keymitt_ble/manifest.json +++ b/homeassistant/components/keymitt_ble/manifest.json @@ -13,8 +13,8 @@ "config_flow": true, "dependencies": ["bluetooth_adapters"], "documentation": "https://www.home-assistant.io/integrations/keymitt_ble", - "integration_type": "hub", + "integration_type": "device", "iot_class": "assumed_state", - "loggers": ["keymitt_ble"], - "requirements": ["PyMicroBot==0.0.17"] + "loggers": ["keymitt_ble", "microbot"], + "requirements": ["PyMicroBot==0.0.23"] } diff --git a/homeassistant/components/knx/__init__.py b/homeassistant/components/knx/__init__.py index 470f7891292..6fa4c8146ba 100644 --- a/homeassistant/components/knx/__init__.py +++ b/homeassistant/components/knx/__init__.py @@ -1,34 +1,17 @@ -"""Support KNX devices.""" +"""The KNX integration.""" from __future__ import annotations import contextlib -import logging from pathlib import Path from typing import Final import voluptuous as vol -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, XKNXException -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 xknx.exceptions import XKNXException from homeassistant.config_entries import ConfigEntry -from homeassistant.const import ( - CONF_EVENT, - CONF_HOST, - CONF_PORT, - CONF_TYPE, - EVENT_HOMEASSISTANT_STOP, - Platform, -) -from homeassistant.core import Event, HomeAssistant +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.reload import async_integration_yaml_config @@ -36,40 +19,17 @@ from homeassistant.helpers.storage import STORAGE_DIR from homeassistant.helpers.typing import ConfigType from .const import ( - CONF_KNX_CONNECTION_TYPE, CONF_KNX_EXPOSE, - 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, DATA_HASS_CONFIG, DOMAIN, - KNX_ADDRESS, KNX_MODULE_KEY, SUPPORTED_PLATFORMS_UI, SUPPORTED_PLATFORMS_YAML, - TELEGRAM_LOG_DEFAULT, ) -from .device import KNXInterfaceDevice -from .expose import KNXExposeSensor, KNXExposeTime, create_knx_exposure -from .project import STORAGE_KEY as PROJECT_STORAGE_KEY, KNXProject +from .expose import create_knx_exposure +from .knx_module import KNXModule +from .project import STORAGE_KEY as PROJECT_STORAGE_KEY from .schema import ( BinarySensorSchema, ButtonSchema, @@ -92,12 +52,10 @@ from .schema import ( WeatherSchema, ) from .services import async_setup_services -from .storage.config_store import STORAGE_KEY as CONFIG_STORAGE_KEY, KNXConfigStore -from .telegrams import STORAGE_KEY as TELEGRAMS_STORAGE_KEY, Telegrams +from .storage.config_store import STORAGE_KEY as CONFIG_STORAGE_KEY +from .telegrams import STORAGE_KEY as TELEGRAMS_STORAGE_KEY from .websocket import register_panel -_LOGGER = logging.getLogger(__name__) - _KNX_YAML_CONFIG: Final = "knx_yaml_config" CONFIG_SCHEMA = vol.Schema( @@ -162,6 +120,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: hass.data[KNX_MODULE_KEY] = knx_module + entry.async_on_unload(entry.add_update_listener(async_update_entry)) + if CONF_KNX_EXPOSE in config: for expose_config in config[CONF_KNX_EXPOSE]: knx_module.exposures.append( @@ -255,243 +215,3 @@ async def async_remove_config_entry_device( if entity.device_id == device_entry.id: await knx_module.config_store.delete_entity(entity.entity_id) return True - - -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.exposures: list[KNXExposeSensor | KNXExposeTime] = [] - self.service_exposures: dict[str, KNXExposeSensor | KNXExposeTime] = {} - 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.knx_event_callback: TelegramQueue.Callback = self.register_event_callback() - - self.entry.async_on_unload( - self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, self.stop) - ) - self.entry.async_on_unload(self.entry.add_update_listener(async_update_entry)) - - 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 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, - ) diff --git a/homeassistant/components/knx/binary_sensor.py b/homeassistant/components/knx/binary_sensor.py index 1bad8bafdf0..947d382a12c 100644 --- a/homeassistant/components/knx/binary_sensor.py +++ b/homeassistant/components/knx/binary_sensor.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP binary sensors.""" +"""Support for KNX binary sensor entities.""" from __future__ import annotations @@ -25,7 +25,6 @@ from homeassistant.helpers.entity_platform import ( from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import ( ATTR_COUNTER, ATTR_SOURCE, @@ -39,6 +38,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxUiEntity, KnxUiEntityPlatformController, KnxYamlEntity +from .knx_module import KNXModule from .storage.const import CONF_ENTITY, CONF_GA_SENSOR from .storage.util import ConfigExtractor diff --git a/homeassistant/components/knx/button.py b/homeassistant/components/knx/button.py index 538299a0556..2c2baa3a218 100644 --- a/homeassistant/components/knx/button.py +++ b/homeassistant/components/knx/button.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP buttons.""" +"""Support for KNX button entities.""" from __future__ import annotations @@ -11,9 +11,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import CONF_PAYLOAD_LENGTH, KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/climate.py b/homeassistant/components/knx/climate.py index fdce5e0c470..f59d48de629 100644 --- a/homeassistant/components/knx/climate.py +++ b/homeassistant/components/knx/climate.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP climate devices.""" +"""Support for KNX climate entities.""" from __future__ import annotations @@ -37,9 +37,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import CONTROLLER_MODES, CURRENT_HVAC_ACTIONS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import ClimateSchema ATTR_COMMAND_VALUE = "command_value" diff --git a/homeassistant/components/knx/const.py b/homeassistant/components/knx/const.py index 3ce79b4ca7a..dbc02f08245 100644 --- a/homeassistant/components/knx/const.py +++ b/homeassistant/components/knx/const.py @@ -14,7 +14,7 @@ from homeassistant.const import Platform from homeassistant.util.hass_dict import HassKey if TYPE_CHECKING: - from . import KNXModule + from .knx_module import KNXModule DOMAIN: Final = "knx" KNX_MODULE_KEY: HassKey[KNXModule] = HassKey(DOMAIN) diff --git a/homeassistant/components/knx/cover.py b/homeassistant/components/knx/cover.py index f5d482b9d14..ef7084661f1 100644 --- a/homeassistant/components/knx/cover.py +++ b/homeassistant/components/knx/cover.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP covers.""" +"""Support for KNX cover entities.""" from __future__ import annotations @@ -28,9 +28,9 @@ from homeassistant.helpers.entity_platform import ( ) from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import CONF_SYNC_STATE, DOMAIN, KNX_MODULE_KEY, CoverConf from .entity import KnxUiEntity, KnxUiEntityPlatformController, KnxYamlEntity +from .knx_module import KNXModule from .schema import CoverSchema from .storage.const import ( CONF_ENTITY, diff --git a/homeassistant/components/knx/date.py b/homeassistant/components/knx/date.py index 7980e6a2bc3..a4fc8d276bc 100644 --- a/homeassistant/components/knx/date.py +++ b/homeassistant/components/knx/date.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP date.""" +"""Support for KNX date entities.""" from __future__ import annotations @@ -22,7 +22,6 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import ( CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, @@ -31,6 +30,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/datetime.py b/homeassistant/components/knx/datetime.py index 7701597a8ef..04d04527241 100644 --- a/homeassistant/components/knx/datetime.py +++ b/homeassistant/components/knx/datetime.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP datetime.""" +"""Support for KNX datetime entities.""" from __future__ import annotations @@ -23,7 +23,6 @@ from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType from homeassistant.util import dt as dt_util -from . import KNXModule from .const import ( CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, @@ -32,6 +31,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/device.py b/homeassistant/components/knx/device.py index b43b5926d86..44fa7163360 100644 --- a/homeassistant/components/knx/device.py +++ b/homeassistant/components/knx/device.py @@ -1,4 +1,4 @@ -"""Handle KNX Devices.""" +"""Handle Home Assistant Devices for the KNX integration.""" from __future__ import annotations diff --git a/homeassistant/components/knx/device_trigger.py b/homeassistant/components/knx/device_trigger.py index 2eb1f86e7fc..e4a48c9c68d 100644 --- a/homeassistant/components/knx/device_trigger.py +++ b/homeassistant/components/knx/device_trigger.py @@ -1,4 +1,4 @@ -"""Provides device triggers for KNX.""" +"""Provide device triggers for KNX.""" from __future__ import annotations diff --git a/homeassistant/components/knx/diagnostics.py b/homeassistant/components/knx/diagnostics.py index 974a6b3b448..6d523dda0f5 100644 --- a/homeassistant/components/knx/diagnostics.py +++ b/homeassistant/components/knx/diagnostics.py @@ -1,4 +1,4 @@ -"""Diagnostics support for KNX.""" +"""Diagnostics support for the KNX integration.""" from __future__ import annotations diff --git a/homeassistant/components/knx/entity.py b/homeassistant/components/knx/entity.py index a042c2b4c6b..c4379bcf869 100644 --- a/homeassistant/components/knx/entity.py +++ b/homeassistant/components/knx/entity.py @@ -1,4 +1,4 @@ -"""Base class for KNX devices.""" +"""Base classes for KNX entities.""" from __future__ import annotations @@ -17,7 +17,7 @@ from .storage.config_store import PlatformControllerBase from .storage.const import CONF_DEVICE_INFO if TYPE_CHECKING: - from . import KNXModule + from .knx_module import KNXModule class KnxUiEntityPlatformController(PlatformControllerBase): diff --git a/homeassistant/components/knx/expose.py b/homeassistant/components/knx/expose.py index 461e6f25879..0a42b6018ba 100644 --- a/homeassistant/components/knx/expose.py +++ b/homeassistant/components/knx/expose.py @@ -1,4 +1,4 @@ -"""Exposures to KNX bus.""" +"""Expose Home Assistant entity states to KNX.""" from __future__ import annotations diff --git a/homeassistant/components/knx/fan.py b/homeassistant/components/knx/fan.py index 926b6458706..23f25dc8469 100644 --- a/homeassistant/components/knx/fan.py +++ b/homeassistant/components/knx/fan.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP fans.""" +"""Support for KNX fan entities.""" from __future__ import annotations @@ -19,9 +19,9 @@ from homeassistant.util.percentage import ( ) from homeassistant.util.scaling import int_states_in_range -from . import KNXModule from .const import KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import FanSchema DEFAULT_PERCENTAGE: Final = 50 diff --git a/homeassistant/components/knx/knx_module.py b/homeassistant/components/knx/knx_module.py new file mode 100644 index 00000000000..8974cad1baa --- /dev/null +++ b/homeassistant/components/knx/knx_module.py @@ -0,0 +1,301 @@ +"""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 KNXExposeSensor, KNXExposeTime +from .project import KNXProject +from .storage.config_store import KNXConfigStore +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.exposures: list[KNXExposeSensor | KNXExposeTime] = [] + self.service_exposures: dict[str, KNXExposeSensor | KNXExposeTime] = {} + 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.knx_event_callback: TelegramQueue.Callback = self.register_event_callback() + + 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 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, + ) diff --git a/homeassistant/components/knx/light.py b/homeassistant/components/knx/light.py index ff0f4538089..cbecb878e12 100644 --- a/homeassistant/components/knx/light.py +++ b/homeassistant/components/knx/light.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP lights.""" +"""Support for KNX light entities.""" from __future__ import annotations @@ -28,9 +28,9 @@ from homeassistant.helpers.entity_platform import ( from homeassistant.helpers.typing import ConfigType from homeassistant.util import color as color_util -from . import KNXModule from .const import CONF_SYNC_STATE, DOMAIN, KNX_ADDRESS, KNX_MODULE_KEY, ColorTempModes from .entity import KnxUiEntity, KnxUiEntityPlatformController, KnxYamlEntity +from .knx_module import KNXModule from .schema import LightSchema from .storage.const import ( CONF_COLOR_TEMP_MAX, diff --git a/homeassistant/components/knx/notify.py b/homeassistant/components/knx/notify.py index 97980ab3d36..d64bac80d9d 100644 --- a/homeassistant/components/knx/notify.py +++ b/homeassistant/components/knx/notify.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP notifications.""" +"""Support for KNX notify entities.""" from __future__ import annotations @@ -12,9 +12,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/number.py b/homeassistant/components/knx/number.py index 67e8778accc..30efb5e01ee 100644 --- a/homeassistant/components/knx/number.py +++ b/homeassistant/components/knx/number.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP numeric values.""" +"""Support for KNX number entities.""" from __future__ import annotations @@ -22,9 +22,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import NumberSchema diff --git a/homeassistant/components/knx/scene.py b/homeassistant/components/knx/scene.py index f5361a6e7da..39e627ca8ff 100644 --- a/homeassistant/components/knx/scene.py +++ b/homeassistant/components/knx/scene.py @@ -1,4 +1,4 @@ -"""Support for KNX scenes.""" +"""Support for KNX scene entities.""" from __future__ import annotations @@ -13,9 +13,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import SceneSchema diff --git a/homeassistant/components/knx/select.py b/homeassistant/components/knx/select.py index e80fa66f9d4..0dc2584876d 100644 --- a/homeassistant/components/knx/select.py +++ b/homeassistant/components/knx/select.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP select entities.""" +"""Support for KNX select entities.""" from __future__ import annotations @@ -20,7 +20,6 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import ( CONF_PAYLOAD_LENGTH, CONF_RESPOND_TO_READ, @@ -30,6 +29,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import SelectSchema diff --git a/homeassistant/components/knx/sensor.py b/homeassistant/components/knx/sensor.py index 8e537ea234e..e75d1f180e2 100644 --- a/homeassistant/components/knx/sensor.py +++ b/homeassistant/components/knx/sensor.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP sensors.""" +"""Support for KNX sensor entities.""" from __future__ import annotations @@ -33,9 +33,9 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType, StateType from homeassistant.util.enum import try_parse_enum -from . import KNXModule from .const import ATTR_SOURCE, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import SensorSchema SCAN_INTERVAL = timedelta(seconds=10) diff --git a/homeassistant/components/knx/services.py b/homeassistant/components/knx/services.py index 04803e140fd..f63612f97ef 100644 --- a/homeassistant/components/knx/services.py +++ b/homeassistant/components/knx/services.py @@ -35,7 +35,7 @@ from .expose import create_knx_exposure from .schema import ExposeSchema, dpt_base_type_validator, ga_validator if TYPE_CHECKING: - from . import KNXModule + from .knx_module import KNXModule _LOGGER = logging.getLogger(__name__) diff --git a/homeassistant/components/knx/storage/__init__.py b/homeassistant/components/knx/storage/__init__.py index 25d84406d03..a588a3d154e 100644 --- a/homeassistant/components/knx/storage/__init__.py +++ b/homeassistant/components/knx/storage/__init__.py @@ -1 +1 @@ -"""Helpers for KNX.""" +"""Handle persistent storage for the KNX integration.""" diff --git a/homeassistant/components/knx/storage/entity_store_validation.py b/homeassistant/components/knx/storage/entity_store_validation.py index 9bad5297853..1da7b58378d 100644 --- a/homeassistant/components/knx/storage/entity_store_validation.py +++ b/homeassistant/components/knx/storage/entity_store_validation.py @@ -1,4 +1,4 @@ -"""KNX Entity Store Validation.""" +"""KNX entity store validation.""" from typing import Literal, TypedDict diff --git a/homeassistant/components/knx/switch.py b/homeassistant/components/knx/switch.py index 5a01457d8d3..4d6ca288dc6 100644 --- a/homeassistant/components/knx/switch.py +++ b/homeassistant/components/knx/switch.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP switches.""" +"""Support for KNX switch entities.""" from __future__ import annotations @@ -25,7 +25,6 @@ from homeassistant.helpers.entity_platform import ( from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import ( CONF_INVERT, CONF_RESPOND_TO_READ, @@ -35,6 +34,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxUiEntity, KnxUiEntityPlatformController, KnxYamlEntity +from .knx_module import KNXModule from .schema import SwitchSchema from .storage.const import CONF_ENTITY, CONF_GA_SWITCH from .storage.util import ConfigExtractor diff --git a/homeassistant/components/knx/text.py b/homeassistant/components/knx/text.py index 9c2bb88f92b..14c9af11ad3 100644 --- a/homeassistant/components/knx/text.py +++ b/homeassistant/components/knx/text.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP text.""" +"""Support for KNX text entities.""" from __future__ import annotations @@ -22,9 +22,9 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, KNX_ADDRESS, KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/time.py b/homeassistant/components/knx/time.py index 2c74ab18af3..3bc171cae31 100644 --- a/homeassistant/components/knx/time.py +++ b/homeassistant/components/knx/time.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP time.""" +"""Support for KNX time entities.""" from __future__ import annotations @@ -22,7 +22,6 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.restore_state import RestoreEntity from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import ( CONF_RESPOND_TO_READ, CONF_STATE_ADDRESS, @@ -31,6 +30,7 @@ from .const import ( KNX_MODULE_KEY, ) from .entity import KnxYamlEntity +from .knx_module import KNXModule async def async_setup_entry( diff --git a/homeassistant/components/knx/trigger.py b/homeassistant/components/knx/trigger.py index ae3ba088357..ba8bfff5d3b 100644 --- a/homeassistant/components/knx/trigger.py +++ b/homeassistant/components/knx/trigger.py @@ -1,4 +1,4 @@ -"""Offer knx telegram automation triggers.""" +"""Provide KNX automation triggers.""" from typing import Final diff --git a/homeassistant/components/knx/weather.py b/homeassistant/components/knx/weather.py index 342ab445611..e8f0036f5bb 100644 --- a/homeassistant/components/knx/weather.py +++ b/homeassistant/components/knx/weather.py @@ -1,4 +1,4 @@ -"""Support for KNX/IP weather station.""" +"""Support for KNX weather entities.""" from __future__ import annotations @@ -19,9 +19,9 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import ConfigType -from . import KNXModule from .const import KNX_MODULE_KEY from .entity import KnxYamlEntity +from .knx_module import KNXModule from .schema import WeatherSchema diff --git a/homeassistant/components/knx/websocket.py b/homeassistant/components/knx/websocket.py index 9ba3e0ccff6..31c5e8297e0 100644 --- a/homeassistant/components/knx/websocket.py +++ b/homeassistant/components/knx/websocket.py @@ -36,7 +36,7 @@ from .storage.entity_store_validation import ( from .telegrams import SIGNAL_KNX_TELEGRAM, TelegramDict if TYPE_CHECKING: - from . import KNXModule + from .knx_module import KNXModule URL_BASE: Final = "/knx_static" diff --git a/homeassistant/components/lamarzocco/__init__.py b/homeassistant/components/lamarzocco/__init__.py index ff977438f38..2d68b3be345 100644 --- a/homeassistant/components/lamarzocco/__init__.py +++ b/homeassistant/components/lamarzocco/__init__.py @@ -23,7 +23,7 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady from homeassistant.helpers import issue_registry as ir -from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.aiohttp_client import async_create_clientsession from .const import CONF_USE_BLUETOOTH, DOMAIN from .coordinator import ( @@ -57,11 +57,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: LaMarzoccoConfigEntry) - assert entry.unique_id serial = entry.unique_id - client = async_get_clientsession(hass) cloud_client = LaMarzoccoCloudClient( username=entry.data[CONF_USERNAME], password=entry.data[CONF_PASSWORD], - client=client, + client=async_create_clientsession(hass), ) try: diff --git a/homeassistant/components/lamarzocco/binary_sensor.py b/homeassistant/components/lamarzocco/binary_sensor.py index 4fc2c0b05df..afbb779b696 100644 --- a/homeassistant/components/lamarzocco/binary_sensor.py +++ b/homeassistant/components/lamarzocco/binary_sensor.py @@ -66,7 +66,7 @@ ENTITIES: tuple[LaMarzoccoBinarySensorEntityDescription, ...] = ( WidgetType.CM_BACK_FLUSH, BackFlush(status=BackFlushStatus.OFF) ), ).status - is BackFlushStatus.REQUESTED + in (BackFlushStatus.REQUESTED, BackFlushStatus.CLEANING) ), entity_category=EntityCategory.DIAGNOSTIC, supported_fn=lambda coordinator: ( diff --git a/homeassistant/components/lamarzocco/config_flow.py b/homeassistant/components/lamarzocco/config_flow.py index 8cb2e4dfc61..e352e337d0b 100644 --- a/homeassistant/components/lamarzocco/config_flow.py +++ b/homeassistant/components/lamarzocco/config_flow.py @@ -33,7 +33,7 @@ from homeassistant.const import ( ) from homeassistant.core import callback from homeassistant.helpers import config_validation as cv -from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.selector import ( SelectOptionDict, SelectSelector, @@ -83,7 +83,7 @@ class LmConfigFlow(ConfigFlow, domain=DOMAIN): **user_input, } - self._client = async_get_clientsession(self.hass) + self._client = async_create_clientsession(self.hass) cloud_client = LaMarzoccoCloudClient( username=data[CONF_USERNAME], password=data[CONF_PASSWORD], diff --git a/homeassistant/components/lamarzocco/manifest.json b/homeassistant/components/lamarzocco/manifest.json index 10cb23146ae..3c070769b5b 100644 --- a/homeassistant/components/lamarzocco/manifest.json +++ b/homeassistant/components/lamarzocco/manifest.json @@ -37,5 +37,5 @@ "iot_class": "cloud_push", "loggers": ["pylamarzocco"], "quality_scale": "platinum", - "requirements": ["pylamarzocco==2.0.10"] + "requirements": ["pylamarzocco==2.0.11"] } diff --git a/homeassistant/components/lifx/const.py b/homeassistant/components/lifx/const.py index ecc572aa006..f0505f9a4fd 100644 --- a/homeassistant/components/lifx/const.py +++ b/homeassistant/components/lifx/const.py @@ -70,6 +70,7 @@ INFRARED_BRIGHTNESS_VALUES_MAP = { } LIFX_CEILING_PRODUCT_IDS = {176, 177, 201, 202} +LIFX_128ZONE_CEILING_PRODUCT_IDS = {201, 202} _LOGGER = logging.getLogger(__package__) diff --git a/homeassistant/components/lifx/coordinator.py b/homeassistant/components/lifx/coordinator.py index 79ce843b339..c96f53d8f77 100644 --- a/homeassistant/components/lifx/coordinator.py +++ b/homeassistant/components/lifx/coordinator.py @@ -41,6 +41,7 @@ from .const import ( DEFAULT_ATTEMPTS, DOMAIN, IDENTIFY_WAVEFORM, + LIFX_128ZONE_CEILING_PRODUCT_IDS, MAX_ATTEMPTS_PER_UPDATE_REQUEST_MESSAGE, MAX_UPDATE_TIME, MESSAGE_RETRIES, @@ -183,6 +184,11 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]): """Return true if this is a matrix device.""" return bool(lifx_features(self.device)["matrix"]) + @cached_property + def is_128zone_matrix(self) -> bool: + """Return true if this is a 128-zone matrix device.""" + return bool(self.device.product in LIFX_128ZONE_CEILING_PRODUCT_IDS) + async def diagnostics(self) -> dict[str, Any]: """Return diagnostic information about the device.""" features = lifx_features(self.device) @@ -216,6 +222,16 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]): "last_result": self.device.last_hev_cycle_result, } + if features["matrix"] is True: + device_data["matrix"] = { + "effect": self.device.effect, + "chain": self.device.chain, + "chain_length": self.device.chain_length, + "tile_devices": self.device.tile_devices, + "tile_devices_count": self.device.tile_devices_count, + "tile_device_width": self.device.tile_device_width, + } + if features["infrared"] is True: device_data["infrared"] = {"brightness": self.device.infrared_brightness} @@ -291,6 +307,37 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]): return calls + @callback + def _async_build_get64_update_requests(self) -> list[Callable]: + """Build one or more get64 update requests.""" + if self.device.tile_device_width == 0: + return [] + + calls: list[Callable] = [] + calls.append( + partial( + self.device.get64, + tile_index=0, + length=1, + x=0, + y=0, + width=self.device.tile_device_width, + ) + ) + if self.is_128zone_matrix: + # For 128-zone ceiling devices, we need another get64 request for the next set of zones + calls.append( + partial( + self.device.get64, + tile_index=0, + length=1, + x=0, + y=4, + width=self.device.tile_device_width, + ) + ) + return calls + async def _async_update_data(self) -> None: """Fetch all device data from the api.""" device = self.device @@ -312,9 +359,9 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]): [ self.device.get_tile_effect, self.device.get_device_chain, - self.device.get64, ] ) + methods.extend(self._async_build_get64_update_requests()) if self.is_extended_multizone: methods.append(self.device.get_extended_color_zones) elif self.is_legacy_multizone: @@ -339,6 +386,7 @@ class LIFXUpdateCoordinator(DataUpdateCoordinator[None]): if self.is_matrix or self.is_extended_multizone or self.is_legacy_multizone: self.active_effect = FirmwareEffect[self.device.effect.get("effect", "OFF")] + if self.is_legacy_multizone and num_zones != self.get_number_of_zones(): # The number of zones has changed so we need # to update the zones again. This happens rarely. diff --git a/homeassistant/components/lifx/manifest.json b/homeassistant/components/lifx/manifest.json index b93714a2cdf..3c755779846 100644 --- a/homeassistant/components/lifx/manifest.json +++ b/homeassistant/components/lifx/manifest.json @@ -52,7 +52,7 @@ "iot_class": "local_polling", "loggers": ["aiolifx", "aiolifx_effects", "bitstring"], "requirements": [ - "aiolifx==1.1.5", + "aiolifx==1.2.1", "aiolifx-effects==0.3.2", "aiolifx-themes==0.6.4" ] diff --git a/homeassistant/components/linkplay/const.py b/homeassistant/components/linkplay/const.py index 74b87f4aae9..ec85e5af97c 100644 --- a/homeassistant/components/linkplay/const.py +++ b/homeassistant/components/linkplay/const.py @@ -19,5 +19,5 @@ class LinkPlaySharedData: DOMAIN = "linkplay" SHARED_DATA = "shared_data" SHARED_DATA_KEY: HassKey[LinkPlaySharedData] = HassKey(SHARED_DATA) -PLATFORMS = [Platform.BUTTON, Platform.MEDIA_PLAYER] +PLATFORMS = [Platform.BUTTON, Platform.MEDIA_PLAYER, Platform.SELECT] DATA_SESSION = "session" diff --git a/homeassistant/components/linkplay/icons.json b/homeassistant/components/linkplay/icons.json index c0fe86d9ac7..26f7202943f 100644 --- a/homeassistant/components/linkplay/icons.json +++ b/homeassistant/components/linkplay/icons.json @@ -4,6 +4,11 @@ "timesync": { "default": "mdi:clock" } + }, + "select": { + "audio_output_hardware_mode": { + "default": "mdi:transit-connection-horizontal" + } } }, "services": { diff --git a/homeassistant/components/linkplay/media_player.py b/homeassistant/components/linkplay/media_player.py index 89cc498ed01..ee1cdfe67e8 100644 --- a/homeassistant/components/linkplay/media_player.py +++ b/homeassistant/components/linkplay/media_player.py @@ -4,7 +4,7 @@ from __future__ import annotations from datetime import timedelta import logging -from typing import Any +from typing import TYPE_CHECKING, Any from linkplay.bridge import LinkPlayBridge from linkplay.consts import EqualizerMode, LoopMode, PlayingMode, PlayingStatus @@ -315,14 +315,19 @@ class LinkPlayMediaPlayerEntity(LinkPlayBaseEntity, MediaPlayerEntity): return [] shared_data = self.hass.data[DOMAIN][SHARED_DATA] + leader_id: str | None = None + followers = [] - return [ - entity_id - for entity_id, bridge in shared_data.entity_to_bridge.items() - if bridge - in [multiroom.leader.device.uuid] - + [follower.device.uuid for follower in multiroom.followers] - ] + # find leader and followers + for ent_id, uuid in shared_data.entity_to_bridge.items(): + if uuid == multiroom.leader.device.uuid: + leader_id = ent_id + elif uuid in {f.device.uuid for f in multiroom.followers}: + followers.append(ent_id) + + if TYPE_CHECKING: + assert leader_id is not None + return [leader_id, *followers] @property def media_image_url(self) -> str | None: diff --git a/homeassistant/components/linkplay/select.py b/homeassistant/components/linkplay/select.py new file mode 100644 index 00000000000..ebf5a05512a --- /dev/null +++ b/homeassistant/components/linkplay/select.py @@ -0,0 +1,112 @@ +"""Support for LinkPlay select.""" + +from __future__ import annotations + +from collections.abc import Awaitable, Callable, Coroutine +from dataclasses import dataclass +import logging +from typing import Any + +from linkplay.bridge import LinkPlayBridge, LinkPlayPlayer +from linkplay.consts import AudioOutputHwMode +from linkplay.manufacturers import MANUFACTURER_WIIM + +from homeassistant.components.select import SelectEntity, SelectEntityDescription +from homeassistant.core import HomeAssistant +from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback + +from . import LinkPlayConfigEntry +from .entity import LinkPlayBaseEntity, exception_wrap + +_LOGGER = logging.getLogger(__name__) + +AUDIO_OUTPUT_HW_MODE_MAP: dict[AudioOutputHwMode, str] = { + AudioOutputHwMode.OPTICAL: "optical", + AudioOutputHwMode.LINE_OUT: "line_out", + AudioOutputHwMode.COAXIAL: "coaxial", + AudioOutputHwMode.HEADPHONES: "headphones", +} + +AUDIO_OUTPUT_HW_MODE_MAP_INV: dict[str, AudioOutputHwMode] = { + v: k for k, v in AUDIO_OUTPUT_HW_MODE_MAP.items() +} + + +async def _get_current_option(bridge: LinkPlayBridge) -> str: + """Get the current hardware mode.""" + modes = await bridge.player.get_audio_output_hw_mode() + return AUDIO_OUTPUT_HW_MODE_MAP[modes.hardware] + + +@dataclass(frozen=True, kw_only=True) +class LinkPlaySelectEntityDescription(SelectEntityDescription): + """Class describing LinkPlay select entities.""" + + set_option_fn: Callable[[LinkPlayPlayer, str], Coroutine[Any, Any, None]] + current_option_fn: Callable[[LinkPlayPlayer], Awaitable[str]] + + +SELECT_TYPES_WIIM: tuple[LinkPlaySelectEntityDescription, ...] = ( + LinkPlaySelectEntityDescription( + key="audio_output_hardware_mode", + translation_key="audio_output_hardware_mode", + current_option_fn=_get_current_option, + set_option_fn=( + lambda linkplay_bridge, + option: linkplay_bridge.player.set_audio_output_hw_mode( + AUDIO_OUTPUT_HW_MODE_MAP_INV[option] + ) + ), + options=list(AUDIO_OUTPUT_HW_MODE_MAP_INV), + ), +) + + +async def async_setup_entry( + hass: HomeAssistant, + config_entry: LinkPlayConfigEntry, + async_add_entities: AddConfigEntryEntitiesCallback, +) -> None: + """Set up the LinkPlay select from config entry.""" + + # add entities + if config_entry.runtime_data.bridge.device.manufacturer == MANUFACTURER_WIIM: + async_add_entities( + LinkPlaySelect(config_entry.runtime_data.bridge, description) + for description in SELECT_TYPES_WIIM + ) + + +class LinkPlaySelect(LinkPlayBaseEntity, SelectEntity): + """Representation of LinkPlay select.""" + + entity_description: LinkPlaySelectEntityDescription + + def __init__( + self, + bridge: LinkPlayPlayer, + description: LinkPlaySelectEntityDescription, + ) -> None: + """Initialize LinkPlay select.""" + super().__init__(bridge) + self.entity_description = description + self._attr_unique_id = f"{bridge.device.uuid}-{description.key}" + + async def async_update(self) -> None: + """Get the current value from the device.""" + try: + # modes = await self.entity_description.current_option_fn(self._bridge) + self._attr_current_option = await self.entity_description.current_option_fn( + self._bridge + ) + + except ValueError as ex: + _LOGGER.debug( + "Cannot retrieve hardware mode value from device with error:, %s", ex + ) + self._attr_current_option = None + + @exception_wrap + async def async_select_option(self, option: str) -> None: + """Set the option.""" + await self.entity_description.set_option_fn(self._bridge, option) diff --git a/homeassistant/components/linkplay/strings.json b/homeassistant/components/linkplay/strings.json index 5d68754879c..7b0a6cbefe1 100644 --- a/homeassistant/components/linkplay/strings.json +++ b/homeassistant/components/linkplay/strings.json @@ -40,6 +40,17 @@ "timesync": { "name": "Sync time" } + }, + "select": { + "audio_output_hardware_mode": { + "name": "Audio output hardware mode", + "state": { + "optical": "Optical", + "line_out": "Line out", + "coaxial": "Coaxial", + "headphones": "Headphones" + } + } } }, "exceptions": { diff --git a/homeassistant/components/litterrobot/coordinator.py b/homeassistant/components/litterrobot/coordinator.py index c99d4794ff6..581257ab2db 100644 --- a/homeassistant/components/litterrobot/coordinator.py +++ b/homeassistant/components/litterrobot/coordinator.py @@ -48,6 +48,9 @@ class LitterRobotDataUpdateCoordinator(DataUpdateCoordinator[None]): """Update all device states from the Litter-Robot API.""" await self.account.refresh_robots() await self.account.load_pets() + for pet in self.account.pets: + # Need to fetch weight history for `get_visits_since` + await pet.fetch_weight_history() async def _async_setup(self) -> None: """Set up the coordinator.""" diff --git a/homeassistant/components/litterrobot/icons.json b/homeassistant/components/litterrobot/icons.json index 2e0cafe43d9..86a95b59b18 100644 --- a/homeassistant/components/litterrobot/icons.json +++ b/homeassistant/components/litterrobot/icons.json @@ -49,6 +49,9 @@ }, "total_cycles": { "default": "mdi:counter" + }, + "visits_today": { + "default": "mdi:counter" } }, "switch": { diff --git a/homeassistant/components/litterrobot/manifest.json b/homeassistant/components/litterrobot/manifest.json index a8945e482bf..33addd85ba2 100644 --- a/homeassistant/components/litterrobot/manifest.json +++ b/homeassistant/components/litterrobot/manifest.json @@ -13,5 +13,5 @@ "iot_class": "cloud_push", "loggers": ["pylitterbot"], "quality_scale": "bronze", - "requirements": ["pylitterbot==2024.2.1"] + "requirements": ["pylitterbot==2024.2.2"] } diff --git a/homeassistant/components/litterrobot/sensor.py b/homeassistant/components/litterrobot/sensor.py index b7ddf3c3249..aa7c3a451be 100644 --- a/homeassistant/components/litterrobot/sensor.py +++ b/homeassistant/components/litterrobot/sensor.py @@ -18,6 +18,7 @@ from homeassistant.components.sensor import ( from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfMass from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.util import dt as dt_util from .coordinator import LitterRobotConfigEntry from .entity import LitterRobotEntity, _WhiskerEntityT @@ -39,6 +40,7 @@ class RobotSensorEntityDescription(SensorEntityDescription, Generic[_WhiskerEnti """A class that describes robot sensor entities.""" icon_fn: Callable[[Any], str | None] = lambda _: None + last_reset_fn: Callable[[], datetime | None] = lambda: None value_fn: Callable[[_WhiskerEntityT], float | datetime | str | None] @@ -179,7 +181,14 @@ PET_SENSORS: list[RobotSensorEntityDescription] = [ native_unit_of_measurement=UnitOfMass.POUNDS, state_class=SensorStateClass.MEASUREMENT, value_fn=lambda pet: pet.weight, - ) + ), + RobotSensorEntityDescription[Pet]( + key="visits_today", + translation_key="visits_today", + state_class=SensorStateClass.TOTAL, + last_reset_fn=dt_util.start_of_local_day, + value_fn=lambda pet: pet.get_visits_since(dt_util.start_of_local_day()), + ), ] @@ -225,3 +234,8 @@ class LitterRobotSensorEntity(LitterRobotEntity[_WhiskerEntityT], SensorEntity): if (icon := self.entity_description.icon_fn(self.state)) is not None: return icon return super().icon + + @property + def last_reset(self) -> datetime | None: + """Return the time when the sensor was last reset, if any.""" + return self.entity_description.last_reset_fn() or super().last_reset diff --git a/homeassistant/components/litterrobot/strings.json b/homeassistant/components/litterrobot/strings.json index 160f5edb6a0..35aff0f9105 100644 --- a/homeassistant/components/litterrobot/strings.json +++ b/homeassistant/components/litterrobot/strings.json @@ -122,6 +122,10 @@ "name": "Total cycles", "unit_of_measurement": "cycles" }, + "visits_today": { + "name": "Visits today", + "unit_of_measurement": "visits" + }, "waste_drawer": { "name": "Waste drawer" } diff --git a/homeassistant/components/matter/number.py b/homeassistant/components/matter/number.py index c948f39834a..ea348c20012 100644 --- a/homeassistant/components/matter/number.py +++ b/homeassistant/components/matter/number.py @@ -339,4 +339,36 @@ DISCOVERY_SCHEMAS = [ clusters.TemperatureControl.Attributes.MaxTemperature, ), ), + MatterDiscoverySchema( + platform=Platform.NUMBER, + entity_description=MatterNumberEntityDescription( + key="InovelliLEDIndicatorIntensityOff", + entity_category=EntityCategory.CONFIG, + translation_key="led_indicator_intensity_off", + native_max_value=75, + native_min_value=0, + native_step=1, + mode=NumberMode.BOX, + ), + entity_class=MatterNumber, + required_attributes=( + custom_clusters.InovelliCluster.Attributes.LEDIndicatorIntensityOff, + ), + ), + MatterDiscoverySchema( + platform=Platform.NUMBER, + entity_description=MatterNumberEntityDescription( + key="InovelliLEDIndicatorIntensityOn", + entity_category=EntityCategory.CONFIG, + translation_key="led_indicator_intensity_on", + native_max_value=75, + native_min_value=0, + native_step=1, + mode=NumberMode.BOX, + ), + entity_class=MatterNumber, + required_attributes=( + custom_clusters.InovelliCluster.Attributes.LEDIndicatorIntensityOn, + ), + ), ] diff --git a/homeassistant/components/matter/sensor.py b/homeassistant/components/matter/sensor.py index f563c246186..9e2ef33167b 100644 --- a/homeassistant/components/matter/sensor.py +++ b/homeassistant/components/matter/sensor.py @@ -1140,6 +1140,18 @@ DISCOVERY_SCHEMAS = [ entity_class=MatterSensor, required_attributes=(clusters.EnergyEvse.Attributes.UserMaximumChargeCurrent,), ), + MatterDiscoverySchema( + platform=Platform.SENSOR, + entity_description=MatterSensorEntityDescription( + key="EnergyEvseStateOfCharge", + translation_key="evse_soc", + native_unit_of_measurement=PERCENTAGE, + device_class=SensorDeviceClass.BATTERY, + state_class=SensorStateClass.MEASUREMENT, + ), + entity_class=MatterSensor, + required_attributes=(clusters.EnergyEvse.Attributes.StateOfCharge,), + ), MatterDiscoverySchema( platform=Platform.SENSOR, entity_description=MatterSensorEntityDescription( diff --git a/homeassistant/components/matter/strings.json b/homeassistant/components/matter/strings.json index f7cec270f54..20d7eb69ba4 100644 --- a/homeassistant/components/matter/strings.json +++ b/homeassistant/components/matter/strings.json @@ -194,6 +194,12 @@ }, "auto_relock_timer": { "name": "Autorelock time" + }, + "led_indicator_intensity_off": { + "name": "LED off intensity" + }, + "led_indicator_intensity_on": { + "name": "LED on intensity" } }, "light": { @@ -402,6 +408,9 @@ "other": "Other fault" } }, + "evse_soc": { + "name": "State of charge" + }, "pump_control_mode": { "name": "Control mode", "state": { diff --git a/homeassistant/components/mealie/manifest.json b/homeassistant/components/mealie/manifest.json index d90e979582e..0aa9aa86847 100644 --- a/homeassistant/components/mealie/manifest.json +++ b/homeassistant/components/mealie/manifest.json @@ -6,5 +6,6 @@ "documentation": "https://www.home-assistant.io/integrations/mealie", "integration_type": "service", "iot_class": "local_polling", + "quality_scale": "silver", "requirements": ["aiomealie==0.9.6"] } diff --git a/homeassistant/components/miele/config_flow.py b/homeassistant/components/miele/config_flow.py index d3c7dbba12b..191cd9a0454 100644 --- a/homeassistant/components/miele/config_flow.py +++ b/homeassistant/components/miele/config_flow.py @@ -26,14 +26,6 @@ class OAuth2FlowHandler( """Return logger.""" return logging.getLogger(__name__) - @property - def extra_authorize_data(self) -> dict: - """Extra data that needs to be appended to the authorize url.""" - # "vg" is mandatory but the value doesn't seem to matter - return { - "vg": "sv-SE", - } - async def async_step_reauth( self, entry_data: Mapping[str, Any] ) -> ConfigFlowResult: diff --git a/homeassistant/components/mqtt/config_flow.py b/homeassistant/components/mqtt/config_flow.py index ee451b5f81d..a3cf2d1d12f 100644 --- a/homeassistant/components/mqtt/config_flow.py +++ b/homeassistant/components/mqtt/config_flow.py @@ -2114,6 +2114,9 @@ def data_schema_from_fields( if schema_section is None: data_schema.update(data_schema_element) continue + if not data_schema_element: + # Do not show empty sections + continue collapsed = ( not any( (default := data_schema_fields[str(option)].default) is vol.UNDEFINED diff --git a/homeassistant/components/mqtt/entity.py b/homeassistant/components/mqtt/entity.py index 338779f32cb..f1594a7b034 100644 --- a/homeassistant/components/mqtt/entity.py +++ b/homeassistant/components/mqtt/entity.py @@ -389,16 +389,6 @@ def async_setup_entity_entry_helper( _async_setup_entities() -def init_entity_id_from_config( - hass: HomeAssistant, entity: Entity, config: ConfigType, entity_id_format: str -) -> None: - """Set entity_id from object_id if defined in config.""" - if CONF_OBJECT_ID in config: - entity.entity_id = async_generate_entity_id( - entity_id_format, config[CONF_OBJECT_ID], None, hass - ) - - class MqttAttributesMixin(Entity): """Mixin used for platforms that support JSON attributes.""" @@ -1312,6 +1302,7 @@ class MqttEntity( _attr_should_poll = False _default_name: str | None _entity_id_format: str + _update_registry_entity_id: str | None = None def __init__( self, @@ -1346,13 +1337,33 @@ class MqttEntity( def _init_entity_id(self) -> None: """Set entity_id from object_id if defined in config.""" - init_entity_id_from_config( - self.hass, self, self._config, self._entity_id_format + if CONF_OBJECT_ID not in self._config: + return + self.entity_id = async_generate_entity_id( + self._entity_id_format, self._config[CONF_OBJECT_ID], None, self.hass ) + if self.unique_id is None: + return + # Check for previous deleted entities + entity_registry = er.async_get(self.hass) + entity_platform = self._entity_id_format.split(".")[0] + if ( + deleted_entry := entity_registry.deleted_entities.get( + (entity_platform, DOMAIN, self.unique_id) + ) + ) and deleted_entry.entity_id != self.entity_id: + # Plan to update the entity_id basis on `object_id` if a deleted entity was found + self._update_registry_entity_id = self.entity_id @final async def async_added_to_hass(self) -> None: """Subscribe to MQTT events.""" + if self._update_registry_entity_id is not None: + entity_registry = er.async_get(self.hass) + entity_registry.async_update_entity( + self.entity_id, new_entity_id=self._update_registry_entity_id + ) + await super().async_added_to_hass() self._subscriptions = {} self._prepare_subscribe_topics() diff --git a/homeassistant/components/mystrom/manifest.json b/homeassistant/components/mystrom/manifest.json index eaf9eb6acdc..c5a981dbf46 100644 --- a/homeassistant/components/mystrom/manifest.json +++ b/homeassistant/components/mystrom/manifest.json @@ -7,5 +7,5 @@ "documentation": "https://www.home-assistant.io/integrations/mystrom", "iot_class": "local_polling", "loggers": ["pymystrom"], - "requirements": ["python-mystrom==2.2.0"] + "requirements": ["python-mystrom==2.4.0"] } diff --git a/homeassistant/components/nextdns/__init__.py b/homeassistant/components/nextdns/__init__.py index eb8bd26cb9b..acc9504988d 100644 --- a/homeassistant/components/nextdns/__init__.py +++ b/homeassistant/components/nextdns/__init__.py @@ -4,7 +4,6 @@ from __future__ import annotations import asyncio from dataclasses import dataclass -from datetime import timedelta from aiohttp.client_exceptions import ClientConnectorError from nextdns import ( @@ -37,9 +36,6 @@ from .const import ( ATTR_STATUS, CONF_PROFILE_ID, DOMAIN, - UPDATE_INTERVAL_ANALYTICS, - UPDATE_INTERVAL_CONNECTION, - UPDATE_INTERVAL_SETTINGS, ) from .coordinator import ( NextDnsConnectionUpdateCoordinator, @@ -69,14 +65,14 @@ class NextDnsData: PLATFORMS = [Platform.BINARY_SENSOR, Platform.BUTTON, Platform.SENSOR, Platform.SWITCH] -COORDINATORS: list[tuple[str, type[NextDnsUpdateCoordinator], timedelta]] = [ - (ATTR_CONNECTION, NextDnsConnectionUpdateCoordinator, UPDATE_INTERVAL_CONNECTION), - (ATTR_DNSSEC, NextDnsDnssecUpdateCoordinator, UPDATE_INTERVAL_ANALYTICS), - (ATTR_ENCRYPTION, NextDnsEncryptionUpdateCoordinator, UPDATE_INTERVAL_ANALYTICS), - (ATTR_IP_VERSIONS, NextDnsIpVersionsUpdateCoordinator, UPDATE_INTERVAL_ANALYTICS), - (ATTR_PROTOCOLS, NextDnsProtocolsUpdateCoordinator, UPDATE_INTERVAL_ANALYTICS), - (ATTR_SETTINGS, NextDnsSettingsUpdateCoordinator, UPDATE_INTERVAL_SETTINGS), - (ATTR_STATUS, NextDnsStatusUpdateCoordinator, UPDATE_INTERVAL_ANALYTICS), +COORDINATORS: list[tuple[str, type[NextDnsUpdateCoordinator]]] = [ + (ATTR_CONNECTION, NextDnsConnectionUpdateCoordinator), + (ATTR_DNSSEC, NextDnsDnssecUpdateCoordinator), + (ATTR_ENCRYPTION, NextDnsEncryptionUpdateCoordinator), + (ATTR_IP_VERSIONS, NextDnsIpVersionsUpdateCoordinator), + (ATTR_PROTOCOLS, NextDnsProtocolsUpdateCoordinator), + (ATTR_SETTINGS, NextDnsSettingsUpdateCoordinator), + (ATTR_STATUS, NextDnsStatusUpdateCoordinator), ] @@ -109,10 +105,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: NextDnsConfigEntry) -> b # Independent DataUpdateCoordinator is used for each API endpoint to avoid # unnecessary requests when entities using this endpoint are disabled. - for coordinator_name, coordinator_class, update_interval in COORDINATORS: - coordinator = coordinator_class( - hass, entry, nextdns, profile_id, update_interval - ) + for coordinator_name, coordinator_class in COORDINATORS: + coordinator = coordinator_class(hass, entry, nextdns, profile_id) tasks.append(coordinator.async_config_entry_first_refresh()) coordinators[coordinator_name] = coordinator diff --git a/homeassistant/components/nextdns/coordinator.py b/homeassistant/components/nextdns/coordinator.py index 9b82e82ffe0..44470fe0070 100644 --- a/homeassistant/components/nextdns/coordinator.py +++ b/homeassistant/components/nextdns/coordinator.py @@ -29,7 +29,12 @@ from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, Upda if TYPE_CHECKING: from . import NextDnsConfigEntry -from .const import DOMAIN +from .const import ( + DOMAIN, + UPDATE_INTERVAL_ANALYTICS, + UPDATE_INTERVAL_CONNECTION, + UPDATE_INTERVAL_SETTINGS, +) _LOGGER = logging.getLogger(__name__) @@ -40,6 +45,7 @@ class NextDnsUpdateCoordinator[CoordinatorDataT: NextDnsData]( """Class to manage fetching NextDNS data API.""" config_entry: NextDnsConfigEntry + _update_interval: timedelta def __init__( self, @@ -47,7 +53,6 @@ class NextDnsUpdateCoordinator[CoordinatorDataT: NextDnsData]( config_entry: NextDnsConfigEntry, nextdns: NextDns, profile_id: str, - update_interval: timedelta, ) -> None: """Initialize.""" self.nextdns = nextdns @@ -58,7 +63,7 @@ class NextDnsUpdateCoordinator[CoordinatorDataT: NextDnsData]( _LOGGER, config_entry=config_entry, name=DOMAIN, - update_interval=update_interval, + update_interval=self._update_interval, ) async def _async_update_data(self) -> CoordinatorDataT: @@ -93,6 +98,8 @@ class NextDnsUpdateCoordinator[CoordinatorDataT: NextDnsData]( class NextDnsStatusUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsStatus]): """Class to manage fetching NextDNS analytics status data from API.""" + _update_interval = UPDATE_INTERVAL_ANALYTICS + async def _async_update_data_internal(self) -> AnalyticsStatus: """Update data via library.""" return await self.nextdns.get_analytics_status(self.profile_id) @@ -101,6 +108,8 @@ class NextDnsStatusUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsStatus]): class NextDnsDnssecUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsDnssec]): """Class to manage fetching NextDNS analytics Dnssec data from API.""" + _update_interval = UPDATE_INTERVAL_ANALYTICS + async def _async_update_data_internal(self) -> AnalyticsDnssec: """Update data via library.""" return await self.nextdns.get_analytics_dnssec(self.profile_id) @@ -109,6 +118,8 @@ class NextDnsDnssecUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsDnssec]): class NextDnsEncryptionUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsEncryption]): """Class to manage fetching NextDNS analytics encryption data from API.""" + _update_interval = UPDATE_INTERVAL_ANALYTICS + async def _async_update_data_internal(self) -> AnalyticsEncryption: """Update data via library.""" return await self.nextdns.get_analytics_encryption(self.profile_id) @@ -117,6 +128,8 @@ class NextDnsEncryptionUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsEncry class NextDnsIpVersionsUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsIpVersions]): """Class to manage fetching NextDNS analytics IP versions data from API.""" + _update_interval = UPDATE_INTERVAL_ANALYTICS + async def _async_update_data_internal(self) -> AnalyticsIpVersions: """Update data via library.""" return await self.nextdns.get_analytics_ip_versions(self.profile_id) @@ -125,6 +138,8 @@ class NextDnsIpVersionsUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsIpVer class NextDnsProtocolsUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsProtocols]): """Class to manage fetching NextDNS analytics protocols data from API.""" + _update_interval = UPDATE_INTERVAL_ANALYTICS + async def _async_update_data_internal(self) -> AnalyticsProtocols: """Update data via library.""" return await self.nextdns.get_analytics_protocols(self.profile_id) @@ -133,6 +148,8 @@ class NextDnsProtocolsUpdateCoordinator(NextDnsUpdateCoordinator[AnalyticsProtoc class NextDnsSettingsUpdateCoordinator(NextDnsUpdateCoordinator[Settings]): """Class to manage fetching NextDNS connection data from API.""" + _update_interval = UPDATE_INTERVAL_SETTINGS + async def _async_update_data_internal(self) -> Settings: """Update data via library.""" return await self.nextdns.get_settings(self.profile_id) @@ -141,6 +158,8 @@ class NextDnsSettingsUpdateCoordinator(NextDnsUpdateCoordinator[Settings]): class NextDnsConnectionUpdateCoordinator(NextDnsUpdateCoordinator[ConnectionStatus]): """Class to manage fetching NextDNS connection data from API.""" + _update_interval = UPDATE_INTERVAL_CONNECTION + async def _async_update_data_internal(self) -> ConnectionStatus: """Update data via library.""" return await self.nextdns.connection_status(self.profile_id) diff --git a/homeassistant/components/nibe_heatpump/binary_sensor.py b/homeassistant/components/nibe_heatpump/binary_sensor.py index 284e4d83569..d49862180bd 100644 --- a/homeassistant/components/nibe_heatpump/binary_sensor.py +++ b/homeassistant/components/nibe_heatpump/binary_sensor.py @@ -39,6 +39,7 @@ class BinarySensor(CoilEntity, BinarySensorEntity): def __init__(self, coordinator: CoilCoordinator, coil: Coil) -> None: """Initialize entity.""" super().__init__(coordinator, coil, ENTITY_ID_FORMAT) + self._on_value = coil.get_mapping_for(1) def _async_read_coil(self, data: CoilData) -> None: - self._attr_is_on = data.value == "ON" + self._attr_is_on = data.value == self._on_value diff --git a/homeassistant/components/nibe_heatpump/button.py b/homeassistant/components/nibe_heatpump/button.py index 849912af656..8b6c8abf359 100644 --- a/homeassistant/components/nibe_heatpump/button.py +++ b/homeassistant/components/nibe_heatpump/button.py @@ -52,6 +52,7 @@ class NibeAlarmResetButton(CoordinatorEntity[CoilCoordinator], ButtonEntity): async def async_press(self) -> None: """Execute the command.""" + await self.coordinator.async_write_coil(self._reset_coil, 0) await self.coordinator.async_write_coil(self._reset_coil, 1) await self.coordinator.async_read_coil(self._alarm_coil) diff --git a/homeassistant/components/nibe_heatpump/coordinator.py b/homeassistant/components/nibe_heatpump/coordinator.py index 2451e2fbda9..05e652d7f42 100644 --- a/homeassistant/components/nibe_heatpump/coordinator.py +++ b/homeassistant/components/nibe_heatpump/coordinator.py @@ -10,12 +10,19 @@ from typing import Any from nibe.coil import Coil, CoilData from nibe.connection import Connection -from nibe.exceptions import CoilNotFoundException, ReadException +from nibe.exceptions import ( + CoilNotFoundException, + ReadException, + WriteDeniedException, + WriteException, + WriteTimeoutException, +) from nibe.heatpump import HeatPump, Series from propcache.api import cached_property from homeassistant.config_entries import ConfigEntry from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed @@ -134,7 +141,33 @@ class CoilCoordinator(ContextCoordinator[dict[int, CoilData], int]): async def async_write_coil(self, coil: Coil, value: float | str) -> None: """Write coil and update state.""" data = CoilData(coil, value) - await self.connection.write_coil(data) + try: + await self.connection.write_coil(data) + except WriteDeniedException: + LOGGER.debug( + "Denied write on address %d with value %s. This is likely already the value the pump has internally", + coil.address, + value, + ) + except WriteTimeoutException as e: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="write_timeout", + translation_placeholders={ + "address": str(coil.address), + }, + ) from e + except WriteException as e: + LOGGER.debug("Failed to write", exc_info=True) + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="write_failed", + translation_placeholders={ + "address": str(coil.address), + "value": str(value), + "error": str(e), + }, + ) from e self.data[coil.address] = data diff --git a/homeassistant/components/nibe_heatpump/number.py b/homeassistant/components/nibe_heatpump/number.py index d85e5e9b765..59f365f52bf 100644 --- a/homeassistant/components/nibe_heatpump/number.py +++ b/homeassistant/components/nibe_heatpump/number.py @@ -4,7 +4,7 @@ from __future__ import annotations from nibe.coil import Coil, CoilData -from homeassistant.components.number import ENTITY_ID_FORMAT, NumberEntity +from homeassistant.components.number import ENTITY_ID_FORMAT, NumberEntity, NumberMode from homeassistant.config_entries import ConfigEntry from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant @@ -61,6 +61,7 @@ class Number(CoilEntity, NumberEntity): self._attr_native_step = 1 / coil.factor self._attr_native_unit_of_measurement = coil.unit + self._attr_mode = NumberMode.BOX def _async_read_coil(self, data: CoilData) -> None: if data.value is None: diff --git a/homeassistant/components/nibe_heatpump/strings.json b/homeassistant/components/nibe_heatpump/strings.json index c65a76d3364..1b339526586 100644 --- a/homeassistant/components/nibe_heatpump/strings.json +++ b/homeassistant/components/nibe_heatpump/strings.json @@ -45,5 +45,13 @@ "unknown": "[%key:common::config_flow::error::unknown%]", "url": "The specified URL is not well formed nor supported" } + }, + "exceptions": { + "write_timeout": { + "message": "Timeout while writing coil {address}" + }, + "write_failed": { + "message": "Writing of coil {address} with value `{value}` failed with error `{error}`" + } } } diff --git a/homeassistant/components/nibe_heatpump/switch.py b/homeassistant/components/nibe_heatpump/switch.py index 2daf3fc48ff..452244f05b5 100644 --- a/homeassistant/components/nibe_heatpump/switch.py +++ b/homeassistant/components/nibe_heatpump/switch.py @@ -41,14 +41,16 @@ class Switch(CoilEntity, SwitchEntity): def __init__(self, coordinator: CoilCoordinator, coil: Coil) -> None: """Initialize entity.""" super().__init__(coordinator, coil, ENTITY_ID_FORMAT) + self._on_value = coil.get_mapping_for(1) + self._off_value = coil.get_mapping_for(0) def _async_read_coil(self, data: CoilData) -> None: - self._attr_is_on = data.value == "ON" + self._attr_is_on = data.value == self._on_value async def async_turn_on(self, **kwargs: Any) -> None: """Turn the entity on.""" - await self._async_write_coil("ON") + await self._async_write_coil(self._on_value) async def async_turn_off(self, **kwargs: Any) -> None: """Turn the entity off.""" - await self._async_write_coil("OFF") + await self._async_write_coil(self._off_value) diff --git a/homeassistant/components/number/const.py b/homeassistant/components/number/const.py index 1b41146cd2a..bfb74d621c3 100644 --- a/homeassistant/components/number/const.py +++ b/homeassistant/components/number/const.py @@ -8,6 +8,7 @@ from typing import Final import voluptuous as vol from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, @@ -78,6 +79,11 @@ class NumberDeviceClass(StrEnum): """Device class for numbers.""" # NumberDeviceClass should be aligned with SensorDeviceClass + ABSOLUTE_HUMIDITY = "absolute_humidity" + """Absolute humidity. + + Unit of measurement: `g/m³`, `mg/m³` + """ APPARENT_POWER = "apparent_power" """Apparent power. @@ -452,6 +458,10 @@ class NumberDeviceClass(StrEnum): DEVICE_CLASSES_SCHEMA: Final = vol.All(vol.Lower, vol.Coerce(NumberDeviceClass)) DEVICE_CLASS_UNITS: dict[NumberDeviceClass, set[type[StrEnum] | str | None]] = { + NumberDeviceClass.ABSOLUTE_HUMIDITY: { + CONCENTRATION_GRAMS_PER_CUBIC_METER, + CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, + }, NumberDeviceClass.APPARENT_POWER: set(UnitOfApparentPower), NumberDeviceClass.AQI: {None}, NumberDeviceClass.AREA: set(UnitOfArea), diff --git a/homeassistant/components/number/icons.json b/homeassistant/components/number/icons.json index dcce09984bd..482b4bc6793 100644 --- a/homeassistant/components/number/icons.json +++ b/homeassistant/components/number/icons.json @@ -3,6 +3,9 @@ "_": { "default": "mdi:ray-vertex" }, + "absolute_humidity": { + "default": "mdi:water-opacity" + }, "apparent_power": { "default": "mdi:flash" }, diff --git a/homeassistant/components/number/strings.json b/homeassistant/components/number/strings.json index 998b9ffba38..1e4290f1d75 100644 --- a/homeassistant/components/number/strings.json +++ b/homeassistant/components/number/strings.json @@ -31,6 +31,9 @@ } } }, + "absolute_humidity": { + "name": "[%key:component::sensor::entity_component::absolute_humidity::name%]" + }, "apparent_power": { "name": "[%key:component::sensor::entity_component::apparent_power::name%]" }, diff --git a/homeassistant/components/nyt_games/manifest.json b/homeassistant/components/nyt_games/manifest.json index c32de754782..db3ad6a85f1 100644 --- a/homeassistant/components/nyt_games/manifest.json +++ b/homeassistant/components/nyt_games/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/nyt_games", "integration_type": "service", "iot_class": "cloud_polling", - "requirements": ["nyt_games==0.4.4"] + "requirements": ["nyt_games==0.5.0"] } diff --git a/homeassistant/components/octoprint/manifest.json b/homeassistant/components/octoprint/manifest.json index 005cf5305d9..25e4062373c 100644 --- a/homeassistant/components/octoprint/manifest.json +++ b/homeassistant/components/octoprint/manifest.json @@ -6,7 +6,7 @@ "documentation": "https://www.home-assistant.io/integrations/octoprint", "iot_class": "local_polling", "loggers": ["pyoctoprintapi"], - "requirements": ["pyoctoprintapi==0.1.12"], + "requirements": ["pyoctoprintapi==0.1.14"], "ssdp": [ { "manufacturer": "The OctoPrint Project", diff --git a/homeassistant/components/ollama/const.py b/homeassistant/components/ollama/const.py index 7e80570bd5e..093e20f5140 100644 --- a/homeassistant/components/ollama/const.py +++ b/homeassistant/components/ollama/const.py @@ -158,7 +158,7 @@ MODEL_NAMES = [ # https://ollama.com/library "yi", "zephyr", ] -DEFAULT_MODEL = "llama3.2:latest" +DEFAULT_MODEL = "qwen3:4b" DEFAULT_CONVERSATION_NAME = "Ollama Conversation" DEFAULT_AI_TASK_NAME = "Ollama AI Task" diff --git a/homeassistant/components/ollama/conversation.py b/homeassistant/components/ollama/conversation.py index f151f8524a0..e0b64702cb4 100644 --- a/homeassistant/components/ollama/conversation.py +++ b/homeassistant/components/ollama/conversation.py @@ -4,7 +4,7 @@ from __future__ import annotations from typing import Literal -from homeassistant.components import assist_pipeline, conversation +from homeassistant.components import conversation from homeassistant.config_entries import ConfigSubentry from homeassistant.const import CONF_LLM_HASS_API, MATCH_ALL from homeassistant.core import HomeAssistant @@ -52,9 +52,6 @@ class OllamaConversationEntity( async def async_added_to_hass(self) -> None: """When entity is added to Home Assistant.""" await super().async_added_to_hass() - assist_pipeline.async_migrate_engine( - self.hass, "conversation", self.entry.entry_id, self.entity_id - ) conversation.async_set_agent(self.hass, self.entry, self) async def async_will_remove_from_hass(self) -> None: diff --git a/homeassistant/components/openai_conversation/__init__.py b/homeassistant/components/openai_conversation/__init__.py index 38c08a1720b..77b71ae372d 100644 --- a/homeassistant/components/openai_conversation/__init__.py +++ b/homeassistant/components/openai_conversation/__init__.py @@ -2,17 +2,14 @@ from __future__ import annotations -import base64 -from mimetypes import guess_file_type from pathlib import Path +from types import MappingProxyType import openai from openai.types.images_response import ImagesResponse from openai.types.responses import ( EasyInputMessageParam, Response, - ResponseInputFileParam, - ResponseInputImageParam, ResponseInputMessageContentListParam, ResponseInputParam, ResponseInputTextParam, @@ -49,34 +46,28 @@ from .const import ( CONF_REASONING_EFFORT, CONF_TEMPERATURE, CONF_TOP_P, + DEFAULT_AI_TASK_NAME, DEFAULT_NAME, DOMAIN, LOGGER, + RECOMMENDED_AI_TASK_OPTIONS, RECOMMENDED_CHAT_MODEL, RECOMMENDED_MAX_TOKENS, RECOMMENDED_REASONING_EFFORT, RECOMMENDED_TEMPERATURE, RECOMMENDED_TOP_P, ) +from .entity import async_prepare_files_for_prompt SERVICE_GENERATE_IMAGE = "generate_image" SERVICE_GENERATE_CONTENT = "generate_content" -PLATFORMS = (Platform.CONVERSATION,) +PLATFORMS = (Platform.AI_TASK, Platform.CONVERSATION) CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) type OpenAIConfigEntry = ConfigEntry[openai.AsyncClient] -def encode_file(file_path: str) -> tuple[str, str]: - """Return base64 version of file contents.""" - mime_type, _ = guess_file_type(file_path) - if mime_type is None: - mime_type = "application/octet-stream" - with open(file_path, "rb") as image_file: - return (mime_type, base64.b64encode(image_file.read()).decode("utf-8")) - - async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up OpenAI Conversation.""" await async_migrate_integration(hass) @@ -146,68 +137,47 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: ResponseInputTextParam(type="input_text", text=call.data[CONF_PROMPT]) ] - def append_files_to_content() -> None: - for filename in call.data[CONF_FILENAMES]: + if filenames := call.data.get(CONF_FILENAMES): + for filename in filenames: if not hass.config.is_allowed_path(filename): raise HomeAssistantError( f"Cannot read `{filename}`, no access to path; " "`allowlist_external_dirs` may need to be adjusted in " "`configuration.yaml`" ) - if not Path(filename).exists(): - raise HomeAssistantError(f"`{filename}` does not exist") - mime_type, base64_file = encode_file(filename) - if "image/" in mime_type: - content.append( - ResponseInputImageParam( - type="input_image", - image_url=f"data:{mime_type};base64,{base64_file}", - detail="auto", - ) - ) - elif "application/pdf" in mime_type: - content.append( - ResponseInputFileParam( - type="input_file", - filename=filename, - file_data=f"data:{mime_type};base64,{base64_file}", - ) - ) - else: - raise HomeAssistantError( - "Only images and PDF are supported by the OpenAI API," - f"`{filename}` is not an image file or PDF" - ) - if CONF_FILENAMES in call.data: - await hass.async_add_executor_job(append_files_to_content) + content.extend( + await async_prepare_files_for_prompt( + hass, [Path(filename) for filename in filenames] + ) + ) messages: ResponseInputParam = [ EasyInputMessageParam(type="message", role="user", content=content) ] - try: - model_args = { - "model": model, - "input": messages, - "max_output_tokens": conversation_subentry.data.get( - CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS - ), - "top_p": conversation_subentry.data.get(CONF_TOP_P, RECOMMENDED_TOP_P), - "temperature": conversation_subentry.data.get( - CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE - ), - "user": call.context.user_id, - "store": False, + model_args = { + "model": model, + "input": messages, + "max_output_tokens": conversation_subentry.data.get( + CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS + ), + "top_p": conversation_subentry.data.get(CONF_TOP_P, RECOMMENDED_TOP_P), + "temperature": conversation_subentry.data.get( + CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE + ), + "user": call.context.user_id, + "store": False, + } + + if model.startswith("o"): + model_args["reasoning"] = { + "effort": conversation_subentry.data.get( + CONF_REASONING_EFFORT, RECOMMENDED_REASONING_EFFORT + ) } - if model.startswith("o"): - model_args["reasoning"] = { - "effort": conversation_subentry.data.get( - CONF_REASONING_EFFORT, RECOMMENDED_REASONING_EFFORT - ) - } - + try: response: Response = await client.responses.create(**model_args) except openai.OpenAIError as err: @@ -394,6 +364,18 @@ async def async_migrate_entry(hass: HomeAssistant, entry: OpenAIConfigEntry) -> hass.config_entries.async_update_entry(entry, minor_version=2) + if entry.version == 2 and entry.minor_version == 2: + hass.config_entries.async_add_subentry( + entry, + ConfigSubentry( + data=MappingProxyType(RECOMMENDED_AI_TASK_OPTIONS), + subentry_type="ai_task_data", + title=DEFAULT_AI_TASK_NAME, + unique_id=None, + ), + ) + hass.config_entries.async_update_entry(entry, minor_version=3) + LOGGER.debug( "Migration to version %s:%s successful", entry.version, entry.minor_version ) diff --git a/homeassistant/components/openai_conversation/ai_task.py b/homeassistant/components/openai_conversation/ai_task.py new file mode 100644 index 00000000000..5fc700a73ad --- /dev/null +++ b/homeassistant/components/openai_conversation/ai_task.py @@ -0,0 +1,80 @@ +"""AI Task integration for OpenAI.""" + +from __future__ import annotations + +from json import JSONDecodeError +import logging + +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 .entity import OpenAIBaseLLMEntity + +_LOGGER = logging.getLogger(__name__) + + +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( + [OpenAITaskEntity(config_entry, subentry)], + config_subentry_id=subentry.subentry_id, + ) + + +class OpenAITaskEntity( + ai_task.AITaskEntity, + OpenAIBaseLLMEntity, +): + """OpenAI AI Task entity.""" + + _attr_supported_features = ( + ai_task.AITaskEntityFeature.GENERATE_DATA + | ai_task.AITaskEntityFeature.SUPPORT_ATTACHMENTS + ) + + async def _async_generate_data( + self, + task: ai_task.GenDataTask, + chat_log: conversation.ChatLog, + ) -> ai_task.GenDataTaskResult: + """Handle a generate data task.""" + await self._async_handle_chat_log(chat_log, task.name, task.structure) + + if not isinstance(chat_log.content[-1], conversation.AssistantContent): + raise HomeAssistantError( + "Last content in chat log is not an AssistantContent" + ) + + text = chat_log.content[-1].content or "" + + if not task.structure: + return ai_task.GenDataTaskResult( + conversation_id=chat_log.conversation_id, + data=text, + ) + try: + data = json_loads(text) + except JSONDecodeError as err: + _LOGGER.error( + "Failed to parse JSON response: %s. Response: %s", + err, + text, + ) + raise HomeAssistantError("Error with OpenAI structured response") from err + + return ai_task.GenDataTaskResult( + conversation_id=chat_log.conversation_id, + data=data, + ) diff --git a/homeassistant/components/openai_conversation/config_flow.py b/homeassistant/components/openai_conversation/config_flow.py index 63ebc351ee3..ce6872c7c20 100644 --- a/homeassistant/components/openai_conversation/config_flow.py +++ b/homeassistant/components/openai_conversation/config_flow.py @@ -55,9 +55,12 @@ from .const import ( CONF_WEB_SEARCH_REGION, CONF_WEB_SEARCH_TIMEZONE, CONF_WEB_SEARCH_USER_LOCATION, + DEFAULT_AI_TASK_NAME, DEFAULT_CONVERSATION_NAME, DOMAIN, + RECOMMENDED_AI_TASK_OPTIONS, RECOMMENDED_CHAT_MODEL, + RECOMMENDED_CONVERSATION_OPTIONS, RECOMMENDED_MAX_TOKENS, RECOMMENDED_REASONING_EFFORT, RECOMMENDED_TEMPERATURE, @@ -66,7 +69,7 @@ from .const import ( RECOMMENDED_WEB_SEARCH_CONTEXT_SIZE, RECOMMENDED_WEB_SEARCH_USER_LOCATION, UNSUPPORTED_MODELS, - WEB_SEARCH_MODELS, + UNSUPPORTED_WEB_SEARCH_MODELS, ) _LOGGER = logging.getLogger(__name__) @@ -77,12 +80,6 @@ STEP_USER_DATA_SCHEMA = vol.Schema( } ) -RECOMMENDED_OPTIONS = { - CONF_RECOMMENDED: True, - CONF_LLM_HASS_API: [llm.LLM_API_ASSIST], - CONF_PROMPT: llm.DEFAULT_INSTRUCTIONS_PROMPT, -} - async def validate_input(hass: HomeAssistant, data: dict[str, Any]) -> None: """Validate the user input allows us to connect. @@ -99,7 +96,7 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for OpenAI Conversation.""" VERSION = 2 - MINOR_VERSION = 2 + MINOR_VERSION = 3 async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -129,10 +126,16 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN): subentries=[ { "subentry_type": "conversation", - "data": RECOMMENDED_OPTIONS, + "data": RECOMMENDED_CONVERSATION_OPTIONS, "title": DEFAULT_CONVERSATION_NAME, "unique_id": None, - } + }, + { + "subentry_type": "ai_task_data", + "data": RECOMMENDED_AI_TASK_OPTIONS, + "title": DEFAULT_AI_TASK_NAME, + "unique_id": None, + }, ], ) @@ -146,11 +149,14 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN): cls, config_entry: ConfigEntry ) -> dict[str, type[ConfigSubentryFlow]]: """Return subentries supported by this integration.""" - return {"conversation": ConversationSubentryFlowHandler} + return { + "conversation": OpenAISubentryFlowHandler, + "ai_task_data": OpenAISubentryFlowHandler, + } -class ConversationSubentryFlowHandler(ConfigSubentryFlow): - """Flow for managing conversation subentries.""" +class OpenAISubentryFlowHandler(ConfigSubentryFlow): + """Flow for managing OpenAI subentries.""" last_rendered_recommended = False options: dict[str, Any] @@ -164,7 +170,10 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: """Add a subentry.""" - self.options = RECOMMENDED_OPTIONS.copy() + if self._subentry_type == "ai_task_data": + self.options = RECOMMENDED_AI_TASK_OPTIONS.copy() + else: + self.options = RECOMMENDED_CONVERSATION_OPTIONS.copy() return await self.async_step_init() async def async_step_reconfigure( @@ -181,6 +190,7 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): # abort if entry is not loaded if self._get_entry().state != ConfigEntryState.LOADED: return self.async_abort(reason="entry_not_loaded") + options = self.options hass_apis: list[SelectOptionDict] = [ @@ -198,28 +208,32 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): step_schema: VolDictType = {} if self._is_new: - step_schema[vol.Required(CONF_NAME, default=DEFAULT_CONVERSATION_NAME)] = ( - str + if self._subentry_type == "ai_task_data": + default_name = DEFAULT_AI_TASK_NAME + else: + default_name = DEFAULT_CONVERSATION_NAME + step_schema[vol.Required(CONF_NAME, default=default_name)] = str + + if self._subentry_type == "conversation": + step_schema.update( + { + vol.Optional( + CONF_PROMPT, + description={ + "suggested_value": options.get( + CONF_PROMPT, llm.DEFAULT_INSTRUCTIONS_PROMPT + ) + }, + ): TemplateSelector(), + vol.Optional(CONF_LLM_HASS_API): SelectSelector( + SelectSelectorConfig(options=hass_apis, multiple=True) + ), + } ) - step_schema.update( - { - vol.Optional( - CONF_PROMPT, - description={ - "suggested_value": options.get( - CONF_PROMPT, llm.DEFAULT_INSTRUCTIONS_PROMPT - ) - }, - ): TemplateSelector(), - vol.Optional(CONF_LLM_HASS_API): SelectSelector( - SelectSelectorConfig(options=hass_apis, multiple=True) - ), - vol.Required( - CONF_RECOMMENDED, default=options.get(CONF_RECOMMENDED, False) - ): bool, - } - ) + step_schema[ + vol.Required(CONF_RECOMMENDED, default=options.get(CONF_RECOMMENDED, False)) + ] = bool if user_input is not None: if not user_input.get(CONF_LLM_HASS_API): @@ -320,7 +334,9 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): elif CONF_REASONING_EFFORT in options: options.pop(CONF_REASONING_EFFORT) - if model.startswith(tuple(WEB_SEARCH_MODELS)): + if self._subentry_type == "conversation" and not model.startswith( + tuple(UNSUPPORTED_WEB_SEARCH_MODELS) + ): step_schema.update( { vol.Optional( @@ -362,7 +378,7 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): if not step_schema: if self._is_new: return self.async_create_entry( - title=options.pop(CONF_NAME, DEFAULT_CONVERSATION_NAME), + title=options.pop(CONF_NAME), data=options, ) return self.async_update_and_abort( @@ -384,7 +400,7 @@ class ConversationSubentryFlowHandler(ConfigSubentryFlow): options.update(user_input) if self._is_new: return self.async_create_entry( - title=options.pop(CONF_NAME, DEFAULT_CONVERSATION_NAME), + title=options.pop(CONF_NAME), data=options, ) return self.async_update_and_abort( diff --git a/homeassistant/components/openai_conversation/const.py b/homeassistant/components/openai_conversation/const.py index 3f1c0dc7429..a15f71118c0 100644 --- a/homeassistant/components/openai_conversation/const.py +++ b/homeassistant/components/openai_conversation/const.py @@ -2,10 +2,14 @@ import logging +from homeassistant.const import CONF_LLM_HASS_API +from homeassistant.helpers import llm + DOMAIN = "openai_conversation" LOGGER: logging.Logger = logging.getLogger(__package__) DEFAULT_CONVERSATION_NAME = "OpenAI Conversation" +DEFAULT_AI_TASK_NAME = "OpenAI AI Task" DEFAULT_NAME = "OpenAI Conversation" CONF_CHAT_MODEL = "chat_model" @@ -24,7 +28,7 @@ CONF_WEB_SEARCH_REGION = "region" CONF_WEB_SEARCH_COUNTRY = "country" CONF_WEB_SEARCH_TIMEZONE = "timezone" RECOMMENDED_CHAT_MODEL = "gpt-4o-mini" -RECOMMENDED_MAX_TOKENS = 150 +RECOMMENDED_MAX_TOKENS = 3000 RECOMMENDED_REASONING_EFFORT = "low" RECOMMENDED_TEMPERATURE = 1.0 RECOMMENDED_TOP_P = 1.0 @@ -44,11 +48,19 @@ UNSUPPORTED_MODELS: list[str] = [ "gpt-4o-mini-realtime-preview-2024-12-17", ] -WEB_SEARCH_MODELS: list[str] = [ - "gpt-4.1", - "gpt-4.1-mini", - "gpt-4o", - "gpt-4o-search-preview", - "gpt-4o-mini", - "gpt-4o-mini-search-preview", +UNSUPPORTED_WEB_SEARCH_MODELS: list[str] = [ + "gpt-3.5", + "gpt-4-turbo", + "gpt-4.1-nano", + "o1", + "o3-mini", ] + +RECOMMENDED_CONVERSATION_OPTIONS = { + CONF_RECOMMENDED: True, + CONF_LLM_HASS_API: [llm.LLM_API_ASSIST], + CONF_PROMPT: llm.DEFAULT_INSTRUCTIONS_PROMPT, +} +RECOMMENDED_AI_TASK_OPTIONS = { + CONF_RECOMMENDED: True, +} diff --git a/homeassistant/components/openai_conversation/conversation.py b/homeassistant/components/openai_conversation/conversation.py index 1ec17163f69..25e89577ef3 100644 --- a/homeassistant/components/openai_conversation/conversation.py +++ b/homeassistant/components/openai_conversation/conversation.py @@ -2,7 +2,7 @@ from typing import Literal -from homeassistant.components import assist_pipeline, conversation +from homeassistant.components import conversation from homeassistant.config_entries import ConfigSubentry from homeassistant.const import CONF_LLM_HASS_API, MATCH_ALL from homeassistant.core import HomeAssistant @@ -57,9 +57,6 @@ class OpenAIConversationEntity( async def async_added_to_hass(self) -> None: """When entity is added to Home Assistant.""" await super().async_added_to_hass() - assist_pipeline.async_migrate_engine( - self.hass, "conversation", self.entry.entry_id, self.entity_id - ) conversation.async_set_agent(self.hass, self.entry, self) async def async_will_remove_from_hass(self) -> None: diff --git a/homeassistant/components/openai_conversation/entity.py b/homeassistant/components/openai_conversation/entity.py index ba7153deb24..7679bef83f1 100644 --- a/homeassistant/components/openai_conversation/entity.py +++ b/homeassistant/components/openai_conversation/entity.py @@ -1,8 +1,13 @@ """Base entity for OpenAI.""" +from __future__ import annotations + +import base64 from collections.abc import AsyncGenerator, Callable import json -from typing import Any, Literal, cast +from mimetypes import guess_file_type +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal, cast import openai from openai._streaming import AsyncStream @@ -17,6 +22,9 @@ from openai.types.responses import ( ResponseFunctionToolCall, ResponseFunctionToolCallParam, ResponseIncompleteEvent, + ResponseInputFileParam, + ResponseInputImageParam, + ResponseInputMessageContentListParam, ResponseInputParam, ResponseOutputItemAddedEvent, ResponseOutputItemDoneEvent, @@ -31,15 +39,17 @@ from openai.types.responses import ( ) from openai.types.responses.response_input_param import FunctionCallOutput from openai.types.responses.web_search_tool_param import UserLocation +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.util import slugify -from . import OpenAIConfigEntry from .const import ( CONF_CHAT_MODEL, CONF_MAX_TOKENS, @@ -63,10 +73,55 @@ from .const import ( RECOMMENDED_WEB_SEARCH_CONTEXT_SIZE, ) +if TYPE_CHECKING: + from . import OpenAIConfigEntry + + # Max number of back and forth with the LLM to generate a response MAX_TOOL_ITERATIONS = 10 +def _adjust_schema(schema: dict[str, Any]) -> None: + """Adjust the schema to be compatible with OpenAI API.""" + if schema["type"] == "object": + if "properties" not in schema: + return + + if "required" not in schema: + schema["required"] = [] + + # Ensure all properties are required + for prop, prop_info in schema["properties"].items(): + _adjust_schema(prop_info) + if prop not in schema["required"]: + prop_info["type"] = [prop_info["type"], "null"] + schema["required"].append(prop) + + elif schema["type"] == "array": + if "items" not in schema: + return + + _adjust_schema(schema["items"]) + + +def _format_structured_output( + schema: vol.Schema, llm_api: llm.APIInstance | None +) -> dict[str, Any]: + """Format the schema to be compatible with OpenAI API.""" + result: dict[str, Any] = convert( + schema, + custom_serializer=( + llm_api.custom_serializer if llm_api else llm.selector_serializer + ), + ) + + _adjust_schema(result) + + result["strict"] = True + result["additionalProperties"] = False + return result + + def _format_tool( tool: llm.Tool, custom_serializer: Callable[[Any], Any] | None ) -> FunctionToolParam: @@ -231,6 +286,8 @@ class OpenAIBaseLLMEntity(Entity): async def _async_handle_chat_log( self, chat_log: conversation.ChatLog, + structure_name: str | None = None, + structure: vol.Schema | None = None, ) -> None: """Generate an answer for the chat log.""" options = self.subentry.data @@ -261,54 +318,136 @@ class OpenAIBaseLLMEntity(Entity): tools = [] tools.append(web_search) - model = options.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL) + model_args = { + "model": options.get(CONF_CHAT_MODEL, RECOMMENDED_CHAT_MODEL), + "input": [], + "max_output_tokens": options.get(CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS), + "top_p": options.get(CONF_TOP_P, RECOMMENDED_TOP_P), + "temperature": options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE), + "user": chat_log.conversation_id, + "store": False, + "stream": True, + } + if tools: + model_args["tools"] = tools + + if model_args["model"].startswith("o"): + model_args["reasoning"] = { + "effort": options.get( + CONF_REASONING_EFFORT, RECOMMENDED_REASONING_EFFORT + ) + } + else: + model_args["store"] = False + messages = [ m for content in chat_log.content for m in _convert_content_to_param(content) ] + last_content = chat_log.content[-1] + + # Handle attachments by adding them to the last user message + if last_content.role == "user" and last_content.attachments: + files = await async_prepare_files_for_prompt( + self.hass, + [a.path for a in last_content.attachments], + ) + last_message = messages[-1] + assert ( + last_message["type"] == "message" + and last_message["role"] == "user" + and isinstance(last_message["content"], str) + ) + last_message["content"] = [ + {"type": "input_text", "text": last_message["content"]}, # type: ignore[list-item] + *files, # type: ignore[list-item] + ] + + if structure and structure_name: + model_args["text"] = { + "format": { + "type": "json_schema", + "name": slugify(structure_name), + "schema": _format_structured_output(structure, chat_log.llm_api), + }, + } + client = self.entry.runtime_data # To prevent infinite loops, we limit the number of iterations for _iteration in range(MAX_TOOL_ITERATIONS): - model_args = { - "model": model, - "input": messages, - "max_output_tokens": options.get( - CONF_MAX_TOKENS, RECOMMENDED_MAX_TOKENS - ), - "top_p": options.get(CONF_TOP_P, RECOMMENDED_TOP_P), - "temperature": options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE), - "user": chat_log.conversation_id, - "stream": True, - } - if tools: - model_args["tools"] = tools - - if model.startswith("o"): - model_args["reasoning"] = { - "effort": options.get( - CONF_REASONING_EFFORT, RECOMMENDED_REASONING_EFFORT - ) - } - else: - model_args["store"] = False + model_args["input"] = messages try: result = await client.responses.create(**model_args) + + async for content in chat_log.async_add_delta_content_stream( + self.entity_id, _transform_stream(chat_log, result, messages) + ): + if not isinstance(content, conversation.AssistantContent): + messages.extend(_convert_content_to_param(content)) except openai.RateLimitError as err: LOGGER.error("Rate limited by OpenAI: %s", err) raise HomeAssistantError("Rate limited or insufficient funds") from err except openai.OpenAIError as err: + if ( + isinstance(err, openai.APIError) + and err.type == "insufficient_quota" + ): + LOGGER.error("Insufficient funds for OpenAI: %s", err) + raise HomeAssistantError("Insufficient funds for OpenAI") from err + LOGGER.error("Error talking to OpenAI: %s", err) raise HomeAssistantError("Error talking to OpenAI") from err - async for content in chat_log.async_add_delta_content_stream( - self.entity_id, _transform_stream(chat_log, result, messages) - ): - if not isinstance(content, conversation.AssistantContent): - messages.extend(_convert_content_to_param(content)) - if not chat_log.unresponded_tool_results: break + + +async def async_prepare_files_for_prompt( + hass: HomeAssistant, files: list[Path] +) -> ResponseInputMessageContentListParam: + """Append files to a prompt. + + Caller needs to ensure that the files are allowed. + """ + + def append_files_to_content() -> ResponseInputMessageContentListParam: + content: ResponseInputMessageContentListParam = [] + + for file_path in files: + if not file_path.exists(): + raise HomeAssistantError(f"`{file_path}` does not exist") + + mime_type, _ = guess_file_type(file_path) + + if not mime_type or not mime_type.startswith(("image/", "application/pdf")): + raise HomeAssistantError( + "Only images and PDF are supported by the OpenAI API," + f"`{file_path}` is not an image file or PDF" + ) + + base64_file = base64.b64encode(file_path.read_bytes()).decode("utf-8") + + if mime_type.startswith("image/"): + content.append( + ResponseInputImageParam( + type="input_image", + image_url=f"data:{mime_type};base64,{base64_file}", + detail="auto", + ) + ) + elif mime_type.startswith("application/pdf"): + content.append( + ResponseInputFileParam( + type="input_file", + filename=str(file_path), + file_data=f"data:{mime_type};base64,{base64_file}", + ) + ) + + return content + + return await hass.async_add_executor_job(append_files_to_content) diff --git a/homeassistant/components/openai_conversation/manifest.json b/homeassistant/components/openai_conversation/manifest.json index 84369eb15a2..83519821f79 100644 --- a/homeassistant/components/openai_conversation/manifest.json +++ b/homeassistant/components/openai_conversation/manifest.json @@ -8,5 +8,5 @@ "documentation": "https://www.home-assistant.io/integrations/openai_conversation", "integration_type": "service", "iot_class": "cloud_polling", - "requirements": ["openai==1.76.2"] + "requirements": ["openai==1.93.3"] } diff --git a/homeassistant/components/openai_conversation/strings.json b/homeassistant/components/openai_conversation/strings.json index ffbe84337b7..5011fc9cf99 100644 --- a/homeassistant/components/openai_conversation/strings.json +++ b/homeassistant/components/openai_conversation/strings.json @@ -68,6 +68,52 @@ "error": { "model_not_supported": "This model is not supported, please select a different model" } + }, + "ai_task_data": { + "initiate_flow": { + "user": "Add Generate data with AI service", + "reconfigure": "Reconfigure Generate data with AI service" + }, + "entry_type": "Generate data with AI service", + "step": { + "init": { + "data": { + "name": "[%key:common::config_flow::data::name%]", + "recommended": "[%key:component::openai_conversation::config_subentries::conversation::step::init::data::recommended%]" + } + }, + "advanced": { + "title": "[%key:component::openai_conversation::config_subentries::conversation::step::advanced::title%]", + "data": { + "chat_model": "[%key:common::generic::model%]", + "max_tokens": "[%key:component::openai_conversation::config_subentries::conversation::step::advanced::data::max_tokens%]", + "temperature": "[%key:component::openai_conversation::config_subentries::conversation::step::advanced::data::temperature%]", + "top_p": "[%key:component::openai_conversation::config_subentries::conversation::step::advanced::data::top_p%]" + } + }, + "model": { + "title": "[%key:component::openai_conversation::config_subentries::conversation::step::model::title%]", + "data": { + "reasoning_effort": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data::reasoning_effort%]", + "web_search": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data::web_search%]", + "search_context_size": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data::search_context_size%]", + "user_location": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data::user_location%]" + }, + "data_description": { + "reasoning_effort": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data_description::reasoning_effort%]", + "web_search": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data_description::web_search%]", + "search_context_size": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data_description::search_context_size%]", + "user_location": "[%key:component::openai_conversation::config_subentries::conversation::step::model::data_description::user_location%]" + } + } + }, + "abort": { + "reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]", + "entry_not_loaded": "[%key:component::openai_conversation::config_subentries::conversation::abort::entry_not_loaded%]" + }, + "error": { + "model_not_supported": "[%key:component::openai_conversation::config_subentries::conversation::error::model_not_supported%]" + } } }, "selector": { diff --git a/homeassistant/components/pegel_online/__init__.py b/homeassistant/components/pegel_online/__init__.py index 1c71603e41e..c8388f40704 100644 --- a/homeassistant/components/pegel_online/__init__.py +++ b/homeassistant/components/pegel_online/__init__.py @@ -12,7 +12,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession -from .const import CONF_STATION +from .const import CONF_STATION, DOMAIN from .coordinator import PegelOnlineConfigEntry, PegelOnlineDataUpdateCoordinator _LOGGER = logging.getLogger(__name__) @@ -30,7 +30,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: PegelOnlineConfigEntry) try: station = await api.async_get_station_details(station_uuid) except CONNECT_ERRORS as err: - raise ConfigEntryNotReady("Failed to connect") from err + raise ConfigEntryNotReady( + translation_domain=DOMAIN, + translation_key="communication_error", + translation_placeholders={"error": str(err)}, + ) from err coordinator = PegelOnlineDataUpdateCoordinator(hass, entry, api, station) diff --git a/homeassistant/components/pegel_online/manifest.json b/homeassistant/components/pegel_online/manifest.json index 0a0f31532b1..c488eca34af 100644 --- a/homeassistant/components/pegel_online/manifest.json +++ b/homeassistant/components/pegel_online/manifest.json @@ -7,5 +7,6 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["aiopegelonline"], + "quality_scale": "platinum", "requirements": ["aiopegelonline==0.1.1"] } diff --git a/homeassistant/components/pegel_online/quality_scale.yaml b/homeassistant/components/pegel_online/quality_scale.yaml new file mode 100644 index 00000000000..aa0a153ee9c --- /dev/null +++ b/homeassistant/components/pegel_online/quality_scale.yaml @@ -0,0 +1,87 @@ +rules: + # Bronze + action-setup: + status: exempt + comment: no actions/services are implemented + appropriate-polling: done + brands: done + common-modules: done + config-flow-test-coverage: done + config-flow: done + dependency-transparency: done + docs-actions: + status: exempt + comment: no actions/services are implemented + docs-high-level-description: done + docs-installation-instructions: done + docs-removal-instructions: done + entity-event-setup: done + entity-unique-id: done + has-entity-name: done + runtime-data: done + test-before-configure: done + test-before-setup: done + unique-config-entry: done + + # Silver + action-exceptions: + status: exempt + comment: no actions/services are implemented + config-entry-unloading: done + docs-configuration-parameters: + status: exempt + comment: has no options flow + docs-installation-parameters: done + entity-unavailable: done + integration-owner: done + log-when-unavailable: done + parallel-updates: done + reauthentication-flow: + status: exempt + comment: no authentication necessary + test-coverage: done + + # Gold + devices: done + diagnostics: done + discovery-update-info: + status: exempt + comment: pure webservice, no discovery + discovery: + status: exempt + comment: pure webservice, no discovery + docs-data-update: done + docs-examples: done + docs-known-limitations: done + docs-supported-devices: done + docs-supported-functions: done + docs-troubleshooting: done + docs-use-cases: done + dynamic-devices: + status: exempt + comment: not applicable - see stale-devices + entity-category: done + entity-device-class: done + entity-disabled-by-default: done + entity-translations: done + exception-translations: done + icon-translations: done + reconfiguration-flow: + status: exempt + comment: | + each config entry represents only one named measurement station, + so when the user wants to add another one, they can just add another config entry + repair-issues: + status: exempt + comment: no known use cases for repair issues or flows, yet + stale-devices: + status: exempt + comment: | + does not apply, since only one measurement station per config-entry + if a measurement station is removed from the data provider, + the user can just remove the related config entry + + # Platinum + async-dependency: done + inject-websession: done + strict-typing: done diff --git a/homeassistant/components/pegel_online/sensor.py b/homeassistant/components/pegel_online/sensor.py index ee2e6750911..30d4edfb041 100644 --- a/homeassistant/components/pegel_online/sensor.py +++ b/homeassistant/components/pegel_online/sensor.py @@ -20,6 +20,9 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .coordinator import PegelOnlineConfigEntry, PegelOnlineDataUpdateCoordinator from .entity import PegelOnlineEntity +# Coordinator is used to centralize the data updates +PARALLEL_UPDATES = 0 + @dataclass(frozen=True, kw_only=True) class PegelOnlineSensorEntityDescription(SensorEntityDescription): diff --git a/homeassistant/components/pi_hole/__init__.py b/homeassistant/components/pi_hole/__init__.py index f211d646c0b..f73b7156d3e 100644 --- a/homeassistant/components/pi_hole/__init__.py +++ b/homeassistant/components/pi_hole/__init__.py @@ -12,7 +12,6 @@ from hole.exceptions import HoleConnectionError, HoleError from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_API_KEY, - CONF_API_VERSION, CONF_HOST, CONF_LOCATION, CONF_NAME, @@ -52,13 +51,13 @@ class PiHoleData: api: Hole coordinator: DataUpdateCoordinator[None] + api_version: int async def async_setup_entry(hass: HomeAssistant, entry: PiHoleConfigEntry) -> bool: """Set up Pi-hole entry.""" name = entry.data[CONF_NAME] host = entry.data[CONF_HOST] - version = entry.data.get(CONF_API_VERSION) # remove obsolet CONF_STATISTICS_ONLY from entry.data if CONF_STATISTICS_ONLY in entry.data: @@ -100,15 +99,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: PiHoleConfigEntry) -> bo await er.async_migrate_entries(hass, entry.entry_id, update_unique_id) - if version is None: - _LOGGER.debug( - "No API version specified, determining Pi-hole API version for %s", host - ) - version = await determine_api_version(hass, dict(entry.data)) - _LOGGER.debug("Pi-hole API version determined: %s", version) - hass.config_entries.async_update_entry( - entry, data={**entry.data, CONF_API_VERSION: version} - ) + _LOGGER.debug("Determining Pi-hole API version for %s", host) + version = await determine_api_version(hass, dict(entry.data)) + _LOGGER.debug("Pi-hole API version determined: %s", version) + # Once API version 5 is deprecated we should instantiate Hole directly api = api_by_version(hass, dict(entry.data), version) @@ -151,7 +145,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: PiHoleConfigEntry) -> bo await coordinator.async_config_entry_first_refresh() - entry.runtime_data = PiHoleData(api, coordinator) + entry.runtime_data = PiHoleData(api, coordinator, version) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) diff --git a/homeassistant/components/pi_hole/config_flow.py b/homeassistant/components/pi_hole/config_flow.py index da994b74e6d..327ce32847e 100644 --- a/homeassistant/components/pi_hole/config_flow.py +++ b/homeassistant/components/pi_hole/config_flow.py @@ -12,7 +12,6 @@ import voluptuous as vol from homeassistant.config_entries import ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_API_KEY, - CONF_API_VERSION, CONF_HOST, CONF_LOCATION, CONF_NAME, @@ -145,7 +144,6 @@ class PiHoleFlowHandler(ConfigFlow, domain=DOMAIN): try: await pi_hole.authenticate() _LOGGER.debug("Success authenticating with pihole API version: %s", 6) - self._config[CONF_API_VERSION] = 6 except HoleError: _LOGGER.debug("Failed authenticating with pihole API version: %s", 6) return {CONF_API_KEY: "invalid_auth"} @@ -171,7 +169,6 @@ class PiHoleFlowHandler(ConfigFlow, domain=DOMAIN): "Success connecting to, but necessarily authenticating with, pihole, API version is: %s", 5, ) - self._config[CONF_API_VERSION] = 5 # the v5 API returns an empty list to unauthenticated requests. if not isinstance(pi_hole.data, dict): _LOGGER.debug( diff --git a/homeassistant/components/pi_hole/sensor.py b/homeassistant/components/pi_hole/sensor.py index aa79805cc2d..844b03acf7c 100644 --- a/homeassistant/components/pi_hole/sensor.py +++ b/homeassistant/components/pi_hole/sensor.py @@ -8,7 +8,7 @@ from typing import Any from hole import Hole from homeassistant.components.sensor import SensorEntity, SensorEntityDescription -from homeassistant.const import CONF_API_VERSION, CONF_NAME, PERCENTAGE +from homeassistant.const import CONF_NAME, PERCENTAGE from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType @@ -133,7 +133,7 @@ async def async_setup_entry( description, ) for description in ( - SENSOR_TYPES if entry.data[CONF_API_VERSION] == 5 else SENSOR_TYPES_V6 + SENSOR_TYPES if hole_data.api_version == 5 else SENSOR_TYPES_V6 ) ] async_add_entities(sensors, True) diff --git a/homeassistant/components/playstation_network/sensor.py b/homeassistant/components/playstation_network/sensor.py index f4a634d5fb5..cfd81fe4033 100644 --- a/homeassistant/components/playstation_network/sensor.py +++ b/homeassistant/components/playstation_network/sensor.py @@ -156,9 +156,9 @@ class PlaystationNetworkSensorEntity( def entity_picture(self) -> str | None: """Return the entity picture to use in the frontend, if any.""" if self.entity_description.key is PlaystationNetworkSensor.ONLINE_ID and ( - profile_pictures := self.coordinator.data.profile["personalDetail"].get( - "profilePictures" - ) + profile_pictures := self.coordinator.data.profile.get( + "personalDetail", {} + ).get("profilePictures") ): return next( (pic.get("url") for pic in profile_pictures if pic.get("size") == "xl"), diff --git a/homeassistant/components/pyload/config_flow.py b/homeassistant/components/pyload/config_flow.py index 50d354d345d..1a1481f9c26 100644 --- a/homeassistant/components/pyload/config_flow.py +++ b/homeassistant/components/pyload/config_flow.py @@ -26,6 +26,7 @@ from homeassistant.helpers.selector import ( TextSelectorConfig, TextSelectorType, ) +from homeassistant.helpers.service_info.hassio import HassioServiceInfo from .const import DEFAULT_NAME, DOMAIN @@ -97,6 +98,8 @@ class PyLoadConfigFlow(ConfigFlow, domain=DOMAIN): VERSION = 1 MINOR_VERSION = 1 + _hassio_discovery: HassioServiceInfo | None = None + async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -211,3 +214,58 @@ class PyLoadConfigFlow(ConfigFlow, domain=DOMAIN): description_placeholders={CONF_NAME: reconfig_entry.data[CONF_USERNAME]}, errors=errors, ) + + async def async_step_hassio( + self, discovery_info: HassioServiceInfo + ) -> ConfigFlowResult: + """Prepare configuration for pyLoad add-on. + + This flow is triggered by the discovery component. + """ + url = URL(discovery_info.config[CONF_URL]).human_repr() + self._async_abort_entries_match({CONF_URL: url}) + await self.async_set_unique_id(discovery_info.uuid) + self._abort_if_unique_id_configured(updates={CONF_URL: url}) + discovery_info.config[CONF_URL] = url + self._hassio_discovery = discovery_info + return await self.async_step_hassio_confirm() + + async def async_step_hassio_confirm( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Confirm Supervisor discovery.""" + assert self._hassio_discovery + errors: dict[str, str] = {} + + data = {**self._hassio_discovery.config, CONF_VERIFY_SSL: False} + + if user_input is not None: + data.update(user_input) + + try: + await validate_input(self.hass, data) + except (CannotConnect, ParserError): + _LOGGER.debug("Cannot connect", exc_info=True) + errors["base"] = "cannot_connect" + except InvalidAuth: + errors["base"] = "invalid_auth" + except Exception: + _LOGGER.exception("Unexpected exception") + errors["base"] = "unknown" + else: + if user_input is None: + self._set_confirm_only() + return self.async_show_form( + step_id="hassio_confirm", + description_placeholders=self._hassio_discovery.config, + ) + return self.async_create_entry(title=self._hassio_discovery.slug, data=data) + + return self.async_show_form( + step_id="hassio_confirm", + data_schema=self.add_suggested_values_to_schema( + data_schema=REAUTH_SCHEMA, suggested_values=data + ), + description_placeholders=self._hassio_discovery.config, + errors=errors if user_input is not None else None, + ) diff --git a/homeassistant/components/pyload/strings.json b/homeassistant/components/pyload/strings.json index 9414f7f7bb8..66435fd2806 100644 --- a/homeassistant/components/pyload/strings.json +++ b/homeassistant/components/pyload/strings.json @@ -39,6 +39,18 @@ "username": "[%key:component::pyload::config::step::user::data_description::username%]", "password": "[%key:component::pyload::config::step::user::data_description::password%]" } + }, + "hassio_confirm": { + "title": "pyLoad via Home Assistant add-on", + "description": "Do you want to configure Home Assistant to connect to the pyLoad service provided by the add-on: {addon}?", + "data": { + "username": "[%key:common::config_flow::data::username%]", + "password": "[%key:common::config_flow::data::password%]" + }, + "data_description": { + "username": "[%key:component::pyload::config::step::user::data_description::username%]", + "password": "[%key:component::pyload::config::step::user::data_description::password%]" + } } }, "error": { diff --git a/homeassistant/components/rainmachine/strings.json b/homeassistant/components/rainmachine/strings.json index aad61458e88..49731df5b6f 100644 --- a/homeassistant/components/rainmachine/strings.json +++ b/homeassistant/components/rainmachine/strings.json @@ -196,12 +196,12 @@ "description": "UNIX timestamp for the weather data. If omitted, the RainMachine device's local time at the time of the call is used." }, "mintemp": { - "name": "Min temp", - "description": "Minimum temperature (°C)." + "name": "Min temperature", + "description": "Minimum temperature in current period (°C)." }, "maxtemp": { - "name": "Max temp", - "description": "Maximum temperature (°C)." + "name": "Max temperature", + "description": "Maximum temperature in current period (°C)." }, "temperature": { "name": "Temperature", @@ -209,11 +209,11 @@ }, "wind": { "name": "Wind speed", - "description": "Wind speed (m/s)." + "description": "Current wind speed (m/s)." }, "solarrad": { "name": "Solar radiation", - "description": "Solar radiation (MJ/m²/h)." + "description": "Current solar radiation (MJ/m²/h)." }, "et": { "name": "Evapotranspiration", @@ -229,11 +229,11 @@ }, "minrh": { "name": "Min relative humidity", - "description": "Min relative humidity (%RH)." + "description": "Minimum relative humidity in current period (%RH)." }, "maxrh": { "name": "Max relative humidity", - "description": "Max relative humidity (%RH)." + "description": "Maximum relative humidity in current period (%RH)." }, "condition": { "name": "Weather condition code", @@ -241,11 +241,11 @@ }, "pressure": { "name": "Barametric pressure", - "description": "Barametric pressure (kPa)." + "description": "Current barametric pressure (kPa)." }, "dewpoint": { "name": "Dew point", - "description": "Dew point (°C)." + "description": "Current dew point (°C)." } } }, diff --git a/homeassistant/components/renson/fan.py b/homeassistant/components/renson/fan.py index 474ab640943..c82cad012c3 100644 --- a/homeassistant/components/renson/fan.py +++ b/homeassistant/components/renson/fan.py @@ -196,7 +196,7 @@ class RensonFan(RensonEntity, FanEntity): all_data = self.coordinator.data breeze_temp = self.api.get_field_value(all_data, BREEZE_TEMPERATURE_FIELD) await self.hass.async_add_executor_job( - self.api.set_breeze, cmd.name, breeze_temp, True + self.api.set_breeze, cmd, breeze_temp, True ) else: await self.hass.async_add_executor_job(self.api.set_manual_level, cmd) diff --git a/homeassistant/components/rest/data.py b/homeassistant/components/rest/data.py index c5dcd0a73a5..3341f296fb9 100644 --- a/homeassistant/components/rest/data.py +++ b/homeassistant/components/rest/data.py @@ -115,6 +115,16 @@ class RestData: for key, value in rendered_params.items(): if isinstance(value, bool): rendered_params[key] = str(value).lower() + elif not isinstance(value, (str, int, float, type(None))): + # For backward compatibility with httpx behavior, convert non-primitive + # types to strings. This maintains compatibility after switching from + # httpx to aiohttp. See https://github.com/home-assistant/core/issues/148153 + _LOGGER.debug( + "REST query parameter '%s' has type %s, converting to string", + key, + type(value).__name__, + ) + rendered_params[key] = str(value) _LOGGER.debug("Updating from %s", self._resource) # Create request kwargs @@ -140,7 +150,14 @@ class RestData: self._method, self._resource, **request_kwargs ) as response: # Read the response - self.data = await response.text(encoding=self._encoding) + # Only use configured encoding if no charset in Content-Type header + # If charset is present in Content-Type, let aiohttp use it + if response.charset: + # Let aiohttp use the charset from Content-Type header + self.data = await response.text() + else: + # Use configured encoding as fallback + self.data = await response.text(encoding=self._encoding) self.headers = response.headers except TimeoutError as ex: diff --git a/homeassistant/components/rest_command/__init__.py b/homeassistant/components/rest_command/__init__.py index c6a4206de4a..0ea5fc60472 100644 --- a/homeassistant/components/rest_command/__init__.py +++ b/homeassistant/components/rest_command/__init__.py @@ -178,6 +178,11 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: ) if not service.return_response: + # always read the response to avoid closing the connection + # before the server has finished sending it, while avoiding excessive memory usage + async for _ in response.content.iter_chunked(1024): + pass + return None _content = None @@ -205,7 +210,11 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: "decoding_type": "text", }, ) from err - return {"content": _content, "status": response.status} + return { + "content": _content, + "status": response.status, + "headers": dict(response.headers), + } except TimeoutError as err: raise HomeAssistantError( diff --git a/homeassistant/components/risco/alarm_control_panel.py b/homeassistant/components/risco/alarm_control_panel.py index 2472baa932e..f485c923776 100644 --- a/homeassistant/components/risco/alarm_control_panel.py +++ b/homeassistant/components/risco/alarm_control_panel.py @@ -82,7 +82,6 @@ async def async_setup_entry( class RiscoAlarm(AlarmControlPanelEntity): """Representation of a Risco cloud partition.""" - _attr_code_format = CodeFormat.NUMBER _attr_has_entity_name = True _attr_name = None @@ -100,8 +99,13 @@ class RiscoAlarm(AlarmControlPanelEntity): self._partition_id = partition_id self._partition = partition self._code = code - self._attr_code_arm_required = options[CONF_CODE_ARM_REQUIRED] - self._code_disarm_required = options[CONF_CODE_DISARM_REQUIRED] + arm_required = options[CONF_CODE_ARM_REQUIRED] + disarm_required = options[CONF_CODE_DISARM_REQUIRED] + self._attr_code_arm_required = arm_required + self._code_disarm_required = disarm_required + self._attr_code_format = ( + CodeFormat.NUMBER if arm_required or disarm_required else None + ) self._risco_to_ha = options[CONF_RISCO_STATES_TO_HA] self._ha_to_risco = options[CONF_HA_STATES_TO_RISCO] for state in self._ha_to_risco: diff --git a/homeassistant/components/russound_rio/const.py b/homeassistant/components/russound_rio/const.py index 9647c419da0..7a8c0bb4fbc 100644 --- a/homeassistant/components/russound_rio/const.py +++ b/homeassistant/components/russound_rio/const.py @@ -6,6 +6,10 @@ from aiorussound import CommandError DOMAIN = "russound_rio" +RUSSOUND_MEDIA_TYPE_PRESET = "preset" + +SELECT_SOURCE_DELAY = 0.5 + RUSSOUND_RIO_EXCEPTIONS = ( CommandError, ConnectionRefusedError, diff --git a/homeassistant/components/russound_rio/media_player.py b/homeassistant/components/russound_rio/media_player.py index aaaad05a2bc..a4b86a85e94 100644 --- a/homeassistant/components/russound_rio/media_player.py +++ b/homeassistant/components/russound_rio/media_player.py @@ -2,9 +2,10 @@ from __future__ import annotations +import asyncio import datetime as dt import logging -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Any from aiorussound import Controller from aiorussound.const import FeatureFlag @@ -19,9 +20,11 @@ from homeassistant.components.media_player import ( MediaType, ) from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import RussoundConfigEntry +from .const import DOMAIN, RUSSOUND_MEDIA_TYPE_PRESET, SELECT_SOURCE_DELAY from .entity import RussoundBaseEntity, command _LOGGER = logging.getLogger(__name__) @@ -45,6 +48,17 @@ async def async_setup_entry( ) +def _parse_preset_source_id(media_id: str) -> tuple[int | None, int]: + source_id = None + if "," in media_id: + source_id_str, preset_id_str = media_id.split(",", maxsplit=1) + source_id = int(source_id_str.strip()) + preset_id = int(preset_id_str.strip()) + else: + preset_id = int(media_id) + return source_id, preset_id + + class RussoundZoneDevice(RussoundBaseEntity, MediaPlayerEntity): """Representation of a Russound Zone.""" @@ -58,6 +72,7 @@ class RussoundZoneDevice(RussoundBaseEntity, MediaPlayerEntity): | MediaPlayerEntityFeature.TURN_OFF | MediaPlayerEntityFeature.SELECT_SOURCE | MediaPlayerEntityFeature.SEEK + | MediaPlayerEntityFeature.PLAY_MEDIA ) _attr_name = None @@ -117,7 +132,7 @@ class RussoundZoneDevice(RussoundBaseEntity, MediaPlayerEntity): @property def media_title(self) -> str | None: """Title of current playing media.""" - return self._source.song_name + return self._source.song_name or self._source.channel @property def media_artist(self) -> str | None: @@ -215,3 +230,37 @@ class RussoundZoneDevice(RussoundBaseEntity, MediaPlayerEntity): async def async_media_seek(self, position: float) -> None: """Seek to a position in the current media.""" await self._zone.set_seek_time(int(position)) + + @command + async def async_play_media( + self, media_type: MediaType | str, media_id: str, **kwargs: Any + ) -> None: + """Play media on the Russound zone.""" + + if media_type != RUSSOUND_MEDIA_TYPE_PRESET: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="unsupported_media_type", + translation_placeholders={ + "media_type": media_type, + }, + ) + + try: + source_id, preset_id = _parse_preset_source_id(media_id) + except ValueError as ve: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="preset_non_integer", + translation_placeholders={"preset_id": media_id}, + ) from ve + if source_id: + await self._zone.select_source(source_id) + await asyncio.sleep(SELECT_SOURCE_DELAY) + if not self._source.presets or preset_id not in self._source.presets: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="missing_preset", + translation_placeholders={"preset_id": media_id}, + ) + await self._zone.restore_preset(preset_id) diff --git a/homeassistant/components/russound_rio/strings.json b/homeassistant/components/russound_rio/strings.json index aa9a1cbc65d..9149a22aac0 100644 --- a/homeassistant/components/russound_rio/strings.json +++ b/homeassistant/components/russound_rio/strings.json @@ -67,6 +67,15 @@ }, "command_error": { "message": "Error executing {function_name} on entity {entity_id}" + }, + "unsupported_media_type": { + "message": "Unsupported media type for Russound zone: {media_type}" + }, + "missing_preset": { + "message": "The specified preset is not available for this source: {preset_id}" + }, + "preset_non_integer": { + "message": "Preset must be an integer, got: {preset_id}" } } } diff --git a/homeassistant/components/screenlogic/manifest.json b/homeassistant/components/screenlogic/manifest.json index 434b8921bc2..2a91fcd6c8e 100644 --- a/homeassistant/components/screenlogic/manifest.json +++ b/homeassistant/components/screenlogic/manifest.json @@ -15,5 +15,5 @@ "documentation": "https://www.home-assistant.io/integrations/screenlogic", "iot_class": "local_push", "loggers": ["screenlogicpy"], - "requirements": ["screenlogicpy==0.10.0"] + "requirements": ["screenlogicpy==0.10.2"] } diff --git a/homeassistant/components/sensor/const.py b/homeassistant/components/sensor/const.py index 994c29b6bbf..5f9d5ec9ca0 100644 --- a/homeassistant/components/sensor/const.py +++ b/homeassistant/components/sensor/const.py @@ -8,6 +8,7 @@ from typing import Final import voluptuous as vol from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, @@ -107,6 +108,12 @@ class SensorDeviceClass(StrEnum): """ # Numerical device classes, these should be aligned with NumberDeviceClass + ABSOLUTE_HUMIDITY = "absolute_humidity" + """Absolute humidity. + + Unit of measurement: `g/m³`, `mg/m³` + """ + APPARENT_POWER = "apparent_power" """Apparent power. @@ -521,6 +528,7 @@ STATE_CLASSES_SCHEMA: Final = vol.All(vol.Lower, vol.Coerce(SensorStateClass)) STATE_CLASSES: Final[list[str]] = [cls.value for cls in SensorStateClass] UNIT_CONVERTERS: dict[SensorDeviceClass | str | None, type[BaseUnitConverter]] = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: MassVolumeConcentrationConverter, SensorDeviceClass.AREA: AreaConverter, SensorDeviceClass.ATMOSPHERIC_PRESSURE: PressureConverter, SensorDeviceClass.BLOOD_GLUCOSE_CONCENTRATION: BloodGlucoseConcentrationConverter, @@ -554,6 +562,10 @@ UNIT_CONVERTERS: dict[SensorDeviceClass | str | None, type[BaseUnitConverter]] = } DEVICE_CLASS_UNITS: dict[SensorDeviceClass, set[type[StrEnum] | str | None]] = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: { + CONCENTRATION_GRAMS_PER_CUBIC_METER, + CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, + }, SensorDeviceClass.APPARENT_POWER: set(UnitOfApparentPower), SensorDeviceClass.AQI: {None}, SensorDeviceClass.AREA: set(UnitOfArea), @@ -651,6 +663,7 @@ DEFAULT_PRECISION_LIMIT = 2 # have 0 decimals, that one should be used and not mW, even though mW also should have # 0 decimals. Otherwise the smaller units will have more decimals than expected. UNITS_PRECISION = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: (CONCENTRATION_GRAMS_PER_CUBIC_METER, 1), SensorDeviceClass.APPARENT_POWER: (UnitOfApparentPower.VOLT_AMPERE, 0), SensorDeviceClass.AREA: (UnitOfArea.SQUARE_CENTIMETERS, 0), SensorDeviceClass.ATMOSPHERIC_PRESSURE: (UnitOfPressure.PA, 0), @@ -691,6 +704,7 @@ UNITS_PRECISION = { } DEVICE_CLASS_STATE_CLASSES: dict[SensorDeviceClass, set[SensorStateClass]] = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: {SensorStateClass.MEASUREMENT}, SensorDeviceClass.APPARENT_POWER: {SensorStateClass.MEASUREMENT}, SensorDeviceClass.AQI: {SensorStateClass.MEASUREMENT}, SensorDeviceClass.AREA: set(SensorStateClass), diff --git a/homeassistant/components/sensor/device_condition.py b/homeassistant/components/sensor/device_condition.py index 2b1eb350c3e..1ad5fe12e99 100644 --- a/homeassistant/components/sensor/device_condition.py +++ b/homeassistant/components/sensor/device_condition.py @@ -33,6 +33,7 @@ from . import ATTR_STATE_CLASS, DOMAIN, SensorDeviceClass DEVICE_CLASS_NONE = "none" +CONF_IS_ABSOLUTE_HUMIDITY = "is_absolute_humidity" CONF_IS_APPARENT_POWER = "is_apparent_power" CONF_IS_AQI = "is_aqi" CONF_IS_AREA = "is_area" @@ -88,6 +89,7 @@ CONF_IS_WIND_DIRECTION = "is_wind_direction" CONF_IS_WIND_SPEED = "is_wind_speed" ENTITY_CONDITIONS = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: [{CONF_TYPE: CONF_IS_ABSOLUTE_HUMIDITY}], SensorDeviceClass.APPARENT_POWER: [{CONF_TYPE: CONF_IS_APPARENT_POWER}], SensorDeviceClass.AQI: [{CONF_TYPE: CONF_IS_AQI}], SensorDeviceClass.AREA: [{CONF_TYPE: CONF_IS_AREA}], @@ -159,6 +161,7 @@ CONDITION_SCHEMA = vol.All( vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid, vol.Required(CONF_TYPE): vol.In( [ + CONF_IS_ABSOLUTE_HUMIDITY, CONF_IS_APPARENT_POWER, CONF_IS_AQI, CONF_IS_AREA, diff --git a/homeassistant/components/sensor/device_trigger.py b/homeassistant/components/sensor/device_trigger.py index d44611a49db..ae2125962e8 100644 --- a/homeassistant/components/sensor/device_trigger.py +++ b/homeassistant/components/sensor/device_trigger.py @@ -32,6 +32,7 @@ from . import ATTR_STATE_CLASS, DOMAIN, SensorDeviceClass DEVICE_CLASS_NONE = "none" +CONF_ABSOLUTE_HUMIDITY = "absolute_humidity" CONF_APPARENT_POWER = "apparent_power" CONF_AQI = "aqi" CONF_AREA = "area" @@ -87,6 +88,7 @@ CONF_WIND_DIRECTION = "wind_direction" CONF_WIND_SPEED = "wind_speed" ENTITY_TRIGGERS = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: [{CONF_TYPE: CONF_ABSOLUTE_HUMIDITY}], SensorDeviceClass.APPARENT_POWER: [{CONF_TYPE: CONF_APPARENT_POWER}], SensorDeviceClass.AQI: [{CONF_TYPE: CONF_AQI}], SensorDeviceClass.AREA: [{CONF_TYPE: CONF_AREA}], @@ -159,6 +161,7 @@ TRIGGER_SCHEMA = vol.All( vol.Required(CONF_ENTITY_ID): cv.entity_id_or_uuid, vol.Required(CONF_TYPE): vol.In( [ + CONF_ABSOLUTE_HUMIDITY, CONF_APPARENT_POWER, CONF_AQI, CONF_AREA, diff --git a/homeassistant/components/sensor/icons.json b/homeassistant/components/sensor/icons.json index 05311868fc6..cea955e061c 100644 --- a/homeassistant/components/sensor/icons.json +++ b/homeassistant/components/sensor/icons.json @@ -3,6 +3,9 @@ "_": { "default": "mdi:eye" }, + "absolute_humidity": { + "default": "mdi:water-opacity" + }, "apparent_power": { "default": "mdi:flash" }, diff --git a/homeassistant/components/sensor/strings.json b/homeassistant/components/sensor/strings.json index ecaeb2504d9..c69bf99eff0 100644 --- a/homeassistant/components/sensor/strings.json +++ b/homeassistant/components/sensor/strings.json @@ -2,6 +2,7 @@ "title": "Sensor", "device_automation": { "condition_type": { + "is_absolute_humidity": "Current {entity_name} absolute humidity", "is_apparent_power": "Current {entity_name} apparent power", "is_aqi": "Current {entity_name} air quality index", "is_area": "Current {entity_name} area", @@ -57,6 +58,7 @@ "is_wind_speed": "Current {entity_name} wind speed" }, "trigger_type": { + "absolute_humidity": "{entity_name} absolute humidity changes", "apparent_power": "{entity_name} apparent power changes", "aqi": "{entity_name} air quality index changes", "area": "{entity_name} area changes", @@ -148,6 +150,9 @@ "duration": { "name": "Duration" }, + "absolute_humidity": { + "name": "Absolute humidity" + }, "apparent_power": { "name": "Apparent power" }, diff --git a/homeassistant/components/sharkiq/manifest.json b/homeassistant/components/sharkiq/manifest.json index 9f9009693e5..c29fc582462 100644 --- a/homeassistant/components/sharkiq/manifest.json +++ b/homeassistant/components/sharkiq/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/sharkiq", "iot_class": "cloud_polling", "loggers": ["sharkiq"], - "requirements": ["sharkiq==1.1.0"] + "requirements": ["sharkiq==1.1.1"] } diff --git a/homeassistant/components/shelly/manifest.json b/homeassistant/components/shelly/manifest.json index 1db8dbf55c6..08c9163bb3b 100644 --- a/homeassistant/components/shelly/manifest.json +++ b/homeassistant/components/shelly/manifest.json @@ -9,7 +9,7 @@ "iot_class": "local_push", "loggers": ["aioshelly"], "quality_scale": "silver", - "requirements": ["aioshelly==13.7.1"], + "requirements": ["aioshelly==13.7.2"], "zeroconf": [ { "type": "_http._tcp.local.", diff --git a/homeassistant/components/smartthings/manifest.json b/homeassistant/components/smartthings/manifest.json index 7c3fc47e512..2c4974a6567 100644 --- a/homeassistant/components/smartthings/manifest.json +++ b/homeassistant/components/smartthings/manifest.json @@ -30,5 +30,5 @@ "iot_class": "cloud_push", "loggers": ["pysmartthings"], "quality_scale": "bronze", - "requirements": ["pysmartthings==3.2.5"] + "requirements": ["pysmartthings==3.2.7"] } diff --git a/homeassistant/components/smartthings/select.py b/homeassistant/components/smartthings/select.py index 99dc7a09f87..3106aba5e49 100644 --- a/homeassistant/components/smartthings/select.py +++ b/homeassistant/components/smartthings/select.py @@ -18,6 +18,11 @@ from .entity import SmartThingsEntity LAMP_TO_HA = { "extraHigh": "extra_high", + "high": "high", + "mid": "mid", + "low": "low", + "on": "on", + "off": "off", } WASHER_SOIL_LEVEL_TO_HA = { diff --git a/homeassistant/components/snapcast/media_player.py b/homeassistant/components/snapcast/media_player.py index 7d9cf74b2cc..8e3f787e71d 100644 --- a/homeassistant/components/snapcast/media_player.py +++ b/homeassistant/components/snapcast/media_player.py @@ -12,9 +12,11 @@ import voluptuous as vol from homeassistant.components.media_player import ( DOMAIN as MEDIA_PLAYER_DOMAIN, + MediaPlayerDeviceClass, MediaPlayerEntity, MediaPlayerEntityFeature, MediaPlayerState, + MediaType, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PORT @@ -180,6 +182,8 @@ class SnapcastBaseDevice(SnapcastCoordinatorEntity, MediaPlayerEntity): | MediaPlayerEntityFeature.VOLUME_SET | MediaPlayerEntityFeature.SELECT_SOURCE ) + _attr_media_content_type = MediaType.MUSIC + _attr_device_class = MediaPlayerDeviceClass.SPEAKER def __init__( self, @@ -275,6 +279,76 @@ class SnapcastBaseDevice(SnapcastCoordinatorEntity, MediaPlayerEntity): """Handle the unjoin service.""" raise NotImplementedError + @property + def metadata(self) -> Mapping[str, Any]: + """Get metadata from the current stream.""" + if metadata := self.coordinator.server.stream( + self._current_group.stream + ).metadata: + return metadata + + # Fallback to an empty dict + return {} + + @property + def media_title(self) -> str | None: + """Title of current playing media.""" + return self.metadata.get("title") + + @property + def media_image_url(self) -> str | None: + """Image url of current playing media.""" + return self.metadata.get("artUrl") + + @property + def media_artist(self) -> str | None: + """Artist of current playing media, music track only.""" + if (value := self.metadata.get("artist")) is not None: + return ", ".join(value) + + return None + + @property + def media_album_name(self) -> str | None: + """Album name of current playing media, music track only.""" + return self.metadata.get("album") + + @property + def media_album_artist(self) -> str | None: + """Album artist of current playing media, music track only.""" + if (value := self.metadata.get("albumArtist")) is not None: + return ", ".join(value) + + return None + + @property + def media_track(self) -> int | None: + """Track number of current playing media, music track only.""" + if (value := self.metadata.get("trackNumber")) is not None: + return int(value) + + return None + + @property + def media_duration(self) -> int | None: + """Duration of current playing media in seconds.""" + if (value := self.metadata.get("duration")) is not None: + return int(value) + + return None + + @property + def media_position(self) -> int | None: + """Position of current playing media in seconds.""" + # Position is part of properties object, not metadata object + if properties := self.coordinator.server.stream( + self._current_group.stream + ).properties: + if (value := properties.get("position")) is not None: + return int(value) + + return None + class SnapcastGroupDevice(SnapcastBaseDevice): """Representation of a Snapcast group device.""" diff --git a/homeassistant/components/snmp/device_tracker.py b/homeassistant/components/snmp/device_tracker.py index f69c844f191..eb963ce6a42 100644 --- a/homeassistant/components/snmp/device_tracker.py +++ b/homeassistant/components/snmp/device_tracker.py @@ -7,13 +7,13 @@ import logging from typing import TYPE_CHECKING from pysnmp.error import PySnmpError -from pysnmp.hlapi.asyncio import ( +from pysnmp.hlapi.v3arch.asyncio import ( CommunityData, Udp6TransportTarget, UdpTransportTarget, UsmUserData, - bulkWalkCmd, - isEndOfMib, + bulk_walk_cmd, + is_end_of_mib, ) import voluptuous as vol @@ -59,7 +59,7 @@ async def async_get_scanner( hass: HomeAssistant, config: ConfigType ) -> SnmpScanner | None: """Validate the configuration and return an SNMP scanner.""" - scanner = SnmpScanner(config[DEVICE_TRACKER_DOMAIN]) + scanner = await SnmpScanner.create(config[DEVICE_TRACKER_DOMAIN]) await scanner.async_init(hass) return scanner if scanner.success_init else None @@ -69,8 +69,8 @@ class SnmpScanner(DeviceScanner): """Queries any SNMP capable Access Point for connected devices.""" def __init__(self, config): - """Initialize the scanner and test the target device.""" - host = config[CONF_HOST] + """Initialize the scanner after testing the target device.""" + community = config[CONF_COMMUNITY] baseoid = config[CONF_BASEOID] authkey = config.get(CONF_AUTH_KEY) @@ -78,19 +78,6 @@ class SnmpScanner(DeviceScanner): privkey = config.get(CONF_PRIV_KEY) privproto = DEFAULT_PRIV_PROTOCOL - try: - # Try IPv4 first. - target = UdpTransportTarget((host, DEFAULT_PORT), timeout=DEFAULT_TIMEOUT) - except PySnmpError: - # Then try IPv6. - try: - target = Udp6TransportTarget( - (host, DEFAULT_PORT), timeout=DEFAULT_TIMEOUT - ) - except PySnmpError as err: - _LOGGER.error("Invalid SNMP host: %s", err) - return - if authkey is not None or privkey is not None: if not authkey: authproto = "none" @@ -109,16 +96,43 @@ class SnmpScanner(DeviceScanner): community, mpModel=SNMP_VERSIONS[DEFAULT_VERSION] ) - self._target = target + self._target: UdpTransportTarget | Udp6TransportTarget self.request_args: RequestArgsType | None = None self.baseoid = baseoid self.last_results = [] self.success_init = False + @classmethod + async def create(cls, config): + """Asynchronously test the target device before fully initializing the scanner.""" + host = config[CONF_HOST] + + try: + # Try IPv4 first. + target = await UdpTransportTarget.create( + (host, DEFAULT_PORT), timeout=DEFAULT_TIMEOUT + ) + except PySnmpError: + # Then try IPv6. + try: + target = Udp6TransportTarget( + (host, DEFAULT_PORT), timeout=DEFAULT_TIMEOUT + ) + except PySnmpError as err: + _LOGGER.error("Invalid SNMP host: %s", err) + return None + instance = cls(config) + instance._target = target + + return instance + async def async_init(self, hass: HomeAssistant) -> None: """Make a one-off read to check if the target device is reachable and readable.""" self.request_args = await async_create_request_cmd_args( - hass, self._auth_data, self._target, self.baseoid + hass, + self._auth_data, + self._target, + self.baseoid, ) data = await self.async_get_snmp_data() self.success_init = data is not None @@ -154,7 +168,7 @@ class SnmpScanner(DeviceScanner): assert self.request_args is not None engine, auth_data, target, context_data, object_type = self.request_args - walker = bulkWalkCmd( + walker = bulk_walk_cmd( engine, auth_data, target, @@ -177,7 +191,7 @@ class SnmpScanner(DeviceScanner): return None for _oid, value in res: - if not isEndOfMib(res): + if not is_end_of_mib(res): try: mac = binascii.hexlify(value.asOctets()).decode("utf-8") except AttributeError: diff --git a/homeassistant/components/snmp/manifest.json b/homeassistant/components/snmp/manifest.json index a2a4405a1b5..ebe1bcc0262 100644 --- a/homeassistant/components/snmp/manifest.json +++ b/homeassistant/components/snmp/manifest.json @@ -6,5 +6,5 @@ "iot_class": "local_polling", "loggers": ["pyasn1", "pysmi", "pysnmp"], "quality_scale": "legacy", - "requirements": ["pysnmp==6.2.6"] + "requirements": ["pysnmp==7.1.21"] } diff --git a/homeassistant/components/snmp/sensor.py b/homeassistant/components/snmp/sensor.py index bd50e2050e0..3574affaccd 100644 --- a/homeassistant/components/snmp/sensor.py +++ b/homeassistant/components/snmp/sensor.py @@ -8,13 +8,13 @@ from struct import unpack from pyasn1.codec.ber import decoder from pysnmp.error import PySnmpError -import pysnmp.hlapi.asyncio as hlapi -from pysnmp.hlapi.asyncio import ( +import pysnmp.hlapi.v3arch.asyncio as hlapi +from pysnmp.hlapi.v3arch.asyncio import ( CommunityData, Udp6TransportTarget, UdpTransportTarget, UsmUserData, - getCmd, + get_cmd, ) from pysnmp.proto.rfc1902 import Opaque from pysnmp.proto.rfc1905 import NoSuchObject @@ -134,7 +134,7 @@ async def async_setup_platform( try: # Try IPv4 first. - target = UdpTransportTarget((host, port), timeout=DEFAULT_TIMEOUT) + target = await UdpTransportTarget.create((host, port), timeout=DEFAULT_TIMEOUT) except PySnmpError: # Then try IPv6. try: @@ -159,7 +159,7 @@ async def async_setup_platform( auth_data = CommunityData(community, mpModel=SNMP_VERSIONS[version]) request_args = await async_create_request_cmd_args(hass, auth_data, target, baseoid) - get_result = await getCmd(*request_args) + get_result = await get_cmd(*request_args) errindication, _, _, _ = get_result if errindication and not accept_errors: @@ -235,7 +235,7 @@ class SnmpData: async def async_update(self): """Get the latest data from the remote SNMP capable host.""" - get_result = await getCmd(*self._request_args) + get_result = await get_cmd(*self._request_args) errindication, errstatus, errindex, restable = get_result if errindication and not self._accept_errors: diff --git a/homeassistant/components/snmp/switch.py b/homeassistant/components/snmp/switch.py index fd405567d60..26fb7d5e99d 100644 --- a/homeassistant/components/snmp/switch.py +++ b/homeassistant/components/snmp/switch.py @@ -5,15 +5,15 @@ from __future__ import annotations import logging from typing import Any -import pysnmp.hlapi.asyncio as hlapi -from pysnmp.hlapi.asyncio import ( +import pysnmp.hlapi.v3arch.asyncio as hlapi +from pysnmp.hlapi.v3arch.asyncio import ( CommunityData, ObjectIdentity, ObjectType, UdpTransportTarget, UsmUserData, - getCmd, - setCmd, + get_cmd, + set_cmd, ) from pysnmp.proto.rfc1902 import ( Counter32, @@ -169,7 +169,7 @@ async def async_setup_platform( else: auth_data = CommunityData(community, mpModel=SNMP_VERSIONS[version]) - transport = UdpTransportTarget((host, port)) + transport = await UdpTransportTarget.create((host, port)) request_args = await async_create_request_cmd_args( hass, auth_data, transport, baseoid ) @@ -228,10 +228,17 @@ class SnmpSwitch(SwitchEntity): self._state: bool | None = None self._payload_on = payload_on self._payload_off = payload_off - self._target = UdpTransportTarget((host, port)) + self._host = host + self._port = port self._request_args = request_args self._command_args = command_args + async def async_added_to_hass(self) -> None: + """Run when this Entity has been added to HA.""" + # The transport creation is done once this entity is registered with HA + # (rather than in the __init__) + self._target = await UdpTransportTarget.create((self._host, self._port)) # pylint: disable=attribute-defined-outside-init + async def async_turn_on(self, **kwargs: Any) -> None: """Turn on the switch.""" # If vartype set, use it - https://www.pysnmp.com/pysnmp/docs/api-reference.html#pysnmp.smi.rfc1902.ObjectType @@ -255,7 +262,7 @@ class SnmpSwitch(SwitchEntity): async def async_update(self) -> None: """Update the state.""" - get_result = await getCmd(*self._request_args) + get_result = await get_cmd(*self._request_args) errindication, errstatus, errindex, restable = get_result if errindication: @@ -291,6 +298,6 @@ class SnmpSwitch(SwitchEntity): async def _set(self, value: Any) -> None: """Set the state of the switch.""" - await setCmd( + await set_cmd( *self._command_args, ObjectType(ObjectIdentity(self._commandoid), value) ) diff --git a/homeassistant/components/snmp/util.py b/homeassistant/components/snmp/util.py index dd3e9a6b6d2..df0171b6610 100644 --- a/homeassistant/components/snmp/util.py +++ b/homeassistant/components/snmp/util.py @@ -4,7 +4,7 @@ from __future__ import annotations import logging -from pysnmp.hlapi.asyncio import ( +from pysnmp.hlapi.v3arch.asyncio import ( CommunityData, ContextData, ObjectIdentity, @@ -14,8 +14,8 @@ from pysnmp.hlapi.asyncio import ( UdpTransportTarget, UsmUserData, ) -from pysnmp.hlapi.asyncio.cmdgen import lcd, vbProcessor -from pysnmp.smi.builder import MibBuilder +from pysnmp.hlapi.v3arch.asyncio.cmdgen import LCD +from pysnmp.smi import view from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import Event, HomeAssistant, callback @@ -80,7 +80,7 @@ async def async_get_snmp_engine(hass: HomeAssistant) -> SnmpEngine: @callback def _async_shutdown_listener(ev: Event) -> None: _LOGGER.debug("Unconfiguring SNMP engine") - lcd.unconfigure(engine, None) + LCD.unconfigure(engine, None) hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_shutdown_listener) return engine @@ -89,10 +89,10 @@ async def async_get_snmp_engine(hass: HomeAssistant) -> SnmpEngine: def _get_snmp_engine() -> SnmpEngine: """Return a cached instance of SnmpEngine.""" engine = SnmpEngine() - mib_controller = vbProcessor.getMibViewController(engine) - # Actually load the MIBs from disk so we do - # not do it in the event loop - builder: MibBuilder = mib_controller.mibBuilder - if "PYSNMP-MIB" not in builder.mibSymbols: - builder.loadModules() + # Actually load the MIBs from disk so we do not do it in the event loop + mib_view_controller = view.MibViewController( + engine.message_dispatcher.mib_instrum_controller.get_mib_builder() + ) + engine.cache["mibViewController"] = mib_view_controller + mib_view_controller.mibBuilder.load_modules() return engine diff --git a/homeassistant/components/snoo/binary_sensor.py b/homeassistant/components/snoo/binary_sensor.py index 3c91db5b86d..c4eaddcc1fe 100644 --- a/homeassistant/components/snoo/binary_sensor.py +++ b/homeassistant/components/snoo/binary_sensor.py @@ -38,7 +38,7 @@ BINARY_SENSOR_DESCRIPTIONS: list[SnooBinarySensorEntityDescription] = [ SnooBinarySensorEntityDescription( key="right_clip", translation_key="right_clip", - value_fn=lambda data: data.left_safety_clip, + value_fn=lambda data: data.right_safety_clip, device_class=BinarySensorDeviceClass.CONNECTIVITY, entity_category=EntityCategory.DIAGNOSTIC, ), diff --git a/homeassistant/components/switch_as_x/__init__.py b/homeassistant/components/switch_as_x/__init__.py index c77eda9b294..b511e2af2b2 100644 --- a/homeassistant/components/switch_as_x/__init__.py +++ b/homeassistant/components/switch_as_x/__init__.py @@ -10,8 +10,11 @@ from homeassistant.components.homeassistant import exposed_entities from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ENTITY_ID from homeassistant.core import HomeAssistant, callback -from homeassistant.helpers import device_registry as dr, entity_registry as er -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from .const import CONF_INVERT, CONF_TARGET_DOMAIN @@ -19,24 +22,14 @@ _LOGGER = logging.getLogger(__name__) @callback -def async_add_to_device( - hass: HomeAssistant, entry: ConfigEntry, entity_id: str -) -> str | None: - """Add our config entry to the tracked entity's device.""" +def async_get_parent_device_id(hass: HomeAssistant, entity_id: str) -> str | None: + """Get the parent device id.""" registry = er.async_get(hass) - device_registry = dr.async_get(hass) - device_id = None - if ( - not (wrapped_switch := registry.async_get(entity_id)) - or not (device_id := wrapped_switch.device_id) - or not (device_registry.async_get(device_id)) - ): - return device_id + if not (wrapped_switch := registry.async_get(entity_id)): + return None - device_registry.async_update_device(device_id, add_config_entry_id=entry.entry_id) - - return device_id + return wrapped_switch.device_id async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: @@ -68,9 +61,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, - source_device_id=async_add_to_device(hass, entry, entity_id), + source_device_id=async_get_parent_device_id(hass, entity_id), source_entity_id_or_uuid=entry.options[CONF_ENTITY_ID], source_entity_removed=source_entity_removed, ) @@ -96,8 +90,18 @@ async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> options = {**config_entry.options} if config_entry.minor_version < 2: options.setdefault(CONF_INVERT, False) + if config_entry.version < 3: + # Remove the switch_as_x config entry from the source device + if source_device_id := async_get_parent_device_id( + hass, options[CONF_ENTITY_ID] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) hass.config_entries.async_update_entry( - config_entry, options=options, minor_version=2 + config_entry, options=options, minor_version=3 ) _LOGGER.debug( diff --git a/homeassistant/components/switch_as_x/config_flow.py b/homeassistant/components/switch_as_x/config_flow.py index aa9f1d411ce..cf442256cbe 100644 --- a/homeassistant/components/switch_as_x/config_flow.py +++ b/homeassistant/components/switch_as_x/config_flow.py @@ -58,7 +58,7 @@ class SwitchAsXConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): options_flow = OPTIONS_FLOW VERSION = 1 - MINOR_VERSION = 2 + MINOR_VERSION = 3 def async_config_entry_title(self, options: Mapping[str, Any]) -> str: """Return config entry title and hide the wrapped entity if registered.""" diff --git a/homeassistant/components/switch_as_x/entity.py b/homeassistant/components/switch_as_x/entity.py index 64bfe712086..7611725d457 100644 --- a/homeassistant/components/switch_as_x/entity.py +++ b/homeassistant/components/switch_as_x/entity.py @@ -15,7 +15,6 @@ from homeassistant.const import ( ) from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er -from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity import Entity, ToggleEntity from homeassistant.helpers.event import async_track_state_change_event @@ -48,12 +47,8 @@ class BaseEntity(Entity): if wrapped_switch: name = wrapped_switch.original_name - self._device_id = device_id if device_id and (device := device_registry.async_get(device_id)): - self._attr_device_info = DeviceInfo( - connections=device.connections, - identifiers=device.identifiers, - ) + self.device_entry = device self._attr_entity_category = entity_category self._attr_has_entity_name = has_entity_name self._attr_name = name diff --git a/homeassistant/components/switchbot/manifest.json b/homeassistant/components/switchbot/manifest.json index 8e727425a2a..5ef7eec9976 100644 --- a/homeassistant/components/switchbot/manifest.json +++ b/homeassistant/components/switchbot/manifest.json @@ -41,5 +41,5 @@ "iot_class": "local_push", "loggers": ["switchbot"], "quality_scale": "gold", - "requirements": ["PySwitchbot==0.67.0"] + "requirements": ["PySwitchbot==0.68.1"] } diff --git a/homeassistant/components/switchbot_cloud/sensor.py b/homeassistant/components/switchbot_cloud/sensor.py index 5a424ea7892..f93df234289 100644 --- a/homeassistant/components/switchbot_cloud/sensor.py +++ b/homeassistant/components/switchbot_cloud/sensor.py @@ -113,11 +113,11 @@ SENSOR_DESCRIPTIONS_BY_DEVICE_TYPES = { ), "Plug Mini (US)": ( VOLTAGE_DESCRIPTION, - CURRENT_DESCRIPTION_IN_A, + CURRENT_DESCRIPTION_IN_MA, ), "Plug Mini (JP)": ( VOLTAGE_DESCRIPTION, - CURRENT_DESCRIPTION_IN_A, + CURRENT_DESCRIPTION_IN_MA, ), "Hub 2": ( TEMPERATURE_DESCRIPTION, diff --git a/homeassistant/components/telegram_bot/services.yaml b/homeassistant/components/telegram_bot/services.yaml index b1d94d381ac..ce7ebea2b66 100644 --- a/homeassistant/components/telegram_bot/services.yaml +++ b/homeassistant/components/telegram_bot/services.yaml @@ -82,6 +82,14 @@ send_photo: example: "My image" selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -90,13 +98,6 @@ send_photo: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: @@ -163,6 +164,14 @@ send_sticker: example: CAACAgIAAxkBAAEDDldhZD-hqWclr6krLq-FWSfCrGNmOQAC9gAD9HsZAAFeYY-ltPYnrCEE selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -171,13 +180,6 @@ send_sticker: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: @@ -235,6 +237,14 @@ send_animation: example: "My animation" selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -243,13 +253,6 @@ send_animation: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: @@ -316,6 +319,14 @@ send_video: example: "My video" selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -324,13 +335,6 @@ send_video: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: @@ -397,6 +401,14 @@ send_voice: example: "My microphone recording" selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -405,13 +417,6 @@ send_voice: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: @@ -469,6 +474,14 @@ send_document: example: Document Title xy selector: text: + authentication: + selector: + select: + options: + - "basic" + - "digest" + - "bearer_token" + translation_key: "authentication" username: example: myuser selector: @@ -477,13 +490,6 @@ send_document: example: myuser_pwd selector: text: - authentication: - default: digest - selector: - select: - options: - - "digest" - - "bearer_token" target: example: "[12345, 67890] or 12345" selector: diff --git a/homeassistant/components/telegram_bot/strings.json b/homeassistant/components/telegram_bot/strings.json index 4187b6311d9..df3de556efb 100644 --- a/homeassistant/components/telegram_bot/strings.json +++ b/homeassistant/components/telegram_bot/strings.json @@ -130,6 +130,13 @@ "html": "HTML", "plain_text": "Plain text" } + }, + "authentication": { + "options": { + "basic": "Basic", + "digest": "Digest", + "bearer_token": "Bearer token" + } } }, "services": { @@ -213,15 +220,15 @@ }, "username": { "name": "[%key:common::config_flow::data::username%]", - "description": "Username for a URL which require HTTP authentication." + "description": "Username for a URL that requires 'Basic' or 'Digest' authentication." }, "password": { "name": "[%key:common::config_flow::data::password%]", - "description": "Password (or bearer token) for a URL which require HTTP authentication." + "description": "Password (or bearer token) for a URL that requires authentication." }, "authentication": { "name": "Authentication method", - "description": "Define which authentication method to use. Set to `digest` to use HTTP digest authentication, or `bearer_token` for OAuth 2.0 bearer token authentication. Defaults to `basic`." + "description": "Define which authentication method to use. Set to 'Basic' for HTTP basic authentication, 'Digest' for HTTP digest authentication, or 'Bearer token' for OAuth 2.0 bearer token authentication." }, "target": { "name": "Target", @@ -943,10 +950,6 @@ "deprecated_yaml_import_issue_error": { "title": "YAML import failed due to invalid {error_field}", "description": "Configuring {integration_title} using YAML is being removed but there was an error while importing your existing configuration ({telegram_bot}): {error_message}.\nSetup will not proceed.\n\nVerify that your {telegram_bot} is operating correctly and restart Home Assistant to attempt the import again.\n\nAlternatively, you may remove the `{domain}` configuration from your configuration.yaml entirely, restart Home Assistant, and add the {integration_title} integration manually." - }, - "proxy_params_auth_deprecation": { - "title": "{telegram_bot}: Proxy authentication should be moved to the URL", - "description": "Authentication details for the the proxy configured in the {telegram_bot} integration should be moved into the {proxy_url} instead. Please update your configuration and restart Home Assistant to fix this issue.\n\nThe {proxy_params} config key will be removed in a future release." } } } diff --git a/homeassistant/components/template/select.py b/homeassistant/components/template/select.py index 8c05e8e2592..256955e70a8 100644 --- a/homeassistant/components/template/select.py +++ b/homeassistant/components/template/select.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging -from typing import Any +from typing import TYPE_CHECKING, Any import voluptuous as vol @@ -32,6 +32,7 @@ from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from . import TriggerUpdateCoordinator from .const import DOMAIN +from .entity import AbstractTemplateEntity from .template_entity import TemplateEntity, make_template_entity_common_modern_schema from .trigger_entity import TriggerEntity @@ -45,7 +46,7 @@ DEFAULT_OPTIMISTIC = False SELECT_SCHEMA = vol.Schema( { - vol.Required(CONF_STATE): cv.template, + vol.Optional(CONF_STATE): cv.template, vol.Required(CONF_SELECT_OPTION): cv.SCRIPT_SCHEMA, vol.Required(ATTR_OPTIONS): cv.template, vol.Optional(CONF_OPTIMISTIC, default=DEFAULT_OPTIMISTIC): cv.boolean, @@ -116,49 +117,22 @@ async def async_setup_entry( async_add_entities([TemplateSelect(hass, validated_config, config_entry.entry_id)]) -class TemplateSelect(TemplateEntity, SelectEntity): - """Representation of a template select.""" +class AbstractTemplateSelect(AbstractTemplateEntity, SelectEntity): + """Representation of a template select features.""" - _attr_should_poll = False + # 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, config: dict[str, Any]) -> None: # pylint: disable=super-init-not-called + """Initialize the features.""" + self._template = config.get(CONF_STATE) - def __init__( - self, - hass: HomeAssistant, - config: dict[str, Any], - unique_id: str | None, - ) -> None: - """Initialize the select.""" - super().__init__(hass, config=config, unique_id=unique_id) - assert self._attr_name is not None - self._value_template = config[CONF_STATE] - # Scripts can be an empty list, therefore we need to check for None - if (select_option := config.get(CONF_SELECT_OPTION)) is not None: - self.add_script(CONF_SELECT_OPTION, select_option, self._attr_name, DOMAIN) self._options_template = config[ATTR_OPTIONS] - self._attr_assumed_state = self._optimistic = config.get(CONF_OPTIMISTIC, False) + + self._attr_assumed_state = self._optimistic = ( + self._template is None or config.get(CONF_OPTIMISTIC, DEFAULT_OPTIMISTIC) + ) self._attr_options = [] self._attr_current_option = None - self._attr_device_info = async_device_info_to_link_from_device_id( - hass, - config.get(CONF_DEVICE_ID), - ) - - @callback - def _async_setup_templates(self) -> None: - """Set up templates.""" - self.add_template_attribute( - "_attr_current_option", - self._value_template, - validator=cv.string, - none_on_template_error=True, - ) - self.add_template_attribute( - "_attr_options", - self._options_template, - validator=vol.All(cv.ensure_list, [cv.string]), - none_on_template_error=True, - ) - super()._async_setup_templates() async def async_select_option(self, option: str) -> None: """Change the selected option.""" @@ -173,11 +147,56 @@ class TemplateSelect(TemplateEntity, SelectEntity): ) -class TriggerSelectEntity(TriggerEntity, SelectEntity): +class TemplateSelect(TemplateEntity, AbstractTemplateSelect): + """Representation of a template select.""" + + _attr_should_poll = False + + def __init__( + self, + hass: HomeAssistant, + config: dict[str, Any], + unique_id: str | None, + ) -> None: + """Initialize the select.""" + TemplateEntity.__init__(self, hass, config=config, unique_id=unique_id) + AbstractTemplateSelect.__init__(self, config) + + name = self._attr_name + if TYPE_CHECKING: + assert name is not None + + if (select_option := config.get(CONF_SELECT_OPTION)) is not None: + self.add_script(CONF_SELECT_OPTION, select_option, name, DOMAIN) + + self._attr_device_info = async_device_info_to_link_from_device_id( + hass, + config.get(CONF_DEVICE_ID), + ) + + @callback + def _async_setup_templates(self) -> None: + """Set up templates.""" + if self._template is not None: + self.add_template_attribute( + "_attr_current_option", + self._template, + validator=cv.string, + none_on_template_error=True, + ) + self.add_template_attribute( + "_attr_options", + self._options_template, + validator=vol.All(cv.ensure_list, [cv.string]), + none_on_template_error=True, + ) + super()._async_setup_templates() + + +class TriggerSelectEntity(TriggerEntity, AbstractTemplateSelect): """Select entity based on trigger data.""" domain = SELECT_DOMAIN - extra_template_keys = (CONF_STATE,) extra_template_keys_complex = (ATTR_OPTIONS,) def __init__( @@ -187,7 +206,12 @@ class TriggerSelectEntity(TriggerEntity, SelectEntity): config: dict, ) -> None: """Initialize the entity.""" - super().__init__(hass, coordinator, config) + TriggerEntity.__init__(self, hass, coordinator, config) + AbstractTemplateSelect.__init__(self, config) + + if CONF_STATE in config: + self._to_render_simple.append(CONF_STATE) + # Scripts can be an empty list, therefore we need to check for None if (select_option := config.get(CONF_SELECT_OPTION)) is not None: self.add_script( @@ -197,24 +221,26 @@ class TriggerSelectEntity(TriggerEntity, SelectEntity): DOMAIN, ) - @property - def current_option(self) -> str | None: - """Return the currently selected option.""" - return self._rendered.get(CONF_STATE) + def _handle_coordinator_update(self): + """Handle updated data from the coordinator.""" + self._process_data() - @property - def options(self) -> list[str]: - """Return the list of available options.""" - return self._rendered.get(ATTR_OPTIONS, []) - - async def async_select_option(self, option: str) -> None: - """Change the selected option.""" - if self._config[CONF_OPTIMISTIC]: - self._attr_current_option = option + if not self.available: + self.async_write_ha_state() + return + + write_ha_state = False + if (options := self._rendered.get(ATTR_OPTIONS)) is not None: + self._attr_options = vol.All(cv.ensure_list, [cv.string])(options) + write_ha_state = True + + if (state := self._rendered.get(CONF_STATE)) is not None: + self._attr_current_option = cv.string(state) + write_ha_state = True + + if len(self._rendered) > 0: + # In case any non optimistic template + write_ha_state = True + + if write_ha_state: self.async_write_ha_state() - if select_option := self._action_scripts.get(CONF_SELECT_OPTION): - await self.async_run_script( - select_option, - run_variables={ATTR_OPTION: option}, - context=self._context, - ) diff --git a/homeassistant/components/tesla_fleet/config_flow.py b/homeassistant/components/tesla_fleet/config_flow.py index ac55a380abb..48eb736ae56 100644 --- a/homeassistant/components/tesla_fleet/config_flow.py +++ b/homeassistant/components/tesla_fleet/config_flow.py @@ -226,5 +226,7 @@ class OAuth2FlowHandler( def _is_valid_domain(self, domain: str) -> bool: """Validate domain format.""" # Basic domain validation regex - domain_pattern = re.compile(r"^(?:[a-zA-Z0-9]+\.)+[a-zA-Z0-9-]+$") + domain_pattern = re.compile( + r"^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$" + ) return bool(domain_pattern.match(domain)) diff --git a/homeassistant/components/teslemetry/__init__.py b/homeassistant/components/teslemetry/__init__.py index 49af8c1a08d..3ffc6c43efb 100644 --- a/homeassistant/components/teslemetry/__init__.py +++ b/homeassistant/components/teslemetry/__init__.py @@ -215,11 +215,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - energysite.info_coordinator.async_config_entry_first_refresh() for energysite in energysites ), - *( - energysite.history_coordinator.async_config_entry_first_refresh() - for energysite in energysites - if energysite.history_coordinator - ), ) # Add energy device models diff --git a/homeassistant/components/teslemetry/binary_sensor.py b/homeassistant/components/teslemetry/binary_sensor.py index 439df76c838..6905cefdc30 100644 --- a/homeassistant/components/teslemetry/binary_sensor.py +++ b/homeassistant/components/teslemetry/binary_sensor.py @@ -125,8 +125,8 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryBinarySensorEntityDescription, ...] = ( key="charge_state_conn_charge_cable", polling=True, polling_value_fn=lambda x: x != "", - streaming_listener=lambda vehicle, callback: vehicle.listen_ChargingCableType( - lambda value: callback(value is not None and value != "Unknown") + streaming_listener=lambda vehicle, callback: vehicle.listen_DetailedChargeState( + lambda value: callback(None if value is None else value != "Disconnected") ), entity_category=EntityCategory.DIAGNOSTIC, device_class=BinarySensorDeviceClass.CONNECTIVITY, diff --git a/homeassistant/components/teslemetry/coordinator.py b/homeassistant/components/teslemetry/coordinator.py index e6b453402e9..eed00ebc64f 100644 --- a/homeassistant/components/teslemetry/coordinator.py +++ b/homeassistant/components/teslemetry/coordinator.py @@ -183,6 +183,7 @@ class TeslemetryEnergyHistoryCoordinator(DataUpdateCoordinator[dict[str, Any]]): update_interval=ENERGY_HISTORY_INTERVAL, ) self.api = api + self.data = {} async def _async_update_data(self) -> dict[str, Any]: """Update energy site data using Teslemetry API.""" diff --git a/homeassistant/components/tessie/update.py b/homeassistant/components/tessie/update.py index e9af673b1f4..cd3c3b32857 100644 --- a/homeassistant/components/tessie/update.py +++ b/homeassistant/components/tessie/update.py @@ -88,6 +88,13 @@ class TessieUpdateEntity(TessieEntity, UpdateEntity): return self.get("vehicle_state_software_update_install_perc") return None + @property + def release_url(self) -> str | None: + """URL to the full release notes of the latest version available.""" + if self.latest_version is None: + return None + return f"https://stats.tessie.com/versions/{self.latest_version}" + async def async_install( self, version: str | None, backup: bool, **kwargs: Any ) -> None: diff --git a/homeassistant/components/threshold/__init__.py b/homeassistant/components/threshold/__init__.py index 9460a50db80..56d51f4f1e0 100644 --- a/homeassistant/components/threshold/__init__.py +++ b/homeassistant/components/threshold/__init__.py @@ -1,5 +1,7 @@ """The threshold component.""" +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ENTITY_ID, Platform from homeassistant.core import HomeAssistant @@ -7,12 +9,18 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) + +_LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Min/Max from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -25,20 +33,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_ENTITY_ID: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_ENTITY_ID] ), source_entity_id_or_uuid=entry.options[CONF_ENTITY_ID], - source_entity_removed=source_entity_removed, ) ) @@ -51,6 +55,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the threshold config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_ENTITY_ID] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Update listener, called when the config entry options are changed.""" diff --git a/homeassistant/components/threshold/binary_sensor.py b/homeassistant/components/threshold/binary_sensor.py index 3227f030812..88fd2784f96 100644 --- a/homeassistant/components/threshold/binary_sensor.py +++ b/homeassistant/components/threshold/binary_sensor.py @@ -31,8 +31,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import config_validation as cv, entity_registry as er -from homeassistant.helpers.device import async_device_info_to_link_from_entity -from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -102,11 +101,6 @@ async def async_setup_entry( registry, config_entry.options[CONF_ENTITY_ID] ) - device_info = async_device_info_to_link_from_entity( - hass, - entity_id, - ) - hysteresis = config_entry.options[CONF_HYSTERESIS] lower = config_entry.options[CONF_LOWER] name = config_entry.title @@ -116,14 +110,14 @@ async def async_setup_entry( async_add_entities( [ ThresholdSensor( - entity_id, - name, - lower, - upper, - hysteresis, - device_class, - unique_id, - device_info=device_info, + hass, + entity_id=entity_id, + name=name, + lower=lower, + upper=upper, + hysteresis=hysteresis, + device_class=device_class, + unique_id=unique_id, ) ] ) @@ -146,7 +140,14 @@ async def async_setup_platform( async_add_entities( [ ThresholdSensor( - entity_id, name, lower, upper, hysteresis, device_class, None + hass, + entity_id=entity_id, + name=name, + lower=lower, + upper=upper, + hysteresis=hysteresis, + device_class=device_class, + unique_id=None, ) ], ) @@ -171,6 +172,8 @@ class ThresholdSensor(BinarySensorEntity): def __init__( self, + hass: HomeAssistant, + *, entity_id: str, name: str, lower: float | None, @@ -178,12 +181,15 @@ class ThresholdSensor(BinarySensorEntity): hysteresis: float, device_class: BinarySensorDeviceClass | None, unique_id: str | None, - device_info: DeviceInfo | None = None, ) -> None: """Initialize the Threshold sensor.""" self._preview_callback: Callable[[str, Mapping[str, Any]], None] | None = None self._attr_unique_id = unique_id - self._attr_device_info = device_info + if entity_id: # Guard against empty entity_id in preview mode + self.device_entry = async_entity_id_to_device( + hass, + entity_id, + ) self._entity_id = entity_id self._attr_name = name if lower is not None: diff --git a/homeassistant/components/threshold/config_flow.py b/homeassistant/components/threshold/config_flow.py index 24f58333782..29f4a0986c1 100644 --- a/homeassistant/components/threshold/config_flow.py +++ b/homeassistant/components/threshold/config_flow.py @@ -80,6 +80,8 @@ OPTIONS_FLOW = { class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow for Threshold.""" + MINOR_VERSION = 2 + config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW @@ -131,13 +133,14 @@ def ws_start_preview( ) preview_entity = ThresholdSensor( - entity_id, - name, - msg["user_input"].get(CONF_LOWER), - msg["user_input"].get(CONF_UPPER), - msg["user_input"].get(CONF_HYSTERESIS), - None, - None, + hass, + entity_id=entity_id, + name=name, + lower=msg["user_input"].get(CONF_LOWER), + upper=msg["user_input"].get(CONF_UPPER), + hysteresis=msg["user_input"].get(CONF_HYSTERESIS), + device_class=None, + unique_id=None, ) preview_entity.hass = hass diff --git a/homeassistant/components/trend/__init__.py b/homeassistant/components/trend/__init__.py index 086ac818c8e..332ec9455eb 100644 --- a/homeassistant/components/trend/__init__.py +++ b/homeassistant/components/trend/__init__.py @@ -2,6 +2,8 @@ from __future__ import annotations +import logging + from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_ENTITY_ID, Platform from homeassistant.core import HomeAssistant @@ -9,14 +11,20 @@ from homeassistant.helpers.device import ( async_entity_id_to_device_id, async_remove_stale_devices_links_keep_entity_device, ) -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) PLATFORMS = [Platform.BINARY_SENSOR] +_LOGGER = logging.getLogger(__name__) + async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Trend from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, @@ -37,6 +45,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( @@ -53,6 +62,40 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: + """Migrate old entry.""" + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 1: + # This means the user has downgraded from a future version + return False + if config_entry.version == 1: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the trend config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_ENTITY_ID] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) + + return True + + async def config_entry_update_listener(hass: HomeAssistant, entry: ConfigEntry) -> None: """Handle an Trend options update.""" await hass.config_entries.async_reload(entry.entry_id) diff --git a/homeassistant/components/trend/binary_sensor.py b/homeassistant/components/trend/binary_sensor.py index 30058bb056c..5a7046c2125 100644 --- a/homeassistant/components/trend/binary_sensor.py +++ b/homeassistant/components/trend/binary_sensor.py @@ -33,8 +33,8 @@ from homeassistant.const import ( STATE_UNKNOWN, ) from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback -from homeassistant.helpers import config_validation as cv, device_registry as dr -from homeassistant.helpers.device import async_device_info_to_link_from_entity +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.entity import generate_entity_id from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, @@ -114,6 +114,7 @@ async def async_setup_platform( for sensor_name, sensor_config in config[CONF_SENSORS].items(): entities.append( SensorTrend( + hass, name=sensor_config.get(CONF_FRIENDLY_NAME, sensor_name), entity_id=sensor_config[CONF_ENTITY_ID], attribute=sensor_config.get(CONF_ATTRIBUTE), @@ -140,14 +141,10 @@ async def async_setup_entry( ) -> None: """Set up trend sensor from config entry.""" - device_info = async_device_info_to_link_from_entity( - hass, - entry.options[CONF_ENTITY_ID], - ) - async_add_entities( [ SensorTrend( + hass, name=entry.title, entity_id=entry.options[CONF_ENTITY_ID], attribute=entry.options.get(CONF_ATTRIBUTE), @@ -159,7 +156,6 @@ async def async_setup_entry( min_samples=entry.options.get(CONF_MIN_SAMPLES, DEFAULT_MIN_SAMPLES), max_samples=entry.options.get(CONF_MAX_SAMPLES, DEFAULT_MAX_SAMPLES), unique_id=entry.entry_id, - device_info=device_info, ) ] ) @@ -174,6 +170,8 @@ class SensorTrend(BinarySensorEntity, RestoreEntity): def __init__( self, + hass: HomeAssistant, + *, name: str, entity_id: str, attribute: str | None, @@ -185,7 +183,6 @@ class SensorTrend(BinarySensorEntity, RestoreEntity): unique_id: str | None = None, device_class: BinarySensorDeviceClass | None = None, sensor_entity_id: str | None = None, - device_info: dr.DeviceInfo | None = None, ) -> None: """Initialize the sensor.""" self._entity_id = entity_id @@ -199,7 +196,10 @@ class SensorTrend(BinarySensorEntity, RestoreEntity): self._attr_name = name self._attr_device_class = device_class self._attr_unique_id = unique_id - self._attr_device_info = device_info + self.device_entry = async_entity_id_to_device( + hass, + entity_id, + ) if sensor_entity_id: self.entity_id = sensor_entity_id diff --git a/homeassistant/components/trend/config_flow.py b/homeassistant/components/trend/config_flow.py index 756b9536d19..3bb06ae3042 100644 --- a/homeassistant/components/trend/config_flow.py +++ b/homeassistant/components/trend/config_flow.py @@ -101,6 +101,8 @@ CONFIG_SCHEMA = vol.Schema( class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow for Trend.""" + MINOR_VERSION = 2 + config_flow = { "user": SchemaFlowFormStep(schema=CONFIG_SCHEMA, next_step="settings"), "settings": SchemaFlowFormStep(get_base_options_schema), diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index c8e6e0f67fb..cf9099448df 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -382,7 +382,7 @@ async def _async_convert_audio( assert process.stderr stderr_data = await process.stderr.read() _LOGGER.error(stderr_data.decode()) - raise RuntimeError( + raise HomeAssistantError( f"Unexpected error while running ffmpeg with arguments: {command}. " "See log for details." ) @@ -976,7 +976,7 @@ class SpeechManager: if engine_instance.name is None or engine_instance.name is UNDEFINED: raise HomeAssistantError("TTS engine name is not set.") - if isinstance(engine_instance, Provider) or isinstance(message_or_stream, str): + if isinstance(engine_instance, Provider): if isinstance(message_or_stream, str): message = message_or_stream else: @@ -996,8 +996,18 @@ class SpeechManager: data_gen = make_data_generator(data) else: + if isinstance(message_or_stream, str): + + async def gen_stream() -> AsyncGenerator[str]: + yield message_or_stream + + stream = gen_stream() + + else: + stream = message_or_stream + tts_result = await engine_instance.internal_async_stream_tts_audio( - TTSAudioRequest(language, options, message_or_stream) + TTSAudioRequest(language, options, stream) ) extension = tts_result.extension data_gen = tts_result.data_gen diff --git a/homeassistant/components/tuya/alarm_control_panel.py b/homeassistant/components/tuya/alarm_control_panel.py index 4972fe88339..61985fb7622 100644 --- a/homeassistant/components/tuya/alarm_control_panel.py +++ b/homeassistant/components/tuya/alarm_control_panel.py @@ -20,7 +20,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import EnumTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import EnumTypeData @dataclass(frozen=True) diff --git a/homeassistant/components/tuya/binary_sensor.py b/homeassistant/components/tuya/binary_sensor.py index 486dd6e1387..4fef11a7335 100644 --- a/homeassistant/components/tuya/binary_sensor.py +++ b/homeassistant/components/tuya/binary_sensor.py @@ -15,9 +15,10 @@ from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback +from homeassistant.util.json import json_loads from . import TuyaConfigEntry -from .const import TUYA_DISCOVERY_NEW, DPCode +from .const import TUYA_DISCOVERY_NEW, DPCode, DPType from .entity import TuyaEntity @@ -31,6 +32,9 @@ class TuyaBinarySensorEntityDescription(BinarySensorEntityDescription): # Value or values to consider binary sensor to be "on" on_value: bool | float | int | str | set[bool | float | int | str] = True + # For DPType.BITMAP, the bitmap_key is used to extract the bit mask + bitmap_key: str | None = None + # Commonly used sensors TAMPER_BINARY_SENSOR = TuyaBinarySensorEntityDescription( @@ -46,6 +50,68 @@ TAMPER_BINARY_SENSOR = TuyaBinarySensorEntityDescription( # end up being a binary sensor. # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { + # CO2 Detector + # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy + "co2bj": ( + TuyaBinarySensorEntityDescription( + key=DPCode.CO2_STATE, + device_class=BinarySensorDeviceClass.SAFETY, + on_value="alarm", + ), + TAMPER_BINARY_SENSOR, + ), + # CO Detector + # https://developer.tuya.com/en/docs/iot/categorycobj?id=Kaiuz3u1j6q1v + "cobj": ( + TuyaBinarySensorEntityDescription( + key=DPCode.CO_STATE, + device_class=BinarySensorDeviceClass.SAFETY, + on_value="1", + ), + TuyaBinarySensorEntityDescription( + key=DPCode.CO_STATUS, + device_class=BinarySensorDeviceClass.SAFETY, + on_value="alarm", + ), + TAMPER_BINARY_SENSOR, + ), + # Dehumidifier + # https://developer.tuya.com/en/docs/iot/categorycs?id=Kaiuz1vcz4dha + "cs": ( + TuyaBinarySensorEntityDescription( + key="tankfull", + dpcode=DPCode.FAULT, + device_class=BinarySensorDeviceClass.PROBLEM, + entity_category=EntityCategory.DIAGNOSTIC, + bitmap_key="tankfull", + translation_key="tankfull", + ), + TuyaBinarySensorEntityDescription( + key="defrost", + dpcode=DPCode.FAULT, + device_class=BinarySensorDeviceClass.PROBLEM, + entity_category=EntityCategory.DIAGNOSTIC, + bitmap_key="defrost", + translation_key="defrost", + ), + TuyaBinarySensorEntityDescription( + key="wet", + dpcode=DPCode.FAULT, + device_class=BinarySensorDeviceClass.PROBLEM, + entity_category=EntityCategory.DIAGNOSTIC, + bitmap_key="wet", + translation_key="wet", + ), + ), + # Smart Pet Feeder + # https://developer.tuya.com/en/docs/iot/categorycwwsq?id=Kaiuz2b6vydld + "cwwsq": ( + TuyaBinarySensorEntityDescription( + key=DPCode.FEED_STATE, + translation_key="feeding", + on_value="feeding", + ), + ), # Multi-functional Sensor # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 "dgnbj": ( @@ -111,40 +177,6 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { ), TAMPER_BINARY_SENSOR, ), - # CO2 Detector - # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy - "co2bj": ( - TuyaBinarySensorEntityDescription( - key=DPCode.CO2_STATE, - device_class=BinarySensorDeviceClass.SAFETY, - on_value="alarm", - ), - TAMPER_BINARY_SENSOR, - ), - # CO Detector - # https://developer.tuya.com/en/docs/iot/categorycobj?id=Kaiuz3u1j6q1v - "cobj": ( - TuyaBinarySensorEntityDescription( - key=DPCode.CO_STATE, - device_class=BinarySensorDeviceClass.SAFETY, - on_value="1", - ), - TuyaBinarySensorEntityDescription( - key=DPCode.CO_STATUS, - device_class=BinarySensorDeviceClass.SAFETY, - on_value="alarm", - ), - TAMPER_BINARY_SENSOR, - ), - # Smart Pet Feeder - # https://developer.tuya.com/en/docs/iot/categorycwwsq?id=Kaiuz2b6vydld - "cwwsq": ( - TuyaBinarySensorEntityDescription( - key=DPCode.FEED_STATE, - translation_key="feeding", - on_value="feeding", - ), - ), # Human Presence Sensor # https://developer.tuya.com/en/docs/iot/categoryhps?id=Kaiuz42yhn1hs "hps": ( @@ -174,6 +206,16 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { ), TAMPER_BINARY_SENSOR, ), + # Luminance Sensor + # https://developer.tuya.com/en/docs/iot/categoryldcg?id=Kaiuz3n7u69l8 + "ldcg": ( + TuyaBinarySensorEntityDescription( + key=DPCode.TEMPER_ALARM, + device_class=BinarySensorDeviceClass.TAMPER, + entity_category=EntityCategory.DIAGNOSTIC, + ), + TAMPER_BINARY_SENSOR, + ), # Door and Window Controller # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r5zjsy9 "mc": ( @@ -205,16 +247,6 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { on_value={"AQAB"}, ), ), - # Luminance Sensor - # https://developer.tuya.com/en/docs/iot/categoryldcg?id=Kaiuz3n7u69l8 - "ldcg": ( - TuyaBinarySensorEntityDescription( - key=DPCode.TEMPER_ALARM, - device_class=BinarySensorDeviceClass.TAMPER, - entity_category=EntityCategory.DIAGNOSTIC, - ), - TAMPER_BINARY_SENSOR, - ), # PIR Detector # https://developer.tuya.com/en/docs/iot/categorypir?id=Kaiuz3ss11b80 "pir": ( @@ -235,6 +267,9 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { ), TAMPER_BINARY_SENSOR, ), + # Temperature and Humidity Sensor with External Probe + # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 + "qxj": (TAMPER_BINARY_SENSOR,), # Gas Detector # https://developer.tuya.com/en/docs/iot/categoryrqbj?id=Kaiuz3d162ubw "rqbj": ( @@ -291,9 +326,6 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { # Temperature and Humidity Sensor # https://developer.tuya.com/en/docs/iot/categorywsdcg?id=Kaiuz3hinij34 "wsdcg": (TAMPER_BINARY_SENSOR,), - # Temperature and Humidity Sensor with External Probe - # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 - "qxj": (TAMPER_BINARY_SENSOR,), # Pressure Sensor # https://developer.tuya.com/en/docs/iot/categoryylcg?id=Kaiuz3kc2e4gm "ylcg": ( @@ -343,6 +375,22 @@ BINARY_SENSORS: dict[str, tuple[TuyaBinarySensorEntityDescription, ...]] = { } +def _get_bitmap_bit_mask( + device: CustomerDevice, dpcode: str, bitmap_key: str | None +) -> int | None: + """Get the bit mask for a given bitmap description.""" + if ( + bitmap_key is None + or (status_range := device.status_range.get(dpcode)) is None + or status_range.type != DPType.BITMAP + or not isinstance(bitmap_values := json_loads(status_range.values), dict) + or not isinstance(bitmap_labels := bitmap_values.get("label"), list) + or bitmap_key not in bitmap_labels + ): + return None + return bitmap_labels.index(bitmap_key) + + async def async_setup_entry( hass: HomeAssistant, entry: TuyaConfigEntry, @@ -361,12 +409,23 @@ async def async_setup_entry( for description in descriptions: dpcode = description.dpcode or description.key if dpcode in device.status: - entities.append( - TuyaBinarySensorEntity( - device, hass_data.manager, description - ) + mask = _get_bitmap_bit_mask( + device, dpcode, description.bitmap_key ) + if ( + description.bitmap_key is None # Regular binary sensor + or mask is not None # Bitmap sensor with valid mask + ): + entities.append( + TuyaBinarySensorEntity( + device, + hass_data.manager, + description, + mask, + ) + ) + async_add_entities(entities) async_discover_device([*hass_data.manager.device_map]) @@ -386,11 +445,13 @@ class TuyaBinarySensorEntity(TuyaEntity, BinarySensorEntity): device: CustomerDevice, device_manager: Manager, description: TuyaBinarySensorEntityDescription, + bit_mask: int | None = None, ) -> None: """Init Tuya binary sensor.""" super().__init__(device, device_manager) self.entity_description = description self._attr_unique_id = f"{super().unique_id}{description.key}" + self._bit_mask = bit_mask @property def is_on(self) -> bool: @@ -399,6 +460,10 @@ class TuyaBinarySensorEntity(TuyaEntity, BinarySensorEntity): if dpcode not in self.device.status: return False + if self._bit_mask is not None: + # For bitmap sensors, check the specific bit mask + return (self.device.status[dpcode] & (1 << self._bit_mask)) != 0 + if isinstance(self.entity_description.on_value, set): return self.device.status[dpcode] in self.entity_description.on_value diff --git a/homeassistant/components/tuya/button.py b/homeassistant/components/tuya/button.py index 8e538b07309..928e584e77d 100644 --- a/homeassistant/components/tuya/button.py +++ b/homeassistant/components/tuya/button.py @@ -17,6 +17,14 @@ from .entity import TuyaEntity # All descriptions can be found here. # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq BUTTONS: dict[str, tuple[ButtonEntityDescription, ...]] = { + # Wake Up Light II + # Not documented + "hxd": ( + ButtonEntityDescription( + key=DPCode.SWITCH_USB6, + translation_key="snooze", + ), + ), # Robot Vacuum # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo "sd": ( @@ -46,14 +54,6 @@ BUTTONS: dict[str, tuple[ButtonEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), - # Wake Up Light II - # Not documented - "hxd": ( - ButtonEntityDescription( - key=DPCode.SWITCH_USB6, - translation_key="snooze", - ), - ), } diff --git a/homeassistant/components/tuya/camera.py b/homeassistant/components/tuya/camera.py index c04a8a043dc..788a9bcc5c3 100644 --- a/homeassistant/components/tuya/camera.py +++ b/homeassistant/components/tuya/camera.py @@ -17,12 +17,12 @@ from .entity import TuyaEntity # All descriptions can be found here: # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq CAMERAS: tuple[str, ...] = ( - # Smart Camera (including doorbells) - # https://developer.tuya.com/en/docs/iot/categorysgbj?id=Kaiuz37tlpbnu - "sp", # Smart Camera - Low power consumption camera # Undocumented, see https://github.com/home-assistant/core/issues/132844 "dghsxj", + # Smart Camera (including doorbells) + # https://developer.tuya.com/en/docs/iot/categorysgbj?id=Kaiuz37tlpbnu + "sp", ) diff --git a/homeassistant/components/tuya/climate.py b/homeassistant/components/tuya/climate.py index 547f3a14c93..734f6ba7f7a 100644 --- a/homeassistant/components/tuya/climate.py +++ b/homeassistant/components/tuya/climate.py @@ -25,7 +25,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import IntegerTypeData TUYA_HVAC_TO_HA = { "auto": HVACMode.HEAT_COOL, @@ -47,6 +48,12 @@ class TuyaClimateEntityDescription(ClimateEntityDescription): CLIMATE_DESCRIPTIONS: dict[str, TuyaClimateEntityDescription] = { + # Electric Fireplace + # https://developer.tuya.com/en/docs/iot/f?id=Kacpeobojffop + "dbl": TuyaClimateEntityDescription( + key="dbl", + switch_only_hvac_mode=HVACMode.HEAT, + ), # Air conditioner # https://developer.tuya.com/en/docs/iot/categorykt?id=Kaiuz0z71ov2n "kt": TuyaClimateEntityDescription( @@ -77,9 +84,6 @@ CLIMATE_DESCRIPTIONS: dict[str, TuyaClimateEntityDescription] = { key="wkf", switch_only_hvac_mode=HVACMode.HEAT, ), - # Electric Fireplace - # https://developer.tuya.com/en/docs/iot/f?id=Kacpeobojffop - "dbl": TuyaClimateEntityDescription(key="dbl", switch_only_hvac_mode=HVACMode.HEAT), } diff --git a/homeassistant/components/tuya/const.py b/homeassistant/components/tuya/const.py index 922aaab193b..f9377114e47 100644 --- a/homeassistant/components/tuya/const.py +++ b/homeassistant/components/tuya/const.py @@ -82,6 +82,7 @@ class WorkMode(StrEnum): class DPType(StrEnum): """Data point types.""" + BITMAP = "Bitmap" BOOLEAN = "Boolean" ENUM = "Enum" INTEGER = "Integer" @@ -314,6 +315,8 @@ class DPCode(StrEnum): SWITCH_6 = "switch_6" # Switch 6 SWITCH_7 = "switch_7" # Switch 7 SWITCH_8 = "switch_8" # Switch 8 + SWITCH_ALARM_LIGHT = "switch_alarm_light" + SWITCH_ALARM_SOUND = "switch_alarm_sound" SWITCH_BACKLIGHT = "switch_backlight" # Backlight switch SWITCH_CHARGE = "switch_charge" SWITCH_CONTROLLER = "switch_controller" diff --git a/homeassistant/components/tuya/cover.py b/homeassistant/components/tuya/cover.py index 315075e7f37..a385a35d903 100644 --- a/homeassistant/components/tuya/cover.py +++ b/homeassistant/components/tuya/cover.py @@ -21,7 +21,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import IntegerTypeData @dataclass(frozen=True) @@ -38,6 +39,31 @@ class TuyaCoverEntityDescription(CoverEntityDescription): COVERS: dict[str, tuple[TuyaCoverEntityDescription, ...]] = { + # Garage Door Opener + # https://developer.tuya.com/en/docs/iot/categoryckmkzq?id=Kaiuz0ipcboee + "ckmkzq": ( + TuyaCoverEntityDescription( + key=DPCode.SWITCH_1, + translation_key="door", + current_state=DPCode.DOORCONTACT_STATE, + current_state_inverse=True, + device_class=CoverDeviceClass.GARAGE, + ), + TuyaCoverEntityDescription( + key=DPCode.SWITCH_2, + translation_key="door_2", + current_state=DPCode.DOORCONTACT_STATE_2, + current_state_inverse=True, + device_class=CoverDeviceClass.GARAGE, + ), + TuyaCoverEntityDescription( + key=DPCode.SWITCH_3, + translation_key="door_3", + current_state=DPCode.DOORCONTACT_STATE_3, + current_state_inverse=True, + device_class=CoverDeviceClass.GARAGE, + ), + ), # Curtain # Note: Multiple curtains isn't documented # https://developer.tuya.com/en/docs/iot/categorycl?id=Kaiuz1hnpo7df @@ -84,31 +110,6 @@ COVERS: dict[str, tuple[TuyaCoverEntityDescription, ...]] = { device_class=CoverDeviceClass.BLIND, ), ), - # Garage Door Opener - # https://developer.tuya.com/en/docs/iot/categoryckmkzq?id=Kaiuz0ipcboee - "ckmkzq": ( - TuyaCoverEntityDescription( - key=DPCode.SWITCH_1, - translation_key="door", - current_state=DPCode.DOORCONTACT_STATE, - current_state_inverse=True, - device_class=CoverDeviceClass.GARAGE, - ), - TuyaCoverEntityDescription( - key=DPCode.SWITCH_2, - translation_key="door_2", - current_state=DPCode.DOORCONTACT_STATE_2, - current_state_inverse=True, - device_class=CoverDeviceClass.GARAGE, - ), - TuyaCoverEntityDescription( - key=DPCode.SWITCH_3, - translation_key="door_3", - current_state=DPCode.DOORCONTACT_STATE_3, - current_state_inverse=True, - device_class=CoverDeviceClass.GARAGE, - ), - ), # Curtain Switch # https://developer.tuya.com/en/docs/iot/category-clkg?id=Kaiuz0gitil39 "clkg": ( diff --git a/homeassistant/components/tuya/entity.py b/homeassistant/components/tuya/entity.py index cc258560067..fbddfb0ab83 100644 --- a/homeassistant/components/tuya/entity.py +++ b/homeassistant/components/tuya/entity.py @@ -2,11 +2,7 @@ from __future__ import annotations -import base64 -from dataclasses import dataclass -import json -import struct -from typing import Any, Literal, Self, overload +from typing import Any, Literal, overload from tuya_sharing import CustomerDevice, Manager @@ -15,11 +11,10 @@ from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity from .const import DOMAIN, LOGGER, TUYA_HA_SIGNAL_UPDATE_ENTITY, DPCode, DPType -from .util import remap_value +from .models import EnumTypeData, IntegerTypeData _DPTYPE_MAPPING: dict[str, DPType] = { - "Bitmap": DPType.RAW, - "bitmap": DPType.RAW, + "bitmap": DPType.BITMAP, "bool": DPType.BOOLEAN, "enum": DPType.ENUM, "json": DPType.JSON, @@ -29,118 +24,6 @@ _DPTYPE_MAPPING: dict[str, DPType] = { } -@dataclass -class IntegerTypeData: - """Integer Type Data.""" - - dpcode: DPCode - min: int - max: int - scale: float - step: float - unit: str | None = None - type: str | None = None - - @property - def max_scaled(self) -> float: - """Return the max scaled.""" - return self.scale_value(self.max) - - @property - def min_scaled(self) -> float: - """Return the min scaled.""" - return self.scale_value(self.min) - - @property - def step_scaled(self) -> float: - """Return the step scaled.""" - return self.step / (10**self.scale) - - def scale_value(self, value: float) -> float: - """Scale a value.""" - return value / (10**self.scale) - - def scale_value_back(self, value: float) -> int: - """Return raw value for scaled.""" - return int(value * (10**self.scale)) - - def remap_value_to( - self, - value: float, - to_min: float = 0, - to_max: float = 255, - reverse: bool = False, - ) -> float: - """Remap a value from this range to a new range.""" - return remap_value(value, self.min, self.max, to_min, to_max, reverse) - - def remap_value_from( - self, - value: float, - from_min: float = 0, - from_max: float = 255, - reverse: bool = False, - ) -> float: - """Remap a value from its current range to this range.""" - return remap_value(value, from_min, from_max, self.min, self.max, reverse) - - @classmethod - def from_json(cls, dpcode: DPCode, data: str) -> IntegerTypeData | None: - """Load JSON string and return a IntegerTypeData object.""" - if not (parsed := json.loads(data)): - return None - - return cls( - dpcode, - min=int(parsed["min"]), - max=int(parsed["max"]), - scale=float(parsed["scale"]), - step=max(float(parsed["step"]), 1), - unit=parsed.get("unit"), - type=parsed.get("type"), - ) - - -@dataclass -class EnumTypeData: - """Enum Type Data.""" - - dpcode: DPCode - range: list[str] - - @classmethod - def from_json(cls, dpcode: DPCode, data: str) -> EnumTypeData | None: - """Load JSON string and return a EnumTypeData object.""" - if not (parsed := json.loads(data)): - return None - return cls(dpcode, **parsed) - - -@dataclass -class ElectricityTypeData: - """Electricity Type Data.""" - - electriccurrent: str | None = None - power: str | None = None - voltage: str | None = None - - @classmethod - def from_json(cls, data: str) -> Self: - """Load JSON string and return a ElectricityTypeData object.""" - return cls(**json.loads(data.lower())) - - @classmethod - def from_raw(cls, data: str) -> Self: - """Decode base64 string and return a ElectricityTypeData object.""" - raw = base64.b64decode(data) - voltage = struct.unpack(">H", raw[0:2])[0] / 10.0 - electriccurrent = struct.unpack(">L", b"\x00" + raw[2:5])[0] / 1000.0 - power = struct.unpack(">L", b"\x00" + raw[5:8])[0] / 1000.0 - return cls( - electriccurrent=str(electriccurrent), power=str(power), voltage=str(voltage) - ) - - class TuyaEntity(Entity): """Tuya base device.""" diff --git a/homeassistant/components/tuya/fan.py b/homeassistant/components/tuya/fan.py index 3b951e75da1..f96ea2c0a65 100644 --- a/homeassistant/components/tuya/fan.py +++ b/homeassistant/components/tuya/fan.py @@ -22,14 +22,15 @@ from homeassistant.util.percentage import ( from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import EnumTypeData, IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import EnumTypeData, IntegerTypeData TUYA_SUPPORT_TYPE = { + "cs", # Dehumidifier "fs", # Fan "fsd", # Fan with Light "fskg", # Fan wall switch "kj", # Air Purifier - "cs", # Dehumidifier } diff --git a/homeassistant/components/tuya/humidifier.py b/homeassistant/components/tuya/humidifier.py index f8fd9237ffc..6539d98e9d8 100644 --- a/homeassistant/components/tuya/humidifier.py +++ b/homeassistant/components/tuya/humidifier.py @@ -19,7 +19,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import IntegerTypeData @dataclass(frozen=True) diff --git a/homeassistant/components/tuya/icons.json b/homeassistant/components/tuya/icons.json index e28371f2b3d..40bbf41fd0d 100644 --- a/homeassistant/components/tuya/icons.json +++ b/homeassistant/components/tuya/icons.json @@ -370,6 +370,12 @@ }, "sterilization": { "default": "mdi:minus-circle-outline" + }, + "arm_beep": { + "default": "mdi:volume-high" + }, + "siren": { + "default": "mdi:alarm-light" } } } diff --git a/homeassistant/components/tuya/light.py b/homeassistant/components/tuya/light.py index 67a94c4e267..3f8fc7d0fb9 100644 --- a/homeassistant/components/tuya/light.py +++ b/homeassistant/components/tuya/light.py @@ -25,7 +25,8 @@ from homeassistant.util import color as color_util from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType, WorkMode -from .entity import IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import IntegerTypeData from .util import remap_value @@ -135,6 +136,22 @@ LIGHTS: dict[str, tuple[TuyaLightEntityDescription, ...]] = { brightness=DPCode.BRIGHT_VALUE, ), ), + # Fan + # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c + "fs": ( + TuyaLightEntityDescription( + key=DPCode.LIGHT, + name=None, + color_mode=DPCode.WORK_MODE, + brightness=DPCode.BRIGHT_VALUE, + color_temp=DPCode.TEMP_VALUE, + ), + TuyaLightEntityDescription( + key=DPCode.SWITCH_LED, + translation_key="light_2", + brightness=DPCode.BRIGHT_VALUE_1, + ), + ), # Ceiling Fan Light # https://developer.tuya.com/en/docs/iot/fsd?id=Kaof8eiei4c2v "fsd": ( @@ -176,6 +193,17 @@ LIGHTS: dict[str, tuple[TuyaLightEntityDescription, ...]] = { color_data=DPCode.COLOUR_DATA, ), ), + # Wake Up Light II + # Not documented + "hxd": ( + TuyaLightEntityDescription( + key=DPCode.SWITCH_LED, + translation_key="light", + brightness=(DPCode.BRIGHT_VALUE_V2, DPCode.BRIGHT_VALUE), + brightness_max=DPCode.BRIGHTNESS_MAX_1, + brightness_min=DPCode.BRIGHTNESS_MIN_1, + ), + ), # Humidifier Light # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b "jsq": ( @@ -316,17 +344,6 @@ LIGHTS: dict[str, tuple[TuyaLightEntityDescription, ...]] = { brightness=DPCode.BRIGHT_VALUE_2, ), ), - # Wake Up Light II - # Not documented - "hxd": ( - TuyaLightEntityDescription( - key=DPCode.SWITCH_LED, - translation_key="light", - brightness=(DPCode.BRIGHT_VALUE_V2, DPCode.BRIGHT_VALUE), - brightness_max=DPCode.BRIGHTNESS_MAX_1, - brightness_min=DPCode.BRIGHTNESS_MIN_1, - ), - ), # Outdoor Flood Light # Not documented "tyd": ( @@ -378,22 +395,6 @@ LIGHTS: dict[str, tuple[TuyaLightEntityDescription, ...]] = { color_temp=DPCode.TEMP_CONTROLLER, ), ), - # Fan - # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c - "fs": ( - TuyaLightEntityDescription( - key=DPCode.LIGHT, - name=None, - color_mode=DPCode.WORK_MODE, - brightness=DPCode.BRIGHT_VALUE, - color_temp=DPCode.TEMP_VALUE, - ), - TuyaLightEntityDescription( - key=DPCode.SWITCH_LED, - translation_key="light_2", - brightness=DPCode.BRIGHT_VALUE_1, - ), - ), } # Socket (duplicate of `kg`) diff --git a/homeassistant/components/tuya/models.py b/homeassistant/components/tuya/models.py new file mode 100644 index 00000000000..b4afca83a85 --- /dev/null +++ b/homeassistant/components/tuya/models.py @@ -0,0 +1,124 @@ +"""Tuya Home Assistant Base Device Model.""" + +from __future__ import annotations + +import base64 +from dataclasses import dataclass +import json +import struct +from typing import Self + +from .const import DPCode +from .util import remap_value + + +@dataclass +class IntegerTypeData: + """Integer Type Data.""" + + dpcode: DPCode + min: int + max: int + scale: float + step: float + unit: str | None = None + type: str | None = None + + @property + def max_scaled(self) -> float: + """Return the max scaled.""" + return self.scale_value(self.max) + + @property + def min_scaled(self) -> float: + """Return the min scaled.""" + return self.scale_value(self.min) + + @property + def step_scaled(self) -> float: + """Return the step scaled.""" + return self.step / (10**self.scale) + + def scale_value(self, value: float) -> float: + """Scale a value.""" + return value / (10**self.scale) + + def scale_value_back(self, value: float) -> int: + """Return raw value for scaled.""" + return int(value * (10**self.scale)) + + def remap_value_to( + self, + value: float, + to_min: float = 0, + to_max: float = 255, + reverse: bool = False, + ) -> float: + """Remap a value from this range to a new range.""" + return remap_value(value, self.min, self.max, to_min, to_max, reverse) + + def remap_value_from( + self, + value: float, + from_min: float = 0, + from_max: float = 255, + reverse: bool = False, + ) -> float: + """Remap a value from its current range to this range.""" + return remap_value(value, from_min, from_max, self.min, self.max, reverse) + + @classmethod + def from_json(cls, dpcode: DPCode, data: str) -> IntegerTypeData | None: + """Load JSON string and return a IntegerTypeData object.""" + if not (parsed := json.loads(data)): + return None + + return cls( + dpcode, + min=int(parsed["min"]), + max=int(parsed["max"]), + scale=float(parsed["scale"]), + step=max(float(parsed["step"]), 1), + unit=parsed.get("unit"), + type=parsed.get("type"), + ) + + +@dataclass +class EnumTypeData: + """Enum Type Data.""" + + dpcode: DPCode + range: list[str] + + @classmethod + def from_json(cls, dpcode: DPCode, data: str) -> EnumTypeData | None: + """Load JSON string and return a EnumTypeData object.""" + if not (parsed := json.loads(data)): + return None + return cls(dpcode, **parsed) + + +@dataclass +class ElectricityTypeData: + """Electricity Type Data.""" + + electriccurrent: str | None = None + power: str | None = None + voltage: str | None = None + + @classmethod + def from_json(cls, data: str) -> Self: + """Load JSON string and return a ElectricityTypeData object.""" + return cls(**json.loads(data.lower())) + + @classmethod + def from_raw(cls, data: str) -> Self: + """Decode base64 string and return a ElectricityTypeData object.""" + raw = base64.b64decode(data) + voltage = struct.unpack(">H", raw[0:2])[0] / 10.0 + electriccurrent = struct.unpack(">L", b"\x00" + raw[2:5])[0] / 1000.0 + power = struct.unpack(">L", b"\x00" + raw[5:8])[0] / 1000.0 + return cls( + electriccurrent=str(electriccurrent), power=str(power), voltage=str(voltage) + ) diff --git a/homeassistant/components/tuya/number.py b/homeassistant/components/tuya/number.py index d4fe7836daa..b5b8437ea8b 100644 --- a/homeassistant/components/tuya/number.py +++ b/homeassistant/components/tuya/number.py @@ -16,21 +16,13 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import DEVICE_CLASS_UNITS, DOMAIN, TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import IntegerTypeData # All descriptions can be found here. Mostly the Integer data types in the # default instructions set of each category end up being a number. # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { - # Multi-functional Sensor - # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 - "dgnbj": ( - NumberEntityDescription( - key=DPCode.ALARM_TIME, - translation_key="time", - entity_category=EntityCategory.CONFIG, - ), - ), # Smart Kettle # https://developer.tuya.com/en/docs/iot/fbh?id=K9gf484m21yq7 "bh": ( @@ -64,6 +56,17 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # CO2 Detector + # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy + "co2bj": ( + NumberEntityDescription( + key=DPCode.ALARM_TIME, + translation_key="alarm_duration", + native_unit_of_measurement=UnitOfTime.SECONDS, + device_class=NumberDeviceClass.DURATION, + entity_category=EntityCategory.CONFIG, + ), + ), # Smart Pet Feeder # https://developer.tuya.com/en/docs/iot/categorycwwsq?id=Kaiuz2b6vydld "cwwsq": ( @@ -76,6 +79,24 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { translation_key="voice_times", ), ), + # Multi-functional Sensor + # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 + "dgnbj": ( + NumberEntityDescription( + key=DPCode.ALARM_TIME, + translation_key="time", + entity_category=EntityCategory.CONFIG, + ), + ), + # Fan + # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c + "fs": ( + NumberEntityDescription( + key=DPCode.TEMP, + translation_key="temperature", + device_class=NumberDeviceClass.TEMPERATURE, + ), + ), # Human Presence Sensor # https://developer.tuya.com/en/docs/iot/categoryhps?id=Kaiuz42yhn1hs "hps": ( @@ -102,6 +123,20 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { device_class=NumberDeviceClass.DISTANCE, ), ), + # Humidifier + # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b + "jsq": ( + NumberEntityDescription( + key=DPCode.TEMP_SET, + translation_key="temperature", + device_class=NumberDeviceClass.TEMPERATURE, + ), + NumberEntityDescription( + key=DPCode.TEMP_SET_F, + translation_key="temperature", + device_class=NumberDeviceClass.TEMPERATURE, + ), + ), # Coffee maker # https://developer.tuya.com/en/docs/iot/categorykfj?id=Kaiuz2p12pc7f "kfj": ( @@ -174,6 +209,26 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # Fingerbot + "szjqr": ( + NumberEntityDescription( + key=DPCode.ARM_DOWN_PERCENT, + translation_key="move_down", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.CONFIG, + ), + NumberEntityDescription( + key=DPCode.ARM_UP_PERCENT, + translation_key="move_up", + native_unit_of_measurement=PERCENTAGE, + entity_category=EntityCategory.CONFIG, + ), + NumberEntityDescription( + key=DPCode.CLICK_SUSTAIN_TIME, + translation_key="down_delay", + entity_category=EntityCategory.CONFIG, + ), + ), # Dimmer Switch # https://developer.tuya.com/en/docs/iot/categorytgkg?id=Kaiuz0ktx7m0o "tgkg": ( @@ -241,49 +296,6 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), - # Fingerbot - "szjqr": ( - NumberEntityDescription( - key=DPCode.ARM_DOWN_PERCENT, - translation_key="move_down", - native_unit_of_measurement=PERCENTAGE, - entity_category=EntityCategory.CONFIG, - ), - NumberEntityDescription( - key=DPCode.ARM_UP_PERCENT, - translation_key="move_up", - native_unit_of_measurement=PERCENTAGE, - entity_category=EntityCategory.CONFIG, - ), - NumberEntityDescription( - key=DPCode.CLICK_SUSTAIN_TIME, - translation_key="down_delay", - entity_category=EntityCategory.CONFIG, - ), - ), - # Fan - # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c - "fs": ( - NumberEntityDescription( - key=DPCode.TEMP, - translation_key="temperature", - device_class=NumberDeviceClass.TEMPERATURE, - ), - ), - # Humidifier - # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b - "jsq": ( - NumberEntityDescription( - key=DPCode.TEMP_SET, - translation_key="temperature", - device_class=NumberDeviceClass.TEMPERATURE, - ), - NumberEntityDescription( - key=DPCode.TEMP_SET_F, - translation_key="temperature", - device_class=NumberDeviceClass.TEMPERATURE, - ), - ), # Pool HeatPump "znrb": ( NumberEntityDescription( @@ -292,17 +304,6 @@ NUMBERS: dict[str, tuple[NumberEntityDescription, ...]] = { device_class=NumberDeviceClass.TEMPERATURE, ), ), - # CO2 Detector - # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy - "co2bj": ( - NumberEntityDescription( - key=DPCode.ALARM_TIME, - translation_key="alarm_duration", - native_unit_of_measurement=UnitOfTime.SECONDS, - device_class=NumberDeviceClass.DURATION, - entity_category=EntityCategory.CONFIG, - ), - ), } # Smart Camera - Low power consumption camera (duplicate of `sp`) diff --git a/homeassistant/components/tuya/select.py b/homeassistant/components/tuya/select.py index 21f88156236..4ad4355f876 100644 --- a/homeassistant/components/tuya/select.py +++ b/homeassistant/components/tuya/select.py @@ -18,6 +18,43 @@ from .entity import TuyaEntity # default instructions set of each category end up being a select. # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { + # Curtain + # https://developer.tuya.com/en/docs/iot/f?id=K9gf46o5mtfyc + "cl": ( + SelectEntityDescription( + key=DPCode.CONTROL_BACK_MODE, + entity_category=EntityCategory.CONFIG, + translation_key="curtain_motor_mode", + ), + SelectEntityDescription( + key=DPCode.MODE, + entity_category=EntityCategory.CONFIG, + translation_key="curtain_mode", + ), + ), + # CO2 Detector + # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy + "co2bj": ( + SelectEntityDescription( + key=DPCode.ALARM_VOLUME, + translation_key="volume", + entity_category=EntityCategory.CONFIG, + ), + ), + # Dehumidifier + # https://developer.tuya.com/en/docs/iot/categorycs?id=Kaiuz1vcz4dha + "cs": ( + SelectEntityDescription( + key=DPCode.COUNTDOWN_SET, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + SelectEntityDescription( + key=DPCode.DEHUMIDITY_SET_ENUM, + translation_key="target_humidity", + entity_category=EntityCategory.CONFIG, + ), + ), # Multi-functional Sensor # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 "dgnbj": ( @@ -27,6 +64,81 @@ SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # Electric Blanket + # https://developer.tuya.com/en/docs/iot/categorydr?id=Kaiuz22dyc66p + "dr": ( + SelectEntityDescription( + key=DPCode.LEVEL, + name="Level", + icon="mdi:thermometer-lines", + translation_key="blanket_level", + ), + SelectEntityDescription( + key=DPCode.LEVEL_1, + name="Side A Level", + icon="mdi:thermometer-lines", + translation_key="blanket_level", + ), + SelectEntityDescription( + key=DPCode.LEVEL_2, + name="Side B Level", + icon="mdi:thermometer-lines", + translation_key="blanket_level", + ), + ), + # Fan + # https://developer.tuya.com/en/docs/iot/f?id=K9gf45vs7vkge + "fs": ( + SelectEntityDescription( + key=DPCode.FAN_VERTICAL, + entity_category=EntityCategory.CONFIG, + translation_key="vertical_fan_angle", + ), + SelectEntityDescription( + key=DPCode.FAN_HORIZONTAL, + entity_category=EntityCategory.CONFIG, + translation_key="horizontal_fan_angle", + ), + SelectEntityDescription( + key=DPCode.COUNTDOWN, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + SelectEntityDescription( + key=DPCode.COUNTDOWN_SET, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + ), + # Humidifier + # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b + "jsq": ( + SelectEntityDescription( + key=DPCode.SPRAY_MODE, + entity_category=EntityCategory.CONFIG, + translation_key="humidifier_spray_mode", + ), + SelectEntityDescription( + key=DPCode.LEVEL, + entity_category=EntityCategory.CONFIG, + translation_key="humidifier_level", + ), + SelectEntityDescription( + key=DPCode.MOODLIGHTING, + entity_category=EntityCategory.CONFIG, + translation_key="humidifier_moodlighting", + ), + SelectEntityDescription( + key=DPCode.COUNTDOWN, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + SelectEntityDescription( + key=DPCode.COUNTDOWN_SET, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + ), # Coffee maker # https://developer.tuya.com/en/docs/iot/categorykfj?id=Kaiuz2p12pc7f "kfj": ( @@ -63,6 +175,20 @@ SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { translation_key="light_mode", ), ), + # Air Purifier + # https://developer.tuya.com/en/docs/iot/f?id=K9gf46h2s6dzm + "kj": ( + SelectEntityDescription( + key=DPCode.COUNTDOWN, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + SelectEntityDescription( + key=DPCode.COUNTDOWN_SET, + entity_category=EntityCategory.CONFIG, + translation_key="countdown", + ), + ), # Heater # https://developer.tuya.com/en/docs/iot/categoryqn?id=Kaiuz18kih0sm "qn": ( @@ -71,6 +197,25 @@ SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { translation_key="temperature_level", ), ), + # Robot Vacuum + # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo + "sd": ( + SelectEntityDescription( + key=DPCode.CISTERN, + entity_category=EntityCategory.CONFIG, + translation_key="vacuum_cistern", + ), + SelectEntityDescription( + key=DPCode.COLLECTION_MODE, + entity_category=EntityCategory.CONFIG, + translation_key="vacuum_collection", + ), + SelectEntityDescription( + key=DPCode.MODE, + entity_category=EntityCategory.CONFIG, + translation_key="vacuum_mode", + ), + ), # Smart Water Timer "sfkzq": ( # Irrigation will not be run within this set delay period @@ -128,6 +273,14 @@ SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { translation_key="motion_sensitivity", ), ), + # Fingerbot + "szjqr": ( + SelectEntityDescription( + key=DPCode.MODE, + entity_category=EntityCategory.CONFIG, + translation_key="fingerbot_mode", + ), + ), # IoT Switch? # Note: Undocumented "tdq": ( @@ -185,173 +338,20 @@ SELECTS: dict[str, tuple[SelectEntityDescription, ...]] = { translation_key="led_type_2", ), ), - # Fingerbot - "szjqr": ( - SelectEntityDescription( - key=DPCode.MODE, - entity_category=EntityCategory.CONFIG, - translation_key="fingerbot_mode", - ), - ), - # Robot Vacuum - # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo - "sd": ( - SelectEntityDescription( - key=DPCode.CISTERN, - entity_category=EntityCategory.CONFIG, - translation_key="vacuum_cistern", - ), - SelectEntityDescription( - key=DPCode.COLLECTION_MODE, - entity_category=EntityCategory.CONFIG, - translation_key="vacuum_collection", - ), - SelectEntityDescription( - key=DPCode.MODE, - entity_category=EntityCategory.CONFIG, - translation_key="vacuum_mode", - ), - ), - # Fan - # https://developer.tuya.com/en/docs/iot/f?id=K9gf45vs7vkge - "fs": ( - SelectEntityDescription( - key=DPCode.FAN_VERTICAL, - entity_category=EntityCategory.CONFIG, - translation_key="vertical_fan_angle", - ), - SelectEntityDescription( - key=DPCode.FAN_HORIZONTAL, - entity_category=EntityCategory.CONFIG, - translation_key="horizontal_fan_angle", - ), - SelectEntityDescription( - key=DPCode.COUNTDOWN, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - SelectEntityDescription( - key=DPCode.COUNTDOWN_SET, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - ), - # Curtain - # https://developer.tuya.com/en/docs/iot/f?id=K9gf46o5mtfyc - "cl": ( - SelectEntityDescription( - key=DPCode.CONTROL_BACK_MODE, - entity_category=EntityCategory.CONFIG, - translation_key="curtain_motor_mode", - ), - SelectEntityDescription( - key=DPCode.MODE, - entity_category=EntityCategory.CONFIG, - translation_key="curtain_mode", - ), - ), - # Humidifier - # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b - "jsq": ( - SelectEntityDescription( - key=DPCode.SPRAY_MODE, - entity_category=EntityCategory.CONFIG, - translation_key="humidifier_spray_mode", - ), - SelectEntityDescription( - key=DPCode.LEVEL, - entity_category=EntityCategory.CONFIG, - translation_key="humidifier_level", - ), - SelectEntityDescription( - key=DPCode.MOODLIGHTING, - entity_category=EntityCategory.CONFIG, - translation_key="humidifier_moodlighting", - ), - SelectEntityDescription( - key=DPCode.COUNTDOWN, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - SelectEntityDescription( - key=DPCode.COUNTDOWN_SET, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - ), - # Air Purifier - # https://developer.tuya.com/en/docs/iot/f?id=K9gf46h2s6dzm - "kj": ( - SelectEntityDescription( - key=DPCode.COUNTDOWN, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - SelectEntityDescription( - key=DPCode.COUNTDOWN_SET, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - ), - # Dehumidifier - # https://developer.tuya.com/en/docs/iot/categorycs?id=Kaiuz1vcz4dha - "cs": ( - SelectEntityDescription( - key=DPCode.COUNTDOWN_SET, - entity_category=EntityCategory.CONFIG, - translation_key="countdown", - ), - SelectEntityDescription( - key=DPCode.DEHUMIDITY_SET_ENUM, - translation_key="target_humidity", - entity_category=EntityCategory.CONFIG, - ), - ), - # CO2 Detector - # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy - "co2bj": ( - SelectEntityDescription( - key=DPCode.ALARM_VOLUME, - translation_key="volume", - entity_category=EntityCategory.CONFIG, - ), - ), - # Electric Blanket - # https://developer.tuya.com/en/docs/iot/categorydr?id=Kaiuz22dyc66p - "dr": ( - SelectEntityDescription( - key=DPCode.LEVEL, - name="Level", - icon="mdi:thermometer-lines", - translation_key="blanket_level", - ), - SelectEntityDescription( - key=DPCode.LEVEL_1, - name="Side A Level", - icon="mdi:thermometer-lines", - translation_key="blanket_level", - ), - SelectEntityDescription( - key=DPCode.LEVEL_2, - name="Side B Level", - icon="mdi:thermometer-lines", - translation_key="blanket_level", - ), - ), } # Socket (duplicate of `kg`) # https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s SELECTS["cz"] = SELECTS["kg"] -# Power Socket (duplicate of `kg`) -# https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s -SELECTS["pc"] = SELECTS["kg"] - # Smart Camera - Low power consumption camera (duplicate of `sp`) # Undocumented, see https://github.com/home-assistant/core/issues/132844 SELECTS["dghsxj"] = SELECTS["sp"] +# Power Socket (duplicate of `kg`) +# https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s +SELECTS["pc"] = SELECTS["kg"] + async def async_setup_entry( hass: HomeAssistant, diff --git a/homeassistant/components/tuya/sensor.py b/homeassistant/components/tuya/sensor.py index bdfc8fe15e7..b45b8214bff 100644 --- a/homeassistant/components/tuya/sensor.py +++ b/homeassistant/components/tuya/sensor.py @@ -35,7 +35,8 @@ from .const import ( DPType, UnitOfMeasurement, ) -from .entity import ElectricityTypeData, EnumTypeData, IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import ElectricityTypeData, EnumTypeData, IntegerTypeData @dataclass(frozen=True) @@ -89,6 +90,169 @@ BATTERY_SENSORS: tuple[TuyaSensorEntityDescription, ...] = ( # end up being a sensor. # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { + # Single Phase power meter + # Note: Undocumented + "aqcz": ( + TuyaSensorEntityDescription( + key=DPCode.CUR_CURRENT, + translation_key="current", + device_class=SensorDeviceClass.CURRENT, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_POWER, + translation_key="power", + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_VOLTAGE, + translation_key="voltage", + device_class=SensorDeviceClass.VOLTAGE, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + ), + # Smart Kettle + # https://developer.tuya.com/en/docs/iot/fbh?id=K9gf484m21yq7 + "bh": ( + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="current_temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT_F, + translation_key="current_temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.STATUS, + translation_key="status", + ), + ), + # Curtain + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48qy7wkre + "cl": ( + TuyaSensorEntityDescription( + key=DPCode.TIME_TOTAL, + translation_key="last_operation_duration", + entity_category=EntityCategory.DIAGNOSTIC, + ), + ), + # CO2 Detector + # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy + "co2bj": ( + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_VALUE, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.CO2_VALUE, + translation_key="carbon_dioxide", + device_class=SensorDeviceClass.CO2, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.CH2O_VALUE, + translation_key="formaldehyde", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.VOC_VALUE, + translation_key="voc", + device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.PM25_VALUE, + translation_key="pm25", + device_class=SensorDeviceClass.PM25, + state_class=SensorStateClass.MEASUREMENT, + ), + *BATTERY_SENSORS, + ), + # CO Detector + # https://developer.tuya.com/en/docs/iot/categorycobj?id=Kaiuz3u1j6q1v + "cobj": ( + TuyaSensorEntityDescription( + key=DPCode.CO_VALUE, + translation_key="carbon_monoxide", + device_class=SensorDeviceClass.CO, + state_class=SensorStateClass.MEASUREMENT, + ), + *BATTERY_SENSORS, + ), + # Dehumidifier + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r6jke8e + "cs": ( + TuyaSensorEntityDescription( + key=DPCode.TEMP_INDOOR, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_INDOOR, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + ), + # Smart Pet Feeder + # https://developer.tuya.com/en/docs/iot/categorycwwsq?id=Kaiuz2b6vydld + "cwwsq": ( + TuyaSensorEntityDescription( + key=DPCode.FEED_REPORT, + translation_key="last_amount", + state_class=SensorStateClass.MEASUREMENT, + ), + ), + # Pet Fountain + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r0as4ln + "cwysj": ( + TuyaSensorEntityDescription( + key=DPCode.UV_RUNTIME, + translation_key="uv_runtime", + device_class=SensorDeviceClass.DURATION, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.PUMP_TIME, + translation_key="pump_time", + device_class=SensorDeviceClass.DURATION, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.FILTER_DURATION, + translation_key="filter_duration", + device_class=SensorDeviceClass.DURATION, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.WATER_TIME, + translation_key="water_time", + device_class=SensorDeviceClass.DURATION, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.WATER_LEVEL, translation_key="water_level_state" + ), + ), # Multi-functional Sensor # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 "dgnbj": ( @@ -162,81 +326,92 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), - # Smart Kettle - # https://developer.tuya.com/en/docs/iot/fbh?id=K9gf484m21yq7 - "bh": ( + # Circuit Breaker + # https://developer.tuya.com/en/docs/iot/dlq?id=Kb0kidk9enyh8 + "dlq": ( TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="current_temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, + key=DPCode.TOTAL_FORWARD_ENERGY, + translation_key="total_energy", + device_class=SensorDeviceClass.ENERGY, + state_class=SensorStateClass.TOTAL_INCREASING, ), TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT_F, - translation_key="current_temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, + key=DPCode.CUR_NEUTRAL, + translation_key="total_production", + device_class=SensorDeviceClass.ENERGY, + state_class=SensorStateClass.TOTAL_INCREASING, ), TuyaSensorEntityDescription( - key=DPCode.STATUS, - translation_key="status", - ), - ), - # CO2 Detector - # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy - "co2bj": ( - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_VALUE, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, + key=DPCode.PHASE_A, + translation_key="phase_a_current", + device_class=SensorDeviceClass.CURRENT, + native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, state_class=SensorStateClass.MEASUREMENT, + subkey="electriccurrent", ), TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, + key=DPCode.PHASE_A, + translation_key="phase_a_power", + device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfPower.KILO_WATT, + subkey="power", ), TuyaSensorEntityDescription( - key=DPCode.CO2_VALUE, - translation_key="carbon_dioxide", - device_class=SensorDeviceClass.CO2, + key=DPCode.PHASE_A, + translation_key="phase_a_voltage", + device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfElectricPotential.VOLT, + subkey="voltage", ), TuyaSensorEntityDescription( - key=DPCode.CH2O_VALUE, - translation_key="formaldehyde", + key=DPCode.PHASE_B, + translation_key="phase_b_current", + device_class=SensorDeviceClass.CURRENT, + native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, state_class=SensorStateClass.MEASUREMENT, + subkey="electriccurrent", ), TuyaSensorEntityDescription( - key=DPCode.VOC_VALUE, - translation_key="voc", - device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, + key=DPCode.PHASE_B, + translation_key="phase_b_power", + device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfPower.KILO_WATT, + subkey="power", ), TuyaSensorEntityDescription( - key=DPCode.PM25_VALUE, - translation_key="pm25", - device_class=SensorDeviceClass.PM25, - state_class=SensorStateClass.MEASUREMENT, - ), - *BATTERY_SENSORS, - ), - # Two-way temperature and humidity switch - # "MOES Temperature and Humidity Smart Switch Module MS-103" - # Documentation not found - "wkcz": ( - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_VALUE, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, + key=DPCode.PHASE_B, + translation_key="phase_b_voltage", + device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfElectricPotential.VOLT, + subkey="voltage", ), TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, + key=DPCode.PHASE_C, + translation_key="phase_c_current", + device_class=SensorDeviceClass.CURRENT, + native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, state_class=SensorStateClass.MEASUREMENT, + subkey="electriccurrent", + ), + TuyaSensorEntityDescription( + key=DPCode.PHASE_C, + translation_key="phase_c_power", + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfPower.KILO_WATT, + subkey="power", + ), + TuyaSensorEntityDescription( + key=DPCode.PHASE_C, + translation_key="phase_c_voltage", + device_class=SensorDeviceClass.VOLTAGE, + state_class=SensorStateClass.MEASUREMENT, + native_unit_of_measurement=UnitOfElectricPotential.VOLT, + subkey="voltage", ), TuyaSensorEntityDescription( key=DPCode.CUR_CURRENT, @@ -260,84 +435,19 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { entity_registry_enabled_default=False, ), ), - # Single Phase power meter - # Note: Undocumented - "aqcz": ( + # Fan + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48quojr54 + "fs": ( TuyaSensorEntityDescription( - key=DPCode.CUR_CURRENT, - translation_key="current", - device_class=SensorDeviceClass.CURRENT, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_POWER, - translation_key="power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_VOLTAGE, - translation_key="voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - ), - # CO Detector - # https://developer.tuya.com/en/docs/iot/categorycobj?id=Kaiuz3u1j6q1v - "cobj": ( - TuyaSensorEntityDescription( - key=DPCode.CO_VALUE, - translation_key="carbon_monoxide", - device_class=SensorDeviceClass.CO, - state_class=SensorStateClass.MEASUREMENT, - ), - *BATTERY_SENSORS, - ), - # Smart Pet Feeder - # https://developer.tuya.com/en/docs/iot/categorycwwsq?id=Kaiuz2b6vydld - "cwwsq": ( - TuyaSensorEntityDescription( - key=DPCode.FEED_REPORT, - translation_key="last_amount", + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), ), - # Pet Fountain - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r0as4ln - "cwysj": ( - TuyaSensorEntityDescription( - key=DPCode.UV_RUNTIME, - translation_key="uv_runtime", - device_class=SensorDeviceClass.DURATION, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.PUMP_TIME, - translation_key="pump_time", - device_class=SensorDeviceClass.DURATION, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.FILTER_DURATION, - translation_key="filter_duration", - device_class=SensorDeviceClass.DURATION, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.WATER_TIME, - translation_key="water_time", - device_class=SensorDeviceClass.DURATION, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.WATER_LEVEL, translation_key="water_level_state" - ), - ), + # Irrigator + # https://developer.tuya.com/en/docs/iot/categoryggq?id=Kaiuz1qib7z0k + "ggq": BATTERY_SENSORS, # Air Quality Monitor # https://developer.tuya.com/en/docs/iot/hjjcy?id=Kbeoad8y1nnlv "hjjcy": ( @@ -428,6 +538,33 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), + # Humidifier + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48qwjz0i3 + "jsq": ( + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_CURRENT, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT_F, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.LEVEL_CURRENT, + translation_key="water_level", + entity_category=EntityCategory.DIAGNOSTIC, + ), + ), # Methane Detector # https://developer.tuya.com/en/docs/iot/categoryjwbj?id=Kaiuz40u98lkm "jwbj": ( @@ -463,61 +600,60 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { entity_registry_enabled_default=False, ), ), - # IoT Switch - # Note: Undocumented - "tdq": ( + # Air Purifier + # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r41mn81 + "kj": ( TuyaSensorEntityDescription( - key=DPCode.CUR_CURRENT, - translation_key="current", - device_class=SensorDeviceClass.CURRENT, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, + key=DPCode.FILTER, + translation_key="filter_utilization", + entity_category=EntityCategory.DIAGNOSTIC, ), TuyaSensorEntityDescription( - key=DPCode.CUR_POWER, - translation_key="power", - device_class=SensorDeviceClass.POWER, + key=DPCode.PM25, + translation_key="pm25", + device_class=SensorDeviceClass.PM25, state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, ), TuyaSensorEntityDescription( - key=DPCode.CUR_VOLTAGE, - translation_key="voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.VA_TEMPERATURE, + key=DPCode.TEMP, translation_key="temperature", device_class=SensorDeviceClass.TEMPERATURE, state_class=SensorStateClass.MEASUREMENT, ), TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.VA_HUMIDITY, + key=DPCode.HUMIDITY, translation_key="humidity", device_class=SensorDeviceClass.HUMIDITY, state_class=SensorStateClass.MEASUREMENT, ), TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_VALUE, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, + key=DPCode.TVOC, + translation_key="total_volatile_organic_compound", + device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, state_class=SensorStateClass.MEASUREMENT, ), TuyaSensorEntityDescription( - key=DPCode.BRIGHT_VALUE, - translation_key="illuminance", - device_class=SensorDeviceClass.ILLUMINANCE, + key=DPCode.ECO2, + translation_key="concentration_carbon_dioxide", + device_class=SensorDeviceClass.CO2, state_class=SensorStateClass.MEASUREMENT, ), - *BATTERY_SENSORS, + TuyaSensorEntityDescription( + key=DPCode.TOTAL_TIME, + translation_key="total_operating_time", + state_class=SensorStateClass.TOTAL_INCREASING, + entity_category=EntityCategory.DIAGNOSTIC, + ), + TuyaSensorEntityDescription( + key=DPCode.TOTAL_PM, + translation_key="total_absorption_particles", + state_class=SensorStateClass.TOTAL_INCREASING, + entity_category=EntityCategory.DIAGNOSTIC, + ), + TuyaSensorEntityDescription( + key=DPCode.AIR_QUALITY, + translation_key="air_quality", + ), ), # Luminance Sensor # https://developer.tuya.com/en/docs/iot/categoryldcg?id=Kaiuz3n7u69l8 @@ -642,6 +778,47 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { state_class=SensorStateClass.MEASUREMENT, ), ), + # Temperature and Humidity Sensor with External Probe + # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 + "qxj": ( + TuyaSensorEntityDescription( + key=DPCode.VA_TEMPERATURE, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT_EXTERNAL, + translation_key="temperature_external", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.VA_HUMIDITY, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_VALUE, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.BRIGHT_VALUE, + translation_key="illuminance", + device_class=SensorDeviceClass.ILLUMINANCE, + state_class=SensorStateClass.MEASUREMENT, + ), + *BATTERY_SENSORS, + ), # Gas Detector # https://developer.tuya.com/en/docs/iot/categoryrqbj?id=Kaiuz3d162ubw "rqbj": ( @@ -653,6 +830,55 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), + # Robot Vacuum + # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo + "sd": ( + TuyaSensorEntityDescription( + key=DPCode.CLEAN_AREA, + translation_key="cleaning_area", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.CLEAN_TIME, + translation_key="cleaning_time", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TOTAL_CLEAN_AREA, + translation_key="total_cleaning_area", + state_class=SensorStateClass.TOTAL_INCREASING, + ), + TuyaSensorEntityDescription( + key=DPCode.TOTAL_CLEAN_TIME, + translation_key="total_cleaning_time", + state_class=SensorStateClass.TOTAL_INCREASING, + ), + TuyaSensorEntityDescription( + key=DPCode.TOTAL_CLEAN_COUNT, + translation_key="total_cleaning_times", + state_class=SensorStateClass.TOTAL_INCREASING, + ), + TuyaSensorEntityDescription( + key=DPCode.DUSTER_CLOTH, + translation_key="duster_cloth_life", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.EDGE_BRUSH, + translation_key="side_brush_life", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.FILTER_LIFE, + translation_key="filter_life", + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.ROLL_BRUSH, + translation_key="rolling_brush_life", + state_class=SensorStateClass.MEASUREMENT, + ), + ), # Smart Water Timer "sfkzq": ( # Total seconds of irrigation. Read-write value; the device appears to ignore the write action (maybe firmware bug) @@ -664,9 +890,6 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), - # Irrigator - # https://developer.tuya.com/en/docs/iot/categoryggq?id=Kaiuz1qib7z0k - "ggq": BATTERY_SENSORS, # Water Detector # https://developer.tuya.com/en/docs/iot/categorysj?id=Kaiuz3iub2sli "sj": BATTERY_SENSORS, @@ -696,8 +919,80 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { state_class=SensorStateClass.MEASUREMENT, ), ), + # Smart Gardening system + # https://developer.tuya.com/en/docs/iot/categorysz?id=Kaiuz4e6h7up0 + "sz": ( + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_CURRENT, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + ), # Fingerbot "szjqr": BATTERY_SENSORS, + # IoT Switch + # Note: Undocumented + "tdq": ( + TuyaSensorEntityDescription( + key=DPCode.CUR_CURRENT, + translation_key="current", + device_class=SensorDeviceClass.CURRENT, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_POWER, + translation_key="power", + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_VOLTAGE, + translation_key="voltage", + device_class=SensorDeviceClass.VOLTAGE, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.VA_TEMPERATURE, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.VA_HUMIDITY, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_VALUE, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.BRIGHT_VALUE, + translation_key="illuminance", + device_class=SensorDeviceClass.ILLUMINANCE, + state_class=SensorStateClass.MEASUREMENT, + ), + *BATTERY_SENSORS, + ), # Solar Light # https://developer.tuya.com/en/docs/iot/tynd?id=Kaof8j02e1t98 "tyndj": BATTERY_SENSORS, @@ -741,9 +1036,87 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), + # Two-way temperature and humidity switch + # "MOES Temperature and Humidity Smart Switch Module MS-103" + # Documentation not found + "wkcz": ( + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY_VALUE, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_CURRENT, + translation_key="current", + device_class=SensorDeviceClass.CURRENT, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_POWER, + translation_key="power", + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_VOLTAGE, + translation_key="voltage", + device_class=SensorDeviceClass.VOLTAGE, + state_class=SensorStateClass.MEASUREMENT, + entity_registry_enabled_default=False, + ), + ), # Thermostatic Radiator Valve # Not documented "wkf": BATTERY_SENSORS, + # eMylo Smart WiFi IR Remote + # Air Conditioner Mate (Smart IR Socket) + "wnykq": ( + TuyaSensorEntityDescription( + key=DPCode.VA_TEMPERATURE, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.VA_HUMIDITY, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_CURRENT, + translation_key="current", + device_class=SensorDeviceClass.CURRENT, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_POWER, + translation_key="power", + device_class=SensorDeviceClass.POWER, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ), + TuyaSensorEntityDescription( + key=DPCode.CUR_VOLTAGE, + translation_key="voltage", + device_class=SensorDeviceClass.VOLTAGE, + state_class=SensorStateClass.MEASUREMENT, + entity_category=EntityCategory.DIAGNOSTIC, + entity_registry_enabled_default=False, + ), + ), # Temperature and Humidity Sensor # https://developer.tuya.com/en/docs/iot/categorywsdcg?id=Kaiuz3hinij34 "wsdcg": ( @@ -779,48 +1152,9 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { ), *BATTERY_SENSORS, ), - # Temperature and Humidity Sensor with External Probe - # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 - "qxj": ( - TuyaSensorEntityDescription( - key=DPCode.VA_TEMPERATURE, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT_EXTERNAL, - translation_key="temperature_external", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.VA_HUMIDITY, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_VALUE, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.BRIGHT_VALUE, - translation_key="illuminance", - device_class=SensorDeviceClass.ILLUMINANCE, - state_class=SensorStateClass.MEASUREMENT, - ), - *BATTERY_SENSORS, - ), - # Pressure Sensor + # Wireless Switch + # https://developer.tuya.com/en/docs/iot/s?id=Kbeoa9fkv6brp + "wxkg": BATTERY_SENSORS, # Pressure Sensor # https://developer.tuya.com/en/docs/iot/categoryylcg?id=Kaiuz3kc2e4gm "ylcg": ( TuyaSensorEntityDescription( @@ -940,353 +1274,6 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { subkey="voltage", ), ), - # Circuit Breaker - # https://developer.tuya.com/en/docs/iot/dlq?id=Kb0kidk9enyh8 - "dlq": ( - TuyaSensorEntityDescription( - key=DPCode.TOTAL_FORWARD_ENERGY, - translation_key="total_energy", - device_class=SensorDeviceClass.ENERGY, - state_class=SensorStateClass.TOTAL_INCREASING, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_NEUTRAL, - translation_key="total_production", - device_class=SensorDeviceClass.ENERGY, - state_class=SensorStateClass.TOTAL_INCREASING, - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_A, - translation_key="phase_a_current", - device_class=SensorDeviceClass.CURRENT, - native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, - state_class=SensorStateClass.MEASUREMENT, - subkey="electriccurrent", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_A, - translation_key="phase_a_power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfPower.KILO_WATT, - subkey="power", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_A, - translation_key="phase_a_voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfElectricPotential.VOLT, - subkey="voltage", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_B, - translation_key="phase_b_current", - device_class=SensorDeviceClass.CURRENT, - native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, - state_class=SensorStateClass.MEASUREMENT, - subkey="electriccurrent", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_B, - translation_key="phase_b_power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfPower.KILO_WATT, - subkey="power", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_B, - translation_key="phase_b_voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfElectricPotential.VOLT, - subkey="voltage", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_C, - translation_key="phase_c_current", - device_class=SensorDeviceClass.CURRENT, - native_unit_of_measurement=UnitOfElectricCurrent.AMPERE, - state_class=SensorStateClass.MEASUREMENT, - subkey="electriccurrent", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_C, - translation_key="phase_c_power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfPower.KILO_WATT, - subkey="power", - ), - TuyaSensorEntityDescription( - key=DPCode.PHASE_C, - translation_key="phase_c_voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - native_unit_of_measurement=UnitOfElectricPotential.VOLT, - subkey="voltage", - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_CURRENT, - translation_key="current", - device_class=SensorDeviceClass.CURRENT, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_POWER, - translation_key="power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_VOLTAGE, - translation_key="voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - entity_registry_enabled_default=False, - ), - ), - # Robot Vacuum - # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo - "sd": ( - TuyaSensorEntityDescription( - key=DPCode.CLEAN_AREA, - translation_key="cleaning_area", - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.CLEAN_TIME, - translation_key="cleaning_time", - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TOTAL_CLEAN_AREA, - translation_key="total_cleaning_area", - state_class=SensorStateClass.TOTAL_INCREASING, - ), - TuyaSensorEntityDescription( - key=DPCode.TOTAL_CLEAN_TIME, - translation_key="total_cleaning_time", - state_class=SensorStateClass.TOTAL_INCREASING, - ), - TuyaSensorEntityDescription( - key=DPCode.TOTAL_CLEAN_COUNT, - translation_key="total_cleaning_times", - state_class=SensorStateClass.TOTAL_INCREASING, - ), - TuyaSensorEntityDescription( - key=DPCode.DUSTER_CLOTH, - translation_key="duster_cloth_life", - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.EDGE_BRUSH, - translation_key="side_brush_life", - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.FILTER_LIFE, - translation_key="filter_life", - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.ROLL_BRUSH, - translation_key="rolling_brush_life", - state_class=SensorStateClass.MEASUREMENT, - ), - ), - # Smart Gardening system - # https://developer.tuya.com/en/docs/iot/categorysz?id=Kaiuz4e6h7up0 - "sz": ( - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_CURRENT, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - ), - # Curtain - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48qy7wkre - "cl": ( - TuyaSensorEntityDescription( - key=DPCode.TIME_TOTAL, - translation_key="last_operation_duration", - entity_category=EntityCategory.DIAGNOSTIC, - ), - ), - # Humidifier - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48qwjz0i3 - "jsq": ( - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_CURRENT, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT_F, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.LEVEL_CURRENT, - translation_key="water_level", - entity_category=EntityCategory.DIAGNOSTIC, - ), - ), - # Air Purifier - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r41mn81 - "kj": ( - TuyaSensorEntityDescription( - key=DPCode.FILTER, - translation_key="filter_utilization", - entity_category=EntityCategory.DIAGNOSTIC, - ), - TuyaSensorEntityDescription( - key=DPCode.PM25, - translation_key="pm25", - device_class=SensorDeviceClass.PM25, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TEMP, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TVOC, - translation_key="total_volatile_organic_compound", - device_class=SensorDeviceClass.VOLATILE_ORGANIC_COMPOUNDS, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.ECO2, - translation_key="concentration_carbon_dioxide", - device_class=SensorDeviceClass.CO2, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.TOTAL_TIME, - translation_key="total_operating_time", - state_class=SensorStateClass.TOTAL_INCREASING, - entity_category=EntityCategory.DIAGNOSTIC, - ), - TuyaSensorEntityDescription( - key=DPCode.TOTAL_PM, - translation_key="total_absorption_particles", - state_class=SensorStateClass.TOTAL_INCREASING, - entity_category=EntityCategory.DIAGNOSTIC, - ), - TuyaSensorEntityDescription( - key=DPCode.AIR_QUALITY, - translation_key="air_quality", - ), - ), - # Fan - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48quojr54 - "fs": ( - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - ), - # eMylo Smart WiFi IR Remote - # Air Conditioner Mate (Smart IR Socket) - "wnykq": ( - TuyaSensorEntityDescription( - key=DPCode.VA_TEMPERATURE, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.VA_HUMIDITY, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_CURRENT, - translation_key="current", - device_class=SensorDeviceClass.CURRENT, - state_class=SensorStateClass.MEASUREMENT, - entity_category=EntityCategory.DIAGNOSTIC, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_POWER, - translation_key="power", - device_class=SensorDeviceClass.POWER, - state_class=SensorStateClass.MEASUREMENT, - entity_category=EntityCategory.DIAGNOSTIC, - entity_registry_enabled_default=False, - ), - TuyaSensorEntityDescription( - key=DPCode.CUR_VOLTAGE, - translation_key="voltage", - device_class=SensorDeviceClass.VOLTAGE, - state_class=SensorStateClass.MEASUREMENT, - entity_category=EntityCategory.DIAGNOSTIC, - entity_registry_enabled_default=False, - ), - ), - # Dehumidifier - # https://developer.tuya.com/en/docs/iot/s?id=K9gf48r6jke8e - "cs": ( - TuyaSensorEntityDescription( - key=DPCode.TEMP_INDOOR, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY_INDOOR, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - ), - # Soil sensor (Plant monitor) - "zwjcy": ( - TuyaSensorEntityDescription( - key=DPCode.TEMP_CURRENT, - translation_key="temperature", - device_class=SensorDeviceClass.TEMPERATURE, - state_class=SensorStateClass.MEASUREMENT, - ), - TuyaSensorEntityDescription( - key=DPCode.HUMIDITY, - translation_key="humidity", - device_class=SensorDeviceClass.HUMIDITY, - state_class=SensorStateClass.MEASUREMENT, - ), - *BATTERY_SENSORS, - ), # VESKA-micro inverter "znnbq": ( TuyaSensorEntityDescription( @@ -1314,23 +1301,36 @@ SENSORS: dict[str, tuple[TuyaSensorEntityDescription, ...]] = { state_class=SensorStateClass.MEASUREMENT, ), ), - # Wireless Switch - # https://developer.tuya.com/en/docs/iot/s?id=Kbeoa9fkv6brp - "wxkg": BATTERY_SENSORS, + # Soil sensor (Plant monitor) + "zwjcy": ( + TuyaSensorEntityDescription( + key=DPCode.TEMP_CURRENT, + translation_key="temperature", + device_class=SensorDeviceClass.TEMPERATURE, + state_class=SensorStateClass.MEASUREMENT, + ), + TuyaSensorEntityDescription( + key=DPCode.HUMIDITY, + translation_key="humidity", + device_class=SensorDeviceClass.HUMIDITY, + state_class=SensorStateClass.MEASUREMENT, + ), + *BATTERY_SENSORS, + ), } # Socket (duplicate of `kg`) # https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s SENSORS["cz"] = SENSORS["kg"] -# Power Socket (duplicate of `kg`) -# https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s -SENSORS["pc"] = SENSORS["kg"] - # Smart Camera - Low power consumption camera (duplicate of `sp`) # Undocumented, see https://github.com/home-assistant/core/issues/132844 SENSORS["dghsxj"] = SENSORS["sp"] +# Power Socket (duplicate of `kg`) +# https://developer.tuya.com/en/docs/iot/s?id=K9gf7o5prgf7s +SENSORS["pc"] = SENSORS["kg"] + async def async_setup_entry( hass: HomeAssistant, diff --git a/homeassistant/components/tuya/siren.py b/homeassistant/components/tuya/siren.py index 039442dafe5..8003dc2cf21 100644 --- a/homeassistant/components/tuya/siren.py +++ b/homeassistant/components/tuya/siren.py @@ -23,6 +23,14 @@ from .entity import TuyaEntity # All descriptions can be found here: # https://developer.tuya.com/en/docs/iot/standarddescription?id=K9i5ql6waswzq SIRENS: dict[str, tuple[SirenEntityDescription, ...]] = { + # CO2 Detector + # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy + "co2bj": ( + SirenEntityDescription( + key=DPCode.ALARM_SWITCH, + entity_category=EntityCategory.CONFIG, + ), + ), # Multi-functional Sensor # https://developer.tuya.com/en/docs/iot/categorydgnbj?id=Kaiuz3yorvzg3 "dgnbj": ( @@ -44,14 +52,6 @@ SIRENS: dict[str, tuple[SirenEntityDescription, ...]] = { key=DPCode.SIREN_SWITCH, ), ), - # CO2 Detector - # https://developer.tuya.com/en/docs/iot/categoryco2bj?id=Kaiuz3wes7yuy - "co2bj": ( - SirenEntityDescription( - key=DPCode.ALARM_SWITCH, - entity_category=EntityCategory.CONFIG, - ), - ), } # Smart Camera - Low power consumption camera (duplicate of `sp`) diff --git a/homeassistant/components/tuya/strings.json b/homeassistant/components/tuya/strings.json index a96f805f248..a5302b2e88b 100644 --- a/homeassistant/components/tuya/strings.json +++ b/homeassistant/components/tuya/strings.json @@ -56,6 +56,15 @@ }, "tilt": { "name": "Tilt" + }, + "tankfull": { + "name": "Tank full" + }, + "defrost": { + "name": "Defrost" + }, + "wet": { + "name": "Wet" } }, "button": { @@ -897,6 +906,12 @@ }, "sterilization": { "name": "Sterilization" + }, + "arm_beep": { + "name": "Arm beep" + }, + "siren": { + "name": "Siren" } } } diff --git a/homeassistant/components/tuya/switch.py b/homeassistant/components/tuya/switch.py index b786644fd05..f455424c2c1 100644 --- a/homeassistant/components/tuya/switch.py +++ b/homeassistant/components/tuya/switch.py @@ -37,6 +37,20 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # Curtain + # https://developer.tuya.com/en/docs/iot/f?id=K9gf46o5mtfyc + "cl": ( + SwitchEntityDescription( + key=DPCode.CONTROL_BACK, + translation_key="reverse", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.OPPOSITE, + translation_key="reverse", + entity_category=EntityCategory.CONFIG, + ), + ), # EasyBaby # Undocumented, might have a wider use "cn": ( @@ -131,6 +145,116 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="switch", ), ), + # Electric Blanket + # https://developer.tuya.com/en/docs/iot/categorydr?id=Kaiuz22dyc66p + "dr": ( + SwitchEntityDescription( + key=DPCode.SWITCH, + name="Power", + icon="mdi:power", + device_class=SwitchDeviceClass.SWITCH, + ), + SwitchEntityDescription( + key=DPCode.SWITCH_1, + name="Side A Power", + icon="mdi:alpha-a", + device_class=SwitchDeviceClass.SWITCH, + ), + SwitchEntityDescription( + key=DPCode.SWITCH_2, + name="Side B Power", + icon="mdi:alpha-b", + device_class=SwitchDeviceClass.SWITCH, + ), + SwitchEntityDescription( + key=DPCode.PREHEAT, + name="Preheat", + icon="mdi:radiator", + device_class=SwitchDeviceClass.SWITCH, + ), + SwitchEntityDescription( + key=DPCode.PREHEAT_1, + name="Side A Preheat", + icon="mdi:radiator", + device_class=SwitchDeviceClass.SWITCH, + ), + SwitchEntityDescription( + key=DPCode.PREHEAT_2, + name="Side B Preheat", + icon="mdi:radiator", + device_class=SwitchDeviceClass.SWITCH, + ), + ), + # Fan + # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c + "fs": ( + SwitchEntityDescription( + key=DPCode.ANION, + translation_key="anion", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.HUMIDIFIER, + translation_key="humidification", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.OXYGEN, + translation_key="oxygen_bar", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.FAN_COOL, + translation_key="natural_wind", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.FAN_BEEP, + translation_key="sound", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.CHILD_LOCK, + translation_key="child_lock", + entity_category=EntityCategory.CONFIG, + ), + ), + # Irrigator + # https://developer.tuya.com/en/docs/iot/categoryggq?id=Kaiuz1qib7z0k + "ggq": ( + SwitchEntityDescription( + key=DPCode.SWITCH_1, + translation_key="switch_1", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_2, + translation_key="switch_2", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_3, + translation_key="switch_3", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_4, + translation_key="switch_4", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_5, + translation_key="switch_5", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_6, + translation_key="switch_6", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_7, + translation_key="switch_7", + ), + SwitchEntityDescription( + key=DPCode.SWITCH_8, + translation_key="switch_8", + ), + ), # Wake Up Light II # Not documented "hxd": ( @@ -163,19 +287,23 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="sleep_aid", ), ), - # Two-way temperature and humidity switch - # "MOES Temperature and Humidity Smart Switch Module MS-103" - # Documentation not found - "wkcz": ( + # Humidifier + # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b + "jsq": ( SwitchEntityDescription( - key=DPCode.SWITCH_1, - translation_key="switch_1", - device_class=SwitchDeviceClass.OUTLET, + key=DPCode.SWITCH_SOUND, + translation_key="voice", + entity_category=EntityCategory.CONFIG, ), SwitchEntityDescription( - key=DPCode.SWITCH_2, - translation_key="switch_2", - device_class=SwitchDeviceClass.OUTLET, + key=DPCode.SLEEP, + translation_key="sleep", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.STERILIZATION, + translation_key="sterilization", + entity_category=EntityCategory.CONFIG, ), ), # Switch @@ -303,6 +431,22 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # Alarm Host + # https://developer.tuya.com/en/docs/iot/alarm-hosts?id=K9gf48r87hyjk + "mal": ( + SwitchEntityDescription( + key=DPCode.SWITCH_ALARM_SOUND, + # This switch is called "Arm Beep" in the official Tuya app + translation_key="arm_beep", + entity_category=EntityCategory.CONFIG, + ), + SwitchEntityDescription( + key=DPCode.SWITCH_ALARM_LIGHT, + # This switch is called "Siren" in the official Tuya app + translation_key="siren", + entity_category=EntityCategory.CONFIG, + ), + ), # Sous Vide Cooker # https://developer.tuya.com/en/docs/iot/categorymzj?id=Kaiuz2vy130ux "mzj": ( @@ -408,6 +552,15 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # SIREN: Siren (switch) with Temperature and Humidity Sensor with External Probe + # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 + "qxj": ( + SwitchEntityDescription( + key=DPCode.SWITCH, + translation_key="switch", + device_class=SwitchDeviceClass.OUTLET, + ), + ), # Robot Vacuum # https://developer.tuya.com/en/docs/iot/fsd?id=K9gf487ck1tlo "sd": ( @@ -429,42 +582,6 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="switch", ), ), - # Irrigator - # https://developer.tuya.com/en/docs/iot/categoryggq?id=Kaiuz1qib7z0k - "ggq": ( - SwitchEntityDescription( - key=DPCode.SWITCH_1, - translation_key="switch_1", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_2, - translation_key="switch_2", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_3, - translation_key="switch_3", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_4, - translation_key="switch_4", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_5, - translation_key="switch_5", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_6, - translation_key="switch_6", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_7, - translation_key="switch_7", - ), - SwitchEntityDescription( - key=DPCode.SWITCH_8, - translation_key="switch_8", - ), - ), # Siren Alarm # https://developer.tuya.com/en/docs/iot/categorysgbj?id=Kaiuz37tlpbnu "sgbj": ( @@ -552,13 +669,6 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="switch", ), ), - # Hejhome whitelabel Fingerbot - "znjxs": ( - SwitchEntityDescription( - key=DPCode.SWITCH, - translation_key="switch", - ), - ), # IoT Switch? # Note: Undocumented "tdq": ( @@ -606,6 +716,21 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { entity_category=EntityCategory.CONFIG, ), ), + # Two-way temperature and humidity switch + # "MOES Temperature and Humidity Smart Switch Module MS-103" + # Documentation not found + "wkcz": ( + SwitchEntityDescription( + key=DPCode.SWITCH_1, + translation_key="switch_1", + device_class=SwitchDeviceClass.OUTLET, + ), + SwitchEntityDescription( + key=DPCode.SWITCH_2, + translation_key="switch_2", + device_class=SwitchDeviceClass.OUTLET, + ), + ), # Thermostatic Radiator Valve # Not documented "wkf": ( @@ -636,15 +761,6 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { device_class=SwitchDeviceClass.OUTLET, ), ), - # SIREN: Siren (switch) with Temperature and Humidity Sensor with External Probe - # New undocumented category qxj, see https://github.com/home-assistant/core/issues/136472 - "qxj": ( - SwitchEntityDescription( - key=DPCode.SWITCH, - translation_key="switch", - device_class=SwitchDeviceClass.OUTLET, - ), - ), # Ceiling Light # https://developer.tuya.com/en/docs/iot/ceiling-light?id=Kaiuz03xxfc4r "xdd": ( @@ -679,71 +795,11 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="switch", ), ), - # Fan - # https://developer.tuya.com/en/docs/iot/categoryfs?id=Kaiuz1xweel1c - "fs": ( + # Hejhome whitelabel Fingerbot + "znjxs": ( SwitchEntityDescription( - key=DPCode.ANION, - translation_key="anion", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.HUMIDIFIER, - translation_key="humidification", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.OXYGEN, - translation_key="oxygen_bar", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.FAN_COOL, - translation_key="natural_wind", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.FAN_BEEP, - translation_key="sound", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.CHILD_LOCK, - translation_key="child_lock", - entity_category=EntityCategory.CONFIG, - ), - ), - # Curtain - # https://developer.tuya.com/en/docs/iot/f?id=K9gf46o5mtfyc - "cl": ( - SwitchEntityDescription( - key=DPCode.CONTROL_BACK, - translation_key="reverse", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.OPPOSITE, - translation_key="reverse", - entity_category=EntityCategory.CONFIG, - ), - ), - # Humidifier - # https://developer.tuya.com/en/docs/iot/categoryjsq?id=Kaiuz1smr440b - "jsq": ( - SwitchEntityDescription( - key=DPCode.SWITCH_SOUND, - translation_key="voice", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.SLEEP, - translation_key="sleep", - entity_category=EntityCategory.CONFIG, - ), - SwitchEntityDescription( - key=DPCode.STERILIZATION, - translation_key="sterilization", - entity_category=EntityCategory.CONFIG, + key=DPCode.SWITCH, + translation_key="switch", ), ), # Pool HeatPump @@ -753,46 +809,6 @@ SWITCHES: dict[str, tuple[SwitchEntityDescription, ...]] = { translation_key="switch", ), ), - # Electric Blanket - # https://developer.tuya.com/en/docs/iot/categorydr?id=Kaiuz22dyc66p - "dr": ( - SwitchEntityDescription( - key=DPCode.SWITCH, - name="Power", - icon="mdi:power", - device_class=SwitchDeviceClass.SWITCH, - ), - SwitchEntityDescription( - key=DPCode.SWITCH_1, - name="Side A Power", - icon="mdi:alpha-a", - device_class=SwitchDeviceClass.SWITCH, - ), - SwitchEntityDescription( - key=DPCode.SWITCH_2, - name="Side B Power", - icon="mdi:alpha-b", - device_class=SwitchDeviceClass.SWITCH, - ), - SwitchEntityDescription( - key=DPCode.PREHEAT, - name="Preheat", - icon="mdi:radiator", - device_class=SwitchDeviceClass.SWITCH, - ), - SwitchEntityDescription( - key=DPCode.PREHEAT_1, - name="Side A Preheat", - icon="mdi:radiator", - device_class=SwitchDeviceClass.SWITCH, - ), - SwitchEntityDescription( - key=DPCode.PREHEAT_2, - name="Side B Preheat", - icon="mdi:radiator", - device_class=SwitchDeviceClass.SWITCH, - ), - ), } # Socket (duplicate of `pc`) diff --git a/homeassistant/components/tuya/vacuum.py b/homeassistant/components/tuya/vacuum.py index e36a682fa4e..d61a624f027 100644 --- a/homeassistant/components/tuya/vacuum.py +++ b/homeassistant/components/tuya/vacuum.py @@ -17,7 +17,8 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import TuyaConfigEntry from .const import TUYA_DISCOVERY_NEW, DPCode, DPType -from .entity import EnumTypeData, IntegerTypeData, TuyaEntity +from .entity import TuyaEntity +from .models import EnumTypeData, IntegerTypeData TUYA_MODE_RETURN_HOME = "chargego" TUYA_STATUS_TO_HA = { @@ -91,14 +92,15 @@ class TuyaVacuumEntity(TuyaEntity, StateVacuumEntity): if self.find_dpcode(DPCode.PAUSE, prefer_function=True): self._attr_supported_features |= VacuumEntityFeature.PAUSE - if self.find_dpcode(DPCode.SWITCH_CHARGE, prefer_function=True) or ( - ( - enum_type := self.find_dpcode( - DPCode.MODE, dptype=DPType.ENUM, prefer_function=True - ) + self._return_home_use_switch_charge = False + if self.find_dpcode(DPCode.SWITCH_CHARGE, prefer_function=True): + self._attr_supported_features |= VacuumEntityFeature.RETURN_HOME + self._return_home_use_switch_charge = True + elif ( + enum_type := self.find_dpcode( + DPCode.MODE, dptype=DPType.ENUM, prefer_function=True ) - and TUYA_MODE_RETURN_HOME in enum_type.range - ): + ) and TUYA_MODE_RETURN_HOME in enum_type.range: self._attr_supported_features |= VacuumEntityFeature.RETURN_HOME if self.find_dpcode(DPCode.SEEK, prefer_function=True): @@ -159,12 +161,10 @@ class TuyaVacuumEntity(TuyaEntity, StateVacuumEntity): def return_to_base(self, **kwargs: Any) -> None: """Return device to dock.""" - self._send_command( - [ - {"code": DPCode.SWITCH_CHARGE, "value": True}, - {"code": DPCode.MODE, "value": TUYA_MODE_RETURN_HOME}, - ] - ) + if self._return_home_use_switch_charge: + self._send_command([{"code": DPCode.SWITCH_CHARGE, "value": True}]) + else: + self._send_command([{"code": DPCode.MODE, "value": TUYA_MODE_RETURN_HOME}]) def locate(self, **kwargs: Any) -> None: """Locate the device.""" diff --git a/homeassistant/components/unifi/hub/hub.py b/homeassistant/components/unifi/hub/hub.py index f2ed95a0c79..6cf8825a26c 100644 --- a/homeassistant/components/unifi/hub/hub.py +++ b/homeassistant/components/unifi/hub/hub.py @@ -91,7 +91,9 @@ class UnifiHub: assert self.config.entry.unique_id is not None self.is_admin = self.api.sites[self.config.entry.unique_id].role == "admin" - self.config.entry.add_update_listener(self.async_config_entry_updated) + self.config.entry.async_on_unload( + self.config.entry.add_update_listener(self.async_config_entry_updated) + ) @property def device_info(self) -> DeviceInfo: diff --git a/homeassistant/components/unifiprotect/manifest.json b/homeassistant/components/unifiprotect/manifest.json index 47e2a01e798..8243a55d779 100644 --- a/homeassistant/components/unifiprotect/manifest.json +++ b/homeassistant/components/unifiprotect/manifest.json @@ -40,7 +40,7 @@ "integration_type": "hub", "iot_class": "local_push", "loggers": ["uiprotect", "unifi_discovery"], - "requirements": ["uiprotect==7.14.1", "unifi-discovery==1.2.0"], + "requirements": ["uiprotect==7.14.2", "unifi-discovery==1.2.0"], "ssdp": [ { "manufacturer": "Ubiquiti Networks", diff --git a/homeassistant/components/utility_meter/__init__.py b/homeassistant/components/utility_meter/__init__.py index 64fa3342c08..8a388058b19 100644 --- a/homeassistant/components/utility_meter/__init__.py +++ b/homeassistant/components/utility_meter/__init__.py @@ -21,7 +21,10 @@ from homeassistant.helpers.device import ( async_remove_stale_devices_links_keep_entity_device, ) from homeassistant.helpers.dispatcher import async_dispatcher_send -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from homeassistant.helpers.typing import ConfigType from .const import ( @@ -199,6 +202,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: """Set up Utility Meter from a config entry.""" + # This can be removed in HA Core 2026.2 async_remove_stale_devices_links_keep_entity_device( hass, entry.entry_id, entry.options[CONF_SOURCE_SENSOR] ) @@ -225,20 +229,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: options={**entry.options, CONF_SOURCE_SENSOR: source_entity_id}, ) - async def source_entity_removed() -> None: - # The source entity has been removed, we need to clean the device links. - async_remove_stale_devices_links_keep_entity_device(hass, entry.entry_id, None) - entry.async_on_unload( async_handle_source_entity_changes( hass, + add_helper_config_entry_to_device=False, helper_config_entry_id=entry.entry_id, set_source_entity_id_or_uuid=set_source_entity_id_or_uuid, source_device_id=async_entity_id_to_device_id( hass, entry.options[CONF_SOURCE_SENSOR] ), source_entity_id_or_uuid=entry.options[CONF_SOURCE_SENSOR], - source_entity_removed=source_entity_removed, ) ) @@ -286,13 +286,39 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_migrate_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> bool: """Migrate old entry.""" - _LOGGER.debug("Migrating from version %s", config_entry.version) + _LOGGER.debug( + "Migrating from version %s.%s", config_entry.version, config_entry.minor_version + ) + + if config_entry.version > 2: + # This means the user has downgraded from a future version + return False if config_entry.version == 1: new = {**config_entry.options} new[CONF_METER_PERIODICALLY_RESETTING] = True hass.config_entries.async_update_entry(config_entry, options=new, version=2) - _LOGGER.info("Migration to version %s successful", config_entry.version) + if config_entry.version == 2: + options = {**config_entry.options} + if config_entry.minor_version < 2: + # Remove the utility_meter config entry from the source device + if source_device_id := async_entity_id_to_device_id( + hass, options[CONF_SOURCE_SENSOR] + ): + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=config_entry.entry_id, + source_device_id=source_device_id, + ) + hass.config_entries.async_update_entry( + config_entry, options=options, minor_version=2 + ) + + _LOGGER.debug( + "Migration to version %s.%s successful", + config_entry.version, + config_entry.minor_version, + ) return True diff --git a/homeassistant/components/utility_meter/config_flow.py b/homeassistant/components/utility_meter/config_flow.py index db7cea6ecf2..933a04accba 100644 --- a/homeassistant/components/utility_meter/config_flow.py +++ b/homeassistant/components/utility_meter/config_flow.py @@ -130,6 +130,7 @@ class ConfigFlowHandler(SchemaConfigFlowHandler, domain=DOMAIN): """Handle a config or options flow for Utility Meter.""" VERSION = 2 + MINOR_VERSION = 2 config_flow = CONFIG_FLOW options_flow = OPTIONS_FLOW diff --git a/homeassistant/components/utility_meter/select.py b/homeassistant/components/utility_meter/select.py index 0c818525c8d..280a1fd7b1a 100644 --- a/homeassistant/components/utility_meter/select.py +++ b/homeassistant/components/utility_meter/select.py @@ -8,8 +8,8 @@ from homeassistant.components.select import SelectEntity from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_NAME, CONF_UNIQUE_ID from homeassistant.core import HomeAssistant -from homeassistant.helpers.device import async_device_info_to_link_from_entity -from homeassistant.helpers.device_registry import DeviceInfo +from homeassistant.helpers.device import async_entity_id_to_device +from homeassistant.helpers.device_registry import DeviceEntry from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, AddEntitiesCallback, @@ -33,7 +33,7 @@ async def async_setup_entry( unique_id = config_entry.entry_id - device_info = async_device_info_to_link_from_entity( + device = async_entity_id_to_device( hass, config_entry.options[CONF_SOURCE_SENSOR], ) @@ -42,7 +42,7 @@ async def async_setup_entry( name=name, tariffs=tariffs, unique_id=unique_id, - device_info=device_info, + device=device, ) async_add_entities([tariff_select]) @@ -91,14 +91,14 @@ class TariffSelect(SelectEntity, RestoreEntity): *, yaml_slug: str | None = None, unique_id: str | None = None, - device_info: DeviceInfo | None = None, + device: DeviceEntry | None = None, ) -> None: """Initialize a tariff selector.""" self._attr_name = name if yaml_slug: # Backwards compatibility with YAML configuration entries self.entity_id = f"select.{yaml_slug}" self._attr_unique_id = unique_id - self._attr_device_info = device_info + self.device_entry = device self._current_tariff: str | None = None self._tariffs = tariffs self._attr_should_poll = False diff --git a/homeassistant/components/utility_meter/sensor.py b/homeassistant/components/utility_meter/sensor.py index d424692ac95..457b02c2b50 100644 --- a/homeassistant/components/utility_meter/sensor.py +++ b/homeassistant/components/utility_meter/sensor.py @@ -39,7 +39,7 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import entity_platform, entity_registry as er -from homeassistant.helpers.device import async_device_info_to_link_from_entity +from homeassistant.helpers.device import async_entity_id_to_device from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity_platform import ( AddConfigEntryEntitiesCallback, @@ -129,11 +129,6 @@ async def async_setup_entry( registry, config_entry.options[CONF_SOURCE_SENSOR] ) - device_info = async_device_info_to_link_from_entity( - hass, - source_entity_id, - ) - cron_pattern = None delta_values = config_entry.options[CONF_METER_DELTA_VALUES] meter_offset = timedelta(days=config_entry.options[CONF_METER_OFFSET]) @@ -154,6 +149,7 @@ async def async_setup_entry( if not tariffs: # Add single sensor, not gated by a tariff selector meter_sensor = UtilityMeterSensor( + hass, cron_pattern=cron_pattern, delta_values=delta_values, meter_offset=meter_offset, @@ -166,7 +162,6 @@ async def async_setup_entry( tariff_entity=tariff_entity, tariff=None, unique_id=entry_id, - device_info=device_info, sensor_always_available=sensor_always_available, ) meters.append(meter_sensor) @@ -175,6 +170,7 @@ async def async_setup_entry( # Add sensors for each tariff for tariff in tariffs: meter_sensor = UtilityMeterSensor( + hass, cron_pattern=cron_pattern, delta_values=delta_values, meter_offset=meter_offset, @@ -187,7 +183,6 @@ async def async_setup_entry( tariff_entity=tariff_entity, tariff=tariff, unique_id=f"{entry_id}_{tariff}", - device_info=device_info, sensor_always_available=sensor_always_available, ) meters.append(meter_sensor) @@ -259,6 +254,7 @@ async def async_setup_platform( CONF_SENSOR_ALWAYS_AVAILABLE ] meter_sensor = UtilityMeterSensor( + hass, cron_pattern=conf_cron_pattern, delta_values=conf_meter_delta_values, meter_offset=conf_meter_offset, @@ -359,6 +355,7 @@ class UtilityMeterSensor(RestoreSensor): def __init__( self, + hass, *, cron_pattern, delta_values, @@ -374,11 +371,13 @@ class UtilityMeterSensor(RestoreSensor): unique_id, sensor_always_available, suggested_entity_id=None, - device_info=None, ): """Initialize the Utility Meter sensor.""" self._attr_unique_id = unique_id - self._attr_device_info = device_info + self.device_entry = async_entity_id_to_device( + hass, + source_entity, + ) self.entity_id = suggested_entity_id self._parent_meter = parent_meter self._sensor_source_id = source_entity diff --git a/homeassistant/components/vacuum/__init__.py b/homeassistant/components/vacuum/__init__.py index 9108fc5d879..4b7a6907455 100644 --- a/homeassistant/components/vacuum/__init__.py +++ b/homeassistant/components/vacuum/__init__.py @@ -321,16 +321,18 @@ class StateVacuumEntity( Integrations should implement a sensor instead. """ - report_usage( - f"is setting the {property} which has been deprecated." - f" Integration {self.platform.platform_name} should implement a sensor" - " instead with a correct device class and link it to the same device", - core_integration_behavior=ReportBehavior.LOG, - custom_integration_behavior=ReportBehavior.LOG, - breaks_in_ha_version="2026.8", - integration_domain=self.platform.platform_name if self.platform else None, - exclude_integrations={DOMAIN}, - ) + if self.platform: + # Don't report usage until after entity added to hass, after init + report_usage( + f"is setting the {property} which has been deprecated." + f" Integration {self.platform.platform_name} should implement a sensor" + " instead with a correct device class and link it to the same device", + core_integration_behavior=ReportBehavior.LOG, + custom_integration_behavior=ReportBehavior.LOG, + breaks_in_ha_version="2026.8", + integration_domain=self.platform.platform_name, + exclude_integrations={DOMAIN}, + ) @callback def _report_deprecated_battery_feature(self) -> None: @@ -339,17 +341,19 @@ class StateVacuumEntity( Integrations should remove the battery supported feature when migrating battery level and icon to a sensor. """ - report_usage( - f"is setting the battery supported feature which has been deprecated." - f" Integration {self.platform.platform_name} should remove this as part of migrating" - " the battery level and icon to a sensor", - core_behavior=ReportBehavior.LOG, - core_integration_behavior=ReportBehavior.LOG, - custom_integration_behavior=ReportBehavior.LOG, - breaks_in_ha_version="2026.8", - integration_domain=self.platform.platform_name if self.platform else None, - exclude_integrations={DOMAIN}, - ) + if self.platform: + # Don't report usage until after entity added to hass, after init + report_usage( + f"is setting the battery supported feature which has been deprecated." + f" Integration {self.platform.platform_name} should remove this as part of migrating" + " the battery level and icon to a sensor", + core_behavior=ReportBehavior.LOG, + core_integration_behavior=ReportBehavior.LOG, + custom_integration_behavior=ReportBehavior.LOG, + breaks_in_ha_version="2026.8", + integration_domain=self.platform.platform_name, + exclude_integrations={DOMAIN}, + ) @cached_property def battery_level(self) -> int | None: diff --git a/homeassistant/components/vicare/manifest.json b/homeassistant/components/vicare/manifest.json index fed777e6435..8e632e46efe 100644 --- a/homeassistant/components/vicare/manifest.json +++ b/homeassistant/components/vicare/manifest.json @@ -11,5 +11,5 @@ "documentation": "https://www.home-assistant.io/integrations/vicare", "iot_class": "cloud_polling", "loggers": ["PyViCare"], - "requirements": ["PyViCare==2.44.0"] + "requirements": ["PyViCare==2.50.0"] } diff --git a/homeassistant/components/wallbox/__init__.py b/homeassistant/components/wallbox/__init__.py index c2983d540df..43b5d3ef91f 100644 --- a/homeassistant/components/wallbox/__init__.py +++ b/homeassistant/components/wallbox/__init__.py @@ -4,13 +4,17 @@ from __future__ import annotations from wallbox import Wallbox -from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_PASSWORD, CONF_USERNAME, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed from .const import UPDATE_INTERVAL -from .coordinator import InvalidAuth, WallboxCoordinator, async_validate_input +from .coordinator import ( + InvalidAuth, + WallboxConfigEntry, + WallboxCoordinator, + async_validate_input, +) PLATFORMS = [ Platform.LOCK, @@ -20,8 +24,6 @@ PLATFORMS = [ Platform.SWITCH, ] -type WallboxConfigEntry = ConfigEntry[WallboxCoordinator] - async def async_setup_entry(hass: HomeAssistant, entry: WallboxConfigEntry) -> bool: """Set up Wallbox from a config entry.""" @@ -45,6 +47,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: WallboxConfigEntry) -> b return True -async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: +async def async_unload_entry(hass: HomeAssistant, entry: WallboxConfigEntry) -> bool: """Unload a config entry.""" return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) diff --git a/homeassistant/components/wallbox/coordinator.py b/homeassistant/components/wallbox/coordinator.py index ffd235157ac..4e743b2106b 100644 --- a/homeassistant/components/wallbox/coordinator.py +++ b/homeassistant/components/wallbox/coordinator.py @@ -14,6 +14,7 @@ from wallbox import Wallbox from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryAuthFailed, HomeAssistantError +from homeassistant.helpers import issue_registry as ir from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( @@ -77,6 +78,8 @@ CHARGER_STATUS: dict[int, ChargerStatus] = { 210: ChargerStatus.LOCKED_CAR_CONNECTED, } +type WallboxConfigEntry = ConfigEntry[WallboxCoordinator] + def _require_authentication[_WallboxCoordinatorT: WallboxCoordinator, **_P]( func: Callable[Concatenate[_WallboxCoordinatorT, _P], Any], @@ -92,7 +95,9 @@ def _require_authentication[_WallboxCoordinatorT: WallboxCoordinator, **_P]( return func(self, *args, **kwargs) except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == HTTPStatus.FORBIDDEN: - raise ConfigEntryAuthFailed from wallbox_connection_error + raise ConfigEntryAuthFailed( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from wallbox_connection_error raise HomeAssistantError( translation_domain=DOMAIN, translation_key="api_failed" ) from wallbox_connection_error @@ -106,7 +111,9 @@ def _validate(wallbox: Wallbox) -> None: wallbox.authenticate() except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: - raise InvalidAuth from wallbox_connection_error + raise InvalidAuth( + translation_domain=DOMAIN, translation_key="invalid_auth" + ) from wallbox_connection_error raise ConnectionError from wallbox_connection_error @@ -118,10 +125,10 @@ async def async_validate_input(hass: HomeAssistant, wallbox: Wallbox) -> None: class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): """Wallbox Coordinator class.""" - config_entry: ConfigEntry + config_entry: WallboxConfigEntry def __init__( - self, hass: HomeAssistant, config_entry: ConfigEntry, wallbox: Wallbox + self, hass: HomeAssistant, config_entry: WallboxConfigEntry, wallbox: Wallbox ) -> None: """Initialize.""" self._station = config_entry.data[CONF_STATION] @@ -191,7 +198,6 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): data[CHARGER_ECO_SMART_KEY] = EcoSmartMode.ECO_MODE elif eco_smart_mode == 1: data[CHARGER_ECO_SMART_KEY] = EcoSmartMode.FULL_SOLAR - return data # noqa: TRY300 except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 429: @@ -222,8 +228,10 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): return data # noqa: TRY300 except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: - raise InvalidAuth( - translation_domain=DOMAIN, translation_key="invalid_auth" + raise InsufficientRights( + translation_domain=DOMAIN, + translation_key="insufficient_rights", + hass=self.hass, ) from wallbox_connection_error if wallbox_connection_error.response.status_code == 429: raise HomeAssistantError( @@ -250,8 +258,10 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): return data # noqa: TRY300 except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: - raise InvalidAuth( - translation_domain=DOMAIN, translation_key="invalid_auth" + raise InsufficientRights( + translation_domain=DOMAIN, + translation_key="insufficient_rights", + hass=self.hass, ) from wallbox_connection_error if wallbox_connection_error.response.status_code == 429: raise HomeAssistantError( @@ -307,8 +317,10 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): return data # noqa: TRY300 except requests.exceptions.HTTPError as wallbox_connection_error: if wallbox_connection_error.response.status_code == 403: - raise InvalidAuth( - translation_domain=DOMAIN, translation_key="invalid_auth" + raise InsufficientRights( + translation_domain=DOMAIN, + translation_key="insufficient_rights", + hass=self.hass, ) from wallbox_connection_error if wallbox_connection_error.response.status_code == 429: raise HomeAssistantError( @@ -373,3 +385,34 @@ class WallboxCoordinator(DataUpdateCoordinator[dict[str, Any]]): class InvalidAuth(HomeAssistantError): """Error to indicate there is invalid auth.""" + + +class InsufficientRights(HomeAssistantError): + """Error to indicate there are insufficient right for the user.""" + + def __init__( + self, + *args: object, + translation_domain: str | None = None, + translation_key: str | None = None, + translation_placeholders: dict[str, str] | None = None, + hass: HomeAssistant, + ) -> None: + """Initialize exception.""" + super().__init__( + self, *args, translation_domain, translation_key, translation_placeholders + ) + self.hass = hass + self._create_insufficient_rights_issue() + + def _create_insufficient_rights_issue(self) -> None: + """Creates an issue for insufficient rights.""" + ir.create_issue( + self.hass, + DOMAIN, + "insufficient_rights", + is_fixable=False, + severity=ir.IssueSeverity.ERROR, + learn_more_url="https://www.home-assistant.io/integrations/wallbox/#troubleshooting", + translation_key="insufficient_rights", + ) diff --git a/homeassistant/components/wallbox/lock.py b/homeassistant/components/wallbox/lock.py index 6ba9058db96..f48ac000110 100644 --- a/homeassistant/components/wallbox/lock.py +++ b/homeassistant/components/wallbox/lock.py @@ -5,7 +5,6 @@ from __future__ import annotations from typing import Any from homeassistant.components.lock import LockEntity, LockEntityDescription -from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -14,7 +13,7 @@ from .const import ( CHARGER_LOCKED_UNLOCKED_KEY, CHARGER_SERIAL_NUMBER_KEY, ) -from .coordinator import WallboxCoordinator +from .coordinator import WallboxConfigEntry, WallboxCoordinator from .entity import WallboxEntity LOCK_TYPES: dict[str, LockEntityDescription] = { @@ -27,7 +26,7 @@ LOCK_TYPES: dict[str, LockEntityDescription] = { async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: WallboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Create wallbox lock entities in HASS.""" diff --git a/homeassistant/components/wallbox/number.py b/homeassistant/components/wallbox/number.py index af4fbe2c38b..6bc37778a61 100644 --- a/homeassistant/components/wallbox/number.py +++ b/homeassistant/components/wallbox/number.py @@ -10,7 +10,6 @@ from dataclasses import dataclass from typing import cast from homeassistant.components.number import NumberEntity, NumberEntityDescription -from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -24,7 +23,7 @@ from .const import ( CHARGER_PART_NUMBER_KEY, CHARGER_SERIAL_NUMBER_KEY, ) -from .coordinator import WallboxCoordinator +from .coordinator import WallboxConfigEntry, WallboxCoordinator from .entity import WallboxEntity @@ -79,7 +78,7 @@ NUMBER_TYPES: dict[str, WallboxNumberEntityDescription] = { async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: WallboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Create wallbox number entities in HASS.""" @@ -103,7 +102,7 @@ class WallboxNumber(WallboxEntity, NumberEntity): def __init__( self, coordinator: WallboxCoordinator, - entry: ConfigEntry, + entry: WallboxConfigEntry, description: WallboxNumberEntityDescription, ) -> None: """Initialize a Wallbox number entity.""" diff --git a/homeassistant/components/wallbox/select.py b/homeassistant/components/wallbox/select.py index 10ac4e61189..8d4cf252344 100644 --- a/homeassistant/components/wallbox/select.py +++ b/homeassistant/components/wallbox/select.py @@ -8,7 +8,6 @@ from dataclasses import dataclass from requests import HTTPError from homeassistant.components.select import SelectEntity, SelectEntityDescription -from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -23,7 +22,7 @@ from .const import ( DOMAIN, EcoSmartMode, ) -from .coordinator import WallboxCoordinator +from .coordinator import WallboxConfigEntry, WallboxCoordinator from .entity import WallboxEntity @@ -58,7 +57,7 @@ SELECT_TYPES: dict[str, WallboxSelectEntityDescription] = { async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: WallboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Create wallbox select entities in HASS.""" diff --git a/homeassistant/components/wallbox/sensor.py b/homeassistant/components/wallbox/sensor.py index 7d5e5b56309..b59e1e5319d 100644 --- a/homeassistant/components/wallbox/sensor.py +++ b/homeassistant/components/wallbox/sensor.py @@ -11,7 +11,6 @@ from homeassistant.components.sensor import ( SensorEntityDescription, SensorStateClass, ) -from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( PERCENTAGE, UnitOfElectricCurrent, @@ -44,7 +43,7 @@ from .const import ( CHARGER_STATE_OF_CHARGE_KEY, CHARGER_STATUS_DESCRIPTION_KEY, ) -from .coordinator import WallboxCoordinator +from .coordinator import WallboxConfigEntry, WallboxCoordinator from .entity import WallboxEntity @@ -169,7 +168,7 @@ SENSOR_TYPES: dict[str, WallboxSensorEntityDescription] = { async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: WallboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Create wallbox sensor entities in HASS.""" diff --git a/homeassistant/components/wallbox/strings.json b/homeassistant/components/wallbox/strings.json index 13f038d14b6..c59b5389658 100644 --- a/homeassistant/components/wallbox/strings.json +++ b/homeassistant/components/wallbox/strings.json @@ -114,6 +114,12 @@ } } }, + "issues": { + "insufficient_rights": { + "title": "The Wallbox account has insufficient rights.", + "description": "The Wallbox account has insufficient rights to lock/unlock and change the charging power. Please assign the user admin rights in the Wallbox portal." + } + }, "exceptions": { "api_failed": { "message": "Error communicating with Wallbox API" @@ -123,6 +129,9 @@ }, "invalid_auth": { "message": "Invalid authentication" + }, + "insufficient_rights": { + "message": "Insufficient rights for Wallbox user" } } } diff --git a/homeassistant/components/wallbox/switch.py b/homeassistant/components/wallbox/switch.py index 7a28f863c4d..74f1783f539 100644 --- a/homeassistant/components/wallbox/switch.py +++ b/homeassistant/components/wallbox/switch.py @@ -5,7 +5,6 @@ from __future__ import annotations from typing import Any from homeassistant.components.switch import SwitchEntity, SwitchEntityDescription -from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -16,7 +15,7 @@ from .const import ( CHARGER_STATUS_DESCRIPTION_KEY, ChargerStatus, ) -from .coordinator import WallboxCoordinator +from .coordinator import WallboxConfigEntry, WallboxCoordinator from .entity import WallboxEntity SWITCH_TYPES: dict[str, SwitchEntityDescription] = { @@ -29,7 +28,7 @@ SWITCH_TYPES: dict[str, SwitchEntityDescription] = { async def async_setup_entry( hass: HomeAssistant, - entry: ConfigEntry, + entry: WallboxConfigEntry, async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Create wallbox sensor entities in HASS.""" diff --git a/homeassistant/components/workday/manifest.json b/homeassistant/components/workday/manifest.json index f9fae38f1f5..86c0884ee9d 100644 --- a/homeassistant/components/workday/manifest.json +++ b/homeassistant/components/workday/manifest.json @@ -7,5 +7,5 @@ "iot_class": "local_polling", "loggers": ["holidays"], "quality_scale": "internal", - "requirements": ["holidays==0.75"] + "requirements": ["holidays==0.76"] } diff --git a/homeassistant/components/xiaomi_ble/strings.json b/homeassistant/components/xiaomi_ble/strings.json index 06b49b8e86f..ffdd8f29a79 100644 --- a/homeassistant/components/xiaomi_ble/strings.json +++ b/homeassistant/components/xiaomi_ble/strings.json @@ -59,13 +59,13 @@ "device_automation": { "trigger_subtype": { "press": "Press", - "double_press": "Double Press", - "long_press": "Long Press", - "motion_detected": "Motion Detected", - "rotate_left": "Rotate Left", - "rotate_right": "Rotate Right", - "rotate_left_pressed": "Rotate Left (Pressed)", - "rotate_right_pressed": "Rotate Right (Pressed)", + "double_press": "Double press", + "long_press": "Long press", + "motion_detected": "Motion detected", + "rotate_left": "Rotate left", + "rotate_right": "Rotate right", + "rotate_left_pressed": "Rotate left (pressed)", + "rotate_right_pressed": "Rotate right (pressed)", "match_successful": "Match successful", "match_failed": "Match failed", "low_quality_too_light_fuzzy": "Low quality (too light, fuzzy)", @@ -224,7 +224,7 @@ "state_attributes": { "event_type": { "state": { - "motion_detected": "Motion Detected" + "motion_detected": "Motion detected" } } } @@ -235,7 +235,7 @@ "name": "Impedance" }, "weight_non_stabilized": { - "name": "Weight non stabilized" + "name": "Weight non-stabilized" } } } diff --git a/homeassistant/components/yolink/binary_sensor.py b/homeassistant/components/yolink/binary_sensor.py index 7f965650354..d57e942734e 100644 --- a/homeassistant/components/yolink/binary_sensor.py +++ b/homeassistant/components/yolink/binary_sensor.py @@ -12,6 +12,7 @@ from yolink.const import ( ATTR_DEVICE_LEAK_SENSOR, ATTR_DEVICE_MOTION_SENSOR, ATTR_DEVICE_MULTI_WATER_METER_CONTROLLER, + ATTR_DEVICE_SMOKE_ALARM, ATTR_DEVICE_VIBRATION_SENSOR, ATTR_DEVICE_WATER_METER_CONTROLLER, ) @@ -53,6 +54,7 @@ SENSOR_DEVICE_TYPE = [ ATTR_DEVICE_CO_SMOKE_SENSOR, ATTR_DEVICE_WATER_METER_CONTROLLER, ATTR_DEVICE_MULTI_WATER_METER_CONTROLLER, + ATTR_DEVICE_SMOKE_ALARM, ] @@ -90,8 +92,10 @@ SENSOR_TYPES: tuple[YoLinkBinarySensorEntityDescription, ...] = ( YoLinkBinarySensorEntityDescription( key="smoke_detected", device_class=BinarySensorDeviceClass.SMOKE, - value=lambda state: state.get("smokeAlarm"), - exists_fn=lambda device: device.device_type == ATTR_DEVICE_CO_SMOKE_SENSOR, + value=lambda state: state.get("smokeAlarm") is True + or state.get("denseSmokeAlarm") is True, + exists_fn=lambda device: device.device_type + in [ATTR_DEVICE_CO_SMOKE_SENSOR, ATTR_DEVICE_SMOKE_ALARM], ), YoLinkBinarySensorEntityDescription( key="pipe_leak_detected", diff --git a/homeassistant/components/yolink/manifest.json b/homeassistant/components/yolink/manifest.json index 779b830637b..89001f98c16 100644 --- a/homeassistant/components/yolink/manifest.json +++ b/homeassistant/components/yolink/manifest.json @@ -6,5 +6,5 @@ "dependencies": ["auth", "application_credentials"], "documentation": "https://www.home-assistant.io/integrations/yolink", "iot_class": "cloud_push", - "requirements": ["yolink-api==0.5.5"] + "requirements": ["yolink-api==0.5.7"] } diff --git a/homeassistant/components/yolink/sensor.py b/homeassistant/components/yolink/sensor.py index bc32d0eea83..37cd763194d 100644 --- a/homeassistant/components/yolink/sensor.py +++ b/homeassistant/components/yolink/sensor.py @@ -21,6 +21,8 @@ from yolink.const import ( ATTR_DEVICE_POWER_FAILURE_ALARM, ATTR_DEVICE_SIREN, ATTR_DEVICE_SMART_REMOTER, + ATTR_DEVICE_SMOKE_ALARM, + ATTR_DEVICE_SOIL_TH_SENSOR, ATTR_DEVICE_SWITCH, ATTR_DEVICE_TH_SENSOR, ATTR_DEVICE_THERMOSTAT, @@ -42,6 +44,7 @@ from homeassistant.const import ( PERCENTAGE, SIGNAL_STRENGTH_DECIBELS_MILLIWATT, EntityCategory, + UnitOfConductivity, UnitOfEnergy, UnitOfLength, UnitOfPower, @@ -103,6 +106,8 @@ SENSOR_DEVICE_TYPE = [ ATTR_DEVICE_MANIPULATOR, ATTR_DEVICE_CO_SMOKE_SENSOR, ATTR_GARAGE_DOOR_CONTROLLER, + ATTR_DEVICE_SOIL_TH_SENSOR, + ATTR_DEVICE_SMOKE_ALARM, ] BATTERY_POWER_SENSOR = [ @@ -122,12 +127,15 @@ BATTERY_POWER_SENSOR = [ ATTR_DEVICE_WATER_DEPTH_SENSOR, ATTR_DEVICE_WATER_METER_CONTROLLER, ATTR_DEVICE_MULTI_WATER_METER_CONTROLLER, + ATTR_DEVICE_SOIL_TH_SENSOR, + ATTR_DEVICE_SMOKE_ALARM, ] MCU_DEV_TEMPERATURE_SENSOR = [ ATTR_DEVICE_LEAK_SENSOR, ATTR_DEVICE_MOTION_SENSOR, ATTR_DEVICE_CO_SMOKE_SENSOR, + ATTR_DEVICE_SMOKE_ALARM, ] NONE_HUMIDITY_SENSOR_MODELS = [ @@ -182,7 +190,7 @@ SENSOR_TYPES: tuple[YoLinkSensorEntityDescription, ...] = ( native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, exists_fn=lambda device: ( - device.device_type in [ATTR_DEVICE_TH_SENSOR] + device.device_type in [ATTR_DEVICE_TH_SENSOR, ATTR_DEVICE_SOIL_TH_SENSOR] and device.device_model_name not in NONE_HUMIDITY_SENSOR_MODELS ), ), @@ -191,7 +199,8 @@ SENSOR_TYPES: tuple[YoLinkSensorEntityDescription, ...] = ( device_class=SensorDeviceClass.TEMPERATURE, native_unit_of_measurement=UnitOfTemperature.CELSIUS, state_class=SensorStateClass.MEASUREMENT, - exists_fn=lambda device: device.device_type in [ATTR_DEVICE_TH_SENSOR], + exists_fn=lambda device: device.device_type + in [ATTR_DEVICE_TH_SENSOR, ATTR_DEVICE_SOIL_TH_SENSOR], ), # mcu temperature YoLinkSensorEntityDescription( @@ -206,7 +215,7 @@ SENSOR_TYPES: tuple[YoLinkSensorEntityDescription, ...] = ( key="loraInfo", device_class=SensorDeviceClass.SIGNAL_STRENGTH, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, - value=lambda value: value["signal"] if value is not None else None, + value=lambda value: value.get("signal") if value is not None else None, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, @@ -302,6 +311,14 @@ SENSOR_TYPES: tuple[YoLinkSensorEntityDescription, ...] = ( exists_fn=lambda device: device.device_model_name in POWER_SUPPORT_MODELS, value=lambda value: value / 100 if value is not None else None, ), + YoLinkSensorEntityDescription( + key="conductivity", + device_class=SensorDeviceClass.CONDUCTIVITY, + native_unit_of_measurement=UnitOfConductivity.MICROSIEMENS_PER_CM, + state_class=SensorStateClass.MEASUREMENT, + exists_fn=lambda device: device.device_type in [ATTR_DEVICE_SOIL_TH_SENSOR], + should_update_entity=lambda value: value is not None, + ), ) diff --git a/homeassistant/components/zabbix/__init__.py b/homeassistant/components/zabbix/__init__.py index 31a09242a71..432b5d50c4e 100644 --- a/homeassistant/components/zabbix/__init__.py +++ b/homeassistant/components/zabbix/__init__.py @@ -13,7 +13,7 @@ from urllib.parse import urljoin import voluptuous as vol from zabbix_utils import ItemValue, Sender, ZabbixAPI -from zabbix_utils.exceptions import APIRequestError +from zabbix_utils.exceptions import APIRequestError, ProcessingError from homeassistant.const import ( CONF_HOST, @@ -282,6 +282,8 @@ class ZabbixThread(threading.Thread): if not self.write_errors: _LOGGER.error("Write error: %s", err) self.write_errors += len(metrics) + except ProcessingError as prerr: + _LOGGER.error("Error writing to Zabbix: %s", prerr) def run(self) -> None: """Process incoming events.""" diff --git a/homeassistant/components/zha/strings.json b/homeassistant/components/zha/strings.json index 87c3903b342..23d17ea128f 100644 --- a/homeassistant/components/zha/strings.json +++ b/homeassistant/components/zha/strings.json @@ -1219,7 +1219,7 @@ "name": "Smart fan LED display levels" }, "increased_non_neutral_output": { - "name": "Non neutral output" + "name": "Increased non-neutral output" }, "leading_or_trailing_edge": { "name": "Dimming mode" diff --git a/homeassistant/components/zone/condition.py b/homeassistant/components/zone/condition.py new file mode 100644 index 00000000000..0fb30eeda9c --- /dev/null +++ b/homeassistant/components/zone/condition.py @@ -0,0 +1,156 @@ +"""Offer zone automation rules.""" + +from __future__ import annotations + +import voluptuous as vol + +from homeassistant.const import ( + ATTR_GPS_ACCURACY, + ATTR_LATITUDE, + ATTR_LONGITUDE, + CONF_CONDITION, + CONF_ENTITY_ID, + CONF_ZONE, + STATE_UNAVAILABLE, + STATE_UNKNOWN, +) +from homeassistant.core import HomeAssistant, State +from homeassistant.exceptions import ConditionErrorContainer, ConditionErrorMessage +from homeassistant.helpers import config_validation as cv +from homeassistant.helpers.condition import ( + Condition, + ConditionCheckerType, + trace_condition_function, +) +from homeassistant.helpers.typing import ConfigType, TemplateVarsType + +from . import in_zone + +_CONDITION_SCHEMA = vol.Schema( + { + **cv.CONDITION_BASE_SCHEMA, + vol.Required(CONF_CONDITION): "zone", + vol.Required(CONF_ENTITY_ID): cv.entity_ids, + vol.Required("zone"): cv.entity_ids, + # To support use_trigger_value in automation + # Deprecated 2016/04/25 + vol.Optional("event"): vol.Any("enter", "leave"), + } +) + + +def zone( + hass: HomeAssistant, + zone_ent: str | State | None, + entity: str | State | None, +) -> bool: + """Test if zone-condition matches. + + Async friendly. + """ + if zone_ent is None: + raise ConditionErrorMessage("zone", "no zone specified") + + if isinstance(zone_ent, str): + zone_ent_id = zone_ent + + if (zone_ent := hass.states.get(zone_ent)) is None: + raise ConditionErrorMessage("zone", f"unknown zone {zone_ent_id}") + + if entity is None: + raise ConditionErrorMessage("zone", "no entity specified") + + if isinstance(entity, str): + entity_id = entity + + if (entity := hass.states.get(entity)) is None: + raise ConditionErrorMessage("zone", f"unknown entity {entity_id}") + else: + entity_id = entity.entity_id + + if entity.state in ( + STATE_UNAVAILABLE, + STATE_UNKNOWN, + ): + return False + + latitude = entity.attributes.get(ATTR_LATITUDE) + longitude = entity.attributes.get(ATTR_LONGITUDE) + + if latitude is None: + raise ConditionErrorMessage( + "zone", f"entity {entity_id} has no 'latitude' attribute" + ) + + if longitude is None: + raise ConditionErrorMessage( + "zone", f"entity {entity_id} has no 'longitude' attribute" + ) + + return in_zone( + zone_ent, latitude, longitude, entity.attributes.get(ATTR_GPS_ACCURACY, 0) + ) + + +class ZoneCondition(Condition): + """Zone condition.""" + + def __init__(self, hass: HomeAssistant, config: ConfigType) -> None: + """Initialize condition.""" + self._config = config + + @classmethod + async def async_validate_condition_config( + cls, hass: HomeAssistant, config: ConfigType + ) -> ConfigType: + """Validate config.""" + return _CONDITION_SCHEMA(config) # type: ignore[no-any-return] + + async def async_condition_from_config(self) -> ConditionCheckerType: + """Wrap action method with zone based condition.""" + entity_ids = self._config.get(CONF_ENTITY_ID, []) + zone_entity_ids = self._config.get(CONF_ZONE, []) + + @trace_condition_function + def if_in_zone(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: + """Test if condition.""" + errors = [] + + all_ok = True + for entity_id in entity_ids: + entity_ok = False + for zone_entity_id in zone_entity_ids: + try: + if zone(hass, zone_entity_id, entity_id): + entity_ok = True + except ConditionErrorMessage as ex: + errors.append( + ConditionErrorMessage( + "zone", + ( + f"error matching {entity_id} with {zone_entity_id}:" + f" {ex.message}" + ), + ) + ) + + if not entity_ok: + all_ok = False + + # Raise the errors only if no definitive result was found + if errors and not all_ok: + raise ConditionErrorContainer("zone", errors=errors) + + return all_ok + + return if_in_zone + + +CONDITIONS: dict[str, type[Condition]] = { + "zone": ZoneCondition, +} + + +async def async_get_conditions(hass: HomeAssistant) -> dict[str, type[Condition]]: + """Return the sun conditions.""" + return CONDITIONS diff --git a/homeassistant/components/zone/trigger.py b/homeassistant/components/zone/trigger.py index af4999e5438..59e0f2f8821 100644 --- a/homeassistant/components/zone/trigger.py +++ b/homeassistant/components/zone/trigger.py @@ -22,7 +22,6 @@ from homeassistant.core import ( callback, ) from homeassistant.helpers import ( - condition, config_validation as cv, entity_registry as er, location, @@ -31,6 +30,8 @@ from homeassistant.helpers.event import async_track_state_change_event from homeassistant.helpers.trigger import TriggerActionType, TriggerInfo from homeassistant.helpers.typing import ConfigType +from . import condition + EVENT_ENTER = "enter" EVENT_LEAVE = "leave" DEFAULT_EVENT = EVENT_ENTER diff --git a/homeassistant/components/zwave_js/discovery.py b/homeassistant/components/zwave_js/discovery.py index 3b541a733cc..74ffedbc53f 100644 --- a/homeassistant/components/zwave_js/discovery.py +++ b/homeassistant/components/zwave_js/discovery.py @@ -263,7 +263,7 @@ WINDOW_COVERING_SLAT_CURRENT_VALUE_SCHEMA = ZWaveValueDiscoverySchema( ) # For device class mapping see: -# https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/deviceClasses.json +# https://github.com/zwave-js/node-zwave-js/blob/master/packages/config/config/ DISCOVERY_SCHEMAS = [ # ====== START OF DEVICE SPECIFIC MAPPING SCHEMAS ======= # Honeywell 39358 In-Wall Fan Control using switch multilevel CC @@ -291,12 +291,16 @@ DISCOVERY_SCHEMAS = [ FanValueMapping(speeds=[(1, 33), (34, 67), (68, 99)]), ), ), - # GE/Jasco - In-Wall Smart Fan Control - 14287 / 55258 / ZW4002 + # GE/Jasco - In-Wall Smart Fan Controls ZWaveDiscoverySchema( platform=Platform.FAN, hint="has_fan_value_mapping", manufacturer_id={0x0063}, - product_id={0x3131, 0x3337}, + product_id={ + 0x3131, + 0x3337, # 14287 / 55258 / ZW4002 + 0x3533, # 58446 / ZWA4013 + }, product_type={0x4944}, primary_value=SWITCH_MULTILEVEL_CURRENT_VALUE_SCHEMA, data_template=FixedFanValueMappingDataTemplate( diff --git a/homeassistant/components/zwave_js/entity.py b/homeassistant/components/zwave_js/entity.py index d1ab9009308..08a587d8d20 100644 --- a/homeassistant/components/zwave_js/entity.py +++ b/homeassistant/components/zwave_js/entity.py @@ -5,7 +5,6 @@ from __future__ import annotations from collections.abc import Sequence from typing import Any -from zwave_js_server.const import NodeStatus from zwave_js_server.exceptions import BaseZwaveJSServerError from zwave_js_server.model.driver import Driver from zwave_js_server.model.value import ( @@ -27,8 +26,6 @@ from .discovery import ZwaveDiscoveryInfo from .helpers import get_device_id, get_unique_id, get_valueless_base_unique_id EVENT_VALUE_REMOVED = "value removed" -EVENT_DEAD = "dead" -EVENT_ALIVE = "alive" class ZWaveBaseEntity(Entity): @@ -141,11 +138,6 @@ class ZWaveBaseEntity(Entity): ) ) - for status_event in (EVENT_ALIVE, EVENT_DEAD): - self.async_on_remove( - self.info.node.on(status_event, self._node_status_alive_or_dead) - ) - self.async_on_remove( async_dispatcher_connect( self.hass, @@ -211,19 +203,7 @@ class ZWaveBaseEntity(Entity): @property def available(self) -> bool: """Return entity availability.""" - return ( - self.driver.client.connected - and bool(self.info.node.ready) - and self.info.node.status != NodeStatus.DEAD - ) - - @callback - def _node_status_alive_or_dead(self, event_data: dict) -> None: - """Call when node status changes to alive or dead. - - Should not be overridden by subclasses. - """ - self.async_write_ha_state() + return self.driver.client.connected and bool(self.info.node.ready) @callback def _value_changed(self, event_data: dict) -> None: diff --git a/homeassistant/components/zwave_js/strings.json b/homeassistant/components/zwave_js/strings.json index 5029e8c6108..63dad248246 100644 --- a/homeassistant/components/zwave_js/strings.json +++ b/homeassistant/components/zwave_js/strings.json @@ -15,7 +15,7 @@ "config_entry_not_loaded": "The Z-Wave configuration entry is not loaded. Please try again when the configuration entry is loaded.", "different_device": "The connected USB device is not the same as previously configured for this config entry. Please instead create a new config entry for the new device.", "discovery_requires_supervisor": "Discovery requires the supervisor.", - "migration_low_sdk_version": "The SDK version of the old adapter is lower than {ok_sdk_version}. This means it's not possible to migrate the Non Volatile Memory (NVM) of the old adapter to another adapter.\n\nCheck the documentation on the manufacturer support pages of the old adapter, if it's possible to upgrade the firmware of the old adapter to a version that is built with SDK version {ok_sdk_version} or higher.", + "migration_low_sdk_version": "The SDK version of the old adapter is lower than {ok_sdk_version}. This means it's not possible to migrate the non-volatile memory (NVM) of the old adapter to another adapter.\n\nCheck the documentation on the manufacturer support pages of the old adapter, if it's possible to upgrade the firmware of the old adapter to a version that is built with SDK version {ok_sdk_version} or higher.", "migration_successful": "Migration successful.", "not_zwave_device": "Discovered device is not a Z-Wave device.", "not_zwave_js_addon": "Discovered add-on is not the official Z-Wave add-on.", diff --git a/homeassistant/components/zwave_js/update.py b/homeassistant/components/zwave_js/update.py index 4355857f5df..89fb4dd4aba 100644 --- a/homeassistant/components/zwave_js/update.py +++ b/homeassistant/components/zwave_js/update.py @@ -199,18 +199,13 @@ class ZWaveNodeFirmwareUpdate(UpdateEntity): ) return - # If device is asleep/dead, wait for it to wake up/become alive before - # attempting an update - for status, event_name in ( - (NodeStatus.ASLEEP, "wake up"), - (NodeStatus.DEAD, "alive"), - ): - if self.node.status == status: - if not self._status_unsub: - self._status_unsub = self.node.once( - event_name, self._update_on_status_change - ) - return + # If device is asleep, wait for it to wake up before attempting an update + if self.node.status == NodeStatus.ASLEEP: + if not self._status_unsub: + self._status_unsub = self.node.once( + "wake up", self._update_on_status_change + ) + return try: # Retrieve all firmware updates including non-stable ones but filter diff --git a/homeassistant/const.py b/homeassistant/const.py index e6da8ba4a69..6b4f16c316f 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -910,6 +910,7 @@ class UnitOfPrecipitationDepth(StrEnum): # Concentration units +CONCENTRATION_GRAMS_PER_CUBIC_METER: Final = "g/m³" CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: Final = "µg/m³" CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER: Final = "mg/m³" CONCENTRATION_MICROGRAMS_PER_CUBIC_FOOT: Final = "μg/ft³" diff --git a/homeassistant/generated/integrations.json b/homeassistant/generated/integrations.json index 6bf63b260de..ec790549519 100644 --- a/homeassistant/generated/integrations.json +++ b/homeassistant/generated/integrations.json @@ -3252,7 +3252,7 @@ }, "keymitt_ble": { "name": "Keymitt MicroBot Push", - "integration_type": "hub", + "integration_type": "device", "config_flow": true, "iot_class": "assumed_state" }, diff --git a/homeassistant/generated/zeroconf.py b/homeassistant/generated/zeroconf.py index 274fafa51cf..47522a69c41 100644 --- a/homeassistant/generated/zeroconf.py +++ b/homeassistant/generated/zeroconf.py @@ -534,6 +534,11 @@ ZEROCONF = { "domain": "homekit_controller", }, ], + "_heos-audio._tcp.local.": [ + { + "domain": "heos", + }, + ], "_homeconnect._tcp.local.": [ { "domain": "home_connect", diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index 5a9ffb6d91b..37ff9b22ff7 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -18,9 +18,6 @@ import voluptuous as vol from homeassistant.const import ( ATTR_DEVICE_CLASS, - ATTR_GPS_ACCURACY, - ATTR_LATITUDE, - ATTR_LONGITUDE, CONF_ABOVE, CONF_AFTER, CONF_ATTRIBUTE, @@ -36,7 +33,6 @@ from homeassistant.const import ( CONF_STATE, CONF_VALUE_TEMPLATE, CONF_WEEKDAY, - CONF_ZONE, ENTITY_MATCH_ALL, ENTITY_MATCH_ANY, STATE_UNAVAILABLE, @@ -95,7 +91,6 @@ _PLATFORM_ALIASES: dict[str | None, str | None] = { "template": None, "time": None, "trigger": None, - "zone": None, } INPUT_ENTITY_ID = re.compile( @@ -919,101 +914,6 @@ def time_from_config(config: ConfigType) -> ConditionCheckerType: return time_if -def zone( - hass: HomeAssistant, - zone_ent: str | State | None, - entity: str | State | None, -) -> bool: - """Test if zone-condition matches. - - Async friendly. - """ - from homeassistant.components import zone as zone_cmp # noqa: PLC0415 - - if zone_ent is None: - raise ConditionErrorMessage("zone", "no zone specified") - - if isinstance(zone_ent, str): - zone_ent_id = zone_ent - - if (zone_ent := hass.states.get(zone_ent)) is None: - raise ConditionErrorMessage("zone", f"unknown zone {zone_ent_id}") - - if entity is None: - raise ConditionErrorMessage("zone", "no entity specified") - - if isinstance(entity, str): - entity_id = entity - - if (entity := hass.states.get(entity)) is None: - raise ConditionErrorMessage("zone", f"unknown entity {entity_id}") - else: - entity_id = entity.entity_id - - if entity.state in ( - STATE_UNAVAILABLE, - STATE_UNKNOWN, - ): - return False - - latitude = entity.attributes.get(ATTR_LATITUDE) - longitude = entity.attributes.get(ATTR_LONGITUDE) - - if latitude is None: - raise ConditionErrorMessage( - "zone", f"entity {entity_id} has no 'latitude' attribute" - ) - - if longitude is None: - raise ConditionErrorMessage( - "zone", f"entity {entity_id} has no 'longitude' attribute" - ) - - return zone_cmp.in_zone( - zone_ent, latitude, longitude, entity.attributes.get(ATTR_GPS_ACCURACY, 0) - ) - - -def zone_from_config(config: ConfigType) -> ConditionCheckerType: - """Wrap action method with zone based condition.""" - entity_ids = config.get(CONF_ENTITY_ID, []) - zone_entity_ids = config.get(CONF_ZONE, []) - - @trace_condition_function - def if_in_zone(hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: - """Test if condition.""" - errors = [] - - all_ok = True - for entity_id in entity_ids: - entity_ok = False - for zone_entity_id in zone_entity_ids: - try: - if zone(hass, zone_entity_id, entity_id): - entity_ok = True - except ConditionErrorMessage as ex: - errors.append( - ConditionErrorMessage( - "zone", - ( - f"error matching {entity_id} with {zone_entity_id}:" - f" {ex.message}" - ), - ) - ) - - if not entity_ok: - all_ok = False - - # Raise the errors only if no definitive result was found - if errors and not all_ok: - raise ConditionErrorContainer("zone", errors=errors) - - return all_ok - - return if_in_zone - - async def async_trigger_from_config( hass: HomeAssistant, config: ConfigType ) -> ConditionCheckerType: diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index ab347e803d6..da1c1c80619 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -1570,18 +1570,6 @@ TRIGGER_CONDITION_SCHEMA = vol.Schema( } ) -ZONE_CONDITION_SCHEMA = vol.Schema( - { - **CONDITION_BASE_SCHEMA, - vol.Required(CONF_CONDITION): "zone", - vol.Required(CONF_ENTITY_ID): entity_ids, - vol.Required("zone"): entity_ids, - # To support use_trigger_value in automation - # Deprecated 2016/04/25 - vol.Optional("event"): vol.Any("enter", "leave"), - } -) - AND_CONDITION_SCHEMA = vol.Schema( { **CONDITION_BASE_SCHEMA, @@ -1729,7 +1717,6 @@ BUILT_IN_CONDITIONS: ValueSchemas = { "template": TEMPLATE_CONDITION_SCHEMA, "time": TIME_CONDITION_SCHEMA, "trigger": TRIGGER_CONDITION_SCHEMA, - "zone": ZONE_CONDITION_SCHEMA, } diff --git a/homeassistant/helpers/device.py b/homeassistant/helpers/device.py index f1404bb068b..bf0e2ab31be 100644 --- a/homeassistant/helpers/device.py +++ b/homeassistant/helpers/device.py @@ -21,6 +21,19 @@ def async_entity_id_to_device_id( return entity.device_id +@callback +def async_entity_id_to_device( + hass: HomeAssistant, + entity_id_or_uuid: str, +) -> dr.DeviceEntry | None: + """Resolve the device entry for the entity id or entity uuid.""" + + if (device_id := async_entity_id_to_device_id(hass, entity_id_or_uuid)) is None: + return None + + return dr.async_get(hass).async_get(device_id) + + @callback def async_device_info_to_link_from_entity( hass: HomeAssistant, diff --git a/homeassistant/helpers/device_registry.py b/homeassistant/helpers/device_registry.py index bad772abaff..bc6e7c810bf 100644 --- a/homeassistant/helpers/device_registry.py +++ b/homeassistant/helpers/device_registry.py @@ -144,13 +144,21 @@ DEVICE_INFO_KEYS = set.union(*(itm for itm in DEVICE_INFO_TYPES.values())) LOW_PRIO_CONFIG_ENTRY_DOMAINS = {"homekit_controller", "matter", "mqtt", "upnp"} -class _EventDeviceRegistryUpdatedData_CreateRemove(TypedDict): - """EventDeviceRegistryUpdated data for action type 'create' and 'remove'.""" +class _EventDeviceRegistryUpdatedData_Create(TypedDict): + """EventDeviceRegistryUpdated data for action type 'create'.""" - action: Literal["create", "remove"] + action: Literal["create"] device_id: str +class _EventDeviceRegistryUpdatedData_Remove(TypedDict): + """EventDeviceRegistryUpdated data for action type 'remove'.""" + + action: Literal["remove"] + device_id: str + device: DeviceEntry + + class _EventDeviceRegistryUpdatedData_Update(TypedDict): """EventDeviceRegistryUpdated data for action type 'update'.""" @@ -160,7 +168,8 @@ class _EventDeviceRegistryUpdatedData_Update(TypedDict): type EventDeviceRegistryUpdatedData = ( - _EventDeviceRegistryUpdatedData_CreateRemove + _EventDeviceRegistryUpdatedData_Create + | _EventDeviceRegistryUpdatedData_Remove | _EventDeviceRegistryUpdatedData_Update ) @@ -1309,8 +1318,8 @@ class DeviceRegistry(BaseRegistry[dict[str, list[dict[str, Any]]]]): self.async_update_device(other_device.id, via_device_id=None) self.hass.bus.async_fire_internal( EVENT_DEVICE_REGISTRY_UPDATED, - _EventDeviceRegistryUpdatedData_CreateRemove( - action="remove", device_id=device_id + _EventDeviceRegistryUpdatedData_Remove( + action="remove", device_id=device_id, device=device ), ) self.async_schedule_save() diff --git a/homeassistant/helpers/entity_platform.py b/homeassistant/helpers/entity_platform.py index 0423a1979bc..e798e85ed02 100644 --- a/homeassistant/helpers/entity_platform.py +++ b/homeassistant/helpers/entity_platform.py @@ -825,21 +825,25 @@ class EntityPlatform: entity.add_to_platform_abort() return - if self.config_entry and (device_info := entity.device_info): - try: - device = dev_reg.async_get(self.hass).async_get_or_create( - config_entry_id=self.config_entry.entry_id, - config_subentry_id=config_subentry_id, - **device_info, - ) - except dev_reg.DeviceInfoError as exc: - self.logger.error( - "%s: Not adding entity with invalid device info: %s", - self.platform_name, - str(exc), - ) - entity.add_to_platform_abort() - return + device: dev_reg.DeviceEntry | None + if self.config_entry: + if device_info := entity.device_info: + try: + device = dev_reg.async_get(self.hass).async_get_or_create( + config_entry_id=self.config_entry.entry_id, + config_subentry_id=config_subentry_id, + **device_info, + ) + except dev_reg.DeviceInfoError as exc: + self.logger.error( + "%s: Not adding entity with invalid device info: %s", + self.platform_name, + str(exc), + ) + entity.add_to_platform_abort() + return + else: + device = entity.device_entry else: device = None diff --git a/homeassistant/helpers/entity_registry.py b/homeassistant/helpers/entity_registry.py index 0b61c3e8f16..7051521b805 100644 --- a/homeassistant/helpers/entity_registry.py +++ b/homeassistant/helpers/entity_registry.py @@ -1103,8 +1103,20 @@ class EntityRegistry(BaseRegistry): entities = async_entries_for_device( self, event.data["device_id"], include_disabled_entities=True ) + removed_device = event.data["device"] for entity in entities: - self.async_remove(entity.entity_id) + config_entry_id = entity.config_entry_id + if ( + config_entry_id in removed_device.config_entries + and entity.config_subentry_id + in removed_device.config_entries_subentries[config_entry_id] + ): + self.async_remove(entity.entity_id) + else: + if entity.entity_id not in self.entities: + # Entity has been removed already, skip it + continue + self.async_update_entity(entity.entity_id, device_id=None) return if event.data["action"] != "update": @@ -1121,29 +1133,38 @@ class EntityRegistry(BaseRegistry): # Remove entities which belong to config entries no longer associated with the # device - entities = async_entries_for_device( - self, event.data["device_id"], include_disabled_entities=True - ) - for entity in entities: - if ( - entity.config_entry_id is not None - and entity.config_entry_id not in device.config_entries - ): - self.async_remove(entity.entity_id) + if old_config_entries := event.data["changes"].get("config_entries"): + entities = async_entries_for_device( + self, event.data["device_id"], include_disabled_entities=True + ) + for entity in entities: + config_entry_id = entity.config_entry_id + if ( + entity.config_entry_id in old_config_entries + and entity.config_entry_id not in device.config_entries + ): + self.async_remove(entity.entity_id) # Remove entities which belong to config subentries no longer associated with the # device - entities = async_entries_for_device( - self, event.data["device_id"], include_disabled_entities=True - ) - for entity in entities: - if ( - (config_entry_id := entity.config_entry_id) is not None - and config_entry_id in device.config_entries - and entity.config_subentry_id - not in device.config_entries_subentries[config_entry_id] - ): - self.async_remove(entity.entity_id) + if old_config_entries_subentries := event.data["changes"].get( + "config_entries_subentries" + ): + entities = async_entries_for_device( + self, event.data["device_id"], include_disabled_entities=True + ) + for entity in entities: + config_entry_id = entity.config_entry_id + config_subentry_id = entity.config_subentry_id + if ( + config_entry_id in device.config_entries + and config_entry_id in old_config_entries_subentries + and config_subentry_id + in old_config_entries_subentries[config_entry_id] + and config_subentry_id + not in device.config_entries_subentries[config_entry_id] + ): + self.async_remove(entity.entity_id) # Re-enable disabled entities if the device is no longer disabled if not device.disabled: diff --git a/homeassistant/helpers/event.py b/homeassistant/helpers/event.py index 3b959337b6d..f2dfb7250f7 100644 --- a/homeassistant/helpers/event.py +++ b/homeassistant/helpers/event.py @@ -316,6 +316,10 @@ def async_track_state_change_event( Unlike async_track_state_change, async_track_state_change_event passes the full event to the callback. + The action will not be called immediately, but will be scheduled to run + in the next event loop iteration, even if the action is decorated with + @callback. + In order to avoid having to iterate a long list of EVENT_STATE_CHANGED and fire and create a job for each one, we keep a dict of entity ids that @@ -866,6 +870,10 @@ def async_track_state_change_filtered( ) -> _TrackStateChangeFiltered: """Track state changes with a TrackStates filter that can be updated. + The action will not be called immediately, but will be scheduled to run + in the next event loop iteration, even if the action is decorated with + @callback. + Args: hass: Home assistant object. @@ -1348,9 +1356,13 @@ def async_track_template_result( then whenever the output from the template changes. The template will be reevaluated if any states referenced in the last run of the template change, or if manually triggered. If the result of the - evaluation is different from the previous run, the listener is passed + evaluation is different from the previous run, the action is passed the result. + The action will not be called immediately, but will be scheduled to run + in the next event loop iteration, even if the action is decorated with + @callback. + If the template results in an TemplateError, this will be returned to the listener the first time this happens but not for subsequent errors. Once the template returns to a non-error condition the result is sent diff --git a/homeassistant/helpers/helper_integration.py b/homeassistant/helpers/helper_integration.py index 61bb0bcd45d..04a1d2cca76 100644 --- a/homeassistant/helpers/helper_integration.py +++ b/homeassistant/helpers/helper_integration.py @@ -14,17 +14,20 @@ from .event import async_track_entity_registry_updated_event def async_handle_source_entity_changes( hass: HomeAssistant, *, + add_helper_config_entry_to_device: bool = True, helper_config_entry_id: str, set_source_entity_id_or_uuid: Callable[[str], None], source_device_id: str | None, source_entity_id_or_uuid: str, - source_entity_removed: Callable[[], Coroutine[Any, Any, None]], + source_entity_removed: Callable[[], Coroutine[Any, Any, None]] | None = None, ) -> CALLBACK_TYPE: """Handle changes to a helper entity's source entity. The following changes are handled: - - Entity removal: If the source entity is removed, the helper config entry - is removed, and the helper entity is cleaned up. + - Entity removal: If the source entity is removed: + - If source_entity_removed is provided, it is called to handle the removal. + - If source_entity_removed is not provided, The helper entity is updated to + not link to any device. - Entity ID changed: If the source entity's entity ID changes and the source entity is identified by an entity ID, the set_source_entity_id_or_uuid is called. If the source entity is identified by a UUID, the helper config entry @@ -51,7 +54,18 @@ def async_handle_source_entity_changes( data = event.data if data["action"] == "remove": - await source_entity_removed() + if source_entity_removed: + await source_entity_removed() + else: + for ( + helper_entity_entry + ) in entity_registry.entities.get_entries_for_config_entry_id( + helper_config_entry_id + ): + # Update the helper entity to link to the new device (or no device) + entity_registry.async_update_entity( + helper_entity_entry.entity_id, device_id=None + ) if data["action"] != "update": return @@ -88,15 +102,17 @@ def async_handle_source_entity_changes( helper_entity.entity_id, device_id=source_entity_entry.device_id ) - if source_entity_entry.device_id is not None: + if add_helper_config_entry_to_device: + if source_entity_entry.device_id is not None: + device_registry.async_update_device( + source_entity_entry.device_id, + add_config_entry_id=helper_config_entry_id, + ) + device_registry.async_update_device( - source_entity_entry.device_id, - add_config_entry_id=helper_config_entry_id, + source_device_id, remove_config_entry_id=helper_config_entry_id ) - device_registry.async_update_device( - source_device_id, remove_config_entry_id=helper_config_entry_id - ) source_device_id = source_entity_entry.device_id # Reload the config entry so the helper entity is recreated with @@ -111,3 +127,46 @@ def async_handle_source_entity_changes( return async_track_entity_registry_updated_event( hass, source_entity_id, async_registry_updated ) + + +def async_remove_helper_config_entry_from_source_device( + hass: HomeAssistant, + *, + helper_config_entry_id: str, + source_device_id: str, +) -> None: + """Remove helper config entry from source device. + + This is a convenience function to migrate from helpers which added their config + entry to the source device. + """ + device_registry = dr.async_get(hass) + + if ( + not (source_device := device_registry.async_get(source_device_id)) + or helper_config_entry_id not in source_device.config_entries + ): + return + + entity_registry = er.async_get(hass) + helper_entity_entries = er.async_entries_for_config_entry( + entity_registry, helper_config_entry_id + ) + + # Disconnect helper entities from the device to prevent them from + # being removed when the config entry link to the device is removed. + modified_helpers: list[er.RegistryEntry] = [] + for helper in helper_entity_entries: + if helper.device_id != source_device_id: + continue + modified_helpers.append(helper) + entity_registry.async_update_entity(helper.entity_id, device_id=None) + # Remove the helper config entry from the device + device_registry.async_update_device( + source_device_id, remove_config_entry_id=helper_config_entry_id + ) + # Connect the helper entity to the device + for helper in modified_helpers: + entity_registry.async_update_entity( + helper.entity_id, device_id=source_device_id + ) diff --git a/homeassistant/helpers/llm.py b/homeassistant/helpers/llm.py index b239ad99119..784288375e9 100644 --- a/homeassistant/helpers/llm.py +++ b/homeassistant/helpers/llm.py @@ -779,13 +779,19 @@ def selector_serializer(schema: Any) -> Any: # noqa: C901 if isinstance(schema, selector.ObjectSelector): result = {"type": "object"} if fields := schema.config.get("fields"): - result["properties"] = { - field: convert( + properties = {} + required = [] + for field, field_schema in fields.items(): + properties[field] = convert( selector.selector(field_schema["selector"]), custom_serializer=selector_serializer, ) - for field, field_schema in fields.items() - } + if field_schema.get("required"): + required.append(field) + result["properties"] = properties + + if required: + result["required"] = required else: result["additionalProperties"] = True if schema.config.get("multiple"): diff --git a/homeassistant/helpers/target.py b/homeassistant/helpers/target.py index 1c0fd0745ca..239d1e66336 100644 --- a/homeassistant/helpers/target.py +++ b/homeassistant/helpers/target.py @@ -20,10 +20,10 @@ from homeassistant.core import ( CALLBACK_TYPE, Event, EventStateChangedData, - HassJobType, HomeAssistant, callback, ) +from homeassistant.exceptions import HomeAssistantError from . import ( area_registry as ar, @@ -259,20 +259,21 @@ class TargetStateChangeTracker: self, hass: HomeAssistant, selector_data: TargetSelectorData, - job_type: HassJobType | None, action: Callable[[Event[EventStateChangedData]], Any], ) -> None: """Initialize the state change tracker.""" self._hass = hass self._selector_data = selector_data - self._job_type = job_type self._action = action self._state_change_unsub: CALLBACK_TYPE | None = None self._registry_unsubs: list[CALLBACK_TYPE] = [] + def async_setup(self) -> Callable[[], None]: + """Set up the state change tracking.""" self._setup_registry_listeners() self._track_entities_state_change() + return self._unsubscribe def _track_entities_state_change(self) -> None: """Set up state change tracking for currently selected entities.""" @@ -293,7 +294,7 @@ class TargetStateChangeTracker: _LOGGER.debug("Tracking state changes for entities: %s", tracked_entities) self._state_change_unsub = async_track_state_change_event( - self._hass, tracked_entities, state_change_listener, job_type=self._job_type + self._hass, tracked_entities, state_change_listener ) def _setup_registry_listeners(self) -> None: @@ -315,22 +316,17 @@ class TargetStateChangeTracker: # changes don't affect which entities are tracked. self._registry_unsubs = [ self._hass.bus.async_listen( - er.EVENT_ENTITY_REGISTRY_UPDATED, - resubscribe_state_change_event, - # TODO(abmantis): filter for entities that match the target selector? - # event_filter=self._filter_entity_registry_changes, + er.EVENT_ENTITY_REGISTRY_UPDATED, resubscribe_state_change_event ), self._hass.bus.async_listen( - dr.EVENT_DEVICE_REGISTRY_UPDATED, - resubscribe_state_change_event, + dr.EVENT_DEVICE_REGISTRY_UPDATED, resubscribe_state_change_event ), self._hass.bus.async_listen( - ar.EVENT_AREA_REGISTRY_UPDATED, - resubscribe_state_change_event, + ar.EVENT_AREA_REGISTRY_UPDATED, resubscribe_state_change_event ), ] - def unsub(self) -> None: + def _unsubscribe(self) -> None: """Unsubscribe from all events.""" for registry_unsub in self._registry_unsubs: registry_unsub() @@ -344,16 +340,12 @@ def async_track_target_selector_state_change_event( hass: HomeAssistant, target_selector_config: ConfigType, action: Callable[[Event[EventStateChangedData]], Any], - job_type: HassJobType | None = None, ) -> CALLBACK_TYPE: """Track state changes for entities referenced directly or indirectly in a target selector.""" selector_data = TargetSelectorData(target_selector_config) if not selector_data.has_any_selector: - _LOGGER.warning( - "Target selector %s does not have any selectors defined", - target_selector_config, + raise HomeAssistantError( + f"Target selector {target_selector_config} does not have any selectors defined" ) - return lambda: None - - tracker = TargetStateChangeTracker(hass, selector_data, job_type, action) - return tracker.unsub + tracker = TargetStateChangeTracker(hass, selector_data, action) + return tracker.async_setup() diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 9d985fae6c5..9e21c5830e4 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -6,7 +6,7 @@ aiodns==3.5.0 aiohasupervisor==0.3.1 aiohttp-asyncmdnsresolver==0.1.1 aiohttp-fast-zlib==0.3.0 -aiohttp==3.12.13 +aiohttp==3.12.14 aiohttp_cors==0.8.1 aiousbwatcher==1.1.1 aiozoneinfo==0.2.3 @@ -20,9 +20,9 @@ audioop-lts==0.2.1 av==13.1.0 awesomeversion==25.5.0 bcrypt==4.3.0 -bleak-retry-connector==3.9.0 -bleak==0.22.3 -bluetooth-adapters==0.21.4 +bleak-retry-connector==4.0.0 +bleak==1.0.1 +bluetooth-adapters==2.0.0 bluetooth-auto-recovery==1.5.2 bluetooth-data-tools==1.28.2 cached-ipaddress==0.10.0 @@ -34,11 +34,11 @@ dbus-fast==2.43.0 fnv-hash-fast==1.5.0 go2rtc-client==0.2.1 ha-ffmpeg==3.2.2 -habluetooth==3.49.0 -hass-nabucasa==0.105.0 +habluetooth==4.0.1 +hass-nabucasa==0.106.0 hassil==2.2.3 home-assistant-bluetooth==1.13.1 -home-assistant-frontend==20250702.1 +home-assistant-frontend==20250702.2 home-assistant-intents==2025.6.23 httpx==0.28.1 ifaddr==0.2.0 diff --git a/homeassistant/util/unit_conversion.py b/homeassistant/util/unit_conversion.py index d0830d1f8bb..5bde108dfc1 100644 --- a/homeassistant/util/unit_conversion.py +++ b/homeassistant/util/unit_conversion.py @@ -7,6 +7,7 @@ from functools import lru_cache from math import floor, log10 from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, @@ -693,12 +694,14 @@ class MassVolumeConcentrationConverter(BaseUnitConverter): UNIT_CLASS = "concentration" _UNIT_CONVERSION: dict[str | None, float] = { - CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: 1000.0, # 1000 µg/m³ = 1 mg/m³ - CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER: 1.0, + CONCENTRATION_MICROGRAMS_PER_CUBIC_METER: 1000000.0, # 1000 µg/m³ = 1 mg/m³ + CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER: 1000.0, # 1000 mg/m³ = 1 g/m³ + CONCENTRATION_GRAMS_PER_CUBIC_METER: 1.0, } VALID_UNITS = { CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, + CONCENTRATION_GRAMS_PER_CUBIC_METER, } diff --git a/pyproject.toml b/pyproject.toml index 25f4d6d4a1a..860b4af379d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dependencies = [ # change behavior based on presence of supervisor. Deprecated with #127228 # Lib can be removed with 2025.11 "aiohasupervisor==0.3.1", - "aiohttp==3.12.13", + "aiohttp==3.12.14", "aiohttp_cors==0.8.1", "aiohttp-fast-zlib==0.3.0", "aiohttp-asyncmdnsresolver==0.1.1", @@ -47,7 +47,7 @@ dependencies = [ "fnv-hash-fast==1.5.0", # hass-nabucasa is imported by helpers which don't depend on the cloud # integration - "hass-nabucasa==0.105.0", + "hass-nabucasa==0.106.0", # When bumping httpx, please check the version pins of # httpcore, anyio, and h11 in gen_requirements_all "httpx==0.28.1", @@ -568,8 +568,6 @@ filterwarnings = [ "ignore:pkg_resources is deprecated as an API:UserWarning:pysiaalarm.data.data", # https://pypi.org/project/pybotvac/ - v0.0.28 - 2025-06-11 "ignore:pkg_resources is deprecated as an API:UserWarning:pybotvac.version", - # https://github.com/home-assistant-ecosystem/python-mystrom/blob/2.2.0/pymystrom/__init__.py#L10 - v2.2.0 - 2023-05-21 - "ignore:pkg_resources is deprecated as an API:UserWarning:pymystrom", # - SyntaxWarning - is with literal # https://github.com/majuss/lupupy/pull/15 - >0.3.2 # https://pypi.org/project/opuslib/ - v3.0.1 - 2018-01-16 diff --git a/requirements.txt b/requirements.txt index d6912b8898b..118d2bedfa6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,7 +5,7 @@ # Home Assistant Core aiodns==3.5.0 aiohasupervisor==0.3.1 -aiohttp==3.12.13 +aiohttp==3.12.14 aiohttp_cors==0.8.1 aiohttp-fast-zlib==0.3.0 aiohttp-asyncmdnsresolver==0.1.1 @@ -22,7 +22,7 @@ certifi>=2021.5.30 ciso8601==2.3.2 cronsim==2.6 fnv-hash-fast==1.5.0 -hass-nabucasa==0.105.0 +hass-nabucasa==0.106.0 httpx==0.28.1 home-assistant-bluetooth==1.13.1 ifaddr==0.2.0 diff --git a/requirements_all.txt b/requirements_all.txt index 73f7819e6f3..a0f903370b4 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -70,7 +70,7 @@ PyMetEireann==2024.11.0 PyMetno==0.13.0 # homeassistant.components.keymitt_ble -PyMicroBot==0.0.17 +PyMicroBot==0.0.23 # homeassistant.components.mobile_app # homeassistant.components.owntracks @@ -84,7 +84,7 @@ PyQRCode==1.2.1 PyRMVtransport==0.3.3 # homeassistant.components.switchbot -PySwitchbot==0.67.0 +PySwitchbot==0.68.1 # homeassistant.components.switchmate PySwitchmate==0.5.1 @@ -100,7 +100,7 @@ PyTransportNSW==0.1.1 PyTurboJPEG==1.8.0 # homeassistant.components.vicare -PyViCare==2.44.0 +PyViCare==2.50.0 # homeassistant.components.xiaomi_aqara PyXiaomiGateway==0.14.3 @@ -185,7 +185,7 @@ aioairzone-cloud==0.6.12 aioairzone==1.0.0 # homeassistant.components.alexa_devices -aioamazondevices==3.2.3 +aioamazondevices==3.2.10 # homeassistant.components.ambient_network # homeassistant.components.ambient_station @@ -204,7 +204,7 @@ aioaseko==1.0.0 aioasuswrt==1.4.0 # homeassistant.components.husqvarna_automower -aioautomower==1.2.0 +aioautomower==1.2.2 # homeassistant.components.azure_devops aioazuredevops==2.2.1 @@ -247,7 +247,7 @@ aioelectricitymaps==0.4.0 aioemonitor==1.0.5 # homeassistant.components.esphome -aioesphomeapi==34.1.0 +aioesphomeapi==35.0.0 # homeassistant.components.flo aioflo==2021.11.0 @@ -283,7 +283,7 @@ aiohue==4.7.4 aioimaplib==2.0.1 # homeassistant.components.immich -aioimmich==0.10.1 +aioimmich==0.10.2 # homeassistant.components.apache_kafka aiokafka==0.10.0 @@ -301,7 +301,7 @@ aiolifx-effects==0.3.2 aiolifx-themes==0.6.4 # homeassistant.components.lifx -aiolifx==1.1.5 +aiolifx==1.2.1 # homeassistant.components.lookin aiolookin==1.0.0 @@ -381,7 +381,7 @@ aioruuvigateway==0.1.0 aiosenz==1.0.0 # homeassistant.components.shelly -aioshelly==13.7.1 +aioshelly==13.7.2 # homeassistant.components.skybell aioskybell==22.7.0 @@ -616,13 +616,13 @@ bizkaibus==0.1.1 # homeassistant.components.eq3btsmart # homeassistant.components.esphome -bleak-esphome==2.16.0 +bleak-esphome==3.1.0 # homeassistant.components.bluetooth -bleak-retry-connector==3.9.0 +bleak-retry-connector==4.0.0 # homeassistant.components.bluetooth -bleak==0.22.3 +bleak==1.0.1 # homeassistant.components.blebox blebox-uniapi==2.5.0 @@ -643,7 +643,7 @@ bluemaestro-ble==0.4.1 # bluepy==1.3.0 # homeassistant.components.bluetooth -bluetooth-adapters==0.21.4 +bluetooth-adapters==2.0.0 # homeassistant.components.bluetooth bluetooth-auto-recovery==1.5.2 @@ -677,7 +677,7 @@ bring-api==1.1.0 broadlink==0.19.0 # homeassistant.components.brother -brother==4.3.1 +brother==5.0.0 # homeassistant.components.brottsplatskartan brottsplatskartan==1.0.5 @@ -1020,7 +1020,7 @@ georss-qld-bushfire-alert-client==0.8 getmac==0.9.5 # homeassistant.components.gios -gios==6.1.0 +gios==6.1.1 # homeassistant.components.gitter gitterpy==0.1.7 @@ -1035,7 +1035,7 @@ go2rtc-client==0.2.1 goalzero==0.2.2 # homeassistant.components.goodwe -goodwe==0.3.6 +goodwe==0.4.8 # homeassistant.components.google_mail # homeassistant.components.google_tasks @@ -1124,10 +1124,10 @@ ha-silabs-firmware-client==0.2.0 habiticalib==0.4.0 # homeassistant.components.bluetooth -habluetooth==3.49.0 +habluetooth==4.0.1 # homeassistant.components.cloud -hass-nabucasa==0.105.0 +hass-nabucasa==0.106.0 # homeassistant.components.splunk hass-splunk==0.1.1 @@ -1165,10 +1165,10 @@ hole==0.9.0 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.75 +holidays==0.76 # homeassistant.components.frontend -home-assistant-frontend==20250702.1 +home-assistant-frontend==20250702.2 # homeassistant.components.conversation home-assistant-intents==2025.6.23 @@ -1234,7 +1234,7 @@ ihcsdk==2.8.5 imeon_inverter_api==0.3.12 # homeassistant.components.imgw_pib -imgw_pib==1.1.0 +imgw_pib==1.2.0 # homeassistant.components.incomfort incomfort-client==0.6.9 @@ -1555,7 +1555,7 @@ numato-gpio==0.13.0 numpy==2.3.0 # homeassistant.components.nyt_games -nyt_games==0.4.4 +nyt_games==0.5.0 # homeassistant.components.oasa_telematics oasatelematics==0.3 @@ -1597,7 +1597,7 @@ open-garage==0.2.0 open-meteo==0.3.2 # homeassistant.components.openai_conversation -openai==1.76.2 +openai==1.93.3 # homeassistant.components.openerz openerz-api==0.3.0 @@ -1848,7 +1848,7 @@ pyatag==0.3.5.3 pyatmo==9.2.1 # homeassistant.components.apple_tv -pyatv==0.16.0 +pyatv==0.16.1 # homeassistant.components.aussie_broadband pyaussiebb==0.1.5 @@ -2100,7 +2100,7 @@ pykwb==0.0.8 pylacrosse==0.4 # homeassistant.components.lamarzocco -pylamarzocco==2.0.10 +pylamarzocco==2.0.11 # homeassistant.components.lastfm pylast==5.1.0 @@ -2118,7 +2118,7 @@ pylibrespot-java==0.1.1 pylitejet==0.6.3 # homeassistant.components.litterrobot -pylitterbot==2024.2.1 +pylitterbot==2024.2.2 # homeassistant.components.lutron_caseta pylutron-caseta==0.24.0 @@ -2196,7 +2196,7 @@ pynzbgetapi==0.2.0 pyobihai==1.4.2 # homeassistant.components.octoprint -pyoctoprintapi==0.1.12 +pyoctoprintapi==0.1.14 # homeassistant.components.ombi pyombi==0.1.10 @@ -2348,7 +2348,7 @@ pysmappee==0.2.29 pysmarlaapi==0.9.0 # homeassistant.components.smartthings -pysmartthings==3.2.5 +pysmartthings==3.2.7 # homeassistant.components.smarty pysmarty2==0.10.2 @@ -2363,7 +2363,7 @@ pysml==0.1.5 pysmlight==0.2.7 # homeassistant.components.snmp -pysnmp==6.2.6 +pysnmp==7.1.21 # homeassistant.components.snooz pysnooz==0.8.6 @@ -2474,7 +2474,7 @@ python-miio==0.5.12 python-mpd2==3.1.1 # homeassistant.components.mystrom -python-mystrom==2.2.0 +python-mystrom==2.4.0 # homeassistant.components.swiss_public_transport python-opendata-transport==0.5.0 @@ -2716,7 +2716,7 @@ sanix==1.0.6 satel-integra==0.3.7 # homeassistant.components.screenlogic -screenlogicpy==0.10.0 +screenlogicpy==0.10.2 # homeassistant.components.scsgate scsgate==0.1.0 @@ -2756,7 +2756,7 @@ sentry-sdk==1.45.1 sfrbox-api==0.0.12 # homeassistant.components.sharkiq -sharkiq==1.1.0 +sharkiq==1.1.1 # homeassistant.components.aquostv sharp_aquos_rc==0.3.2 @@ -2994,7 +2994,7 @@ typedmonarchmoney==0.4.4 uasiren==0.0.1 # homeassistant.components.unifiprotect -uiprotect==7.14.1 +uiprotect==7.14.2 # homeassistant.components.landisgyr_heat_meter ultraheat-api==0.5.7 @@ -3163,7 +3163,7 @@ yeelight==0.7.16 yeelightsunflower==0.0.10 # homeassistant.components.yolink -yolink-api==0.5.5 +yolink-api==0.5.7 # homeassistant.components.youless youless-api==2.2.0 diff --git a/requirements_test_all.txt b/requirements_test_all.txt index a17bf245623..aee0dc556a1 100644 --- a/requirements_test_all.txt +++ b/requirements_test_all.txt @@ -67,7 +67,7 @@ PyMetEireann==2024.11.0 PyMetno==0.13.0 # homeassistant.components.keymitt_ble -PyMicroBot==0.0.17 +PyMicroBot==0.0.23 # homeassistant.components.mobile_app # homeassistant.components.owntracks @@ -81,7 +81,7 @@ PyQRCode==1.2.1 PyRMVtransport==0.3.3 # homeassistant.components.switchbot -PySwitchbot==0.67.0 +PySwitchbot==0.68.1 # homeassistant.components.syncthru PySyncThru==0.8.0 @@ -94,7 +94,7 @@ PyTransportNSW==0.1.1 PyTurboJPEG==1.8.0 # homeassistant.components.vicare -PyViCare==2.44.0 +PyViCare==2.50.0 # homeassistant.components.xiaomi_aqara PyXiaomiGateway==0.14.3 @@ -173,7 +173,7 @@ aioairzone-cloud==0.6.12 aioairzone==1.0.0 # homeassistant.components.alexa_devices -aioamazondevices==3.2.3 +aioamazondevices==3.2.10 # homeassistant.components.ambient_network # homeassistant.components.ambient_station @@ -192,7 +192,7 @@ aioaseko==1.0.0 aioasuswrt==1.4.0 # homeassistant.components.husqvarna_automower -aioautomower==1.2.0 +aioautomower==1.2.2 # homeassistant.components.azure_devops aioazuredevops==2.2.1 @@ -235,7 +235,7 @@ aioelectricitymaps==0.4.0 aioemonitor==1.0.5 # homeassistant.components.esphome -aioesphomeapi==34.1.0 +aioesphomeapi==35.0.0 # homeassistant.components.flo aioflo==2021.11.0 @@ -268,7 +268,7 @@ aiohue==4.7.4 aioimaplib==2.0.1 # homeassistant.components.immich -aioimmich==0.10.1 +aioimmich==0.10.2 # homeassistant.components.apache_kafka aiokafka==0.10.0 @@ -283,7 +283,7 @@ aiolifx-effects==0.3.2 aiolifx-themes==0.6.4 # homeassistant.components.lifx -aiolifx==1.1.5 +aiolifx==1.2.1 # homeassistant.components.lookin aiolookin==1.0.0 @@ -363,7 +363,7 @@ aioruuvigateway==0.1.0 aiosenz==1.0.0 # homeassistant.components.shelly -aioshelly==13.7.1 +aioshelly==13.7.2 # homeassistant.components.skybell aioskybell==22.7.0 @@ -550,13 +550,13 @@ bimmer-connected[china]==0.17.2 # homeassistant.components.eq3btsmart # homeassistant.components.esphome -bleak-esphome==2.16.0 +bleak-esphome==3.1.0 # homeassistant.components.bluetooth -bleak-retry-connector==3.9.0 +bleak-retry-connector==4.0.0 # homeassistant.components.bluetooth -bleak==0.22.3 +bleak==1.0.1 # homeassistant.components.blebox blebox-uniapi==2.5.0 @@ -574,7 +574,7 @@ bluemaestro-ble==0.4.1 # bluepy==1.3.0 # homeassistant.components.bluetooth -bluetooth-adapters==0.21.4 +bluetooth-adapters==2.0.0 # homeassistant.components.bluetooth bluetooth-auto-recovery==1.5.2 @@ -604,7 +604,7 @@ bring-api==1.1.0 broadlink==0.19.0 # homeassistant.components.brother -brother==4.3.1 +brother==5.0.0 # homeassistant.components.brottsplatskartan brottsplatskartan==1.0.5 @@ -890,7 +890,7 @@ georss-qld-bushfire-alert-client==0.8 getmac==0.9.5 # homeassistant.components.gios -gios==6.1.0 +gios==6.1.1 # homeassistant.components.glances glances-api==0.8.0 @@ -902,7 +902,7 @@ go2rtc-client==0.2.1 goalzero==0.2.2 # homeassistant.components.goodwe -goodwe==0.3.6 +goodwe==0.4.8 # homeassistant.components.google_mail # homeassistant.components.google_tasks @@ -985,10 +985,10 @@ ha-silabs-firmware-client==0.2.0 habiticalib==0.4.0 # homeassistant.components.bluetooth -habluetooth==3.49.0 +habluetooth==4.0.1 # homeassistant.components.cloud -hass-nabucasa==0.105.0 +hass-nabucasa==0.106.0 # homeassistant.components.assist_satellite # homeassistant.components.conversation @@ -1014,10 +1014,10 @@ hole==0.9.0 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.75 +holidays==0.76 # homeassistant.components.frontend -home-assistant-frontend==20250702.1 +home-assistant-frontend==20250702.2 # homeassistant.components.conversation home-assistant-intents==2025.6.23 @@ -1068,7 +1068,7 @@ igloohome-api==0.1.1 imeon_inverter_api==0.3.12 # homeassistant.components.imgw_pib -imgw_pib==1.1.0 +imgw_pib==1.2.0 # homeassistant.components.incomfort incomfort-client==0.6.9 @@ -1329,7 +1329,7 @@ numato-gpio==0.13.0 numpy==2.3.0 # homeassistant.components.nyt_games -nyt_games==0.4.4 +nyt_games==0.5.0 # homeassistant.components.google oauth2client==4.1.3 @@ -1365,7 +1365,7 @@ open-garage==0.2.0 open-meteo==0.3.2 # homeassistant.components.openai_conversation -openai==1.76.2 +openai==1.93.3 # homeassistant.components.openerz openerz-api==0.3.0 @@ -1553,7 +1553,7 @@ pyatag==0.3.5.3 pyatmo==9.2.1 # homeassistant.components.apple_tv -pyatv==0.16.0 +pyatv==0.16.1 # homeassistant.components.aussie_broadband pyaussiebb==0.1.5 @@ -1745,7 +1745,7 @@ pykrakenapi==0.1.8 pykulersky==0.5.8 # homeassistant.components.lamarzocco -pylamarzocco==2.0.10 +pylamarzocco==2.0.11 # homeassistant.components.lastfm pylast==5.1.0 @@ -1763,7 +1763,7 @@ pylibrespot-java==0.1.1 pylitejet==0.6.3 # homeassistant.components.litterrobot -pylitterbot==2024.2.1 +pylitterbot==2024.2.2 # homeassistant.components.lutron_caseta pylutron-caseta==0.24.0 @@ -1829,7 +1829,7 @@ pynzbgetapi==0.2.0 pyobihai==1.4.2 # homeassistant.components.octoprint -pyoctoprintapi==0.1.12 +pyoctoprintapi==0.1.14 # homeassistant.components.openuv pyopenuv==2023.02.0 @@ -1951,7 +1951,7 @@ pysmappee==0.2.29 pysmarlaapi==0.9.0 # homeassistant.components.smartthings -pysmartthings==3.2.5 +pysmartthings==3.2.7 # homeassistant.components.smarty pysmarty2==0.10.2 @@ -1966,7 +1966,7 @@ pysml==0.1.5 pysmlight==0.2.7 # homeassistant.components.snmp -pysnmp==6.2.6 +pysnmp==7.1.21 # homeassistant.components.snooz pysnooz==0.8.6 @@ -2047,7 +2047,7 @@ python-miio==0.5.12 python-mpd2==3.1.1 # homeassistant.components.mystrom -python-mystrom==2.2.0 +python-mystrom==2.4.0 # homeassistant.components.swiss_public_transport python-opendata-transport==0.5.0 @@ -2244,7 +2244,7 @@ samsungtvws[async,encrypted]==2.7.2 sanix==1.0.6 # homeassistant.components.screenlogic -screenlogicpy==0.10.0 +screenlogicpy==0.10.2 # homeassistant.components.backup securetar==2025.2.1 @@ -2278,7 +2278,7 @@ sentry-sdk==1.45.1 sfrbox-api==0.0.12 # homeassistant.components.sharkiq -sharkiq==1.1.0 +sharkiq==1.1.1 # homeassistant.components.simplefin simplefin4py==0.0.18 @@ -2468,7 +2468,7 @@ typedmonarchmoney==0.4.4 uasiren==0.0.1 # homeassistant.components.unifiprotect -uiprotect==7.14.1 +uiprotect==7.14.2 # homeassistant.components.landisgyr_heat_meter ultraheat-api==0.5.7 @@ -2610,7 +2610,7 @@ yalexs==8.10.0 yeelight==0.7.16 # homeassistant.components.yolink -yolink-api==0.5.5 +yolink-api==0.5.7 # homeassistant.components.youless youless-api==2.2.0 diff --git a/script/hassfest/conditions.py b/script/hassfest/conditions.py index 7eb9a2c3fc0..2a1d363a5fc 100644 --- a/script/hassfest/conditions.py +++ b/script/hassfest/conditions.py @@ -54,6 +54,7 @@ CONDITIONS_SCHEMA = vol.Schema( NON_MIGRATED_INTEGRATIONS = { "device_automation", "sun", + "zone", } diff --git a/script/hassfest/dependencies.py b/script/hassfest/dependencies.py index ee932280201..447b3ec79b8 100644 --- a/script/hassfest/dependencies.py +++ b/script/hassfest/dependencies.py @@ -140,8 +140,6 @@ IGNORE_VIOLATIONS = { ("websocket_api", "lovelace"), ("websocket_api", "shopping_list"), "logbook", - # Temporary needed for migration until 2024.10 - ("conversation", "assist_pipeline"), } diff --git a/script/hassfest/quality_scale.py b/script/hassfest/quality_scale.py index 46751bda4f8..b5fd8c3ad7a 100644 --- a/script/hassfest/quality_scale.py +++ b/script/hassfest/quality_scale.py @@ -763,7 +763,6 @@ INTEGRATIONS_WITHOUT_QUALITY_SCALE_FILE = [ "pandora", "panel_iframe", "peco", - "pegel_online", "pencom", "permobil", "persistent_notification", @@ -1667,7 +1666,6 @@ INTEGRATIONS_WITHOUT_SCALE = [ "matter", "maxcube", "mazda", - "mealie", "meater", "medcom_ble", "media_extractor", @@ -1819,7 +1817,6 @@ INTEGRATIONS_WITHOUT_SCALE = [ "palazzetti", "panel_iframe", "peco", - "pegel_online", "pencom", "permobil", "persistent_notification", diff --git a/script/hassfest/requirements.py b/script/hassfest/requirements.py index d7d064fff28..9c3f60a827c 100644 --- a/script/hassfest/requirements.py +++ b/script/hassfest/requirements.py @@ -27,6 +27,7 @@ PACKAGE_CHECK_VERSION_RANGE = { "aiohttp": "SemVer", "attrs": "CalVer", "awesomeversion": "CalVer", + "bleak": "SemVer", "grpcio": "SemVer", "httpx": "SemVer", "mashumaro": "SemVer", @@ -221,11 +222,6 @@ FORBIDDEN_PACKAGE_EXCEPTIONS: dict[str, dict[str, set[str]]] = { # pymonoprice > pyserial-asyncio "pymonoprice": {"pyserial-asyncio"} }, - "mystrom": { - # https://github.com/home-assistant-ecosystem/python-mystrom/issues/55 - # python-mystrom > setuptools - "python-mystrom": {"setuptools"} - }, "nibe_heatpump": {"nibe": {"async-timeout"}}, "norway_air": {"pymetno": {"async-timeout"}}, "nx584": { @@ -297,10 +293,6 @@ PYTHON_VERSION_CHECK_EXCEPTIONS: dict[str, dict[str, set[str]]] = { # - domain is the integration domain # - package is the package (can be transitive) referencing the dependency # - dependencyX should be the name of the referenced dependency - "bluetooth": { - # https://github.com/hbldh/bleak/pull/1718 (not yet released) - "homeassistant": {"bleak"} - }, "python_script": { # Security audits are needed for each Python version "homeassistant": {"restrictedpython"} @@ -501,17 +493,9 @@ def get_requirements(integration: Integration, packages: set[str]) -> set[str]: continue # Check for restrictive version limits on Python - if ( - (requires_python := metadata(package)["Requires-Python"]) - and not all( - _is_dependency_version_range_valid(version_part, "SemVer") - for version_part in requires_python.split(",") - ) - # "bleak" is a transient dependency of 53 integrations, and we don't - # want to add the whole list to PYTHON_VERSION_CHECK_EXCEPTIONS - # This extra check can be removed when bleak is updated - # https://github.com/hbldh/bleak/pull/1718 - and (package in packages or package != "bleak") + if (requires_python := metadata(package)["Requires-Python"]) and not all( + _is_dependency_version_range_valid(version_part, "SemVer") + for version_part in requires_python.split(",") ): needs_python_version_check_exception = True integration.add_warning_or_error( diff --git a/script/licenses.py b/script/licenses.py index 6d5f7e58f2f..d7819cba536 100644 --- a/script/licenses.py +++ b/script/licenses.py @@ -178,7 +178,6 @@ OSI_APPROVED_LICENSES = { } EXCEPTIONS = { - "PyMicroBot", # https://github.com/spycle/pyMicroBot/pull/3 "PySwitchmate", # https://github.com/Danielhiversen/pySwitchmate/pull/16 "PyXiaomiGateway", # https://github.com/Danielhiversen/PyXiaomiGateway/pull/201 "chacha20poly1305", # LGPL diff --git a/tests/components/ai_task/snapshots/test_task.ambr b/tests/components/ai_task/snapshots/test_task.ambr index 3b40b0632a6..181fc383d64 100644 --- a/tests/components/ai_task/snapshots/test_task.ambr +++ b/tests/components/ai_task/snapshots/test_task.ambr @@ -9,6 +9,7 @@ 'role': 'system', }), dict({ + 'attachments': None, 'content': 'Test prompt', 'role': 'user', }), diff --git a/tests/components/ai_task/test_init.py b/tests/components/ai_task/test_init.py index 840285493ac..19f73045532 100644 --- a/tests/components/ai_task/test_init.py +++ b/tests/components/ai_task/test_init.py @@ -1,5 +1,6 @@ """Test initialization of the AI Task component.""" +from pathlib import Path from typing import Any from unittest.mock import patch @@ -89,6 +90,7 @@ async def test_generate_data_service( return_value=media_source.PlayMedia( url="http://example.com/media.mp4", mime_type="video/mp4", + path=Path("media.mp4"), ), ): result = await hass.services.async_call( @@ -118,9 +120,7 @@ async def test_generate_data_service( assert attachment.url == "http://example.com/media.mp4" assert attachment.mime_type == "video/mp4" assert attachment.media_content_id == msg_attachment["media_content_id"] - assert ( - str(attachment) == f"" - ) + assert attachment.path == Path("media.mp4") async def test_generate_data_service_structure_fields( diff --git a/tests/components/alexa/test_entities.py b/tests/components/alexa/test_entities.py index 6998b2acc97..4d8d0dca67f 100644 --- a/tests/components/alexa/test_entities.py +++ b/tests/components/alexa/test_entities.py @@ -5,6 +5,7 @@ from unittest.mock import patch import pytest +from homeassistant.components import fan, humidifier, remote, water_heater from homeassistant.components.alexa import smart_home from homeassistant.const import EntityCategory, UnitOfTemperature, __version__ from homeassistant.core import HomeAssistant @@ -200,3 +201,167 @@ async def test_serialize_discovery_recovers( "Error serializing Alexa.PowerController discovery" f" for {hass.states.get('switch.bla')}" ) in caplog.text + + +@pytest.mark.parametrize( + ("domain", "state", "state_attributes", "mode_controller_exists"), + [ + ("switch", "on", {}, False), + ( + "fan", + "on", + { + "preset_modes": ["eco", "auto"], + "preset_mode": "eco", + "supported_features": fan.FanEntityFeature.PRESET_MODE.value, + }, + True, + ), + ( + "fan", + "on", + { + "preset_modes": ["eco", "auto"], + "preset_mode": None, + "supported_features": fan.FanEntityFeature.PRESET_MODE.value, + }, + True, + ), + ( + "fan", + "on", + { + "preset_modes": ["eco"], + "preset_mode": None, + "supported_features": fan.FanEntityFeature.PRESET_MODE.value, + }, + True, + ), + ( + "fan", + "on", + { + "preset_modes": [], + "preset_mode": None, + "supported_features": fan.FanEntityFeature.PRESET_MODE.value, + }, + False, + ), + ( + "humidifier", + "on", + { + "available_modes": ["auto", "manual"], + "mode": "auto", + "supported_features": humidifier.HumidifierEntityFeature.MODES.value, + }, + True, + ), + ( + "humidifier", + "on", + { + "available_modes": ["auto"], + "mode": None, + "supported_features": humidifier.HumidifierEntityFeature.MODES.value, + }, + True, + ), + ( + "humidifier", + "on", + { + "available_modes": [], + "mode": None, + "supported_features": humidifier.HumidifierEntityFeature.MODES.value, + }, + False, + ), + ( + "remote", + "on", + { + "activity_list": ["tv", "dvd"], + "current_activity": "tv", + "supported_features": remote.RemoteEntityFeature.ACTIVITY.value, + }, + True, + ), + ( + "remote", + "on", + { + "activity_list": ["tv"], + "current_activity": None, + "supported_features": remote.RemoteEntityFeature.ACTIVITY.value, + }, + True, + ), + ( + "remote", + "on", + { + "activity_list": [], + "current_activity": None, + "supported_features": remote.RemoteEntityFeature.ACTIVITY.value, + }, + False, + ), + ( + "water_heater", + "on", + { + "operation_list": ["on", "auto"], + "operation_mode": "auto", + "supported_features": water_heater.WaterHeaterEntityFeature.OPERATION_MODE.value, + }, + True, + ), + ( + "water_heater", + "on", + { + "operation_list": ["on"], + "operation_mode": None, + "supported_features": water_heater.WaterHeaterEntityFeature.OPERATION_MODE.value, + }, + True, + ), + ( + "water_heater", + "on", + { + "operation_list": [], + "operation_mode": None, + "supported_features": water_heater.WaterHeaterEntityFeature.OPERATION_MODE.value, + }, + False, + ), + ], +) +async def test_mode_controller_is_omitted_if_no_modes_are_set( + hass: HomeAssistant, + domain: str, + state: str, + state_attributes: dict[str, Any], + mode_controller_exists: bool, +) -> None: + """Test we do not generate an invalid discovery with AlexaModeController during serialize discovery. + + AlexModeControllers need at least 2 modes. If one mode is set, an extra mode will be added for compatibility. + If no modes are offered, the mode controller should be omitted to prevent schema validations. + """ + request = get_new_request("Alexa.Discovery", "Discover") + + hass.states.async_set( + f"{domain}.bla", state, {"friendly_name": "Boop Woz"} | state_attributes + ) + + msg = await smart_home.async_handle_message(hass, get_default_config(hass), request) + msg = msg["event"] + + interfaces = { + ifc["interface"] for ifc in msg["payload"]["endpoints"][0]["capabilities"] + } + + assert ("Alexa.ModeController" in interfaces) is mode_controller_exists diff --git a/tests/components/alexa_devices/conftest.py b/tests/components/alexa_devices/conftest.py index 79851550528..a5a49a343a9 100644 --- a/tests/components/alexa_devices/conftest.py +++ b/tests/components/alexa_devices/conftest.py @@ -50,6 +50,7 @@ def mock_amazon_devices_client() -> Generator[AsyncMock]: device_type="echo", device_owner_customer_id="amazon_ower_id", device_cluster_members=[TEST_SERIAL_NUMBER], + device_locale="en-US", online=True, serial_number=TEST_SERIAL_NUMBER, software_version="echo_test_software_version", diff --git a/tests/components/alexa_devices/test_config_flow.py b/tests/components/alexa_devices/test_config_flow.py index def3a6ec547..e1b2974184b 100644 --- a/tests/components/alexa_devices/test_config_flow.py +++ b/tests/components/alexa_devices/test_config_flow.py @@ -2,7 +2,12 @@ from unittest.mock import AsyncMock -from aioamazondevices.exceptions import CannotAuthenticate, CannotConnect, WrongCountry +from aioamazondevices.exceptions import ( + CannotAuthenticate, + CannotConnect, + CannotRetrieveData, + WrongCountry, +) import pytest from homeassistant.components.alexa_devices.const import CONF_LOGIN_DATA, DOMAIN @@ -57,6 +62,7 @@ async def test_full_flow( [ (CannotConnect, "cannot_connect"), (CannotAuthenticate, "invalid_auth"), + (CannotRetrieveData, "cannot_retrieve_data"), (WrongCountry, "wrong_country"), ], ) @@ -165,6 +171,7 @@ async def test_reauth_successful( [ (CannotConnect, "cannot_connect"), (CannotAuthenticate, "invalid_auth"), + (CannotRetrieveData, "cannot_retrieve_data"), ], ) async def test_reauth_not_successful( diff --git a/tests/components/alexa_devices/test_utils.py b/tests/components/alexa_devices/test_utils.py index 12009719a2f..1cf190bd297 100644 --- a/tests/components/alexa_devices/test_utils.py +++ b/tests/components/alexa_devices/test_utils.py @@ -21,8 +21,8 @@ ENTITY_ID = "switch.echo_test_do_not_disturb" @pytest.mark.parametrize( ("side_effect", "key", "error"), [ - (CannotConnect, "cannot_connect", "CannotConnect()"), - (CannotRetrieveData, "cannot_retrieve_data", "CannotRetrieveData()"), + (CannotConnect, "cannot_connect_with_error", "CannotConnect()"), + (CannotRetrieveData, "cannot_retrieve_data_with_error", "CannotRetrieveData()"), ], ) async def test_alexa_api_call_exceptions( diff --git a/tests/components/anthropic/snapshots/test_conversation.ambr b/tests/components/anthropic/snapshots/test_conversation.ambr index 09618b135db..d97eaab41e4 100644 --- a/tests/components/anthropic/snapshots/test_conversation.ambr +++ b/tests/components/anthropic/snapshots/test_conversation.ambr @@ -12,6 +12,7 @@ 'role': 'system', }), dict({ + 'attachments': None, 'content': 'Please call the test function', 'role': 'user', }), diff --git a/tests/components/assist_pipeline/snapshots/test_pipeline.ambr b/tests/components/assist_pipeline/snapshots/test_pipeline.ambr index 7f760d069e6..95415ddb902 100644 --- a/tests/components/assist_pipeline/snapshots/test_pipeline.ambr +++ b/tests/components/assist_pipeline/snapshots/test_pipeline.ambr @@ -1,5 +1,5 @@ # serializer version: 1 -# name: test_chat_log_tts_streaming[to_stream_deltas0-0-] +# name: test_chat_log_tts_streaming[to_stream_deltas0-1-hello, how are you?] list([ dict({ 'data': dict({ diff --git a/tests/components/assist_pipeline/test_init.py b/tests/components/assist_pipeline/test_init.py index 0294f9953db..a6a449bddd4 100644 --- a/tests/components/assist_pipeline/test_init.py +++ b/tests/components/assist_pipeline/test_init.py @@ -12,7 +12,7 @@ import hass_nabucasa import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components import assist_pipeline, stt +from homeassistant.components import assist_pipeline, conversation, stt from homeassistant.components.assist_pipeline.const import ( BYTES_PER_CHUNK, CONF_DEBUG_RECORDING_DIR, @@ -116,7 +116,7 @@ async def test_pipeline_from_audio_stream_legacy( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": "en-US", "language": "en", "name": "test_name", @@ -184,7 +184,7 @@ async def test_pipeline_from_audio_stream_entity( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": "en-US", "language": "en", "name": "test_name", @@ -252,7 +252,7 @@ async def test_pipeline_from_audio_stream_no_stt( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": "en-US", "language": "en", "name": "test_name", diff --git a/tests/components/assist_pipeline/test_pipeline.py b/tests/components/assist_pipeline/test_pipeline.py index 1302925dab9..5bc7b86c38c 100644 --- a/tests/components/assist_pipeline/test_pipeline.py +++ b/tests/components/assist_pipeline/test_pipeline.py @@ -29,7 +29,6 @@ from homeassistant.components.assist_pipeline.pipeline import ( async_create_default_pipeline, async_get_pipeline, async_get_pipelines, - async_migrate_engine, async_update_pipeline, ) from homeassistant.const import MATCH_ALL @@ -162,12 +161,6 @@ async def test_loading_pipelines_from_storage( hass: HomeAssistant, hass_storage: dict[str, Any] ) -> None: """Test loading stored pipelines on start.""" - async_migrate_engine( - hass, - "conversation", - conversation.OLD_HOME_ASSISTANT_AGENT, - conversation.HOME_ASSISTANT_AGENT, - ) id_1 = "01GX8ZWBAQYWNB1XV3EXEZ75DY" hass_storage[STORAGE_KEY] = { "version": STORAGE_VERSION, @@ -176,7 +169,7 @@ async def test_loading_pipelines_from_storage( "data": { "items": [ { - "conversation_engine": conversation.OLD_HOME_ASSISTANT_AGENT, + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": "language_1", "id": id_1, "language": "language_1", @@ -668,43 +661,6 @@ async def test_update_pipeline( } -@pytest.mark.usefixtures("init_supporting_components") -async def test_migrate_after_load(hass: HomeAssistant) -> None: - """Test migrating an engine after done loading.""" - assert await async_setup_component(hass, "assist_pipeline", {}) - - pipeline_data: PipelineData = hass.data[DOMAIN] - store = pipeline_data.pipeline_store - assert len(store.data) == 1 - - assert ( - await async_create_default_pipeline( - hass, - stt_engine_id="bla", - tts_engine_id="bla", - pipeline_name="Bla pipeline", - ) - is None - ) - pipeline = await async_create_default_pipeline( - hass, - stt_engine_id="test", - tts_engine_id="test", - pipeline_name="Test pipeline", - ) - assert pipeline is not None - - async_migrate_engine(hass, "stt", "test", "stt.test") - async_migrate_engine(hass, "tts", "test", "tts.test") - - await hass.async_block_till_done(wait_background_tasks=True) - - pipeline_updated = async_get_pipeline(hass, pipeline.id) - - assert pipeline_updated.stt_engine == "stt.test" - assert pipeline_updated.tts_engine == "tts.test" - - def test_fallback_intent_filter() -> None: """Test that we filter the right things.""" assert ( @@ -1364,7 +1320,7 @@ async def test_stt_language_used_instead_of_conversation_language( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": MATCH_ALL, "language": "en", "name": "test_name", @@ -1440,7 +1396,7 @@ async def test_tts_language_used_instead_of_conversation_language( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": MATCH_ALL, "language": "en", "name": "test_name", @@ -1516,7 +1472,7 @@ async def test_pipeline_language_used_instead_of_conversation_language( await client.send_json_auto_id( { "type": "assist_pipeline/pipeline/create", - "conversation_engine": "homeassistant", + "conversation_engine": conversation.HOME_ASSISTANT_AGENT, "conversation_language": MATCH_ALL, "language": "en", "name": "test_name", @@ -1594,9 +1550,9 @@ async def test_pipeline_language_used_instead_of_conversation_language( "?", ], ), - # We are not streaming, so 0 chunks via streaming method - 0, - "", + # We always stream when possible, so 1 chunk via streaming method + 1, + "hello, how are you?", ), # Size above STREAM_RESPONSE_CHUNKS ( diff --git a/tests/components/bluemaestro/__init__.py b/tests/components/bluemaestro/__init__.py index e598eb34597..259457453b1 100644 --- a/tests/components/bluemaestro/__init__.py +++ b/tests/components/bluemaestro/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/bluetooth/__init__.py b/tests/components/bluetooth/__init__.py index 31d301e2dac..d439f46bb71 100644 --- a/tests/components/bluetooth/__init__.py +++ b/tests/components/bluetooth/__init__.py @@ -1,11 +1,11 @@ """Tests for the Bluetooth integration.""" -from collections.abc import Iterable +from collections.abc import Generator, Iterable from contextlib import contextmanager import itertools import time from typing import Any -from unittest.mock import MagicMock, patch +from unittest.mock import MagicMock, PropertyMock, patch from bleak import BleakClient from bleak.backends.scanner import AdvertisementData, BLEDevice @@ -53,7 +53,6 @@ ADVERTISEMENT_DATA_DEFAULTS = { BLE_DEVICE_DEFAULTS = { "name": None, - "rssi": -127, "details": None, } @@ -89,7 +88,6 @@ def generate_ble_device( address: str | None = None, name: str | None = None, details: Any | None = None, - rssi: int | None = None, **kwargs: Any, ) -> BLEDevice: """Generate a BLEDevice with defaults.""" @@ -100,8 +98,6 @@ def generate_ble_device( new["name"] = name if details is not None: new["details"] = details - if rssi is not None: - new["rssi"] = rssi for key, value in BLE_DEVICE_DEFAULTS.items(): new.setdefault(key, value) return BLEDevice(**new) @@ -215,34 +211,35 @@ def inject_bluetooth_service_info( @contextmanager -def patch_all_discovered_devices(mock_discovered: list[BLEDevice]) -> None: +def patch_all_discovered_devices(mock_discovered: list[BLEDevice]) -> Generator[None]: """Mock all the discovered devices from all the scanners.""" manager = _get_manager() - original_history = {} scanners = list( itertools.chain( manager._connectable_scanners, manager._non_connectable_scanners ) ) - for scanner in scanners: - data = scanner.discovered_devices_and_advertisement_data - original_history[scanner] = data.copy() - data.clear() - if scanners: - data = scanners[0].discovered_devices_and_advertisement_data - data.clear() - data.update( - {device.address: (device, MagicMock()) for device in mock_discovered} - ) - yield - for scanner in scanners: - data = scanner.discovered_devices_and_advertisement_data - data.clear() - data.update(original_history[scanner]) + if scanners and getattr(scanners[0], "scanner", None): + with patch.object( + scanners[0].scanner.__class__, + "discovered_devices_and_advertisement_data", + new=PropertyMock( + side_effect=[ + { + device.address: (device, MagicMock()) + for device in mock_discovered + }, + ] + + [{}] * (len(scanners)) + ), + ): + yield + else: + yield @contextmanager -def patch_discovered_devices(mock_discovered: list[BLEDevice]) -> None: +def patch_discovered_devices(mock_discovered: list[BLEDevice]) -> Generator[None]: """Mock the combined best path to discovered devices from all the scanners.""" manager = _get_manager() original_all_history = manager._all_history @@ -305,6 +302,9 @@ class MockBleakClient(BleakClient): """Mock clear_cache.""" return True + def set_disconnected_callback(self, callback, **kwargs): + """Mock set_disconnected_callback.""" + class FakeScannerMixin: def get_discovered_device_advertisement_data( diff --git a/tests/components/bluetooth/test_api.py b/tests/components/bluetooth/test_api.py index 1468367fd9a..74373da6865 100644 --- a/tests/components/bluetooth/test_api.py +++ b/tests/components/bluetooth/test_api.py @@ -82,7 +82,6 @@ async def test_async_scanner_devices_by_address_connectable( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -116,7 +115,6 @@ async def test_async_scanner_devices_by_address_non_connectable( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", diff --git a/tests/components/bluetooth/test_base_scanner.py b/tests/components/bluetooth/test_base_scanner.py index 25dc1b9738d..f2aa3d87778 100644 --- a/tests/components/bluetooth/test_base_scanner.py +++ b/tests/components/bluetooth/test_base_scanner.py @@ -54,7 +54,6 @@ async def test_remote_scanner(hass: HomeAssistant, name_2: str | None) -> None: "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -67,7 +66,6 @@ async def test_remote_scanner(hass: HomeAssistant, name_2: str | None) -> None: "44:44:33:11:23:45", name_2, {}, - rssi=-100, ) switchbot_device_adv_2 = generate_advertisement_data( local_name=name_2, @@ -80,7 +78,6 @@ async def test_remote_scanner(hass: HomeAssistant, name_2: str | None) -> None: "44:44:33:11:23:45", "wohandlonger", {}, - rssi=-100, ) switchbot_device_adv_3 = generate_advertisement_data( local_name="wohandlonger", @@ -146,7 +143,6 @@ async def test_remote_scanner_expires_connectable(hass: HomeAssistant) -> None: "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -199,7 +195,6 @@ async def test_remote_scanner_expires_non_connectable(hass: HomeAssistant) -> No "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -272,7 +267,6 @@ async def test_base_scanner_connecting_behavior(hass: HomeAssistant) -> None: "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -376,7 +370,6 @@ async def test_device_with_ten_minute_advertising_interval(hass: HomeAssistant) "44:44:33:11:23:45", "bparasite", {}, - rssi=-100, ) bparasite_device_adv = generate_advertisement_data( local_name="bparasite", @@ -501,7 +494,6 @@ async def test_scanner_stops_responding(hass: HomeAssistant) -> None: "44:44:33:11:23:45", "bparasite", {}, - rssi=-100, ) bparasite_device_adv = generate_advertisement_data( local_name="bparasite", @@ -545,7 +537,6 @@ async def test_remote_scanner_bluetooth_config_entry( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", diff --git a/tests/components/bluetooth/test_diagnostics.py b/tests/components/bluetooth/test_diagnostics.py index 540bf1bfbd1..5c4d8bda70d 100644 --- a/tests/components/bluetooth/test_diagnostics.py +++ b/tests/components/bluetooth/test_diagnostics.py @@ -37,7 +37,7 @@ class FakeHaScanner(FakeScannerMixin, HaScanner): """Return the discovered devices and advertisement data.""" return { "44:44:33:11:23:45": ( - generate_ble_device(name="x", rssi=-127, address="44:44:33:11:23:45"), + generate_ble_device(name="x", address="44:44:33:11:23:45"), generate_advertisement_data(local_name="x"), ) } diff --git a/tests/components/bluetooth/test_manager.py b/tests/components/bluetooth/test_manager.py index 7488aa6e33c..f34afba01ef 100644 --- a/tests/components/bluetooth/test_manager.py +++ b/tests/components/bluetooth/test_manager.py @@ -78,11 +78,9 @@ async def test_advertisements_do_not_switch_adapters_for_no_reason( address = "44:44:33:11:23:12" - switchbot_device_signal_100 = generate_ble_device( - address, "wohand_signal_100", rssi=-100 - ) + switchbot_device_signal_100 = generate_ble_device(address, "wohand_signal_100") switchbot_adv_signal_100 = generate_advertisement_data( - local_name="wohand_signal_100", service_uuids=[] + local_name="wohand_signal_100", service_uuids=[], rssi=-100 ) inject_advertisement_with_source( hass, switchbot_device_signal_100, switchbot_adv_signal_100, HCI0_SOURCE_ADDRESS @@ -93,11 +91,9 @@ async def test_advertisements_do_not_switch_adapters_for_no_reason( is switchbot_device_signal_100 ) - switchbot_device_signal_99 = generate_ble_device( - address, "wohand_signal_99", rssi=-99 - ) + switchbot_device_signal_99 = generate_ble_device(address, "wohand_signal_99") switchbot_adv_signal_99 = generate_advertisement_data( - local_name="wohand_signal_99", service_uuids=[] + local_name="wohand_signal_99", service_uuids=[], rssi=-99 ) inject_advertisement_with_source( hass, switchbot_device_signal_99, switchbot_adv_signal_99, HCI0_SOURCE_ADDRESS @@ -108,11 +104,9 @@ async def test_advertisements_do_not_switch_adapters_for_no_reason( is switchbot_device_signal_99 ) - switchbot_device_signal_98 = generate_ble_device( - address, "wohand_good_signal", rssi=-98 - ) + switchbot_device_signal_98 = generate_ble_device(address, "wohand_good_signal") switchbot_adv_signal_98 = generate_advertisement_data( - local_name="wohand_good_signal", service_uuids=[] + local_name="wohand_good_signal", service_uuids=[], rssi=-98 ) inject_advertisement_with_source( hass, switchbot_device_signal_98, switchbot_adv_signal_98, HCI1_SOURCE_ADDRESS @@ -805,13 +799,11 @@ async def test_goes_unavailable_connectable_only_and_recovers( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_non_connectable = generate_ble_device( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -978,7 +970,6 @@ async def test_goes_unavailable_dismisses_discovery_and_makes_discoverable( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -1394,7 +1385,6 @@ async def test_bluetooth_rediscover( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -1571,7 +1561,6 @@ async def test_bluetooth_rediscover_no_match( "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", @@ -1693,11 +1682,9 @@ async def test_async_register_disappeared_callback( """Test bluetooth async_register_disappeared_callback handles failures.""" address = "44:44:33:11:23:12" - switchbot_device_signal_100 = generate_ble_device( - address, "wohand_signal_100", rssi=-100 - ) + switchbot_device_signal_100 = generate_ble_device(address, "wohand_signal_100") switchbot_adv_signal_100 = generate_advertisement_data( - local_name="wohand_signal_100", service_uuids=[] + local_name="wohand_signal_100", service_uuids=[], rssi=-100 ) inject_advertisement_with_source( hass, switchbot_device_signal_100, switchbot_adv_signal_100, "hci0" diff --git a/tests/components/bluetooth/test_models.py b/tests/components/bluetooth/test_models.py index d36741b4d5d..af367dec187 100644 --- a/tests/components/bluetooth/test_models.py +++ b/tests/components/bluetooth/test_models.py @@ -124,7 +124,7 @@ async def test_wrapped_bleak_client_local_adapter_only(hass: HomeAssistant) -> N "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True ), ): - assert await client.connect() is True + await client.connect() assert client.is_connected is True client.set_disconnected_callback(lambda client: None) await client.disconnect() @@ -145,7 +145,6 @@ async def test_wrapped_bleak_client_set_disconnected_callback_after_connected( "source": "esp32_has_connection_slot", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-40, ) switchbot_proxy_device_adv_has_connection_slot = generate_advertisement_data( local_name="wohand", @@ -215,7 +214,7 @@ async def test_wrapped_bleak_client_set_disconnected_callback_after_connected( "bleak.backends.bluezdbus.client.BleakClientBlueZDBus.is_connected", True ), ): - assert await client.connect() is True + await client.connect() assert client.is_connected is True client.set_disconnected_callback(lambda client: None) await client.disconnect() @@ -236,10 +235,9 @@ async def test_ble_device_with_proxy_client_out_of_connections_no_scanners( "source": "esp32", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-30, ) switchbot_adv = generate_advertisement_data( - local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"} + local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-30 ) inject_advertisement_with_source( @@ -275,10 +273,9 @@ async def test_ble_device_with_proxy_client_out_of_connections( "source": "esp32", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-30, ) switchbot_adv = generate_advertisement_data( - local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"} + local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-30 ) class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner): @@ -340,10 +337,9 @@ async def test_ble_device_with_proxy_clear_cache(hass: HomeAssistant) -> None: "source": "esp32", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-30, ) switchbot_adv = generate_advertisement_data( - local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"} + local_name="wohand", service_uuids=[], manufacturer_data={1: b"\x01"}, rssi=-30 ) class FakeScanner(FakeScannerMixin, BaseHaRemoteScanner): @@ -417,7 +413,6 @@ async def test_ble_device_with_proxy_client_out_of_connections_uses_best_availab "source": "esp32_has_connection_slot", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-40, ) switchbot_proxy_device_adv_has_connection_slot = generate_advertisement_data( local_name="wohand", @@ -511,7 +506,6 @@ async def test_ble_device_with_proxy_client_out_of_connections_uses_best_availab "source": "esp32_no_connection_slot", "path": "/org/bluez/hci0/dev_44_44_33_11_23_45", }, - rssi=-30, ) switchbot_proxy_device_no_connection_slot_adv = generate_advertisement_data( local_name="wohand", @@ -538,7 +532,6 @@ async def test_ble_device_with_proxy_client_out_of_connections_uses_best_availab "44:44:33:11:23:45", "wohand", {}, - rssi=-100, ) switchbot_device_adv = generate_advertisement_data( local_name="wohand", diff --git a/tests/components/bluetooth/test_usage.py b/tests/components/bluetooth/test_usage.py index d5d4e7ad9d0..9c3c8c6cebb 100644 --- a/tests/components/bluetooth/test_usage.py +++ b/tests/components/bluetooth/test_usage.py @@ -17,9 +17,7 @@ from . import generate_ble_device MOCK_BLE_DEVICE = generate_ble_device( "00:00:00:00:00:00", "any", - delegate="", details={"path": "/dev/hci0/device"}, - rssi=-127, ) diff --git a/tests/components/bluetooth/test_websocket_api.py b/tests/components/bluetooth/test_websocket_api.py index 57199d04078..2e613932f3c 100644 --- a/tests/components/bluetooth/test_websocket_api.py +++ b/tests/components/bluetooth/test_websocket_api.py @@ -38,11 +38,9 @@ async def test_subscribe_advertisements( """Test bluetooth subscribe_advertisements.""" address = "44:44:33:11:23:12" - switchbot_device_signal_100 = generate_ble_device( - address, "wohand_signal_100", rssi=-100 - ) + switchbot_device_signal_100 = generate_ble_device(address, "wohand_signal_100") switchbot_adv_signal_100 = generate_advertisement_data( - local_name="wohand_signal_100", service_uuids=[] + local_name="wohand_signal_100", service_uuids=[], rssi=-100 ) inject_advertisement_with_source( hass, switchbot_device_signal_100, switchbot_adv_signal_100, HCI0_SOURCE_ADDRESS @@ -68,7 +66,7 @@ async def test_subscribe_advertisements( "connectable": True, "manufacturer_data": {}, "name": "wohand_signal_100", - "rssi": -127, + "rssi": -100, "service_data": {}, "service_uuids": [], "source": HCI0_SOURCE_ADDRESS, @@ -134,11 +132,9 @@ async def test_subscribe_connection_allocations( """Test bluetooth subscribe_connection_allocations.""" address = "44:44:33:11:23:12" - switchbot_device_signal_100 = generate_ble_device( - address, "wohand_signal_100", rssi=-100 - ) + switchbot_device_signal_100 = generate_ble_device(address, "wohand_signal_100") switchbot_adv_signal_100 = generate_advertisement_data( - local_name="wohand_signal_100", service_uuids=[] + local_name="wohand_signal_100", service_uuids=[], rssi=-100 ) inject_advertisement_with_source( hass, switchbot_device_signal_100, switchbot_adv_signal_100, HCI0_SOURCE_ADDRESS diff --git a/tests/components/bluetooth/test_wrappers.py b/tests/components/bluetooth/test_wrappers.py index bfe7445f614..413c96535a6 100644 --- a/tests/components/bluetooth/test_wrappers.py +++ b/tests/components/bluetooth/test_wrappers.py @@ -92,17 +92,13 @@ class FakeBleakClient(BaseFakeBleakClient): async def connect(self, *args, **kwargs): """Connect.""" + + @property + def is_connected(self): + """Connected.""" return True -class FakeBleakClientFailsToConnect(BaseFakeBleakClient): - """Fake bleak client that fails to connect.""" - - async def connect(self, *args, **kwargs): - """Connect.""" - return False - - class FakeBleakClientRaisesOnConnect(BaseFakeBleakClient): """Fake bleak client that raises on connect.""" @@ -110,6 +106,11 @@ class FakeBleakClientRaisesOnConnect(BaseFakeBleakClient): """Connect.""" raise ConnectionError("Test exception") + @property + def is_connected(self): + """Not connected.""" + return False + def _generate_ble_device_and_adv_data( interface: str, mac: str, rssi: int @@ -119,7 +120,6 @@ def _generate_ble_device_and_adv_data( generate_ble_device( mac, "any", - delegate="", details={"path": f"/org/bluez/{interface}/dev_{mac}"}, ), generate_advertisement_data(rssi=rssi), @@ -144,16 +144,6 @@ def mock_platform_client_fixture(): yield -@pytest.fixture(name="mock_platform_client_that_fails_to_connect") -def mock_platform_client_that_fails_to_connect_fixture(): - """Fixture that mocks the platform client that fails to connect.""" - with patch( - "habluetooth.wrappers.get_platform_client_backend_type", - return_value=FakeBleakClientFailsToConnect, - ): - yield - - @pytest.fixture(name="mock_platform_client_that_raises_on_connect") def mock_platform_client_that_raises_on_connect_fixture(): """Fixture that mocks the platform client that fails to connect.""" @@ -219,7 +209,8 @@ async def test_test_switch_adapters_when_out_of_slots( ): ble_device = hci0_device_advs["00:00:00:00:00:01"][0] client = bleak.BleakClient(ble_device) - assert await client.connect() is True + await client.connect() + assert client.is_connected is True assert allocate_slot_mock.call_count == 1 assert release_slot_mock.call_count == 0 @@ -251,7 +242,8 @@ async def test_test_switch_adapters_when_out_of_slots( ): ble_device = hci0_device_advs["00:00:00:00:00:03"][0] client = bleak.BleakClient(ble_device) - assert await client.connect() is True + await client.connect() + assert client.is_connected is True assert release_slot_mock.call_count == 0 cancel_hci0() @@ -262,7 +254,7 @@ async def test_test_switch_adapters_when_out_of_slots( async def test_release_slot_on_connect_failure( hass: HomeAssistant, install_bleak_catcher, - mock_platform_client_that_fails_to_connect, + mock_platform_client_that_raises_on_connect, ) -> None: """Ensure the slot gets released on connection failure.""" manager = _get_manager() @@ -278,7 +270,9 @@ async def test_release_slot_on_connect_failure( ): ble_device = hci0_device_advs["00:00:00:00:00:01"][0] client = bleak.BleakClient(ble_device) - assert await client.connect() is False + with pytest.raises(ConnectionError): + await client.connect() + assert client.is_connected is False assert allocate_slot_mock.call_count == 1 assert release_slot_mock.call_count == 1 @@ -335,13 +329,18 @@ async def test_passing_subclassed_str_as_address( async def connect(self, *args, **kwargs): """Connect.""" + + @property + def is_connected(self): + """Connected.""" return True with patch( "habluetooth.wrappers.get_platform_client_backend_type", return_value=FakeBleakClient, ): - assert await client.connect() is True + await client.connect() + assert client.is_connected is True cancel_hci0() cancel_hci1() diff --git a/tests/components/bring/test_services.py b/tests/components/bring/test_services.py new file mode 100644 index 00000000000..d010c2b86a0 --- /dev/null +++ b/tests/components/bring/test_services.py @@ -0,0 +1,190 @@ +"""Test actions of Bring! integration.""" + +from unittest.mock import AsyncMock + +from bring_api import ( + ActivityType, + BringActivityResponse, + BringNotificationType, + BringRequestException, + ReactionType, +) +import pytest + +from homeassistant.components.bring.const import ( + ATTR_REACTION, + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, +) +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError +from homeassistant.helpers import entity_registry as er + +from tests.common import MockConfigEntry + + +@pytest.mark.parametrize( + ("reaction", "call_arg"), + [ + ("drooling", ReactionType.DROOLING), + ("heart", ReactionType.HEART), + ("monocle", ReactionType.MONOCLE), + ("thumbs_up", ReactionType.THUMBS_UP), + ], +) +async def test_send_reaction( + hass: HomeAssistant, + bring_config_entry: MockConfigEntry, + mock_bring_client: AsyncMock, + reaction: str, + call_arg: ReactionType, +) -> None: + """Test send activity stream reaction.""" + + bring_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(bring_config_entry.entry_id) + await hass.async_block_till_done() + + assert bring_config_entry.state is ConfigEntryState.LOADED + + await hass.services.async_call( + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, + service_data={ + ATTR_ENTITY_ID: "event.einkauf_activities", + ATTR_REACTION: reaction, + }, + blocking=True, + ) + + mock_bring_client.notify.assert_called_once_with( + "e542eef6-dba7-4c31-a52c-29e6ab9d83a5", + BringNotificationType.LIST_ACTIVITY_STREAM_REACTION, + receiver="9a21fdfc-63a4-441a-afc1-ef3030605a9d", + activity="673594a9-f92d-4cb6-adf1-d2f7a83207a4", + activity_type=ActivityType.LIST_ITEMS_CHANGED, + reaction=call_arg, + ) + + +async def test_send_reaction_exception( + hass: HomeAssistant, + bring_config_entry: MockConfigEntry, + mock_bring_client: AsyncMock, +) -> None: + """Test send activity stream reaction with exception.""" + + bring_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(bring_config_entry.entry_id) + await hass.async_block_till_done() + + assert bring_config_entry.state is ConfigEntryState.LOADED + mock_bring_client.notify.side_effect = BringRequestException + with pytest.raises( + HomeAssistantError, + match="Failed to send reaction for Bring! due to a connection error, try again later", + ): + await hass.services.async_call( + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, + service_data={ + ATTR_ENTITY_ID: "event.einkauf_activities", + ATTR_REACTION: "heart", + }, + blocking=True, + ) + + +@pytest.mark.usefixtures("mock_bring_client") +async def test_send_reaction_config_entry_not_loaded( + hass: HomeAssistant, + bring_config_entry: MockConfigEntry, +) -> None: + """Test send activity stream reaction config entry not loaded exception.""" + + bring_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(bring_config_entry.entry_id) + await hass.async_block_till_done() + + assert await hass.config_entries.async_unload(bring_config_entry.entry_id) + + assert bring_config_entry.state is ConfigEntryState.NOT_LOADED + + with pytest.raises( + ServiceValidationError, + match="The account associated with this Bring! list is either not loaded or disabled in Home Assistant", + ): + await hass.services.async_call( + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, + service_data={ + ATTR_ENTITY_ID: "event.einkauf_activities", + ATTR_REACTION: "heart", + }, + blocking=True, + ) + + +@pytest.mark.usefixtures("mock_bring_client") +async def test_send_reaction_unknown_entity( + hass: HomeAssistant, + bring_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, +) -> None: + """Test send activity stream reaction unknown entity exception.""" + + bring_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(bring_config_entry.entry_id) + await hass.async_block_till_done() + + assert bring_config_entry.state is ConfigEntryState.LOADED + + entity_registry.async_update_entity( + "event.einkauf_activities", disabled_by=er.RegistryEntryDisabler.USER + ) + with pytest.raises( + ServiceValidationError, + match="Failed to send reaction for Bring! — Unknown entity event.einkauf_activities", + ): + await hass.services.async_call( + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, + service_data={ + ATTR_ENTITY_ID: "event.einkauf_activities", + ATTR_REACTION: "heart", + }, + blocking=True, + ) + + +async def test_send_reaction_not_found( + hass: HomeAssistant, + bring_config_entry: MockConfigEntry, + mock_bring_client: AsyncMock, +) -> None: + """Test send activity stream reaction not found validation error.""" + mock_bring_client.get_activity.return_value = BringActivityResponse.from_dict( + {"timeline": [], "timestamp": "2025-01-01T03:09:33.036Z", "totalEvents": 0} + ) + + bring_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(bring_config_entry.entry_id) + await hass.async_block_till_done() + + assert bring_config_entry.state is ConfigEntryState.LOADED + + with pytest.raises( + HomeAssistantError, + match="Failed to send reaction for Bring! — No recent activity found", + ): + await hass.services.async_call( + DOMAIN, + SERVICE_ACTIVITY_STREAM_REACTION, + service_data={ + ATTR_ENTITY_ID: "event.einkauf_activities", + ATTR_REACTION: "heart", + }, + blocking=True, + ) diff --git a/tests/components/cloud/conftest.py b/tests/components/cloud/conftest.py index 0e118f251de..e63af0ced09 100644 --- a/tests/components/cloud/conftest.py +++ b/tests/components/cloud/conftest.py @@ -5,7 +5,7 @@ from pathlib import Path from typing import Any from unittest.mock import DEFAULT, AsyncMock, MagicMock, PropertyMock, patch -from hass_nabucasa import Cloud +from hass_nabucasa import Cloud, payments_api from hass_nabucasa.auth import CognitoAuth from hass_nabucasa.cloudhooks import Cloudhooks from hass_nabucasa.const import DEFAULT_SERVERS, DEFAULT_VALUES, STATE_CONNECTED @@ -71,6 +71,10 @@ async def cloud_fixture() -> AsyncGenerator[MagicMock]: mock_cloud.voice = MagicMock(spec=Voice) mock_cloud.files = MagicMock(spec=Files) mock_cloud.started = None + mock_cloud.payments = MagicMock( + spec=payments_api.PaymentsApi, + subscription_info=AsyncMock(), + ) mock_cloud.ice_servers = MagicMock( spec=IceServers, async_register_ice_servers_listener=AsyncMock( diff --git a/tests/components/cloud/test_http_api.py b/tests/components/cloud/test_http_api.py index 79764e552c7..84630bc0320 100644 --- a/tests/components/cloud/test_http_api.py +++ b/tests/components/cloud/test_http_api.py @@ -18,6 +18,7 @@ from hass_nabucasa.auth import ( UnknownError, ) from hass_nabucasa.const import STATE_CONNECTED +from hass_nabucasa.payments_api import PaymentsApiError from hass_nabucasa.remote import CertificateStatus import pytest from syrupy.assertion import SnapshotAssertion @@ -1008,16 +1009,14 @@ async def test_websocket_subscription_info( cloud: MagicMock, setup_cloud: None, ) -> None: - """Test subscription info and connecting because valid account.""" - aioclient_mock.get(SUBSCRIPTION_INFO_URL, json={"provider": "stripe"}) + """Test subscription info.""" + cloud.payments.subscription_info.return_value = {"provider": "stripe"} client = await hass_ws_client(hass) - mock_renew = cloud.auth.async_renew_access_token await client.send_json({"id": 5, "type": "cloud/subscription"}) response = await client.receive_json() assert response["result"] == {"provider": "stripe"} - assert mock_renew.call_count == 1 async def test_websocket_subscription_fail( @@ -1028,7 +1027,9 @@ async def test_websocket_subscription_fail( setup_cloud: None, ) -> None: """Test subscription info fail.""" - aioclient_mock.get(SUBSCRIPTION_INFO_URL, status=HTTPStatus.INTERNAL_SERVER_ERROR) + cloud.payments.subscription_info.side_effect = PaymentsApiError( + "Failed to fetch subscription information" + ) client = await hass_ws_client(hass) await client.send_json({"id": 5, "type": "cloud/subscription"}) diff --git a/tests/components/cloud/test_subscription.py b/tests/components/cloud/test_subscription.py index 22839b585fd..c34ca1bc871 100644 --- a/tests/components/cloud/test_subscription.py +++ b/tests/components/cloud/test_subscription.py @@ -2,7 +2,7 @@ from unittest.mock import AsyncMock, Mock -from hass_nabucasa import Cloud +from hass_nabucasa import Cloud, payments_api import pytest from homeassistant.components.cloud.subscription import ( @@ -22,6 +22,10 @@ async def mocked_cloud_object(hass: HomeAssistant) -> Cloud: accounts_server="accounts.nabucasa.com", auth=Mock(async_check_token=AsyncMock()), websession=async_get_clientsession(hass), + payments=Mock( + spec=payments_api.PaymentsApi, + subscription_info=AsyncMock(), + ), ) @@ -31,14 +35,13 @@ async def test_fetching_subscription_with_timeout_error( mocked_cloud: Cloud, ) -> None: """Test that we handle timeout error.""" - aioclient_mock.get( - "https://accounts.nabucasa.com/payments/subscription_info", - exc=TimeoutError(), + mocked_cloud.payments.subscription_info.side_effect = payments_api.PaymentsApiError( + "Timeout reached while calling API" ) assert await async_subscription_info(mocked_cloud) is None assert ( - "A timeout of 10 was reached while trying to fetch subscription information" + "Failed to fetch subscription information - Timeout reached while calling API" in caplog.text ) diff --git a/tests/components/conversation/snapshots/test_http.ambr b/tests/components/conversation/snapshots/test_http.ambr index 5179409deb0..391fb609d65 100644 --- a/tests/components/conversation/snapshots/test_http.ambr +++ b/tests/components/conversation/snapshots/test_http.ambr @@ -327,37 +327,6 @@ }), }) # --- -# name: test_http_processing_intent[homeassistant] - dict({ - 'continue_conversation': False, - 'conversation_id': , - 'response': dict({ - 'card': dict({ - }), - 'data': dict({ - 'failed': list([ - ]), - 'success': list([ - dict({ - 'id': 'light.kitchen', - 'name': 'kitchen', - 'type': 'entity', - }), - ]), - 'targets': list([ - ]), - }), - 'language': 'en', - 'response_type': 'action_done', - 'speech': dict({ - 'plain': dict({ - 'extra_data': None, - 'speech': 'Turned on the light', - }), - }), - }), - }) -# --- # name: test_ws_api[payload0] dict({ 'continue_conversation': False, diff --git a/tests/components/conversation/snapshots/test_init.ambr b/tests/components/conversation/snapshots/test_init.ambr index a853faa7a3d..779bb256180 100644 --- a/tests/components/conversation/snapshots/test_init.ambr +++ b/tests/components/conversation/snapshots/test_init.ambr @@ -108,37 +108,6 @@ }), }) # --- -# name: test_turn_on_intent[None-turn kitchen on-homeassistant] - dict({ - 'continue_conversation': False, - 'conversation_id': , - 'response': dict({ - 'card': dict({ - }), - 'data': dict({ - 'failed': list([ - ]), - 'success': list([ - dict({ - 'id': 'light.kitchen', - 'name': 'kitchen', - 'type': , - }), - ]), - 'targets': list([ - ]), - }), - 'language': 'en', - 'response_type': 'action_done', - 'speech': dict({ - 'plain': dict({ - 'extra_data': None, - 'speech': 'Turned on the light', - }), - }), - }), - }) -# --- # name: test_turn_on_intent[None-turn on kitchen-None] dict({ 'continue_conversation': False, @@ -201,37 +170,6 @@ }), }) # --- -# name: test_turn_on_intent[None-turn on kitchen-homeassistant] - dict({ - 'continue_conversation': False, - 'conversation_id': , - 'response': dict({ - 'card': dict({ - }), - 'data': dict({ - 'failed': list([ - ]), - 'success': list([ - dict({ - 'id': 'light.kitchen', - 'name': 'kitchen', - 'type': , - }), - ]), - 'targets': list([ - ]), - }), - 'language': 'en', - 'response_type': 'action_done', - 'speech': dict({ - 'plain': dict({ - 'extra_data': None, - 'speech': 'Turned on the light', - }), - }), - }), - }) -# --- # name: test_turn_on_intent[my_new_conversation-turn kitchen on-None] dict({ 'continue_conversation': False, @@ -294,37 +232,6 @@ }), }) # --- -# name: test_turn_on_intent[my_new_conversation-turn kitchen on-homeassistant] - dict({ - 'continue_conversation': False, - 'conversation_id': , - 'response': dict({ - 'card': dict({ - }), - 'data': dict({ - 'failed': list([ - ]), - 'success': list([ - dict({ - 'id': 'light.kitchen', - 'name': 'kitchen', - 'type': , - }), - ]), - 'targets': list([ - ]), - }), - 'language': 'en', - 'response_type': 'action_done', - 'speech': dict({ - 'plain': dict({ - 'extra_data': None, - 'speech': 'Turned on the light', - }), - }), - }), - }) -# --- # name: test_turn_on_intent[my_new_conversation-turn on kitchen-None] dict({ 'continue_conversation': False, @@ -387,34 +294,3 @@ }), }) # --- -# name: test_turn_on_intent[my_new_conversation-turn on kitchen-homeassistant] - dict({ - 'continue_conversation': False, - 'conversation_id': , - 'response': dict({ - 'card': dict({ - }), - 'data': dict({ - 'failed': list([ - ]), - 'success': list([ - dict({ - 'id': 'light.kitchen', - 'name': 'kitchen', - 'type': , - }), - ]), - 'targets': list([ - ]), - }), - 'language': 'en', - 'response_type': 'action_done', - 'speech': dict({ - 'plain': dict({ - 'extra_data': None, - 'speech': 'Turned on the light', - }), - }), - }), - }) -# --- diff --git a/tests/components/conversation/test_http.py b/tests/components/conversation/test_http.py index 77fa97ad845..29cd567e904 100644 --- a/tests/components/conversation/test_http.py +++ b/tests/components/conversation/test_http.py @@ -8,7 +8,10 @@ import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.conversation import default_agent -from homeassistant.components.conversation.const import DATA_DEFAULT_ENTITY +from homeassistant.components.conversation.const import ( + DATA_DEFAULT_ENTITY, + HOME_ASSISTANT_AGENT, +) from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.core import HomeAssistant @@ -22,8 +25,6 @@ from tests.typing import ClientSessionGenerator, WebSocketGenerator AGENT_ID_OPTIONS = [ None, - # Old value of conversation.HOME_ASSISTANT_AGENT, - "homeassistant", # Current value of conversation.HOME_ASSISTANT_AGENT, "conversation.home_assistant", ] @@ -187,7 +188,7 @@ async def test_http_api_wrong_data( }, { "text": "Test Text", - "agent_id": "homeassistant", + "agent_id": HOME_ASSISTANT_AGENT, }, ], ) diff --git a/tests/components/conversation/test_init.py b/tests/components/conversation/test_init.py index c3de5f1127c..e757c56042b 100644 --- a/tests/components/conversation/test_init.py +++ b/tests/components/conversation/test_init.py @@ -14,7 +14,10 @@ from homeassistant.components.conversation import ( async_handle_sentence_triggers, default_agent, ) -from homeassistant.components.conversation.const import DATA_DEFAULT_ENTITY +from homeassistant.components.conversation.const import ( + DATA_DEFAULT_ENTITY, + HOME_ASSISTANT_AGENT, +) from homeassistant.components.light import DOMAIN as LIGHT_DOMAIN from homeassistant.core import Context, HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -28,8 +31,6 @@ from tests.typing import ClientSessionGenerator AGENT_ID_OPTIONS = [ None, - # Old value of conversation.HOME_ASSISTANT_AGENT, - "homeassistant", # Current value of conversation.HOME_ASSISTANT_AGENT, "conversation.home_assistant", ] @@ -205,8 +206,8 @@ async def test_get_agent_info( """Test get agent info.""" agent_info = conversation.async_get_agent_info(hass) # Test it's the default - assert conversation.async_get_agent_info(hass, "homeassistant") == agent_info - assert conversation.async_get_agent_info(hass, "homeassistant") == snapshot + assert conversation.async_get_agent_info(hass, HOME_ASSISTANT_AGENT) == agent_info + assert conversation.async_get_agent_info(hass, HOME_ASSISTANT_AGENT) == snapshot assert ( conversation.async_get_agent_info(hass, mock_conversation_agent.agent_id) == snapshot @@ -223,7 +224,7 @@ async def test_get_agent_info( default_agent = conversation.async_get_agent(hass) default_agent._attr_supports_streaming = True assert ( - conversation.async_get_agent_info(hass, "homeassistant").supports_streaming + conversation.async_get_agent_info(hass, HOME_ASSISTANT_AGENT).supports_streaming is True ) diff --git a/tests/components/derivative/test_init.py b/tests/components/derivative/test_init.py index 533f91c8a33..abe90e72b56 100644 --- a/tests/components/derivative/test_init.py +++ b/tests/components/derivative/test_init.py @@ -7,8 +7,8 @@ import pytest from homeassistant.components import derivative from homeassistant.components.derivative.config_flow import ConfigFlowHandler from homeassistant.components.derivative.const import DOMAIN -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -82,6 +82,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -214,7 +215,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( derivative_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(derivative_config_entry.entry_id) @@ -229,7 +230,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( derivative_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 async def test_async_handle_source_entity_changes_source_entity_removed( @@ -240,6 +241,54 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the derivative config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(derivative_config_entry.entry_id) + await hass.async_block_till_done() + + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert derivative_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, derivative_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.derivative.async_unload_entry", + wraps=derivative.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the entity is no longer linked to the source device + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id is None + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the derivative config entry is not removed + assert derivative_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["update"] + + +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + derivative_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the derivative config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -256,7 +305,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert derivative_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert derivative_config_entry.entry_id in sensor_device.config_entries + assert derivative_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, derivative_entity_entry.entity_id) @@ -273,7 +322,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() - # Check that the derivative config entry is removed from the device + # Check that the entity is no longer linked to the source device + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id is None + + # Check that the derivative config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert derivative_config_entry.entry_id not in sensor_device.config_entries @@ -300,7 +353,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert derivative_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert derivative_config_entry.entry_id in sensor_device.config_entries + assert derivative_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, derivative_entity_entry.entity_id) @@ -315,7 +368,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the derivative config entry is removed from the device + # Check that the entity is no longer linked to the source device + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id is None + + # Check that the derivative config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert derivative_config_entry.entry_id not in sensor_device.config_entries @@ -348,7 +405,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert derivative_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert derivative_config_entry.entry_id in sensor_device.config_entries + assert derivative_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert derivative_config_entry.entry_id not in sensor_device_2.config_entries @@ -365,11 +422,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the derivative config entry is moved to the other device + # Check that the entity is linked to the other device + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id == sensor_device_2.id + + # Check that the derivative config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert derivative_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert derivative_config_entry.entry_id in sensor_device_2.config_entries + assert derivative_config_entry.entry_id not in sensor_device_2.config_entries # Check that the derivative config entry is not removed assert derivative_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -394,7 +455,7 @@ async def test_async_handle_source_entity_new_entity_id( assert derivative_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert derivative_config_entry.entry_id in sensor_device.config_entries + assert derivative_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, derivative_entity_entry.entity_id) @@ -412,12 +473,128 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the derivative config entry is updated with the new entity ID assert derivative_config_entry.options["source"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert derivative_config_entry.entry_id in sensor_device.config_entries + assert derivative_config_entry.entry_id not in sensor_device.config_entries # Check that the derivative config entry is not removed assert derivative_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +@pytest.mark.parametrize( + ("unit_prefix", "expect_prefix"), + [ + ({}, None), + ({"unit_prefix": "k"}, "k"), + ({"unit_prefix": "none"}, None), + ], +) +async def test_migration_1_1(hass: HomeAssistant, unit_prefix, expect_prefix) -> None: + """Test migration from v1.1 deletes "none" unit_prefix.""" + + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My derivative", + "round": 1.0, + "source": "sensor.power", + "time_window": {"seconds": 0.0}, + **unit_prefix, + "unit_time": "min", + }, + title="My derivative", + version=1, + minor_version=1, + ) + 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 config_entry.options["unit_time"] == "min" + assert config_entry.options.get("unit_prefix") == expect_prefix + + assert config_entry.version == 1 + assert config_entry.minor_version == 3 + + +async def test_migration_1_2( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test migration from v1.2 removes derivative config entry from device.""" + + derivative_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My derivative", + "round": 1.0, + "source": "sensor.test_unique", + "time_window": {"seconds": 0.0}, + "unit_prefix": "k", + "unit_time": "min", + }, + title="My derivative", + version=1, + minor_version=2, + ) + derivative_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=derivative_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert derivative_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(derivative_config_entry.entry_id) + await hass.async_block_till_done() + + assert derivative_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert derivative_config_entry.entry_id not in sensor_device.config_entries + derivative_entity_entry = entity_registry.async_get("sensor.my_derivative") + assert derivative_entity_entry.device_id == sensor_entity_entry.device_id + + assert derivative_config_entry.version == 1 + assert derivative_config_entry.minor_version == 3 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My derivative", + "round": 1.0, + "source": "sensor.power", + "time_window": {"seconds": 0.0}, + "unit_prefix": "k", + "unit_time": "min", + }, + title="My derivative", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/diagnostics/test_init.py b/tests/components/diagnostics/test_init.py index ffed7e21f60..fe62efeebac 100644 --- a/tests/components/diagnostics/test_init.py +++ b/tests/components/diagnostics/test_init.py @@ -1,13 +1,15 @@ """Test the Diagnostics integration.""" +from datetime import datetime from http import HTTPStatus from unittest.mock import AsyncMock, Mock, patch +from freezegun import freeze_time import pytest from homeassistant.components.websocket_api import TYPE_RESULT from homeassistant.core import HomeAssistant -from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import device_registry as dr, issue_registry as ir from homeassistant.helpers.system_info import async_get_system_info from homeassistant.loader import async_get_integration from homeassistant.setup import async_setup_component @@ -81,10 +83,20 @@ async def test_websocket( @pytest.mark.usefixtures("enable_custom_integrations") +@pytest.mark.parametrize( + "ignore_missing_translations", + [ + [ + "component.fake_integration.issues.test_issue.title", + "component.fake_integration.issues.test_issue.description", + ] + ], +) async def test_download_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, device_registry: dr.DeviceRegistry, + issue_registry: ir.IssueRegistry, ) -> None: """Test download diagnostics.""" config_entry = MockConfigEntry(domain="fake_integration") @@ -95,6 +107,18 @@ async def test_download_diagnostics( integration = await async_get_integration(hass, "fake_integration") original_manifest = integration.manifest.copy() original_manifest["codeowners"] = ["@test"] + + with freeze_time(datetime(2025, 7, 9, 14, 00, 00)): + issue_registry.async_get_or_create( + domain="fake_integration", + issue_id="test_issue", + breaks_in_ha_version="2023.10.0", + severity=ir.IssueSeverity.WARNING, + is_fixable=False, + is_persistent=True, + translation_key="test_issue", + ) + with patch.object(integration, "manifest", original_manifest): response = await _get_diagnostics_for_config_entry( hass, hass_client, config_entry @@ -179,6 +203,23 @@ async def test_download_diagnostics( "requirements": [], }, "data": {"config_entry": "info"}, + "issues": [ + { + "breaks_in_ha_version": "2023.10.0", + "created": "2025-07-09T14:00:00+00:00", + "data": None, + "dismissed_version": None, + "domain": "fake_integration", + "is_fixable": False, + "is_persistent": True, + "issue_domain": None, + "issue_id": "test_issue", + "learn_more_url": None, + "severity": "warning", + "translation_key": "test_issue", + "translation_placeholders": None, + }, + ], } device = device_registry.async_get_or_create( @@ -266,6 +307,23 @@ async def test_download_diagnostics( "requirements": [], }, "data": {"device": "info"}, + "issues": [ + { + "breaks_in_ha_version": "2023.10.0", + "created": "2025-07-09T14:00:00+00:00", + "data": None, + "dismissed_version": None, + "domain": "fake_integration", + "is_fixable": False, + "is_persistent": True, + "issue_domain": None, + "issue_id": "test_issue", + "learn_more_url": None, + "severity": "warning", + "translation_key": "test_issue", + "translation_placeholders": None, + }, + ], "setup_times": {}, } diff --git a/tests/components/emoncms/conftest.py b/tests/components/emoncms/conftest.py index 100fb2bd879..c9c1eafc838 100644 --- a/tests/components/emoncms/conftest.py +++ b/tests/components/emoncms/conftest.py @@ -43,6 +43,8 @@ FLOW_RESULT = { SENSOR_NAME = "emoncms@1.1.1.1" +UNIQUE_ID = "123-53535292" + @pytest.fixture def config_entry() -> MockConfigEntry: @@ -65,7 +67,7 @@ def config_entry_unique_id() -> MockConfigEntry: domain=DOMAIN, title=SENSOR_NAME, data=FLOW_RESULT_SECOND_URL, - unique_id="123-53535292", + unique_id=UNIQUE_ID, ) @@ -121,5 +123,5 @@ async def emoncms_client() -> AsyncGenerator[AsyncMock]: ): client = mock_client.return_value client.async_request.return_value = {"success": True, "message": FEEDS} - client.async_get_uuid.return_value = "123-53535292" + client.async_get_uuid.return_value = UNIQUE_ID yield client diff --git a/tests/components/emoncms/test_config_flow.py b/tests/components/emoncms/test_config_flow.py index 3157ccdd574..bbb994002ac 100644 --- a/tests/components/emoncms/test_config_flow.py +++ b/tests/components/emoncms/test_config_flow.py @@ -2,6 +2,8 @@ from unittest.mock import AsyncMock +import pytest + from homeassistant.components.emoncms.const import ( CONF_ONLY_INCLUDE_FEEDID, DOMAIN, @@ -15,7 +17,7 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from . import setup_integration -from .conftest import EMONCMS_FAILURE, FLOW_RESULT, SENSOR_NAME +from .conftest import EMONCMS_FAILURE, FLOW_RESULT, SENSOR_NAME, UNIQUE_ID from tests.common import MockConfigEntry @@ -25,6 +27,74 @@ USER_INPUT = { } +@pytest.mark.parametrize( + ("url", "api_key"), + [ + (USER_INPUT[CONF_URL], "regenerated_api_key"), + ("http://1.1.1.2", USER_INPUT[CONF_API_KEY]), + ], +) +async def test_reconfigure( + hass: HomeAssistant, + emoncms_client: AsyncMock, + url: str, + api_key: str, +) -> None: + """Test reconfigure flow.""" + new_input = { + CONF_URL: url, + CONF_API_KEY: api_key, + } + config_entry = MockConfigEntry( + domain=DOMAIN, + title=SENSOR_NAME, + data=new_input, + unique_id=UNIQUE_ID, + ) + await setup_integration(hass, config_entry) + result = await config_entry.start_reconfigure_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + new_input, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data == new_input + + +async def test_reconfigure_api_error( + hass: HomeAssistant, + emoncms_client: AsyncMock, +) -> None: + """Test reconfigure flow with API error.""" + config_entry = MockConfigEntry( + domain=DOMAIN, + title=SENSOR_NAME, + data=USER_INPUT, + unique_id=UNIQUE_ID, + ) + await setup_integration(hass, config_entry) + emoncms_client.async_request.return_value = EMONCMS_FAILURE + result = await config_entry.start_reconfigure_flow(hass) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + USER_INPUT, + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": "api_error"} + assert result["description_placeholders"]["details"] == "failure" + assert result["step_id"] == "reconfigure" + + async def test_user_flow_failure( hass: HomeAssistant, emoncms_client: AsyncMock ) -> None: diff --git a/tests/components/energy/test_sensor.py b/tests/components/energy/test_sensor.py index a9a249a8498..b7ccbadbe1c 100644 --- a/tests/components/energy/test_sensor.py +++ b/tests/components/energy/test_sensor.py @@ -29,6 +29,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util +from homeassistant.util.unit_conversion import _WH_TO_CAL, _WH_TO_J from homeassistant.util.unit_system import METRIC_SYSTEM, US_CUSTOMARY_SYSTEM from tests.components.recorder.common import async_wait_recording_done @@ -748,10 +749,12 @@ async def test_cost_sensor_price_entity_total_no_reset( @pytest.mark.parametrize( ("energy_unit", "factor"), [ + (UnitOfEnergy.MILLIWATT_HOUR, 1e6), (UnitOfEnergy.WATT_HOUR, 1000), (UnitOfEnergy.KILO_WATT_HOUR, 1), (UnitOfEnergy.MEGA_WATT_HOUR, 0.001), - (UnitOfEnergy.GIGA_JOULE, 0.001 * 3.6), + (UnitOfEnergy.GIGA_JOULE, _WH_TO_J / 1e6), + (UnitOfEnergy.CALORIE, _WH_TO_CAL * 1e3), ], ) async def test_cost_sensor_handle_energy_units( @@ -815,6 +818,7 @@ async def test_cost_sensor_handle_energy_units( @pytest.mark.parametrize( ("price_unit", "factor"), [ + (f"EUR/{UnitOfEnergy.MILLIWATT_HOUR}", 1e-6), (f"EUR/{UnitOfEnergy.WATT_HOUR}", 0.001), (f"EUR/{UnitOfEnergy.KILO_WATT_HOUR}", 1), (f"EUR/{UnitOfEnergy.MEGA_WATT_HOUR}", 1000), diff --git a/tests/components/energy/test_validate.py b/tests/components/energy/test_validate.py index 6389ac0b372..9e7a2151b04 100644 --- a/tests/components/energy/test_validate.py +++ b/tests/components/energy/test_validate.py @@ -12,6 +12,10 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.json import JSON_DUMP from homeassistant.setup import async_setup_component +ENERGY_UNITS_STRING = ", ".join(tuple(UnitOfEnergy)) + +ENERGY_PRICE_UNITS_STRING = ", ".join(f"EUR/{unit}" for unit in tuple(UnitOfEnergy)) + @pytest.fixture def mock_is_entity_recorded(): @@ -69,6 +73,7 @@ async def test_validation_empty_config(hass: HomeAssistant) -> None: @pytest.mark.parametrize( ("state_class", "energy_unit", "extra"), [ + ("total_increasing", UnitOfEnergy.MILLIWATT_HOUR, {}), ("total_increasing", UnitOfEnergy.KILO_WATT_HOUR, {}), ("total_increasing", UnitOfEnergy.MEGA_WATT_HOUR, {}), ("total_increasing", UnitOfEnergy.WATT_HOUR, {}), @@ -76,6 +81,7 @@ async def test_validation_empty_config(hass: HomeAssistant) -> None: ("total", UnitOfEnergy.KILO_WATT_HOUR, {"last_reset": "abc"}), ("measurement", UnitOfEnergy.KILO_WATT_HOUR, {"last_reset": "abc"}), ("total_increasing", UnitOfEnergy.GIGA_JOULE, {}), + ("total_increasing", UnitOfEnergy.CALORIE, {}), ], ) async def test_validation( @@ -235,9 +241,7 @@ async def test_validation_device_consumption_entity_unexpected_unit( { "type": "entity_unexpected_unit_energy", "affected_entities": {("sensor.unexpected_unit", "beers")}, - "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh" - }, + "translation_placeholders": {"energy_units": ENERGY_UNITS_STRING}, } ] ], @@ -325,9 +329,7 @@ async def test_validation_solar( { "type": "entity_unexpected_unit_energy", "affected_entities": {("sensor.solar_production", "beers")}, - "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh" - }, + "translation_placeholders": {"energy_units": ENERGY_UNITS_STRING}, } ] ], @@ -378,9 +380,7 @@ async def test_validation_battery( ("sensor.battery_import", "beers"), ("sensor.battery_export", "beers"), }, - "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh" - }, + "translation_placeholders": {"energy_units": ENERGY_UNITS_STRING}, }, ] ], @@ -449,9 +449,7 @@ async def test_validation_grid( ("sensor.grid_consumption_1", "beers"), ("sensor.grid_production_1", "beers"), }, - "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh" - }, + "translation_placeholders": {"energy_units": ENERGY_UNITS_STRING}, }, { "type": "statistics_not_defined", @@ -538,9 +536,7 @@ async def test_validation_grid_external_cost_compensation( ("sensor.grid_consumption_1", "beers"), ("sensor.grid_production_1", "beers"), }, - "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh" - }, + "translation_placeholders": {"energy_units": ENERGY_UNITS_STRING}, }, { "type": "statistics_not_defined", @@ -710,9 +706,7 @@ async def test_validation_grid_auto_cost_entity_errors( { "type": "entity_unexpected_unit_energy_price", "affected_entities": {("sensor.grid_price_1", "$/Ws")}, - "translation_placeholders": { - "price_units": "EUR/GJ, EUR/kWh, EUR/MJ, EUR/MWh, EUR/Wh" - }, + "translation_placeholders": {"price_units": ENERGY_PRICE_UNITS_STRING}, }, ), ], @@ -855,7 +849,7 @@ async def test_validation_gas( "type": "entity_unexpected_unit_gas", "affected_entities": {("sensor.gas_consumption_1", "beers")}, "translation_placeholders": { - "energy_units": "GJ, kWh, MJ, MWh, Wh", + "energy_units": ENERGY_UNITS_STRING, "gas_units": "CCF, ft³, m³, L", }, }, @@ -885,7 +879,7 @@ async def test_validation_gas( "affected_entities": {("sensor.gas_price_2", "EUR/invalid")}, "translation_placeholders": { "price_units": ( - "EUR/GJ, EUR/kWh, EUR/MJ, EUR/MWh, EUR/Wh, EUR/CCF, EUR/ft³, EUR/m³, EUR/L" + f"{ENERGY_PRICE_UNITS_STRING}, EUR/CCF, EUR/ft³, EUR/m³, EUR/L" ) }, }, diff --git a/tests/components/eq3btsmart/conftest.py b/tests/components/eq3btsmart/conftest.py index 92f1be29b70..ce55a1fccbd 100644 --- a/tests/components/eq3btsmart/conftest.py +++ b/tests/components/eq3btsmart/conftest.py @@ -28,7 +28,7 @@ def fake_service_info(): source="local", connectable=False, time=0, - device=generate_ble_device(address=MAC, name="CC-RT-BLE", rssi=0), + device=generate_ble_device(address=MAC, name="CC-RT-BLE"), advertisement=AdvertisementData( local_name="CC-RT-BLE", manufacturer_data={}, diff --git a/tests/components/esphome/bluetooth/test_client.py b/tests/components/esphome/bluetooth/test_client.py index 554f1725f4b..86db1fc3109 100644 --- a/tests/components/esphome/bluetooth/test_client.py +++ b/tests/components/esphome/bluetooth/test_client.py @@ -55,4 +55,4 @@ async def test_client_usage_while_not_connected(client_data: ESPHomeClientData) with pytest.raises( BleakError, match=f"{ESP_NAME}.*{ESP_MAC_ADDRESS}.*not connected" ): - assert await client.write_gatt_char("test", b"test") is False + assert await client.write_gatt_char("test", b"test", False) is False diff --git a/tests/components/esphome/test_alarm_control_panel.py b/tests/components/esphome/test_alarm_control_panel.py index 62924404458..e06b88432a9 100644 --- a/tests/components/esphome/test_alarm_control_panel.py +++ b/tests/components/esphome/test_alarm_control_panel.py @@ -73,7 +73,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.ARM_AWAY, "1234")] + [call(1, AlarmControlPanelCommand.ARM_AWAY, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -87,7 +87,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.ARM_CUSTOM_BYPASS, "1234")] + [call(1, AlarmControlPanelCommand.ARM_CUSTOM_BYPASS, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -101,7 +101,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.ARM_HOME, "1234")] + [call(1, AlarmControlPanelCommand.ARM_HOME, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -115,7 +115,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.ARM_NIGHT, "1234")] + [call(1, AlarmControlPanelCommand.ARM_NIGHT, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -129,7 +129,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.ARM_VACATION, "1234")] + [call(1, AlarmControlPanelCommand.ARM_VACATION, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -143,7 +143,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.TRIGGER, "1234")] + [call(1, AlarmControlPanelCommand.TRIGGER, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -157,7 +157,7 @@ async def test_generic_alarm_control_panel_requires_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.DISARM, "1234")] + [call(1, AlarmControlPanelCommand.DISARM, "1234", device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() @@ -203,7 +203,7 @@ async def test_generic_alarm_control_panel_no_code( blocking=True, ) mock_client.alarm_control_panel_command.assert_has_calls( - [call(1, AlarmControlPanelCommand.DISARM, None)] + [call(1, AlarmControlPanelCommand.DISARM, None, device_id=0)] ) mock_client.alarm_control_panel_command.reset_mock() diff --git a/tests/components/esphome/test_binary_sensor.py b/tests/components/esphome/test_binary_sensor.py index d2cab36c672..d6e94e61766 100644 --- a/tests/components/esphome/test_binary_sensor.py +++ b/tests/components/esphome/test_binary_sensor.py @@ -1,6 +1,6 @@ """Test ESPHome binary sensors.""" -from aioesphomeapi import APIClient, BinarySensorInfo, BinarySensorState +from aioesphomeapi import APIClient, BinarySensorInfo, BinarySensorState, SubDeviceInfo import pytest from homeassistant.const import STATE_OFF, STATE_ON, STATE_UNKNOWN @@ -127,3 +127,157 @@ async def test_binary_sensor_has_state_false( state = hass.states.get("binary_sensor.test_my_binary_sensor") assert state is not None assert state.state == STATE_ON + + +async def test_binary_sensors_same_key_different_device_id( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test binary sensors with same key but different device_id.""" + # Create sub-devices + sub_devices = [ + SubDeviceInfo(device_id=11111111, name="Sub Device 1", area_id=0), + SubDeviceInfo(device_id=22222222, name="Sub Device 2", area_id=0), + ] + + device_info = { + "name": "test", + "devices": sub_devices, + } + + # Both sub-devices have a binary sensor with key=1 + entity_info = [ + BinarySensorInfo( + object_id="sensor", + key=1, + name="Motion", + unique_id="motion_1", + device_id=11111111, + ), + BinarySensorInfo( + object_id="sensor", + key=1, + name="Motion", + unique_id="motion_2", + device_id=22222222, + ), + ] + + # States for both sensors with same key but different device_id + states = [ + BinarySensorState(key=1, state=True, missing_state=False, device_id=11111111), + BinarySensorState(key=1, state=False, missing_state=False, device_id=22222222), + ] + + mock_device = await mock_esphome_device( + mock_client=mock_client, + device_info=device_info, + entity_info=entity_info, + states=states, + ) + + # Verify both entities exist and have correct states + state1 = hass.states.get("binary_sensor.sub_device_1_motion") + assert state1 is not None + assert state1.state == STATE_ON + + state2 = hass.states.get("binary_sensor.sub_device_2_motion") + assert state2 is not None + assert state2.state == STATE_OFF + + # Update states to verify they update independently + mock_device.set_state( + BinarySensorState(key=1, state=False, missing_state=False, device_id=11111111) + ) + await hass.async_block_till_done() + + state1 = hass.states.get("binary_sensor.sub_device_1_motion") + assert state1.state == STATE_OFF + + # Sub device 2 should remain unchanged + state2 = hass.states.get("binary_sensor.sub_device_2_motion") + assert state2.state == STATE_OFF + + # Update sub device 2 + mock_device.set_state( + BinarySensorState(key=1, state=True, missing_state=False, device_id=22222222) + ) + await hass.async_block_till_done() + + state2 = hass.states.get("binary_sensor.sub_device_2_motion") + assert state2.state == STATE_ON + + # Sub device 1 should remain unchanged + state1 = hass.states.get("binary_sensor.sub_device_1_motion") + assert state1.state == STATE_OFF + + +async def test_binary_sensor_main_and_sub_device_same_key( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test binary sensor on main device and sub-device with same key.""" + # Create sub-device + sub_devices = [ + SubDeviceInfo(device_id=11111111, name="Sub Device", area_id=0), + ] + + device_info = { + "name": "test", + "devices": sub_devices, + } + + # Main device and sub-device both have a binary sensor with key=1 + entity_info = [ + BinarySensorInfo( + object_id="main_sensor", + key=1, + name="Main Sensor", + unique_id="main_1", + device_id=0, # Main device + ), + BinarySensorInfo( + object_id="sub_sensor", + key=1, + name="Sub Sensor", + unique_id="sub_1", + device_id=11111111, + ), + ] + + # States for both sensors + states = [ + BinarySensorState(key=1, state=True, missing_state=False, device_id=0), + BinarySensorState(key=1, state=False, missing_state=False, device_id=11111111), + ] + + mock_device = await mock_esphome_device( + mock_client=mock_client, + device_info=device_info, + entity_info=entity_info, + states=states, + ) + + # Verify both entities exist + main_state = hass.states.get("binary_sensor.test_main_sensor") + assert main_state is not None + assert main_state.state == STATE_ON + + sub_state = hass.states.get("binary_sensor.sub_device_sub_sensor") + assert sub_state is not None + assert sub_state.state == STATE_OFF + + # Update main device sensor + mock_device.set_state( + BinarySensorState(key=1, state=False, missing_state=False, device_id=0) + ) + await hass.async_block_till_done() + + main_state = hass.states.get("binary_sensor.test_main_sensor") + assert main_state.state == STATE_OFF + + # Sub device sensor should remain unchanged + sub_state = hass.states.get("binary_sensor.sub_device_sub_sensor") + assert sub_state.state == STATE_OFF diff --git a/tests/components/esphome/test_button.py b/tests/components/esphome/test_button.py index d3fec2a56d2..3cedc3526d4 100644 --- a/tests/components/esphome/test_button.py +++ b/tests/components/esphome/test_button.py @@ -39,7 +39,7 @@ async def test_button_generic_entity( {ATTR_ENTITY_ID: "button.test_my_button"}, blocking=True, ) - mock_client.button_command.assert_has_calls([call(1)]) + mock_client.button_command.assert_has_calls([call(1, device_id=0)]) state = hass.states.get("button.test_my_button") assert state is not None assert state.state != STATE_UNKNOWN diff --git a/tests/components/esphome/test_climate.py b/tests/components/esphome/test_climate.py index 3c529adf21f..5c907eef3b1 100644 --- a/tests/components/esphome/test_climate.py +++ b/tests/components/esphome/test_climate.py @@ -93,7 +93,9 @@ async def test_climate_entity( {ATTR_ENTITY_ID: "climate.test_my_climate", ATTR_TEMPERATURE: 25}, blocking=True, ) - mock_client.climate_command.assert_has_calls([call(key=1, target_temperature=25.0)]) + mock_client.climate_command.assert_has_calls( + [call(key=1, target_temperature=25.0, device_id=0)] + ) mock_client.climate_command.reset_mock() @@ -167,6 +169,7 @@ async def test_climate_entity_with_step_and_two_point( mode=ClimateMode.AUTO, target_temperature_low=20.0, target_temperature_high=30.0, + device_id=0, ) ] ) @@ -232,7 +235,7 @@ async def test_climate_entity_with_step_and_target_temp( blocking=True, ) mock_client.climate_command.assert_has_calls( - [call(key=1, mode=ClimateMode.AUTO, target_temperature=25.0)] + [call(key=1, mode=ClimateMode.AUTO, target_temperature=25.0, device_id=0)] ) mock_client.climate_command.reset_mock() @@ -263,6 +266,7 @@ async def test_climate_entity_with_step_and_target_temp( call( key=1, mode=ClimateMode.HEAT, + device_id=0, ) ] ) @@ -279,6 +283,7 @@ async def test_climate_entity_with_step_and_target_temp( call( key=1, preset=ClimatePreset.AWAY, + device_id=0, ) ] ) @@ -290,7 +295,9 @@ async def test_climate_entity_with_step_and_target_temp( {ATTR_ENTITY_ID: "climate.test_my_climate", ATTR_PRESET_MODE: "preset1"}, blocking=True, ) - mock_client.climate_command.assert_has_calls([call(key=1, custom_preset="preset1")]) + mock_client.climate_command.assert_has_calls( + [call(key=1, custom_preset="preset1", device_id=0)] + ) mock_client.climate_command.reset_mock() await hass.services.async_call( @@ -300,7 +307,7 @@ async def test_climate_entity_with_step_and_target_temp( blocking=True, ) mock_client.climate_command.assert_has_calls( - [call(key=1, fan_mode=ClimateFanMode.HIGH)] + [call(key=1, fan_mode=ClimateFanMode.HIGH, device_id=0)] ) mock_client.climate_command.reset_mock() @@ -310,7 +317,9 @@ async def test_climate_entity_with_step_and_target_temp( {ATTR_ENTITY_ID: "climate.test_my_climate", ATTR_FAN_MODE: "fan2"}, blocking=True, ) - mock_client.climate_command.assert_has_calls([call(key=1, custom_fan_mode="fan2")]) + mock_client.climate_command.assert_has_calls( + [call(key=1, custom_fan_mode="fan2", device_id=0)] + ) mock_client.climate_command.reset_mock() await hass.services.async_call( @@ -320,7 +329,7 @@ async def test_climate_entity_with_step_and_target_temp( blocking=True, ) mock_client.climate_command.assert_has_calls( - [call(key=1, swing_mode=ClimateSwingMode.BOTH)] + [call(key=1, swing_mode=ClimateSwingMode.BOTH, device_id=0)] ) mock_client.climate_command.reset_mock() @@ -383,7 +392,9 @@ async def test_climate_entity_with_humidity( {ATTR_ENTITY_ID: "climate.test_my_climate", ATTR_HUMIDITY: 23}, blocking=True, ) - mock_client.climate_command.assert_has_calls([call(key=1, target_humidity=23)]) + mock_client.climate_command.assert_has_calls( + [call(key=1, target_humidity=23, device_id=0)] + ) mock_client.climate_command.reset_mock() diff --git a/tests/components/esphome/test_cover.py b/tests/components/esphome/test_cover.py index f6ec9f20d6b..93524905f6b 100644 --- a/tests/components/esphome/test_cover.py +++ b/tests/components/esphome/test_cover.py @@ -74,7 +74,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover"}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, position=0.0)]) + mock_client.cover_command.assert_has_calls([call(key=1, position=0.0, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -83,7 +83,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover"}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, position=1.0)]) + mock_client.cover_command.assert_has_calls([call(key=1, position=1.0, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -92,7 +92,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover", ATTR_POSITION: 50}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, position=0.5)]) + mock_client.cover_command.assert_has_calls([call(key=1, position=0.5, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -101,7 +101,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover"}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, stop=True)]) + mock_client.cover_command.assert_has_calls([call(key=1, stop=True, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -110,7 +110,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover"}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, tilt=1.0)]) + mock_client.cover_command.assert_has_calls([call(key=1, tilt=1.0, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -119,7 +119,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover"}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, tilt=0.0)]) + mock_client.cover_command.assert_has_calls([call(key=1, tilt=0.0, device_id=0)]) mock_client.cover_command.reset_mock() await hass.services.async_call( @@ -128,7 +128,7 @@ async def test_cover_entity( {ATTR_ENTITY_ID: "cover.test_my_cover", ATTR_TILT_POSITION: 50}, blocking=True, ) - mock_client.cover_command.assert_has_calls([call(key=1, tilt=0.5)]) + mock_client.cover_command.assert_has_calls([call(key=1, tilt=0.5, device_id=0)]) mock_client.cover_command.reset_mock() mock_device.set_state( diff --git a/tests/components/esphome/test_date.py b/tests/components/esphome/test_date.py index 331c3d50bd4..387838e0b23 100644 --- a/tests/components/esphome/test_date.py +++ b/tests/components/esphome/test_date.py @@ -47,7 +47,7 @@ async def test_generic_date_entity( {ATTR_ENTITY_ID: "date.test_my_date", ATTR_DATE: "1999-01-01"}, blocking=True, ) - mock_client.date_command.assert_has_calls([call(1, 1999, 1, 1)]) + mock_client.date_command.assert_has_calls([call(1, 1999, 1, 1, device_id=0)]) mock_client.date_command.reset_mock() diff --git a/tests/components/esphome/test_datetime.py b/tests/components/esphome/test_datetime.py index 63ca02360fd..6fcfe7ed947 100644 --- a/tests/components/esphome/test_datetime.py +++ b/tests/components/esphome/test_datetime.py @@ -50,7 +50,7 @@ async def test_generic_datetime_entity( }, blocking=True, ) - mock_client.datetime_command.assert_has_calls([call(1, 946689825)]) + mock_client.datetime_command.assert_has_calls([call(1, 946689825, device_id=0)]) mock_client.datetime_command.reset_mock() diff --git a/tests/components/esphome/test_entity.py b/tests/components/esphome/test_entity.py index ba6a82bbd23..f364e1f528f 100644 --- a/tests/components/esphome/test_entity.py +++ b/tests/components/esphome/test_entity.py @@ -754,9 +754,9 @@ async def test_entity_assignment_to_sub_device( ] states = [ - BinarySensorState(key=1, state=True, missing_state=False), - BinarySensorState(key=2, state=False, missing_state=False), - BinarySensorState(key=3, state=True, missing_state=False), + BinarySensorState(key=1, state=True, missing_state=False, device_id=0), + BinarySensorState(key=2, state=False, missing_state=False, device_id=11111111), + BinarySensorState(key=3, state=True, missing_state=False, device_id=22222222), ] device = await mock_esphome_device( @@ -938,7 +938,7 @@ async def test_entity_switches_between_devices( ] states = [ - BinarySensorState(key=1, state=True, missing_state=False), + BinarySensorState(key=1, state=True, missing_state=False, device_id=0), ] device = await mock_esphome_device( @@ -1507,7 +1507,7 @@ async def test_entity_device_id_rename_in_yaml( ] states = [ - BinarySensorState(key=1, state=True, missing_state=False), + BinarySensorState(key=1, state=True, missing_state=False, device_id=11111111), ] device = await mock_esphome_device( diff --git a/tests/components/esphome/test_fan.py b/tests/components/esphome/test_fan.py index 558acb281b5..a33be1a6fca 100644 --- a/tests/components/esphome/test_fan.py +++ b/tests/components/esphome/test_fan.py @@ -77,7 +77,7 @@ async def test_fan_entity_with_all_features_old_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, speed=FanSpeed.LOW, state=True)] + [call(key=1, speed=FanSpeed.LOW, state=True, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -88,7 +88,7 @@ async def test_fan_entity_with_all_features_old_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, speed=FanSpeed.MEDIUM, state=True)] + [call(key=1, speed=FanSpeed.MEDIUM, state=True, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -99,7 +99,7 @@ async def test_fan_entity_with_all_features_old_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, speed=FanSpeed.LOW, state=True)] + [call(key=1, speed=FanSpeed.LOW, state=True, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -110,7 +110,7 @@ async def test_fan_entity_with_all_features_old_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, speed=FanSpeed.HIGH, state=True)] + [call(key=1, speed=FanSpeed.HIGH, state=True, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -120,7 +120,7 @@ async def test_fan_entity_with_all_features_old_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, state=False)]) + mock_client.fan_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -130,7 +130,7 @@ async def test_fan_entity_with_all_features_old_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, speed=FanSpeed.HIGH, state=True)] + [call(key=1, speed=FanSpeed.HIGH, state=True, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -182,7 +182,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PERCENTAGE: 20}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, speed_level=1, state=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, speed_level=1, state=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -191,7 +193,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PERCENTAGE: 50}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, speed_level=2, state=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, speed_level=2, state=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -200,7 +204,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, speed_level=2, state=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, speed_level=2, state=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -209,7 +215,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, speed_level=4, state=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, speed_level=4, state=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -218,7 +226,7 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, state=False)]) + mock_client.fan_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -227,7 +235,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PERCENTAGE: 100}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, speed_level=4, state=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, speed_level=4, state=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -236,7 +246,7 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PERCENTAGE: 0}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, state=False)]) + mock_client.fan_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -245,7 +255,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_OSCILLATING: True}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, oscillating=True)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, oscillating=True, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -254,7 +266,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_OSCILLATING: False}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, oscillating=False)]) + mock_client.fan_command.assert_has_calls( + [call(key=1, oscillating=False, device_id=0)] + ) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -264,7 +278,7 @@ async def test_fan_entity_with_all_features_new_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, direction=FanDirection.FORWARD)] + [call(key=1, direction=FanDirection.FORWARD, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -275,7 +289,7 @@ async def test_fan_entity_with_all_features_new_api( blocking=True, ) mock_client.fan_command.assert_has_calls( - [call(key=1, direction=FanDirection.REVERSE)] + [call(key=1, direction=FanDirection.REVERSE, device_id=0)] ) mock_client.fan_command.reset_mock() @@ -285,7 +299,9 @@ async def test_fan_entity_with_all_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PRESET_MODE: "Preset1"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, preset_mode="Preset1")]) + mock_client.fan_command.assert_has_calls( + [call(key=1, preset_mode="Preset1", device_id=0)] + ) mock_client.fan_command.reset_mock() @@ -326,7 +342,7 @@ async def test_fan_entity_with_no_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, state=True)]) + mock_client.fan_command.assert_has_calls([call(key=1, state=True, device_id=0)]) mock_client.fan_command.reset_mock() await hass.services.async_call( @@ -335,5 +351,5 @@ async def test_fan_entity_with_no_features_new_api( {ATTR_ENTITY_ID: "fan.test_my_fan"}, blocking=True, ) - mock_client.fan_command.assert_has_calls([call(key=1, state=False)]) + mock_client.fan_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.fan_command.reset_mock() diff --git a/tests/components/esphome/test_light.py b/tests/components/esphome/test_light.py index 34ada36a4f8..4377a714b17 100644 --- a/tests/components/esphome/test_light.py +++ b/tests/components/esphome/test_light.py @@ -81,7 +81,7 @@ async def test_light_on_off( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=True, color_mode=LightColorCapability.ON_OFF)] + [call(key=1, state=True, color_mode=LightColorCapability.ON_OFF, device_id=0)] ) mock_client.light_command.reset_mock() @@ -123,7 +123,14 @@ async def test_light_brightness( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=True, color_mode=LightColorCapability.BRIGHTNESS)] + [ + call( + key=1, + state=True, + color_mode=LightColorCapability.BRIGHTNESS, + device_id=0, + ) + ] ) mock_client.light_command.reset_mock() @@ -140,6 +147,7 @@ async def test_light_brightness( state=True, color_mode=LightColorCapability.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -152,7 +160,7 @@ async def test_light_brightness( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=False, transition_length=2.0)] + [call(key=1, state=False, transition_length=2.0, device_id=0)] ) mock_client.light_command.reset_mock() @@ -163,7 +171,7 @@ async def test_light_brightness( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=False, flash_length=10.0)] + [call(key=1, state=False, flash_length=10.0, device_id=0)] ) mock_client.light_command.reset_mock() @@ -180,6 +188,7 @@ async def test_light_brightness( state=True, transition_length=2.0, color_mode=LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -198,6 +207,7 @@ async def test_light_brightness( state=True, flash_length=2.0, color_mode=LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -248,7 +258,14 @@ async def test_light_legacy_brightness( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=True, color_mode=LightColorCapability.BRIGHTNESS)] + [ + call( + key=1, + state=True, + color_mode=LightColorCapability.BRIGHTNESS, + device_id=0, + ) + ] ) mock_client.light_command.reset_mock() @@ -303,6 +320,7 @@ async def test_light_brightness_on_off( key=1, state=True, color_mode=ESPColorMode.BRIGHTNESS.value, + device_id=0, ) ] ) @@ -321,6 +339,7 @@ async def test_light_brightness_on_off( state=True, color_mode=ESPColorMode.BRIGHTNESS.value, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -375,6 +394,7 @@ async def test_light_legacy_white_converted_to_brightness( color_mode=LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS | LightColorCapability.WHITE, + device_id=0, ) ] ) @@ -439,6 +459,7 @@ async def test_light_legacy_white_with_rgb( brightness=pytest.approx(0.23529411764705882), white=1.0, color_mode=color_mode, + device_id=0, ) ] ) @@ -496,6 +517,7 @@ async def test_light_brightness_on_off_with_unknown_color_mode( key=1, state=True, color_mode=LIGHT_COLOR_CAPABILITY_UNKNOWN, + device_id=0, ) ] ) @@ -514,6 +536,7 @@ async def test_light_brightness_on_off_with_unknown_color_mode( state=True, color_mode=ESPColorMode.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -560,7 +583,7 @@ async def test_light_on_and_brightness( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=True, color_mode=LightColorCapability.ON_OFF)] + [call(key=1, state=True, color_mode=LightColorCapability.ON_OFF, device_id=0)] ) mock_client.light_command.reset_mock() @@ -618,6 +641,7 @@ async def test_rgb_color_temp_light( key=1, state=True, color_mode=ESPColorMode.BRIGHTNESS, + device_id=0, ) ] ) @@ -636,6 +660,7 @@ async def test_rgb_color_temp_light( state=True, color_mode=ESPColorMode.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -654,6 +679,7 @@ async def test_rgb_color_temp_light( state=True, color_mode=ESPColorMode.COLOR_TEMPERATURE, color_temperature=400, + device_id=0, ) ] ) @@ -706,6 +732,7 @@ async def test_light_rgb( color_mode=LightColorCapability.RGB | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -726,6 +753,7 @@ async def test_light_rgb( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -752,6 +780,7 @@ async def test_light_rgb( | LightColorCapability.BRIGHTNESS, rgb=(pytest.approx(0.3333333333333333), 1.0, 0.0), brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -773,6 +802,7 @@ async def test_light_rgb( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(1, 1, 1), + device_id=0, ) ] ) @@ -843,6 +873,7 @@ async def test_light_rgbw( | LightColorCapability.WHITE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -864,6 +895,7 @@ async def test_light_rgbw( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -892,6 +924,7 @@ async def test_light_rgbw( white=0, rgb=(pytest.approx(0.3333333333333333), 1.0, 0.0), brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -915,6 +948,7 @@ async def test_light_rgbw( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(0, 0, 0), + device_id=0, ) ] ) @@ -938,6 +972,7 @@ async def test_light_rgbw( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(1, 1, 1), + device_id=0, ) ] ) @@ -1017,6 +1052,7 @@ async def test_light_rgbww_with_cold_warm_white_support( key=1, state=True, color_mode=ESPColorMode.RGB_COLD_WARM_WHITE, + device_id=0, ) ] ) @@ -1035,6 +1071,7 @@ async def test_light_rgbww_with_cold_warm_white_support( state=True, color_mode=ESPColorMode.RGB_COLD_WARM_WHITE, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -1059,6 +1096,7 @@ async def test_light_rgbww_with_cold_warm_white_support( color_mode=ESPColorMode.RGB, rgb=(pytest.approx(0.3333333333333333), 1.0, 0.0), brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -1078,6 +1116,7 @@ async def test_light_rgbww_with_cold_warm_white_support( color_brightness=1.0, color_mode=ESPColorMode.RGB, rgb=(1.0, 1.0, 1.0), + device_id=0, ) ] ) @@ -1098,6 +1137,7 @@ async def test_light_rgbww_with_cold_warm_white_support( white=1, color_mode=ESPColorMode.RGB_WHITE, rgb=(1.0, 1.0, 1.0), + device_id=0, ) ] ) @@ -1122,6 +1162,7 @@ async def test_light_rgbww_with_cold_warm_white_support( warm_white=1, color_mode=ESPColorMode.RGB_COLD_WARM_WHITE, rgb=(1, 1, 1), + device_id=0, ) ] ) @@ -1140,6 +1181,7 @@ async def test_light_rgbww_with_cold_warm_white_support( state=True, color_temperature=400.0, color_mode=ESPColorMode.COLOR_TEMPERATURE, + device_id=0, ) ] ) @@ -1217,6 +1259,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -1239,6 +1282,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -1268,6 +1312,7 @@ async def test_light_rgbww_without_cold_warm_white_support( white=0, rgb=(pytest.approx(0.3333333333333333), 1.0, 0.0), brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -1294,6 +1339,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(0, pytest.approx(0.5462962962962963), 1.0), + device_id=0, ) ] ) @@ -1319,6 +1365,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(0, pytest.approx(0.5462962962962963), 1.0), + device_id=0, ) ] ) @@ -1347,6 +1394,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(1, 1, 1), + device_id=0, ) ] ) @@ -1372,6 +1420,7 @@ async def test_light_rgbww_without_cold_warm_white_support( | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, rgb=(0, 0, 0), + device_id=0, ) ] ) @@ -1437,6 +1486,7 @@ async def test_light_color_temp( color_mode=LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -1448,7 +1498,7 @@ async def test_light_color_temp( {ATTR_ENTITY_ID: "light.test_my_light"}, blocking=True, ) - mock_client.light_command.assert_has_calls([call(key=1, state=False)]) + mock_client.light_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.light_command.reset_mock() @@ -1511,6 +1561,7 @@ async def test_light_color_temp_no_mireds_set( color_mode=LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -1531,6 +1582,7 @@ async def test_light_color_temp_no_mireds_set( color_mode=LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -1542,7 +1594,7 @@ async def test_light_color_temp_no_mireds_set( {ATTR_ENTITY_ID: "light.test_my_light"}, blocking=True, ) - mock_client.light_command.assert_has_calls([call(key=1, state=False)]) + mock_client.light_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.light_command.reset_mock() @@ -1615,6 +1667,7 @@ async def test_light_color_temp_legacy( color_mode=LightColorCapability.COLOR_TEMPERATURE | LightColorCapability.ON_OFF | LightColorCapability.BRIGHTNESS, + device_id=0, ) ] ) @@ -1626,7 +1679,7 @@ async def test_light_color_temp_legacy( {ATTR_ENTITY_ID: "light.test_my_light"}, blocking=True, ) - mock_client.light_command.assert_has_calls([call(key=1, state=False)]) + mock_client.light_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.light_command.reset_mock() @@ -1695,6 +1748,7 @@ async def test_light_rgb_legacy( call( key=1, state=True, + device_id=0, ) ] ) @@ -1706,7 +1760,7 @@ async def test_light_rgb_legacy( {ATTR_ENTITY_ID: "light.test_my_light"}, blocking=True, ) - mock_client.light_command.assert_has_calls([call(key=1, state=False)]) + mock_client.light_command.assert_has_calls([call(key=1, state=False, device_id=0)]) mock_client.light_command.reset_mock() await hass.services.async_call( @@ -1722,6 +1776,7 @@ async def test_light_rgb_legacy( state=True, rgb=(1.0, 1.0, 1.0), color_brightness=1.0, + device_id=0, ) ] ) @@ -1780,6 +1835,7 @@ async def test_light_effects( state=True, color_mode=ESPColorMode.BRIGHTNESS, effect="effect1", + device_id=0, ) ] ) @@ -1843,7 +1899,7 @@ async def test_only_cold_warm_white_support( blocking=True, ) mock_client.light_command.assert_has_calls( - [call(key=1, state=True, color_mode=color_modes)] + [call(key=1, state=True, color_mode=color_modes, device_id=0)] ) mock_client.light_command.reset_mock() @@ -1860,6 +1916,7 @@ async def test_only_cold_warm_white_support( state=True, color_mode=color_modes, brightness=pytest.approx(0.4980392156862745), + device_id=0, ) ] ) @@ -1878,6 +1935,7 @@ async def test_only_cold_warm_white_support( state=True, color_mode=color_modes, color_temperature=400.0, + device_id=0, ) ] ) @@ -1922,5 +1980,7 @@ async def test_light_no_color_modes( {ATTR_ENTITY_ID: "light.test_my_light"}, blocking=True, ) - mock_client.light_command.assert_has_calls([call(key=1, state=True, color_mode=0)]) + mock_client.light_command.assert_has_calls( + [call(key=1, state=True, color_mode=0, device_id=0)] + ) mock_client.light_command.reset_mock() diff --git a/tests/components/esphome/test_lock.py b/tests/components/esphome/test_lock.py index ab16311fc68..eaa03947a7d 100644 --- a/tests/components/esphome/test_lock.py +++ b/tests/components/esphome/test_lock.py @@ -57,7 +57,7 @@ async def test_lock_entity_no_open( {ATTR_ENTITY_ID: "lock.test_my_lock"}, blocking=True, ) - mock_client.lock_command.assert_has_calls([call(1, LockCommand.LOCK)]) + mock_client.lock_command.assert_has_calls([call(1, LockCommand.LOCK, device_id=0)]) mock_client.lock_command.reset_mock() @@ -122,7 +122,7 @@ async def test_lock_entity_supports_open( {ATTR_ENTITY_ID: "lock.test_my_lock"}, blocking=True, ) - mock_client.lock_command.assert_has_calls([call(1, LockCommand.LOCK)]) + mock_client.lock_command.assert_has_calls([call(1, LockCommand.LOCK, device_id=0)]) mock_client.lock_command.reset_mock() await hass.services.async_call( @@ -131,7 +131,9 @@ async def test_lock_entity_supports_open( {ATTR_ENTITY_ID: "lock.test_my_lock"}, blocking=True, ) - mock_client.lock_command.assert_has_calls([call(1, LockCommand.UNLOCK, None)]) + mock_client.lock_command.assert_has_calls( + [call(1, LockCommand.UNLOCK, None, device_id=0)] + ) mock_client.lock_command.reset_mock() await hass.services.async_call( @@ -140,4 +142,4 @@ async def test_lock_entity_supports_open( {ATTR_ENTITY_ID: "lock.test_my_lock"}, blocking=True, ) - mock_client.lock_command.assert_has_calls([call(1, LockCommand.OPEN)]) + mock_client.lock_command.assert_has_calls([call(1, LockCommand.OPEN, device_id=0)]) diff --git a/tests/components/esphome/test_media_player.py b/tests/components/esphome/test_media_player.py index ecd0ec4cb8b..6d7a3b220d1 100644 --- a/tests/components/esphome/test_media_player.py +++ b/tests/components/esphome/test_media_player.py @@ -85,7 +85,7 @@ async def test_media_player_entity( blocking=True, ) mock_client.media_player_command.assert_has_calls( - [call(1, command=MediaPlayerCommand.MUTE)] + [call(1, command=MediaPlayerCommand.MUTE, device_id=0)] ) mock_client.media_player_command.reset_mock() @@ -99,7 +99,7 @@ async def test_media_player_entity( blocking=True, ) mock_client.media_player_command.assert_has_calls( - [call(1, command=MediaPlayerCommand.MUTE)] + [call(1, command=MediaPlayerCommand.MUTE, device_id=0)] ) mock_client.media_player_command.reset_mock() @@ -112,7 +112,9 @@ async def test_media_player_entity( }, blocking=True, ) - mock_client.media_player_command.assert_has_calls([call(1, volume=0.5)]) + mock_client.media_player_command.assert_has_calls( + [call(1, volume=0.5, device_id=0)] + ) mock_client.media_player_command.reset_mock() await hass.services.async_call( @@ -124,7 +126,7 @@ async def test_media_player_entity( blocking=True, ) mock_client.media_player_command.assert_has_calls( - [call(1, command=MediaPlayerCommand.PAUSE)] + [call(1, command=MediaPlayerCommand.PAUSE, device_id=0)] ) mock_client.media_player_command.reset_mock() @@ -137,7 +139,7 @@ async def test_media_player_entity( blocking=True, ) mock_client.media_player_command.assert_has_calls( - [call(1, command=MediaPlayerCommand.PLAY)] + [call(1, command=MediaPlayerCommand.PLAY, device_id=0)] ) mock_client.media_player_command.reset_mock() @@ -150,7 +152,7 @@ async def test_media_player_entity( blocking=True, ) mock_client.media_player_command.assert_has_calls( - [call(1, command=MediaPlayerCommand.STOP)] + [call(1, command=MediaPlayerCommand.STOP, device_id=0)] ) mock_client.media_player_command.reset_mock() @@ -257,7 +259,14 @@ async def test_media_player_entity_with_source( ) mock_client.media_player_command.assert_has_calls( - [call(1, media_url="http://www.example.com/xy.mp3", announcement=None)] + [ + call( + 1, + media_url="http://www.example.com/xy.mp3", + announcement=None, + device_id=0, + ) + ] ) client = await hass_ws_client() @@ -284,7 +293,14 @@ async def test_media_player_entity_with_source( ) mock_client.media_player_command.assert_has_calls( - [call(1, media_url="media-source://tts?message=hello", announcement=True)] + [ + call( + 1, + media_url="media-source://tts?message=hello", + announcement=True, + device_id=0, + ) + ] ) diff --git a/tests/components/esphome/test_number.py b/tests/components/esphome/test_number.py index 932d86c70e3..d7a59222d47 100644 --- a/tests/components/esphome/test_number.py +++ b/tests/components/esphome/test_number.py @@ -60,7 +60,7 @@ async def test_generic_number_entity( {ATTR_ENTITY_ID: "number.test_my_number", ATTR_VALUE: 50}, blocking=True, ) - mock_client.number_command.assert_has_calls([call(1, 50)]) + mock_client.number_command.assert_has_calls([call(1, 50, device_id=0)]) mock_client.number_command.reset_mock() diff --git a/tests/components/esphome/test_select.py b/tests/components/esphome/test_select.py index a30075b5833..6b7415889d8 100644 --- a/tests/components/esphome/test_select.py +++ b/tests/components/esphome/test_select.py @@ -89,7 +89,7 @@ async def test_select_generic_entity( {ATTR_ENTITY_ID: "select.test_my_select", ATTR_OPTION: "b"}, blocking=True, ) - mock_client.select_command.assert_has_calls([call(1, "b")]) + mock_client.select_command.assert_has_calls([call(1, "b", device_id=0)]) async def test_wake_word_select_no_wake_words( diff --git a/tests/components/esphome/test_switch.py b/tests/components/esphome/test_switch.py index 0efb3d86256..c62101125bd 100644 --- a/tests/components/esphome/test_switch.py +++ b/tests/components/esphome/test_switch.py @@ -2,17 +2,17 @@ from unittest.mock import call -from aioesphomeapi import APIClient, SwitchInfo, SwitchState +from aioesphomeapi import APIClient, SubDeviceInfo, SwitchInfo, SwitchState from homeassistant.components.switch import ( DOMAIN as SWITCH_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) -from homeassistant.const import ATTR_ENTITY_ID, STATE_ON +from homeassistant.const import ATTR_ENTITY_ID, STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant -from .conftest import MockGenericDeviceEntryType +from .conftest import MockESPHomeDeviceType, MockGenericDeviceEntryType async def test_switch_generic_entity( @@ -47,7 +47,7 @@ async def test_switch_generic_entity( {ATTR_ENTITY_ID: "switch.test_my_switch"}, blocking=True, ) - mock_client.switch_command.assert_has_calls([call(1, True)]) + mock_client.switch_command.assert_has_calls([call(1, True, device_id=0)]) await hass.services.async_call( SWITCH_DOMAIN, @@ -55,4 +55,95 @@ async def test_switch_generic_entity( {ATTR_ENTITY_ID: "switch.test_my_switch"}, blocking=True, ) - mock_client.switch_command.assert_has_calls([call(1, False)]) + mock_client.switch_command.assert_has_calls([call(1, False, device_id=0)]) + + +async def test_switch_sub_device_non_zero_device_id( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test switch on sub-device with non-zero device_id passes through to API.""" + # Create sub-device + sub_devices = [ + SubDeviceInfo(device_id=11111111, name="Sub Device", area_id=0), + ] + device_info = { + "name": "test", + "devices": sub_devices, + } + # Create switches on both main device and sub-device + entity_info = [ + SwitchInfo( + object_id="main_switch", + key=1, + name="Main Switch", + unique_id="main_switch_1", + device_id=0, # Main device + ), + SwitchInfo( + object_id="sub_switch", + key=2, + name="Sub Switch", + unique_id="sub_switch_1", + device_id=11111111, # Sub-device + ), + ] + # States for both switches + states = [ + SwitchState(key=1, state=True, device_id=0), + SwitchState(key=2, state=False, device_id=11111111), + ] + await mock_esphome_device( + mock_client=mock_client, + device_info=device_info, + entity_info=entity_info, + states=states, + ) + + # Verify both entities exist with correct states + main_state = hass.states.get("switch.test_main_switch") + assert main_state is not None + assert main_state.state == STATE_ON + + sub_state = hass.states.get("switch.sub_device_sub_switch") + assert sub_state is not None + assert sub_state.state == STATE_OFF + + # Test turning on the sub-device switch - should pass device_id=11111111 + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.sub_device_sub_switch"}, + blocking=True, + ) + mock_client.switch_command.assert_has_calls([call(2, True, device_id=11111111)]) + mock_client.switch_command.reset_mock() + + # Test turning off the sub-device switch - should pass device_id=11111111 + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "switch.sub_device_sub_switch"}, + blocking=True, + ) + mock_client.switch_command.assert_has_calls([call(2, False, device_id=11111111)]) + mock_client.switch_command.reset_mock() + + # Test main device switch still uses device_id=0 + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.test_main_switch"}, + blocking=True, + ) + mock_client.switch_command.assert_has_calls([call(1, True, device_id=0)]) + mock_client.switch_command.reset_mock() + + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: "switch.test_main_switch"}, + blocking=True, + ) + mock_client.switch_command.assert_has_calls([call(1, False, device_id=0)]) diff --git a/tests/components/esphome/test_text.py b/tests/components/esphome/test_text.py index c8a7b2b9b45..f8c1d33e224 100644 --- a/tests/components/esphome/test_text.py +++ b/tests/components/esphome/test_text.py @@ -51,7 +51,7 @@ async def test_generic_text_entity( {ATTR_ENTITY_ID: "text.test_my_text", ATTR_VALUE: "goodbye"}, blocking=True, ) - mock_client.text_command.assert_has_calls([call(1, "goodbye")]) + mock_client.text_command.assert_has_calls([call(1, "goodbye", device_id=0)]) mock_client.text_command.reset_mock() diff --git a/tests/components/esphome/test_time.py b/tests/components/esphome/test_time.py index 9342bd16055..75e2a0dc664 100644 --- a/tests/components/esphome/test_time.py +++ b/tests/components/esphome/test_time.py @@ -47,7 +47,7 @@ async def test_generic_time_entity( {ATTR_ENTITY_ID: "time.test_my_time", ATTR_TIME: "01:23:45"}, blocking=True, ) - mock_client.time_command.assert_has_calls([call(1, 1, 23, 45)]) + mock_client.time_command.assert_has_calls([call(1, 1, 23, 45, device_id=0)]) mock_client.time_command.reset_mock() diff --git a/tests/components/esphome/test_update.py b/tests/components/esphome/test_update.py index fd852949e65..96b77281485 100644 --- a/tests/components/esphome/test_update.py +++ b/tests/components/esphome/test_update.py @@ -544,7 +544,9 @@ async def test_generic_device_update_entity_has_update( assert state.attributes[ATTR_IN_PROGRESS] is True assert state.attributes[ATTR_UPDATE_PERCENTAGE] is None - mock_client.update_command.assert_called_with(key=1, command=UpdateCommand.CHECK) + mock_client.update_command.assert_called_with( + key=1, command=UpdateCommand.CHECK, device_id=0 + ) async def test_update_entity_release_notes( diff --git a/tests/components/esphome/test_valve.py b/tests/components/esphome/test_valve.py index d31e2bfb09e..aaa52551115 100644 --- a/tests/components/esphome/test_valve.py +++ b/tests/components/esphome/test_valve.py @@ -66,7 +66,7 @@ async def test_valve_entity( {ATTR_ENTITY_ID: "valve.test_my_valve"}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, position=0.0)]) + mock_client.valve_command.assert_has_calls([call(key=1, position=0.0, device_id=0)]) mock_client.valve_command.reset_mock() await hass.services.async_call( @@ -75,7 +75,7 @@ async def test_valve_entity( {ATTR_ENTITY_ID: "valve.test_my_valve"}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, position=1.0)]) + mock_client.valve_command.assert_has_calls([call(key=1, position=1.0, device_id=0)]) mock_client.valve_command.reset_mock() await hass.services.async_call( @@ -84,7 +84,7 @@ async def test_valve_entity( {ATTR_ENTITY_ID: "valve.test_my_valve", ATTR_POSITION: 50}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, position=0.5)]) + mock_client.valve_command.assert_has_calls([call(key=1, position=0.5, device_id=0)]) mock_client.valve_command.reset_mock() await hass.services.async_call( @@ -93,7 +93,7 @@ async def test_valve_entity( {ATTR_ENTITY_ID: "valve.test_my_valve"}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, stop=True)]) + mock_client.valve_command.assert_has_calls([call(key=1, stop=True, device_id=0)]) mock_client.valve_command.reset_mock() mock_device.set_state( @@ -164,7 +164,7 @@ async def test_valve_entity_without_position( {ATTR_ENTITY_ID: "valve.test_my_valve"}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, position=0.0)]) + mock_client.valve_command.assert_has_calls([call(key=1, position=0.0, device_id=0)]) mock_client.valve_command.reset_mock() await hass.services.async_call( @@ -173,7 +173,7 @@ async def test_valve_entity_without_position( {ATTR_ENTITY_ID: "valve.test_my_valve"}, blocking=True, ) - mock_client.valve_command.assert_has_calls([call(key=1, position=1.0)]) + mock_client.valve_command.assert_has_calls([call(key=1, position=1.0, device_id=0)]) mock_client.valve_command.reset_mock() mock_device.set_state( diff --git a/tests/components/fritzbox/test_coordinator.py b/tests/components/fritzbox/test_coordinator.py index 61de0c99940..794d6ac4397 100644 --- a/tests/components/fritzbox/test_coordinator.py +++ b/tests/components/fritzbox/test_coordinator.py @@ -15,7 +15,12 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.util.dt import utcnow -from . import FritzDeviceCoverMock, FritzDeviceSwitchMock, FritzEntityBaseMock +from . import ( + FritzDeviceCoverMock, + FritzDeviceSensorMock, + FritzDeviceSwitchMock, + FritzEntityBaseMock, +) from .const import MOCK_CONFIG from tests.common import MockConfigEntry, async_fire_time_changed @@ -140,3 +145,42 @@ async def test_coordinator_automatic_registry_cleanup( assert len(er.async_entries_for_config_entry(entity_registry, entry.entry_id)) == 12 assert len(dr.async_entries_for_config_entry(device_registry, entry.entry_id)) == 1 + + +async def test_coordinator_workaround_sub_units_without_main_device( + hass: HomeAssistant, + fritz: Mock, + device_registry: dr.DeviceRegistry, +) -> None: + """Test the workaround for sub units without main device.""" + fritz().get_devices.return_value = [ + FritzDeviceSensorMock( + ain="bad_device-1", + device_and_unit_id=("bad_device", "1"), + name="bad_sensor_sub", + ), + FritzDeviceSensorMock( + ain="good_device", + device_and_unit_id=("good_device", None), + name="good_sensor", + ), + FritzDeviceSensorMock( + ain="good_device-1", + device_and_unit_id=("good_device", "1"), + name="good_sensor_sub", + ), + ] + + entry = MockConfigEntry( + domain=DOMAIN, + data=MOCK_CONFIG[DOMAIN][CONF_DEVICES][0], + unique_id="any", + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + device_entries = dr.async_entries_for_config_entry(device_registry, entry.entry_id) + assert len(device_entries) == 2 + assert device_entries[0].identifiers == {(DOMAIN, "good_device")} + assert device_entries[1].identifiers == {(DOMAIN, "bad_device")} diff --git a/tests/components/gardena_bluetooth/snapshots/test_init.ambr b/tests/components/gardena_bluetooth/snapshots/test_init.ambr index 8dc9d220e85..d2af92b3f8f 100644 --- a/tests/components/gardena_bluetooth/snapshots/test_init.ambr +++ b/tests/components/gardena_bluetooth/snapshots/test_init.ambr @@ -6,6 +6,10 @@ 'config_entries_subentries': , 'configuration_url': None, 'connections': set({ + tuple( + 'bluetooth', + '00000000-0000-0000-0000-000000000001', + ), }), 'disabled_by': None, 'entry_type': None, diff --git a/tests/components/generic_hygrostat/test_init.py b/tests/components/generic_hygrostat/test_init.py index 254d4da5806..64db21eab8c 100644 --- a/tests/components/generic_hygrostat/test_init.py +++ b/tests/components/generic_hygrostat/test_init.py @@ -9,8 +9,8 @@ import pytest from homeassistant.components import generic_hygrostat from homeassistant.components.generic_hygrostat import DOMAIN from homeassistant.components.generic_hygrostat.config_flow import ConfigFlowHandler -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -119,10 +119,20 @@ def generic_hygrostat_config_entry( return config_entry +@pytest.fixture +def expected_helper_device_id( + request: pytest.FixtureRequest, + switch_device: dr.DeviceEntry, +) -> str | None: + """Fixture to provide the expected helper device ID.""" + return switch_device.id if request.param == "switch_device_id" else None + + def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[str]: """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -201,7 +211,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( helper_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(helper_config_entry.entry_id) @@ -216,9 +226,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( helper_config_entry.entry_id ) - assert len(devices_after_reload) == 1 - - assert devices_after_reload[0].id == source_device1_entry.id + assert len(devices_after_reload) == 0 @pytest.mark.usefixtures( @@ -229,8 +237,12 @@ async def test_device_cleaning( "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "expected_events"), - [("switch.test_unique", True, ["update"]), ("sensor.test_unique", False, [])], + ("source_entity_id", "expected_helper_device_id", "expected_events"), + [ + ("switch.test_unique", None, ["update"]), + ("sensor.test_unique", "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], ) async def test_async_handle_source_entity_changes_source_entity_removed( hass: HomeAssistant, @@ -239,7 +251,83 @@ async def test_async_handle_source_entity_changes_source_entity_removed( generic_hygrostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, + expected_helper_device_id: str | None, + expected_events: list[str], +) -> None: + """Test the generic_hygrostat config entry is removed when the source entity is removed.""" + source_entity_entry = entity_registry.async_get(source_entity_id) + + assert await hass.config_entries.async_setup( + generic_hygrostat_config_entry.entry_id + ) + await hass.async_block_till_done() + + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id + + source_device = device_registry.async_get(source_entity_entry.device_id) + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries + + events = track_entity_registry_actions( + hass, generic_hygrostat_entity_entry.entity_id + ) + + # Remove the source entity's config entry from the device, this removes the + # source entity + with patch( + "homeassistant.components.generic_hygrostat.async_unload_entry", + wraps=generic_hygrostat.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + source_device.id, remove_config_entry_id=source_entity_entry.config_entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the helper entity is linked to the expected source device + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == expected_helper_device_id + + # Check that the device is removed + assert not device_registry.async_get(source_device.id) + + # Check that the generic_hygrostat config entry is not removed + assert ( + generic_hygrostat_config_entry.entry_id in hass.config_entries.async_entry_ids() + ) + + # Check we got the expected events + assert events == expected_events + + +@pytest.mark.usefixtures( + "sensor_config_entry", + "sensor_device", + "sensor_entity_entry", + "switch_config_entry", + "switch_device", +) +@pytest.mark.parametrize( + ("source_entity_id", "expected_helper_device_id", "expected_events"), + [ + ("switch.test_unique", None, ["update"]), + ("sensor.test_unique", "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], +) +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + generic_hygrostat_config_entry: MockConfigEntry, + switch_entity_entry: er.RegistryEntry, + source_entity_id: str, + expected_helper_device_id: str | None, expected_events: list[str], ) -> None: """Test the generic_hygrostat config entry is removed when the source entity is removed.""" @@ -263,9 +351,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_hygrostat_entity_entry.entity_id @@ -284,6 +370,13 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() + # Check that the helper entity is linked to the expected source device + switch_entity_entry = entity_registry.async_get("switch.test_unique") + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == expected_helper_device_id + # Check if the generic_hygrostat config entry is not in the device source_device = device_registry.async_get(source_device.id) assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries @@ -305,8 +398,17 @@ async def test_async_handle_source_entity_changes_source_entity_removed( "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "unload_entry_calls", "expected_events"), - [("switch.test_unique", True, 1, ["update"]), ("sensor.test_unique", False, 0, [])], + ( + "source_entity_id", + "unload_entry_calls", + "expected_helper_device_id", + "expected_events", + ), + [ + ("switch.test_unique", 1, None, ["update"]), + ("sensor.test_unique", 0, "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], ) async def test_async_handle_source_entity_changes_source_entity_removed_from_device( hass: HomeAssistant, @@ -315,8 +417,8 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev generic_hygrostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, unload_entry_calls: int, + expected_helper_device_id: str | None, expected_events: list[str], ) -> None: """Test the source entity removed from the source device.""" @@ -333,9 +435,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_hygrostat_entity_entry.entity_id @@ -352,7 +452,13 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() assert len(mock_unload_entry.mock_calls) == unload_entry_calls - # Check that the generic_hygrostat config entry is removed from the device + # Check that the helper entity is linked to the expected source device + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == expected_helper_device_id + + # Check that the generic_hygrostat config entry is not in the device source_device = device_registry.async_get(source_device.id) assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries @@ -373,8 +479,8 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "unload_entry_calls", "expected_events"), - [("switch.test_unique", True, 1, ["update"]), ("sensor.test_unique", False, 0, [])], + ("source_entity_id", "unload_entry_calls", "expected_events"), + [("switch.test_unique", 1, ["update"]), ("sensor.test_unique", 0, [])], ) async def test_async_handle_source_entity_changes_source_entity_moved_other_device( hass: HomeAssistant, @@ -383,7 +489,6 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi generic_hygrostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, unload_entry_calls: int, expected_events: list[str], ) -> None: @@ -406,9 +511,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries source_device_2 = device_registry.async_get(source_device_2.id) assert generic_hygrostat_config_entry.entry_id not in source_device_2.config_entries @@ -427,13 +530,18 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() assert len(mock_unload_entry.mock_calls) == unload_entry_calls - # Check that the generic_hygrostat config entry is moved to the other device + # Check that the helper entity is linked to the expected source device + switch_entity_entry = entity_registry.async_get(switch_entity_entry.entity_id) + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id + + # Check that the generic_hygrostat config entry is not in any of the devices source_device = device_registry.async_get(source_device.id) assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries source_device_2 = device_registry.async_get(source_device_2.id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device_2.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device_2.config_entries # Check that the generic_hygrostat config entry is not removed assert ( @@ -452,10 +560,10 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "new_entity_id", "helper_in_device", "config_key"), + ("source_entity_id", "new_entity_id", "config_key"), [ - ("switch.test_unique", "switch.new_entity_id", True, "humidifier"), - ("sensor.test_unique", "sensor.new_entity_id", False, "target_sensor"), + ("switch.test_unique", "switch.new_entity_id", "humidifier"), + ("sensor.test_unique", "sensor.new_entity_id", "target_sensor"), ], ) async def test_async_handle_source_entity_new_entity_id( @@ -466,7 +574,6 @@ async def test_async_handle_source_entity_new_entity_id( switch_entity_entry: er.RegistryEntry, source_entity_id: str, new_entity_id: str, - helper_in_device: bool, config_key: str, ) -> None: """Test the source entity's entity ID is changed.""" @@ -483,9 +590,7 @@ async def test_async_handle_source_entity_new_entity_id( assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_hygrostat_entity_entry.entity_id @@ -505,11 +610,9 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the generic_hygrostat config entry is updated with the new entity ID assert generic_hygrostat_config_entry.options[config_key] == new_entity_id - # Check that the helper config is still in the device + # Check that the helper config is not in the device source_device = device_registry.async_get(source_device.id) - assert ( - generic_hygrostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_hygrostat_config_entry.entry_id not in source_device.config_entries # Check that the generic_hygrostat config entry is not removed assert ( @@ -518,3 +621,84 @@ async def test_async_handle_source_entity_new_entity_id( # Check we got the expected events assert events == [] + + +@pytest.mark.usefixtures("sensor_device") +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + switch_device: dr.DeviceEntry, + switch_entity_entry: er.RegistryEntry, +) -> None: + """Test migration from v1.1 removes generic_hygrostat config entry from device.""" + + generic_hygrostat_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "device_class": "humidifier", + "dry_tolerance": 2.0, + "humidifier": switch_entity_entry.entity_id, + "name": "My generic hygrostat", + "target_sensor": sensor_entity_entry.entity_id, + "wet_tolerance": 4.0, + }, + title="My generic hygrostat", + version=1, + minor_version=1, + ) + generic_hygrostat_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + switch_device.id, add_config_entry_id=generic_hygrostat_config_entry.entry_id + ) + + # Check preconditions + switch_device = device_registry.async_get(switch_device.id) + assert generic_hygrostat_config_entry.entry_id in switch_device.config_entries + + await hass.config_entries.async_setup(generic_hygrostat_config_entry.entry_id) + await hass.async_block_till_done() + + assert generic_hygrostat_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + switch_device = device_registry.async_get(switch_device.id) + assert generic_hygrostat_config_entry.entry_id not in switch_device.config_entries + generic_hygrostat_entity_entry = entity_registry.async_get( + "humidifier.my_generic_hygrostat" + ) + assert generic_hygrostat_entity_entry.device_id == switch_entity_entry.device_id + + assert generic_hygrostat_config_entry.version == 1 + assert generic_hygrostat_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "device_class": "humidifier", + "dry_tolerance": 2.0, + "humidifier": "switch.test", + "name": "My generic hygrostat", + "target_sensor": "sensor.test", + "wet_tolerance": 4.0, + }, + title="My generic hygrostat", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/generic_thermostat/test_init.py b/tests/components/generic_thermostat/test_init.py index 9131e3ffdd4..ceca7ecc444 100644 --- a/tests/components/generic_thermostat/test_init.py +++ b/tests/components/generic_thermostat/test_init.py @@ -9,8 +9,8 @@ import pytest from homeassistant.components import generic_thermostat from homeassistant.components.generic_thermostat.config_flow import ConfigFlowHandler from homeassistant.components.generic_thermostat.const import DOMAIN -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -117,10 +117,20 @@ def generic_thermostat_config_entry( return config_entry +@pytest.fixture +def expected_helper_device_id( + request: pytest.FixtureRequest, + switch_device: dr.DeviceEntry, +) -> str | None: + """Fixture to provide the expected helper device ID.""" + return switch_device.id if request.param == "switch_device_id" else None + + def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[str]: """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -199,7 +209,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( helper_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(helper_config_entry.entry_id) @@ -214,9 +224,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( helper_config_entry.entry_id ) - assert len(devices_after_reload) == 1 - - assert devices_after_reload[0].id == source_device1_entry.id + assert len(devices_after_reload) == 0 @pytest.mark.usefixtures( @@ -227,8 +235,12 @@ async def test_device_cleaning( "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "expected_events"), - [("switch.test_unique", True, ["update"]), ("sensor.test_unique", False, [])], + ("source_entity_id", "expected_helper_device_id", "expected_events"), + [ + ("switch.test_unique", None, ["update"]), + ("sensor.test_unique", "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], ) async def test_async_handle_source_entity_changes_source_entity_removed( hass: HomeAssistant, @@ -237,7 +249,84 @@ async def test_async_handle_source_entity_changes_source_entity_removed( generic_thermostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, + expected_helper_device_id: str | None, + expected_events: list[str], +) -> None: + """Test the generic_thermostat config entry is removed when the source entity is removed.""" + source_entity_entry = entity_registry.async_get(source_entity_id) + + assert await hass.config_entries.async_setup( + generic_thermostat_config_entry.entry_id + ) + await hass.async_block_till_done() + + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id + + source_device = device_registry.async_get(source_entity_entry.device_id) + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries + + events = track_entity_registry_actions( + hass, generic_thermostat_entity_entry.entity_id + ) + + # Remove the source entity's config entry from the device, this removes the + # source entity + with patch( + "homeassistant.components.generic_thermostat.async_unload_entry", + wraps=generic_thermostat.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + source_device.id, remove_config_entry_id=source_entity_entry.config_entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the helper entity is linked to the expected source device + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == expected_helper_device_id + + # Check that the device is removed + assert not device_registry.async_get(source_device.id) + + # Check that the generic_thermostat config entry is not removed + assert ( + generic_thermostat_config_entry.entry_id + in hass.config_entries.async_entry_ids() + ) + + # Check we got the expected events + assert events == expected_events + + +@pytest.mark.usefixtures( + "sensor_config_entry", + "sensor_device", + "sensor_entity_entry", + "switch_config_entry", + "switch_device", +) +@pytest.mark.parametrize( + ("source_entity_id", "expected_helper_device_id", "expected_events"), + [ + ("switch.test_unique", None, ["update"]), + ("sensor.test_unique", "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], +) +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + generic_thermostat_config_entry: MockConfigEntry, + switch_entity_entry: er.RegistryEntry, + source_entity_id: str, + expected_helper_device_id: str | None, expected_events: list[str], ) -> None: """Test the generic_thermostat config entry is removed when the source entity is removed.""" @@ -261,9 +350,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_thermostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_thermostat_entity_entry.entity_id @@ -282,6 +369,13 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() + # Check that the helper entity is linked to the expected source device + switch_entity_entry = entity_registry.async_get("switch.test_unique") + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == expected_helper_device_id + # Check if the generic_thermostat config entry is not in the device source_device = device_registry.async_get(source_device.id) assert generic_thermostat_config_entry.entry_id not in source_device.config_entries @@ -304,8 +398,17 @@ async def test_async_handle_source_entity_changes_source_entity_removed( "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "unload_entry_calls", "expected_events"), - [("switch.test_unique", True, 1, ["update"]), ("sensor.test_unique", False, 0, [])], + ( + "source_entity_id", + "unload_entry_calls", + "expected_helper_device_id", + "expected_events", + ), + [ + ("switch.test_unique", 1, None, ["update"]), + ("sensor.test_unique", 0, "switch_device_id", []), + ], + indirect=["expected_helper_device_id"], ) async def test_async_handle_source_entity_changes_source_entity_removed_from_device( hass: HomeAssistant, @@ -314,8 +417,8 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev generic_thermostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, unload_entry_calls: int, + expected_helper_device_id: str | None, expected_events: list[str], ) -> None: """Test the source entity removed from the source device.""" @@ -332,9 +435,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_thermostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_thermostat_entity_entry.entity_id @@ -351,7 +452,13 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() assert len(mock_unload_entry.mock_calls) == unload_entry_calls - # Check that the generic_thermostat config entry is removed from the device + # Check that the helper entity is linked to the expected source device + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == expected_helper_device_id + + # Check that the generic_thermostat config entry is not in the device source_device = device_registry.async_get(source_device.id) assert generic_thermostat_config_entry.entry_id not in source_device.config_entries @@ -373,8 +480,8 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "helper_in_device", "unload_entry_calls", "expected_events"), - [("switch.test_unique", True, 1, ["update"]), ("sensor.test_unique", False, 0, [])], + ("source_entity_id", "unload_entry_calls", "expected_events"), + [("switch.test_unique", 1, ["update"]), ("sensor.test_unique", 0, [])], ) async def test_async_handle_source_entity_changes_source_entity_moved_other_device( hass: HomeAssistant, @@ -383,7 +490,6 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi generic_thermostat_config_entry: MockConfigEntry, switch_entity_entry: er.RegistryEntry, source_entity_id: str, - helper_in_device: bool, unload_entry_calls: int, expected_events: list[str], ) -> None: @@ -406,9 +512,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_thermostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries source_device_2 = device_registry.async_get(source_device_2.id) assert ( generic_thermostat_config_entry.entry_id not in source_device_2.config_entries @@ -429,13 +533,20 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() assert len(mock_unload_entry.mock_calls) == unload_entry_calls - # Check that the generic_thermostat config entry is moved to the other device + # Check that the helper entity is linked to the expected source device + switch_entity_entry = entity_registry.async_get(switch_entity_entry.entity_id) + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id + + # Check that the generic_thermostat config entry is not in any of the devices source_device = device_registry.async_get(source_device.id) assert generic_thermostat_config_entry.entry_id not in source_device.config_entries source_device_2 = device_registry.async_get(source_device_2.id) assert ( - generic_thermostat_config_entry.entry_id in source_device_2.config_entries - ) == helper_in_device + generic_thermostat_config_entry.entry_id not in source_device_2.config_entries + ) # Check that the generic_thermostat config entry is not removed assert ( @@ -455,10 +566,10 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi "switch_device", ) @pytest.mark.parametrize( - ("source_entity_id", "new_entity_id", "helper_in_device", "config_key"), + ("source_entity_id", "new_entity_id", "config_key"), [ - ("switch.test_unique", "switch.new_entity_id", True, "heater"), - ("sensor.test_unique", "sensor.new_entity_id", False, "target_sensor"), + ("switch.test_unique", "switch.new_entity_id", "heater"), + ("sensor.test_unique", "sensor.new_entity_id", "target_sensor"), ], ) async def test_async_handle_source_entity_new_entity_id( @@ -469,7 +580,6 @@ async def test_async_handle_source_entity_new_entity_id( switch_entity_entry: er.RegistryEntry, source_entity_id: str, new_entity_id: str, - helper_in_device: bool, config_key: str, ) -> None: """Test the source entity's entity ID is changed.""" @@ -486,9 +596,7 @@ async def test_async_handle_source_entity_new_entity_id( assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id source_device = device_registry.async_get(source_entity_entry.device_id) - assert ( - generic_thermostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries events = track_entity_registry_actions( hass, generic_thermostat_entity_entry.entity_id @@ -508,11 +616,9 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the generic_thermostat config entry is updated with the new entity ID assert generic_thermostat_config_entry.options[config_key] == new_entity_id - # Check that the helper config is still in the device + # Check that the helper config is not in the device source_device = device_registry.async_get(source_device.id) - assert ( - generic_thermostat_config_entry.entry_id in source_device.config_entries - ) == helper_in_device + assert generic_thermostat_config_entry.entry_id not in source_device.config_entries # Check that the generic_thermostat config entry is not removed assert ( @@ -522,3 +628,84 @@ async def test_async_handle_source_entity_new_entity_id( # Check we got the expected events assert events == [] + + +@pytest.mark.usefixtures("sensor_device") +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + switch_device: dr.DeviceEntry, + switch_entity_entry: er.RegistryEntry, +) -> None: + """Test migration from v1.1 removes generic_thermostat config entry from device.""" + + generic_thermostat_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My generic thermostat", + "heater": switch_entity_entry.entity_id, + "target_sensor": sensor_entity_entry.entity_id, + "ac_mode": False, + "cold_tolerance": 0.3, + "hot_tolerance": 0.3, + }, + title="My generic thermostat", + version=1, + minor_version=1, + ) + generic_thermostat_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + switch_device.id, add_config_entry_id=generic_thermostat_config_entry.entry_id + ) + + # Check preconditions + switch_device = device_registry.async_get(switch_device.id) + assert generic_thermostat_config_entry.entry_id in switch_device.config_entries + + await hass.config_entries.async_setup(generic_thermostat_config_entry.entry_id) + await hass.async_block_till_done() + + assert generic_thermostat_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + switch_device = device_registry.async_get(switch_device.id) + assert generic_thermostat_config_entry.entry_id not in switch_device.config_entries + generic_thermostat_entity_entry = entity_registry.async_get( + "climate.my_generic_thermostat" + ) + assert generic_thermostat_entity_entry.device_id == switch_entity_entry.device_id + + assert generic_thermostat_config_entry.version == 1 + assert generic_thermostat_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My generic thermostat", + "heater": "switch.test", + "target_sensor": "sensor.test", + "ac_mode": False, + "cold_tolerance": 0.3, + "hot_tolerance": 0.3, + }, + title="My generic thermostat", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/gios/fixtures/sensors.json b/tests/components/gios/fixtures/sensors.json index 0fe387d3126..64cb9685f97 100644 --- a/tests/components/gios/fixtures/sensors.json +++ b/tests/components/gios/fixtures/sensors.json @@ -20,6 +20,13 @@ { "Data": "2020-07-31 13:00:00", "Wartość": 251.097 } ] }, + "no": { + "Lista danych pomiarowych": [ + { "Data": "2020-07-31 15:00:00", "Wartość": 5.1 }, + { "Data": "2020-07-31 14:00:00", "Wartość": 4.0 }, + { "Data": "2020-07-31 13:00:00", "Wartość": 5.2 } + ] + }, "no2": { "Lista danych pomiarowych": [ { "Data": "2020-07-31 15:00:00", "Wartość": 7.13411 }, @@ -27,6 +34,13 @@ { "Data": "2020-07-31 13:00:00", "Wartość": 9.32578 } ] }, + "nox": { + "Lista danych pomiarowych": [ + { "Data": "2020-07-31 15:00:00", "Wartość": 5.5 }, + { "Data": "2020-07-31 14:00:00", "Wartość": 6.3 }, + { "Data": "2020-07-31 13:00:00", "Wartość": 4.9 } + ] + }, "o3": { "Lista danych pomiarowych": [ { "Data": "2020-07-31 15:00:00", "Wartość": 95.7768 }, diff --git a/tests/components/gios/fixtures/station.json b/tests/components/gios/fixtures/station.json index 167e4db3aee..1d112c0947b 100644 --- a/tests/components/gios/fixtures/station.json +++ b/tests/components/gios/fixtures/station.json @@ -23,6 +23,14 @@ "Wskaźnik - kod": "CO", "Id wskaźnika": 8 }, + { + "Identyfikator stanowiska": 664, + "Identyfikator stacji": 117, + "Wskaźnik": "tlenek azotu", + "Wskaźnik - wzór": "NO", + "Wskaźnik - kod": "NO", + "Id wskaźnika": 16 + }, { "Identyfikator stanowiska": 665, "Identyfikator stacji": 117, @@ -31,6 +39,14 @@ "Wskaźnik - kod": "NO2", "Id wskaźnika": 6 }, + { + "Identyfikator stanowiska": 666, + "Identyfikator stacji": 117, + "Wskaźnik": "tlenki azotu", + "Wskaźnik - wzór": "NOx", + "Wskaźnik - kod": "NOx", + "Id wskaźnika": 7 + }, { "Identyfikator stanowiska": 667, "Identyfikator stacji": 117, diff --git a/tests/components/gios/snapshots/test_diagnostics.ambr b/tests/components/gios/snapshots/test_diagnostics.ambr index 4095bf8bf53..722d14e3681 100644 --- a/tests/components/gios/snapshots/test_diagnostics.ambr +++ b/tests/components/gios/snapshots/test_diagnostics.ambr @@ -42,14 +42,24 @@ 'name': 'carbon monoxide', 'value': 251.874, }), - 'no': None, + 'no': dict({ + 'id': 664, + 'index': None, + 'name': 'nitrogen monoxide', + 'value': 5.1, + }), 'no2': dict({ 'id': 665, 'index': 'good', 'name': 'nitrogen dioxide', 'value': 7.13411, }), - 'nox': None, + 'nox': dict({ + 'id': 666, + 'index': None, + 'name': 'nitrogen oxides', + 'value': 5.5, + }), 'o3': dict({ 'id': 667, 'index': 'good', diff --git a/tests/components/gios/snapshots/test_sensor.ambr b/tests/components/gios/snapshots/test_sensor.ambr index fd74cc222c8..2a0afcc72b1 100644 --- a/tests/components/gios/snapshots/test_sensor.ambr +++ b/tests/components/gios/snapshots/test_sensor.ambr @@ -302,6 +302,119 @@ 'state': 'good', }) # --- +# name: test_sensor[sensor.home_nitrogen_monoxide-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.home_nitrogen_monoxide', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Nitrogen monoxide', + 'platform': 'gios', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '123-no', + 'unit_of_measurement': 'µg/m³', + }) +# --- +# name: test_sensor[sensor.home_nitrogen_monoxide-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'attribution': 'Data provided by GIOŚ', + 'device_class': 'nitrogen_monoxide', + 'friendly_name': 'Home Nitrogen monoxide', + 'state_class': , + 'unit_of_measurement': 'µg/m³', + }), + 'context': , + 'entity_id': 'sensor.home_nitrogen_monoxide', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '5.1', + }) +# --- +# name: test_sensor[sensor.home_nitrogen_oxides-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.home_nitrogen_oxides', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Nitrogen oxides', + 'platform': 'gios', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'nox', + 'unique_id': '123-nox', + 'unit_of_measurement': 'µg/m³', + }) +# --- +# name: test_sensor[sensor.home_nitrogen_oxides-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'attribution': 'Data provided by GIOŚ', + 'friendly_name': 'Home Nitrogen oxides', + 'state_class': , + 'unit_of_measurement': 'µg/m³', + }), + 'context': , + 'entity_id': 'sensor.home_nitrogen_oxides', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '5.5', + }) +# --- # name: test_sensor[sensor.home_ozone-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/google_assistant_sdk/test_init.py b/tests/components/google_assistant_sdk/test_init.py index 9bb08c802c2..caddf9ba797 100644 --- a/tests/components/google_assistant_sdk/test_init.py +++ b/tests/components/google_assistant_sdk/test_init.py @@ -116,6 +116,25 @@ async def test_expired_token_refresh_failure( assert entries[0].state is expected_state +@pytest.mark.parametrize("expires_at", [time.time() - 3600], ids=["expired"]) +async def test_setup_client_error( + hass: HomeAssistant, + setup_integration: ComponentSetup, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Test setup handling aiohttp.ClientError.""" + aioclient_mock.post( + "https://oauth2.googleapis.com/token", + exc=aiohttp.ClientError, + ) + + await setup_integration() + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + assert entries[0].state is ConfigEntryState.SETUP_RETRY + + @pytest.mark.parametrize( ("configured_language_code", "expected_language_code"), [("", "en-US"), ("en-US", "en-US"), ("es-ES", "es-ES")], diff --git a/tests/components/google_generative_ai_conversation/snapshots/test_diagnostics.ambr b/tests/components/google_generative_ai_conversation/snapshots/test_diagnostics.ambr index bf44b1cbc04..d3e27eb99d2 100644 --- a/tests/components/google_generative_ai_conversation/snapshots/test_diagnostics.ambr +++ b/tests/components/google_generative_ai_conversation/snapshots/test_diagnostics.ambr @@ -21,7 +21,7 @@ 'dangerous_block_threshold': 'BLOCK_MEDIUM_AND_ABOVE', 'harassment_block_threshold': 'BLOCK_MEDIUM_AND_ABOVE', 'hate_block_threshold': 'BLOCK_MEDIUM_AND_ABOVE', - 'max_tokens': 1500, + 'max_tokens': 3000, 'prompt': 'Speak like a pirate', 'recommended': False, 'sexual_block_threshold': 'BLOCK_MEDIUM_AND_ABOVE', diff --git a/tests/components/google_generative_ai_conversation/test_ai_task.py b/tests/components/google_generative_ai_conversation/test_ai_task.py index b2b44aa1cd6..6326bd94ad9 100644 --- a/tests/components/google_generative_ai_conversation/test_ai_task.py +++ b/tests/components/google_generative_ai_conversation/test_ai_task.py @@ -1,12 +1,13 @@ """Test AI Task platform of Google Generative AI Conversation integration.""" -from unittest.mock import AsyncMock +from pathlib import Path +from unittest.mock import AsyncMock, patch -from google.genai.types import GenerateContentResponse +from google.genai.types import File, FileState, GenerateContentResponse import pytest import voluptuous as vol -from homeassistant.components import ai_task +from homeassistant.components import ai_task, media_source from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er, selector @@ -64,6 +65,93 @@ async def test_generate_data( ) assert result.data == "Hi there!" + # Test with attachments + mock_send_message_stream.return_value = [ + [ + GenerateContentResponse( + candidates=[ + { + "content": { + "parts": [{"text": "Hi there!"}], + "role": "model", + }, + } + ], + ), + ], + ] + file1 = File(name="doorbell_snapshot.jpg", state=FileState.ACTIVE) + file2 = File(name="context.txt", state=FileState.ACTIVE) + with ( + patch( + "homeassistant.components.media_source.async_resolve_media", + side_effect=[ + media_source.PlayMedia( + url="http://example.com/doorbell_snapshot.jpg", + mime_type="image/jpeg", + path=Path("doorbell_snapshot.jpg"), + ), + media_source.PlayMedia( + url="http://example.com/context.txt", + mime_type="text/plain", + path=Path("context.txt"), + ), + ], + ), + patch( + "google.genai.files.Files.upload", + side_effect=[file1, file2], + ) as mock_upload, + patch("pathlib.Path.exists", return_value=True), + patch.object(hass.config, "is_allowed_path", return_value=True), + patch("mimetypes.guess_type", return_value=["image/jpeg"]), + ): + result = await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id=entity_id, + instructions="Test prompt", + attachments=[ + {"media_content_id": "media-source://media/doorbell_snapshot.jpg"}, + {"media_content_id": "media-source://media/context.txt"}, + ], + ) + + outgoing_message = mock_send_message_stream.mock_calls[1][2]["message"] + assert outgoing_message == ["Test prompt", file1, file2] + + assert result.data == "Hi there!" + assert len(mock_upload.mock_calls) == 2 + assert mock_upload.mock_calls[0][2]["file"] == Path("doorbell_snapshot.jpg") + assert mock_upload.mock_calls[1][2]["file"] == Path("context.txt") + + # Test attachments require play media with a path + with ( + patch( + "homeassistant.components.media_source.async_resolve_media", + side_effect=[ + media_source.PlayMedia( + url="http://example.com/doorbell_snapshot.jpg", + mime_type="image/jpeg", + path=None, + ), + ], + ), + pytest.raises( + HomeAssistantError, match="Only local attachments are currently supported" + ), + ): + result = await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id=entity_id, + instructions="Test prompt", + attachments=[ + {"media_content_id": "media-source://media/doorbell_snapshot.jpg"}, + ], + ) + + # Test with structure mock_send_message_stream.return_value = [ [ GenerateContentResponse( @@ -97,7 +185,7 @@ async def test_generate_data( ) assert result.data == {"characters": ["Mario", "Luigi"]} - assert len(mock_chat_create.mock_calls) == 2 + assert len(mock_chat_create.mock_calls) == 3 config = mock_chat_create.mock_calls[-1][2]["config"] assert config.response_mime_type == "application/json" assert config.response_schema == { diff --git a/tests/components/google_generative_ai_conversation/test_init.py b/tests/components/google_generative_ai_conversation/test_init.py index 351895c89fb..e154f9d33c9 100644 --- a/tests/components/google_generative_ai_conversation/test_init.py +++ b/tests/components/google_generative_ai_conversation/test_init.py @@ -1,5 +1,6 @@ """Tests for the Google Generative AI Conversation integration.""" +from typing import Any from unittest.mock import AsyncMock, Mock, mock_open, patch from google.genai.types import File, FileState @@ -17,11 +18,17 @@ from homeassistant.components.google_generative_ai_conversation.const import ( RECOMMENDED_CONVERSATION_OPTIONS, RECOMMENDED_TTS_OPTIONS, ) -from homeassistant.config_entries import ConfigEntryState, ConfigSubentryData +from homeassistant.config_entries import ( + ConfigEntryDisabler, + ConfigEntryState, + ConfigSubentryData, +) from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers.device_registry import DeviceEntryDisabler +from homeassistant.helpers.entity_registry import RegistryEntryDisabler from . import API_ERROR_500, CLIENT_ERROR_API_KEY_INVALID @@ -87,7 +94,6 @@ async def test_generate_content_service_with_image( ), patch("pathlib.Path.exists", return_value=True), patch.object(hass.config, "is_allowed_path", return_value=True), - patch("builtins.open", mock_open(read_data="this is an image")), patch("mimetypes.guess_type", return_value=["image/jpeg"]), ): response = await hass.services.async_call( @@ -480,7 +486,7 @@ async def test_migration_from_v1( assert len(entries) == 1 entry = entries[0] assert entry.version == 2 - assert entry.minor_version == 3 + assert entry.minor_version == 4 assert not entry.options assert entry.title == DEFAULT_TITLE assert len(entry.subentries) == 4 @@ -557,6 +563,223 @@ async def test_migration_from_v1( } +@pytest.mark.parametrize( + ( + "config_entry_disabled_by", + "merged_config_entry_disabled_by", + "conversation_subentry_data", + "main_config_entry", + ), + [ + ( + [ConfigEntryDisabler.USER, None], + None, + [ + { + "conversation_entity_id": "conversation.google_generative_ai_conversation_2", + "device_disabled_by": None, + "entity_disabled_by": None, + "device": 1, + }, + { + "conversation_entity_id": "conversation.google_generative_ai_conversation", + "device_disabled_by": DeviceEntryDisabler.USER, + "entity_disabled_by": RegistryEntryDisabler.DEVICE, + "device": 0, + }, + ], + 1, + ), + ( + [None, ConfigEntryDisabler.USER], + None, + [ + { + "conversation_entity_id": "conversation.google_generative_ai_conversation", + "device_disabled_by": DeviceEntryDisabler.USER, + "entity_disabled_by": RegistryEntryDisabler.DEVICE, + "device": 0, + }, + { + "conversation_entity_id": "conversation.google_generative_ai_conversation_2", + "device_disabled_by": None, + "entity_disabled_by": None, + "device": 1, + }, + ], + 0, + ), + ( + [ConfigEntryDisabler.USER, ConfigEntryDisabler.USER], + ConfigEntryDisabler.USER, + [ + { + "conversation_entity_id": "conversation.google_generative_ai_conversation", + "device_disabled_by": DeviceEntryDisabler.CONFIG_ENTRY, + "entity_disabled_by": RegistryEntryDisabler.CONFIG_ENTRY, + "device": 0, + }, + { + "conversation_entity_id": "conversation.google_generative_ai_conversation_2", + "device_disabled_by": None, + "entity_disabled_by": None, + "device": 1, + }, + ], + 0, + ), + ], +) +async def test_migration_from_v1_disabled( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + config_entry_disabled_by: list[ConfigEntryDisabler | None], + merged_config_entry_disabled_by: ConfigEntryDisabler | None, + conversation_subentry_data: list[dict[str, Any]], + main_config_entry: int, +) -> None: + """Test migration where the config entries are disabled.""" + # Create a v1 config entry with conversation options and an entity + options = { + "recommended": True, + "llm_hass_api": ["assist"], + "prompt": "You are a helpful assistant", + "chat_model": "models/gemini-2.0-flash", + } + mock_config_entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_API_KEY: "1234"}, + options=options, + version=1, + title="Google Generative AI", + disabled_by=config_entry_disabled_by[0], + ) + mock_config_entry.add_to_hass(hass) + mock_config_entry_2 = MockConfigEntry( + domain=DOMAIN, + data={CONF_API_KEY: "1234"}, + options=options, + version=1, + title="Google Generative AI 2", + disabled_by=config_entry_disabled_by[1], + ) + mock_config_entry_2.add_to_hass(hass) + mock_config_entries = [mock_config_entry, mock_config_entry_2] + + device_1 = device_registry.async_get_or_create( + config_entry_id=mock_config_entry.entry_id, + identifiers={(DOMAIN, mock_config_entry.entry_id)}, + name=mock_config_entry.title, + manufacturer="Google", + model="Generative AI", + entry_type=dr.DeviceEntryType.SERVICE, + disabled_by=DeviceEntryDisabler.CONFIG_ENTRY, + ) + entity_registry.async_get_or_create( + "conversation", + DOMAIN, + mock_config_entry.entry_id, + config_entry=mock_config_entry, + device_id=device_1.id, + suggested_object_id="google_generative_ai_conversation", + disabled_by=RegistryEntryDisabler.CONFIG_ENTRY, + ) + + device_2 = device_registry.async_get_or_create( + config_entry_id=mock_config_entry_2.entry_id, + identifiers={(DOMAIN, mock_config_entry_2.entry_id)}, + name=mock_config_entry_2.title, + manufacturer="Google", + model="Generative AI", + entry_type=dr.DeviceEntryType.SERVICE, + ) + entity_registry.async_get_or_create( + "conversation", + DOMAIN, + mock_config_entry_2.entry_id, + config_entry=mock_config_entry_2, + device_id=device_2.id, + suggested_object_id="google_generative_ai_conversation_2", + ) + + devices = [device_1, device_2] + + # Run migration + with patch( + "homeassistant.components.google_generative_ai_conversation.async_setup_entry", + return_value=True, + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + entry = entries[0] + assert entry.disabled_by is merged_config_entry_disabled_by + assert entry.version == 2 + assert entry.minor_version == 4 + assert not entry.options + assert entry.title == DEFAULT_TITLE + assert len(entry.subentries) == 4 + conversation_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "conversation" + ] + assert len(conversation_subentries) == 2 + for subentry in conversation_subentries: + assert subentry.subentry_type == "conversation" + assert subentry.data == options + assert "Google Generative AI" in subentry.title + tts_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "tts" + ] + assert len(tts_subentries) == 1 + assert tts_subentries[0].data == RECOMMENDED_TTS_OPTIONS + assert tts_subentries[0].title == DEFAULT_TTS_NAME + ai_task_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "ai_task_data" + ] + assert len(ai_task_subentries) == 1 + assert ai_task_subentries[0].data == RECOMMENDED_AI_TASK_OPTIONS + assert ai_task_subentries[0].title == DEFAULT_AI_TASK_NAME + + assert not device_registry.async_get_device( + identifiers={(DOMAIN, mock_config_entry.entry_id)} + ) + assert not device_registry.async_get_device( + identifiers={(DOMAIN, mock_config_entry_2.entry_id)} + ) + + for idx, subentry in enumerate(conversation_subentries): + subentry_data = conversation_subentry_data[idx] + entity = entity_registry.async_get(subentry_data["conversation_entity_id"]) + assert entity.unique_id == subentry.subentry_id + assert entity.config_subentry_id == subentry.subentry_id + assert entity.config_entry_id == entry.entry_id + assert entity.disabled_by is subentry_data["entity_disabled_by"] + + assert ( + device := device_registry.async_get_device( + identifiers={(DOMAIN, subentry.subentry_id)} + ) + ) + assert device.identifiers == {(DOMAIN, subentry.subentry_id)} + assert device.id == devices[subentry_data["device"]].id + assert device.config_entries == { + mock_config_entries[main_config_entry].entry_id + } + assert device.config_entries_subentries == { + mock_config_entries[main_config_entry].entry_id: {subentry.subentry_id} + } + assert device.disabled_by is subentry_data["device_disabled_by"] + + async def test_migration_from_v1_with_multiple_keys( hass: HomeAssistant, device_registry: dr.DeviceRegistry, @@ -634,7 +857,7 @@ async def test_migration_from_v1_with_multiple_keys( for entry in entries: assert entry.version == 2 - assert entry.minor_version == 3 + assert entry.minor_version == 4 assert not entry.options assert entry.title == DEFAULT_TITLE assert len(entry.subentries) == 3 @@ -737,7 +960,7 @@ async def test_migration_from_v1_with_same_keys( assert len(entries) == 1 entry = entries[0] assert entry.version == 2 - assert entry.minor_version == 3 + assert entry.minor_version == 4 assert not entry.options assert entry.title == DEFAULT_TITLE assert len(entry.subentries) == 4 @@ -958,7 +1181,7 @@ async def test_migration_from_v2_1( assert len(entries) == 1 entry = entries[0] assert entry.version == 2 - assert entry.minor_version == 3 + assert entry.minor_version == 4 assert not entry.options assert entry.title == DEFAULT_TITLE assert len(entry.subentries) == 4 @@ -1095,7 +1318,7 @@ async def test_migrate_entry_from_v2_2(hass: HomeAssistant) -> None: # Check version and subversion were updated assert entry.version == 2 - assert entry.minor_version == 3 + assert entry.minor_version == 4 # Check we now have conversation, tts and ai_task_data subentries assert len(entry.subentries) == 3 @@ -1124,3 +1347,194 @@ async def test_migrate_entry_from_v2_2(hass: HomeAssistant) -> None: assert tts_subentry is not None assert tts_subentry.title == DEFAULT_TTS_NAME assert tts_subentry.data == RECOMMENDED_TTS_OPTIONS + + +@pytest.mark.parametrize( + ( + "config_entry_disabled_by", + "device_disabled_by", + "entity_disabled_by", + "setup_result", + "minor_version_after_migration", + "config_entry_disabled_by_after_migration", + "device_disabled_by_after_migration", + "entity_disabled_by_after_migration", + ), + [ + # Config entry not disabled, update device and entity disabled by config entry + ( + None, + DeviceEntryDisabler.CONFIG_ENTRY, + RegistryEntryDisabler.CONFIG_ENTRY, + True, + 4, + None, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.DEVICE, + ), + ( + None, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.DEVICE, + True, + 4, + None, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.DEVICE, + ), + ( + None, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.USER, + True, + 4, + None, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.USER, + ), + ( + None, + None, + None, + True, + 4, + None, + None, + None, + ), + # Config entry disabled, migration does not run + ( + ConfigEntryDisabler.USER, + DeviceEntryDisabler.CONFIG_ENTRY, + RegistryEntryDisabler.CONFIG_ENTRY, + False, + 3, + ConfigEntryDisabler.USER, + DeviceEntryDisabler.CONFIG_ENTRY, + RegistryEntryDisabler.CONFIG_ENTRY, + ), + ( + ConfigEntryDisabler.USER, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.DEVICE, + False, + 3, + ConfigEntryDisabler.USER, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.DEVICE, + ), + ( + ConfigEntryDisabler.USER, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.USER, + False, + 3, + ConfigEntryDisabler.USER, + DeviceEntryDisabler.USER, + RegistryEntryDisabler.USER, + ), + ( + ConfigEntryDisabler.USER, + None, + None, + False, + 3, + ConfigEntryDisabler.USER, + None, + None, + ), + ], +) +async def test_migrate_entry_from_v2_3( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + config_entry_disabled_by: ConfigEntryDisabler | None, + device_disabled_by: DeviceEntryDisabler | None, + entity_disabled_by: RegistryEntryDisabler | None, + setup_result: bool, + minor_version_after_migration: int, + config_entry_disabled_by_after_migration: ConfigEntryDisabler | None, + device_disabled_by_after_migration: ConfigEntryDisabler | None, + entity_disabled_by_after_migration: RegistryEntryDisabler | None, +) -> None: + """Test migration from version 2.3.""" + # Create a v2.3 config entry with conversation and TTS subentries + conversation_subentry_id = "blabla" + mock_config_entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_API_KEY: "test-api-key"}, + disabled_by=config_entry_disabled_by, + version=2, + minor_version=3, + subentries_data=[ + { + "data": RECOMMENDED_CONVERSATION_OPTIONS, + "subentry_id": conversation_subentry_id, + "subentry_type": "conversation", + "title": DEFAULT_CONVERSATION_NAME, + "unique_id": None, + }, + { + "data": RECOMMENDED_TTS_OPTIONS, + "subentry_type": "tts", + "title": DEFAULT_TTS_NAME, + "unique_id": None, + }, + ], + ) + mock_config_entry.add_to_hass(hass) + + conversation_device = device_registry.async_get_or_create( + config_entry_id=mock_config_entry.entry_id, + config_subentry_id=conversation_subentry_id, + disabled_by=device_disabled_by, + identifiers={(DOMAIN, mock_config_entry.entry_id)}, + name=mock_config_entry.title, + manufacturer="Google", + model="Generative AI", + entry_type=dr.DeviceEntryType.SERVICE, + ) + conversation_entity = entity_registry.async_get_or_create( + "conversation", + DOMAIN, + mock_config_entry.entry_id, + config_entry=mock_config_entry, + config_subentry_id=conversation_subentry_id, + disabled_by=entity_disabled_by, + device_id=conversation_device.id, + suggested_object_id="google_generative_ai_conversation", + ) + + # Verify initial state + assert mock_config_entry.version == 2 + assert mock_config_entry.minor_version == 3 + assert len(mock_config_entry.subentries) == 2 + assert mock_config_entry.disabled_by == config_entry_disabled_by + assert conversation_device.disabled_by == device_disabled_by + assert conversation_entity.disabled_by == entity_disabled_by + + # Run setup to trigger migration + with patch( + "homeassistant.components.google_generative_ai_conversation.async_setup_entry", + return_value=True, + ): + result = await hass.config_entries.async_setup(mock_config_entry.entry_id) + assert result is setup_result + await hass.async_block_till_done() + + # Verify migration completed + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + entry = entries[0] + + # Check version and subversion were updated + assert entry.version == 2 + assert entry.minor_version == minor_version_after_migration + + # Check the disabled_by flag on config entry, device and entity are as expected + conversation_device = device_registry.async_get(conversation_device.id) + conversation_entity = entity_registry.async_get(conversation_entity.entity_id) + assert mock_config_entry.disabled_by == config_entry_disabled_by_after_migration + assert conversation_device.disabled_by == device_disabled_by_after_migration + assert conversation_entity.disabled_by == entity_disabled_by_after_migration diff --git a/tests/components/habitica/snapshots/test_sensor.ambr b/tests/components/habitica/snapshots/test_sensor.ambr index 06f9ff9a6cd..30c0f9d66eb 100644 --- a/tests/components/habitica/snapshots/test_sensor.ambr +++ b/tests/components/habitica/snapshots/test_sensor.ambr @@ -381,214 +381,6 @@ 'state': '137.625872146098', }) # --- -# name: test_sensors[sensor.test_user_habits-entry] - EntityRegistryEntrySnapshot({ - 'aliases': set({ - }), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': , - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'sensor', - 'entity_category': None, - 'entity_id': 'sensor.test_user_habits', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'options': dict({ - }), - 'original_device_class': None, - 'original_icon': None, - 'original_name': 'Habits', - 'platform': 'habitica', - 'previous_unique_id': None, - 'suggested_object_id': 'test_user_habits', - 'supported_features': 0, - 'translation_key': , - 'unique_id': 'a380546a-94be-4b8e-8a0b-23e0d5c03303_habits', - 'unit_of_measurement': 'tasks', - }) -# --- -# name: test_sensors[sensor.test_user_habits-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - '1d147de6-5c02-4740-8e2f-71d3015a37f4': dict({ - 'challenge': dict({ - 'broken': None, - 'id': None, - 'shortName': None, - 'taskId': None, - 'winner': None, - }), - 'created_at': '2024-07-07T17:51:53.266000+00:00', - 'frequency': 'daily', - 'group': dict({ - 'assignedDate': None, - 'assignedUsers': list([ - ]), - 'assignedUsersDetail': dict({ - }), - 'assigningUsername': None, - 'completedBy': dict({ - 'date': None, - 'userId': None, - }), - 'id': None, - 'managerNotes': None, - 'taskId': None, - }), - 'priority': 1, - 'repeat': dict({ - 'f': False, - 'm': True, - 's': False, - 'su': False, - 't': True, - 'th': False, - 'w': True, - }), - 'text': 'Eine kurze Pause machen', - 'type': 'habit', - 'up': True, - }), - 'bc1d1855-b2b8-4663-98ff-62e7b763dfc4': dict({ - 'challenge': dict({ - 'broken': None, - 'id': None, - 'shortName': None, - 'taskId': None, - 'winner': None, - }), - 'created_at': '2024-07-07T17:51:53.265000+00:00', - 'down': True, - 'frequency': 'daily', - 'group': dict({ - 'assignedDate': None, - 'assignedUsers': list([ - ]), - 'assignedUsersDetail': dict({ - }), - 'assigningUsername': None, - 'completedBy': dict({ - 'date': None, - 'userId': None, - }), - 'id': None, - 'managerNotes': None, - 'taskId': None, - }), - 'notes': 'Oder lösche es über die Bearbeitungs-Ansicht', - 'priority': 1, - 'repeat': dict({ - 'f': False, - 'm': True, - 's': False, - 'su': False, - 't': True, - 'th': False, - 'w': True, - }), - 'text': 'Klicke hier um dies als schlechte Gewohnheit zu markieren, die Du gerne loswerden möchtest', - 'type': 'habit', - }), - 'e97659e0-2c42-4599-a7bb-00282adc410d': dict({ - 'challenge': dict({ - 'broken': None, - 'id': None, - 'shortName': None, - 'taskId': None, - 'winner': None, - }), - 'created_at': '2024-07-07T17:51:53.264000+00:00', - 'frequency': 'daily', - 'group': dict({ - 'assignedDate': None, - 'assignedUsers': list([ - ]), - 'assignedUsersDetail': dict({ - }), - 'assigningUsername': None, - 'completedBy': dict({ - 'date': None, - 'userId': None, - }), - 'id': None, - 'managerNotes': None, - 'taskId': None, - }), - 'notes': 'Eine Gewohnheit, eine Tagesaufgabe oder ein To-Do', - 'priority': 1, - 'repeat': dict({ - 'f': False, - 'm': True, - 's': False, - 'su': False, - 't': True, - 'th': False, - 'w': True, - }), - 'text': 'Füge eine Aufgabe zu Habitica hinzu', - 'type': 'habit', - 'up': True, - }), - 'f21fa608-cfc6-4413-9fc7-0eb1b48ca43a': dict({ - 'challenge': dict({ - 'broken': None, - 'id': None, - 'shortName': None, - 'taskId': None, - 'winner': None, - }), - 'created_at': '2024-07-07T17:51:53.268000+00:00', - 'down': True, - 'frequency': 'daily', - 'group': dict({ - 'assignedDate': None, - 'assignedUsers': list([ - ]), - 'assignedUsersDetail': dict({ - }), - 'assigningUsername': None, - 'completedBy': dict({ - 'date': None, - 'userId': None, - }), - 'id': None, - 'managerNotes': None, - 'taskId': None, - }), - 'priority': 1, - 'repeat': dict({ - 'f': False, - 'm': True, - 's': False, - 'su': False, - 't': True, - 'th': False, - 'w': True, - }), - 'text': 'Gesundes Essen/Junkfood', - 'type': 'habit', - 'up': True, - }), - 'friendly_name': 'test-user Habits', - 'unit_of_measurement': 'tasks', - }), - 'context': , - 'entity_id': 'sensor.test_user_habits', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': '4', - }) -# --- # name: test_sensors[sensor.test_user_hatching_potions-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ @@ -853,55 +645,6 @@ 'state': '50.9', }) # --- -# name: test_sensors[sensor.test_user_max_health-entry] - EntityRegistryEntrySnapshot({ - 'aliases': set({ - }), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': , - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'sensor', - 'entity_category': None, - 'entity_id': 'sensor.test_user_max_health', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'options': dict({ - }), - 'original_device_class': None, - 'original_icon': None, - 'original_name': 'Max. health', - 'platform': 'habitica', - 'previous_unique_id': None, - 'suggested_object_id': 'test_user_max_health', - 'supported_features': 0, - 'translation_key': , - 'unique_id': 'a380546a-94be-4b8e-8a0b-23e0d5c03303_health_max', - 'unit_of_measurement': 'HP', - }) -# --- -# name: test_sensors[sensor.test_user_max_health-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - 'friendly_name': 'test-user Max. health', - 'unit_of_measurement': 'HP', - }), - 'context': , - 'entity_id': 'sensor.test_user_max_health', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': '50', - }) -# --- # name: test_sensors[sensor.test_user_max_mana-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ @@ -1321,98 +1064,6 @@ 'state': '2', }) # --- -# name: test_sensors[sensor.test_user_rewards-entry] - EntityRegistryEntrySnapshot({ - 'aliases': set({ - }), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': , - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'sensor', - 'entity_category': None, - 'entity_id': 'sensor.test_user_rewards', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'options': dict({ - }), - 'original_device_class': None, - 'original_icon': None, - 'original_name': 'Rewards', - 'platform': 'habitica', - 'previous_unique_id': None, - 'suggested_object_id': 'test_user_rewards', - 'supported_features': 0, - 'translation_key': , - 'unique_id': 'a380546a-94be-4b8e-8a0b-23e0d5c03303_rewards', - 'unit_of_measurement': 'tasks', - }) -# --- -# name: test_sensors[sensor.test_user_rewards-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - '5e2ea1df-f6e6-4ba3-bccb-97c5ec63e99b': dict({ - 'challenge': dict({ - 'broken': None, - 'id': None, - 'shortName': None, - 'taskId': None, - 'winner': None, - }), - 'created_at': '2024-07-07T17:51:53.266000+00:00', - 'group': dict({ - 'assignedDate': None, - 'assignedUsers': list([ - ]), - 'assignedUsersDetail': dict({ - }), - 'assigningUsername': None, - 'completedBy': dict({ - 'date': None, - 'userId': None, - }), - 'id': None, - 'managerNotes': None, - 'taskId': None, - }), - 'notes': 'Schaue fern, spiele ein Spiel, gönne Dir einen Leckerbissen, es liegt ganz bei Dir!', - 'priority': 1, - 'repeat': dict({ - 'f': False, - 'm': True, - 's': False, - 'su': False, - 't': True, - 'th': False, - 'w': True, - }), - 'tags': list([ - '3450351f-1323-4c7e-9fd2-0cdff25b3ce0', - 'b2780f82-b3b5-49a3-a677-48f2c8c7e3bb', - ]), - 'text': 'Belohne Dich selbst', - 'type': 'reward', - 'value': 10.0, - }), - 'friendly_name': 'test-user Rewards', - 'unit_of_measurement': 'tasks', - }), - 'context': , - 'entity_id': 'sensor.test_user_rewards', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': '1', - }) -# --- # name: test_sensors[sensor.test_user_saddles-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/habitica/test_sensor.py b/tests/components/habitica/test_sensor.py index 1c648e38720..9dde266d214 100644 --- a/tests/components/habitica/test_sensor.py +++ b/tests/components/habitica/test_sensor.py @@ -6,13 +6,10 @@ from unittest.mock import patch import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components.habitica.const import DOMAIN -from homeassistant.components.habitica.sensor import HabiticaSensorEntity -from homeassistant.components.sensor.const import DOMAIN as SENSOR_DOMAIN from homeassistant.config_entries import ConfigEntryState from homeassistant.const import Platform from homeassistant.core import HomeAssistant -from homeassistant.helpers import entity_registry as er, issue_registry as ir +from homeassistant.helpers import entity_registry as er from tests.common import MockConfigEntry, snapshot_platform @@ -36,19 +33,6 @@ async def test_sensors( ) -> None: """Test setup of the Habitica sensor platform.""" - for entity in ( - ("test_user_habits", "habits"), - ("test_user_rewards", "rewards"), - ("test_user_max_health", "health_max"), - ): - entity_registry.async_get_or_create( - SENSOR_DOMAIN, - DOMAIN, - f"a380546a-94be-4b8e-8a0b-23e0d5c03303_{entity[1]}", - suggested_object_id=entity[0], - disabled_by=None, - ) - config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() @@ -56,96 +40,3 @@ async def test_sensors( assert config_entry.state is ConfigEntryState.LOADED await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id) - - -@pytest.mark.parametrize( - ("entity_id", "key"), - [ - ("test_user_habits", HabiticaSensorEntity.HABITS), - ("test_user_rewards", HabiticaSensorEntity.REWARDS), - ("test_user_max_health", HabiticaSensorEntity.HEALTH_MAX), - ], -) -@pytest.mark.usefixtures("habitica", "entity_registry_enabled_by_default") -async def test_sensor_deprecation_issue( - hass: HomeAssistant, - config_entry: MockConfigEntry, - issue_registry: ir.IssueRegistry, - entity_registry: er.EntityRegistry, - entity_id: str, - key: HabiticaSensorEntity, -) -> None: - """Test sensor deprecation issue.""" - entity_registry.async_get_or_create( - SENSOR_DOMAIN, - DOMAIN, - f"a380546a-94be-4b8e-8a0b-23e0d5c03303_{key}", - suggested_object_id=entity_id, - disabled_by=None, - ) - - assert entity_registry is not None - with patch( - "homeassistant.components.habitica.sensor.entity_used_in", return_value=True - ): - 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 entity_registry.async_get(f"sensor.{entity_id}") is not None - assert issue_registry.async_get_issue( - domain=DOMAIN, - issue_id=f"deprecated_entity_{key}", - ) - - -@pytest.mark.parametrize( - ("entity_id", "key"), - [ - ("test_user_habits", HabiticaSensorEntity.HABITS), - ("test_user_rewards", HabiticaSensorEntity.REWARDS), - ("test_user_max_health", HabiticaSensorEntity.HEALTH_MAX), - ], -) -@pytest.mark.usefixtures("habitica", "entity_registry_enabled_by_default") -async def test_sensor_deprecation_delete_disabled( - hass: HomeAssistant, - config_entry: MockConfigEntry, - issue_registry: ir.IssueRegistry, - entity_registry: er.EntityRegistry, - entity_id: str, - key: HabiticaSensorEntity, -) -> None: - """Test sensor deletion .""" - - entity_registry.async_get_or_create( - SENSOR_DOMAIN, - DOMAIN, - f"a380546a-94be-4b8e-8a0b-23e0d5c03303_{key}", - suggested_object_id=entity_id, - disabled_by=er.RegistryEntryDisabler.USER, - ) - - assert entity_registry is not None - with patch( - "homeassistant.components.habitica.sensor.entity_used_in", return_value=True - ): - 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 ( - issue_registry.async_get_issue( - domain=DOMAIN, - issue_id=f"deprecated_entity_{key}", - ) - is None - ) - - assert entity_registry.async_get(f"sensor.{entity_id}") is None diff --git a/tests/components/hassio/test_ingress.py b/tests/components/hassio/test_ingress.py index 069abaa8513..cad410e6a21 100644 --- a/tests/components/hassio/test_ingress.py +++ b/tests/components/hassio/test_ingress.py @@ -4,6 +4,7 @@ from http import HTTPStatus from unittest.mock import MagicMock, patch from aiohttp.hdrs import X_FORWARDED_FOR, X_FORWARDED_HOST, X_FORWARDED_PROTO +from multidict import CIMultiDict import pytest from homeassistant.components.hassio.const import X_AUTH_TOKEN @@ -28,15 +29,22 @@ async def test_ingress_request_get( aioclient_mock.get( f"http://127.0.0.1/ingress/{build_type[0]}/{build_type[1]}", text="test", + headers=CIMultiDict( + [("Set-Cookie", "cookie1=value1"), ("Set-Cookie", "cookie2=value2")] + ), ) resp = await hassio_noauth_client.get( f"/api/hassio_ingress/{build_type[0]}/{build_type[1]}", - headers={"X-Test-Header": "beer"}, + headers=CIMultiDict( + [("X-Test-Header", "beer"), ("X-Test-Header", "more beer")] + ), ) # Check we got right response assert resp.status == HTTPStatus.OK + assert resp.headers["Set-Cookie"] == "cookie1=value1" + assert resp.headers.getall("Set-Cookie") == ["cookie1=value1", "cookie2=value2"] body = await resp.text() assert body == "test" @@ -49,6 +57,10 @@ async def test_ingress_request_get( == f"/api/hassio_ingress/{build_type[0]}" ) assert aioclient_mock.mock_calls[-1][3]["X-Test-Header"] == "beer" + assert aioclient_mock.mock_calls[-1][3].getall("X-Test-Header") == [ + "beer", + "more beer", + ] assert aioclient_mock.mock_calls[-1][3][X_FORWARDED_FOR] assert aioclient_mock.mock_calls[-1][3][X_FORWARDED_HOST] assert aioclient_mock.mock_calls[-1][3][X_FORWARDED_PROTO] diff --git a/tests/components/hddtemp/test_sensor.py b/tests/components/hddtemp/test_sensor.py index 62882c7df8b..56ad9fdcb0e 100644 --- a/tests/components/hddtemp/test_sensor.py +++ b/tests/components/hddtemp/test_sensor.py @@ -1,15 +1,12 @@ """The tests for the hddtemp platform.""" import socket -from unittest.mock import Mock, patch +from unittest.mock import patch import pytest -from homeassistant.components.hddtemp import DOMAIN -from homeassistant.components.sensor import DOMAIN as PLATFORM_DOMAIN from homeassistant.const import UnitOfTemperature -from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant -from homeassistant.helpers import issue_registry as ir +from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component VALID_CONFIG_MINIMAL = {"sensor": {"platform": "hddtemp"}} @@ -195,17 +192,3 @@ async def test_hddtemp_host_unreachable(hass: HomeAssistant, telnetmock) -> None assert await async_setup_component(hass, "sensor", VALID_CONFIG_HOST_UNREACHABLE) await hass.async_block_till_done() assert len(hass.states.async_all()) == 0 - - -@patch.dict("sys.modules", gsp=Mock()) -async def test_repair_issue_is_created( - hass: HomeAssistant, - issue_registry: ir.IssueRegistry, -) -> None: - """Test repair issue is created.""" - assert await async_setup_component(hass, PLATFORM_DOMAIN, VALID_CONFIG_MINIMAL) - await hass.async_block_till_done() - assert ( - HOMEASSISTANT_DOMAIN, - f"deprecated_system_packages_yaml_integration_{DOMAIN}", - ) in issue_registry.issues diff --git a/tests/components/heos/conftest.py b/tests/components/heos/conftest.py index 835e4436398..e72c72c7334 100644 --- a/tests/components/heos/conftest.py +++ b/tests/components/heos/conftest.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Callable, Iterator +from ipaddress import ip_address from unittest.mock import Mock, patch from pyheos import ( @@ -39,6 +40,7 @@ from homeassistant.helpers.service_info.ssdp import ( ATTR_UPNP_UDN, SsdpServiceInfo, ) +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from . import MockHeos @@ -284,6 +286,36 @@ def discovery_data_fixture_bedroom() -> SsdpServiceInfo: ) +@pytest.fixture(name="zeroconf_discovery_data") +def zeroconf_discovery_data_fixture() -> ZeroconfServiceInfo: + """Return mock discovery data for testing.""" + host = "127.0.0.1" + return ZeroconfServiceInfo( + ip_address=ip_address(host), + ip_addresses=[ip_address(host)], + port=10101, + hostname=host, + type="mock_type", + name="MyDenon._heos-audio._tcp.local.", + properties={}, + ) + + +@pytest.fixture(name="zeroconf_discovery_data_bedroom") +def zeroconf_discovery_data_fixture_bedroom() -> ZeroconfServiceInfo: + """Return mock discovery data for testing.""" + host = "127.0.0.2" + return ZeroconfServiceInfo( + ip_address=ip_address(host), + ip_addresses=[ip_address(host)], + port=10101, + hostname=host, + type="mock_type", + name="MyDenonBedroom._heos-audio._tcp.local.", + properties={}, + ) + + @pytest.fixture(name="quick_selects") def quick_selects_fixture() -> dict[int, str]: """Create a dict of quick selects for testing.""" diff --git a/tests/components/heos/test_config_flow.py b/tests/components/heos/test_config_flow.py index 69d9aa3a38e..4749dc48b01 100644 --- a/tests/components/heos/test_config_flow.py +++ b/tests/components/heos/test_config_flow.py @@ -18,12 +18,14 @@ from homeassistant.config_entries import ( SOURCE_IGNORE, SOURCE_SSDP, SOURCE_USER, + SOURCE_ZEROCONF, ConfigEntryState, ) from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo +from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo from . import MockHeos @@ -244,6 +246,143 @@ async def test_discovery_updates( assert config_entry.data[CONF_HOST] == "127.0.0.2" +async def test_zeroconf_discovery( + hass: HomeAssistant, + zeroconf_discovery_data: ZeroconfServiceInfo, + zeroconf_discovery_data_bedroom: ZeroconfServiceInfo, + controller: MockHeos, + system: HeosSystem, +) -> None: + """Test discovery shows form to confirm, then creates entry.""" + # Single discovered, selects preferred host, shows confirm + controller.get_system_info.return_value = system + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=zeroconf_discovery_data_bedroom, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "confirm_discovery" + assert controller.connect.call_count == 1 + assert controller.get_system_info.call_count == 1 + assert controller.disconnect.call_count == 1 + + # Subsequent discovered hosts abort. + subsequent_result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_discovery_data + ) + assert subsequent_result["type"] is FlowResultType.ABORT + assert subsequent_result["reason"] == "already_in_progress" + + # Confirm set up + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == DOMAIN + assert result["title"] == "HEOS System" + assert result["data"] == {CONF_HOST: "127.0.0.1"} + + +async def test_zeroconf_discovery_flow_aborts_already_setup( + hass: HomeAssistant, + zeroconf_discovery_data_bedroom: ZeroconfServiceInfo, + config_entry: MockConfigEntry, + controller: MockHeos, +) -> None: + """Test discovery flow aborts when entry already setup and hosts didn't change.""" + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + assert config_entry.data[CONF_HOST] == "127.0.0.1" + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=zeroconf_discovery_data_bedroom, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "single_instance_allowed" + assert controller.get_system_info.call_count == 0 + assert config_entry.data[CONF_HOST] == "127.0.0.1" + + +async def test_zeroconf_discovery_aborts_same_system( + hass: HomeAssistant, + zeroconf_discovery_data_bedroom: ZeroconfServiceInfo, + controller: MockHeos, + config_entry: MockConfigEntry, + system: HeosSystem, +) -> None: + """Test discovery does not update when current host is part of discovered's system.""" + config_entry.add_to_hass(hass) + assert config_entry.data[CONF_HOST] == "127.0.0.1" + + controller.get_system_info.return_value = system + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=zeroconf_discovery_data_bedroom, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "single_instance_allowed" + assert controller.get_system_info.call_count == 1 + assert config_entry.data[CONF_HOST] == "127.0.0.1" + + +async def test_zeroconf_discovery_ignored_aborts( + hass: HomeAssistant, + zeroconf_discovery_data: ZeroconfServiceInfo, +) -> None: + """Test discovery aborts when ignored.""" + MockConfigEntry(domain=DOMAIN, unique_id=DOMAIN, source=SOURCE_IGNORE).add_to_hass( + hass + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_discovery_data + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "single_instance_allowed" + + +async def test_zeroconf_discovery_fails_to_connect_aborts( + hass: HomeAssistant, + zeroconf_discovery_data: ZeroconfServiceInfo, + controller: MockHeos, +) -> None: + """Test discovery aborts when trying to connect to host.""" + controller.connect.side_effect = HeosError() + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_ZEROCONF}, data=zeroconf_discovery_data + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "cannot_connect" + assert controller.connect.call_count == 1 + assert controller.disconnect.call_count == 1 + + +async def test_zeroconf_discovery_updates( + hass: HomeAssistant, + zeroconf_discovery_data_bedroom: ZeroconfServiceInfo, + controller: MockHeos, + config_entry: MockConfigEntry, +) -> None: + """Test discovery updates existing entry.""" + config_entry.add_to_hass(hass) + assert config_entry.data[CONF_HOST] == "127.0.0.1" + + host = HeosHost("Player", "Model", None, None, "127.0.0.2", NetworkType.WIRED, True) + controller.get_system_info.return_value = HeosSystem(None, host, [host]) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=zeroconf_discovery_data_bedroom, + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert config_entry.data[CONF_HOST] == "127.0.0.2" + + async def test_reconfigure_validates_and_updates_config( hass: HomeAssistant, config_entry: MockConfigEntry, controller: MockHeos ) -> None: diff --git a/tests/components/history_stats/test_init.py b/tests/components/history_stats/test_init.py index cb3350f497f..7f81fe6625f 100644 --- a/tests/components/history_stats/test_init.py +++ b/tests/components/history_stats/test_init.py @@ -18,7 +18,7 @@ from homeassistant.components.history_stats.const import ( ) from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.const import CONF_ENTITY_ID, CONF_NAME, CONF_STATE, CONF_TYPE -from homeassistant.core import Event, HomeAssistant +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -92,6 +92,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -181,7 +182,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( history_stats_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(history_stats_config_entry.entry_id) @@ -196,9 +197,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( history_stats_config_entry.entry_id ) - assert len(devices_after_reload) == 1 - - assert devices_after_reload[0].id == source_device1_entry.id + assert len(devices_after_reload) == 0 @pytest.mark.usefixtures("recorder_mock") @@ -210,6 +209,56 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the history_stats config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(history_stats_config_entry.entry_id) + await hass.async_block_till_done() + + history_stats_entity_entry = entity_registry.async_get("sensor.my_history_stats") + assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert history_stats_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, history_stats_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.history_stats.async_unload_entry", + wraps=history_stats.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_called_once() + + # Check that the helper entity is removed + assert not entity_registry.async_get("sensor.my_history_stats") + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the history_stats config entry is removed + assert ( + history_stats_config_entry.entry_id not in hass.config_entries.async_entry_ids() + ) + + # Check we got the expected events + assert events == ["remove"] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + history_stats_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the history_stats config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -226,7 +275,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert history_stats_config_entry.entry_id in sensor_device.config_entries + assert history_stats_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, history_stats_entity_entry.entity_id) @@ -243,7 +292,10 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the history_stats config entry is removed from the device + # Check that the helper entity is removed + assert not entity_registry.async_get("sensor.my_history_stats") + + # Check that the history_stats config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert history_stats_config_entry.entry_id not in sensor_device.config_entries @@ -273,7 +325,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert history_stats_config_entry.entry_id in sensor_device.config_entries + assert history_stats_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, history_stats_entity_entry.entity_id) @@ -288,7 +340,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the history_stats config entry is removed from the device + # Check that the entity is no longer linked to the source device + history_stats_entity_entry = entity_registry.async_get("sensor.my_history_stats") + assert history_stats_entity_entry.device_id is None + + # Check that the history_stats config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert history_stats_config_entry.entry_id not in sensor_device.config_entries @@ -322,7 +378,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert history_stats_config_entry.entry_id in sensor_device.config_entries + assert history_stats_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert history_stats_config_entry.entry_id not in sensor_device_2.config_entries @@ -339,11 +395,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the history_stats config entry is moved to the other device + # Check that the entity is linked to the other device + history_stats_entity_entry = entity_registry.async_get("sensor.my_history_stats") + assert history_stats_entity_entry.device_id == sensor_device_2.id + + # Check that the history_stats config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert history_stats_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert history_stats_config_entry.entry_id in sensor_device_2.config_entries + assert history_stats_config_entry.entry_id not in sensor_device_2.config_entries # Check that the history_stats config entry is not removed assert history_stats_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -369,7 +429,7 @@ async def test_async_handle_source_entity_new_entity_id( assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert history_stats_config_entry.entry_id in sensor_device.config_entries + assert history_stats_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, history_stats_entity_entry.entity_id) @@ -387,12 +447,91 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the history_stats config entry is updated with the new entity ID assert history_stats_config_entry.options[CONF_ENTITY_ID] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert history_stats_config_entry.entry_id in sensor_device.config_entries + assert history_stats_config_entry.entry_id not in sensor_device.config_entries # Check that the history_stats config entry is not removed assert history_stats_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +@pytest.mark.usefixtures("recorder_mock") +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, +) -> None: + """Test migration from v1.1 removes history_stats config entry from device.""" + + history_stats_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + CONF_NAME: DEFAULT_NAME, + CONF_ENTITY_ID: sensor_entity_entry.entity_id, + CONF_STATE: ["on"], + CONF_TYPE: "count", + CONF_START: "{{ as_timestamp(utcnow()) - 3600 }}", + CONF_END: "{{ utcnow() }}", + }, + title="My history stats", + version=1, + minor_version=1, + ) + history_stats_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=history_stats_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert history_stats_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(history_stats_config_entry.entry_id) + await hass.async_block_till_done() + + assert history_stats_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert history_stats_config_entry.entry_id not in sensor_device.config_entries + history_stats_entity_entry = entity_registry.async_get("sensor.my_history_stats") + assert history_stats_entity_entry.device_id == sensor_entity_entry.device_id + + assert history_stats_config_entry.version == 1 + assert history_stats_config_entry.minor_version == 2 + + +@pytest.mark.usefixtures("recorder_mock") +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + CONF_NAME: DEFAULT_NAME, + CONF_ENTITY_ID: "sensor.test", + CONF_STATE: ["on"], + CONF_TYPE: "count", + CONF_START: "{{ as_timestamp(utcnow()) - 3600 }}", + CONF_END: "{{ utcnow() }}", + }, + title="My history stats", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/home_connect/test_button.py b/tests/components/home_connect/test_button.py index ee4d5f1d729..e61ec5e2b1f 100644 --- a/tests/components/home_connect/test_button.py +++ b/tests/components/home_connect/test_button.py @@ -1,12 +1,14 @@ """Tests for home_connect button entities.""" from collections.abc import Awaitable, Callable -from typing import Any +from typing import Any, cast from unittest.mock import AsyncMock, MagicMock from aiohomeconnect.model import ( ArrayOfCommands, CommandKey, + Event, + EventKey, EventMessage, HomeAppliance, ) @@ -317,3 +319,62 @@ async def test_stop_program_button_exception( {ATTR_ENTITY_ID: entity_id}, blocking=True, ) + + +@pytest.mark.parametrize("appliance", ["Washer"], indirect=True) +async def test_enable_resume_command_on_pause( + hass: HomeAssistant, + client: MagicMock, + config_entry: MockConfigEntry, + integration_setup: Callable[[MagicMock], Awaitable[bool]], + appliance: HomeAppliance, +) -> None: + """Test if all commands enabled option works as expected.""" + entity_id = "button.washer_resume_program" + + original_get_available_commands = client.get_available_commands + + async def get_available_commands_side_effect(ha_id: str) -> ArrayOfCommands: + array_of_commands = cast( + ArrayOfCommands, await original_get_available_commands(ha_id) + ) + if ha_id == appliance.ha_id: + for command in array_of_commands.commands: + if command.key == CommandKey.BSH_COMMON_RESUME_PROGRAM: + # Simulate that the resume command is not available initially + array_of_commands.commands.remove(command) + break + return array_of_commands + + client.get_available_commands = AsyncMock( + side_effect=get_available_commands_side_effect + ) + + assert await integration_setup(client) + assert config_entry.state is ConfigEntryState.LOADED + + assert not hass.states.get(entity_id) + + await client.add_events( + [ + EventMessage( + appliance.ha_id, + EventType.STATUS, + data=ArrayOfEvents( + [ + Event( + key=EventKey.BSH_COMMON_STATUS_OPERATION_STATE, + raw_key=EventKey.BSH_COMMON_STATUS_OPERATION_STATE.value, + timestamp=0, + level="", + handling="", + value="BSH.Common.EnumType.OperationState.Pause", + ) + ] + ), + ) + ] + ) + await hass.async_block_till_done() + + assert hass.states.get(entity_id) diff --git a/tests/components/home_connect/test_coordinator.py b/tests/components/home_connect/test_coordinator.py index f9fed995b89..a368cfbef2d 100644 --- a/tests/components/home_connect/test_coordinator.py +++ b/tests/components/home_connect/test_coordinator.py @@ -2,7 +2,6 @@ from collections.abc import Awaitable, Callable from datetime import timedelta -from http import HTTPStatus from typing import Any, cast from unittest.mock import AsyncMock, MagicMock, patch @@ -53,16 +52,11 @@ from homeassistant.core import ( HomeAssistant, callback, ) -from homeassistant.helpers import ( - device_registry as dr, - entity_registry as er, - issue_registry as ir, -) +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util from tests.common import MockConfigEntry, async_fire_time_changed -from tests.typing import ClientSessionGenerator INITIAL_FETCH_CLIENT_METHODS = [ "get_settings", @@ -580,8 +574,7 @@ async def test_paired_disconnected_devices_not_fetching( async def test_coordinator_disabling_updates_for_appliance( hass: HomeAssistant, - hass_client: ClientSessionGenerator, - issue_registry: ir.IssueRegistry, + freezer: FrozenDateTimeFactory, client: MagicMock, config_entry: MockConfigEntry, integration_setup: Callable[[MagicMock], Awaitable[bool]], @@ -592,7 +585,6 @@ async def test_coordinator_disabling_updates_for_appliance( When the user confirms the issue the updates should be enabled again. """ appliance_ha_id = "SIEMENS-HCS02DWH1-6BE58C26DCC1" - issue_id = f"home_connect_too_many_connected_paired_events_{appliance_ha_id}" assert await integration_setup(client) assert config_entry.state is ConfigEntryState.LOADED @@ -606,13 +598,26 @@ async def test_coordinator_disabling_updates_for_appliance( EventType.CONNECTED, data=ArrayOfEvents([]), ) - for _ in range(8) + for _ in range(6) ] ) await hass.async_block_till_done() - issue = issue_registry.async_get_issue(DOMAIN, issue_id) - assert issue + freezer.tick(timedelta(minutes=10)) + await client.add_events( + [ + EventMessage( + appliance_ha_id, + EventType.CONNECTED, + data=ArrayOfEvents([]), + ) + for _ in range(2) + ] + ) + await hass.async_block_till_done() + + # At this point, the updates have been blocked because + # 6 + 2 connected events have been received in less than an hour get_settings_original_side_effect = client.get_settings.side_effect @@ -644,18 +649,36 @@ async def test_coordinator_disabling_updates_for_appliance( assert hass.states.is_state("switch.dishwasher_power", STATE_ON) - _client = await hass_client() - resp = await _client.post( - "/api/repairs/issues/fix", - json={"handler": DOMAIN, "issue_id": issue.issue_id}, + # After 55 minutes, the updates should be enabled again + # because one hour has passed since the first connect events, + # so there are 2 connected events in the execution_tracker + freezer.tick(timedelta(minutes=55)) + await client.add_events( + [ + EventMessage( + appliance_ha_id, + EventType.CONNECTED, + data=ArrayOfEvents([]), + ) + ] ) - assert resp.status == HTTPStatus.OK - flow_id = (await resp.json())["flow_id"] - resp = await _client.post(f"/api/repairs/issues/fix/{flow_id}") - assert resp.status == HTTPStatus.OK + await hass.async_block_till_done() - assert not issue_registry.async_get_issue(DOMAIN, issue_id) + assert hass.states.is_state("switch.dishwasher_power", STATE_OFF) + # If more connect events are sent, it should be blocked again + await client.add_events( + [ + EventMessage( + appliance_ha_id, + EventType.CONNECTED, + data=ArrayOfEvents([]), + ) + for _ in range(5) # 2 + 1 + 5 = 8 connect events in less than an hour + ] + ) + await hass.async_block_till_done() + client.get_settings = get_settings_original_side_effect await client.add_events( [ EventMessage( @@ -672,7 +695,6 @@ async def test_coordinator_disabling_updates_for_appliance( async def test_coordinator_disabling_updates_for_appliance_is_gone_after_entry_reload( hass: HomeAssistant, - issue_registry: ir.IssueRegistry, client: MagicMock, config_entry: MockConfigEntry, integration_setup: Callable[[MagicMock], Awaitable[bool]], @@ -682,7 +704,6 @@ async def test_coordinator_disabling_updates_for_appliance_is_gone_after_entry_r The repair issue should also be deleted. """ appliance_ha_id = "SIEMENS-HCS02DWH1-6BE58C26DCC1" - issue_id = f"home_connect_too_many_connected_paired_events_{appliance_ha_id}" assert await integration_setup(client) assert config_entry.state is ConfigEntryState.LOADED @@ -701,14 +722,9 @@ async def test_coordinator_disabling_updates_for_appliance_is_gone_after_entry_r ) await hass.async_block_till_done() - issue = issue_registry.async_get_issue(DOMAIN, issue_id) - assert issue - await hass.config_entries.async_unload(config_entry.entry_id) await hass.async_block_till_done() - assert not issue_registry.async_get_issue(DOMAIN, issue_id) - assert await integration_setup(client) assert config_entry.state is ConfigEntryState.LOADED diff --git a/tests/components/homekit_controller/conftest.py b/tests/components/homekit_controller/conftest.py index 882d0d60e66..bf05efada72 100644 --- a/tests/components/homekit_controller/conftest.py +++ b/tests/components/homekit_controller/conftest.py @@ -66,9 +66,7 @@ def fake_ble_discovery() -> Generator[None]: """Fake BLE discovery.""" class FakeBLEDiscovery(FakeDiscovery): - device = BLEDevice( - address="AA:BB:CC:DD:EE:FF", name="TestDevice", rssi=-50, details=() - ) + device = BLEDevice(address="AA:BB:CC:DD:EE:FF", name="TestDevice", details=()) with patch("aiohomekit.testing.FakeDiscovery", FakeBLEDiscovery): yield diff --git a/tests/components/homematicip_cloud/fixtures/homematicip_cloud.json b/tests/components/homematicip_cloud/fixtures/homematicip_cloud.json index 65f8afe55fa..c378190d00c 100644 --- a/tests/components/homematicip_cloud/fixtures/homematicip_cloud.json +++ b/tests/components/homematicip_cloud/fixtures/homematicip_cloud.json @@ -8297,6 +8297,152 @@ "type": "DOOR_BELL_CONTACT_INTERFACE", "updateState": "UP_TO_DATE" }, + "3014F7110000000000000CTV": { + "availableFirmwareVersion": "0.0.0", + "connectionType": "HMIP_RF", + "deviceArchetype": "HMIP", + "firmwareVersion": "1.0.6", + "firmwareVersionInteger": 65542, + "functionalChannels": { + "0": { + "busConfigMismatch": null, + "coProFaulty": false, + "coProRestartNeeded": false, + "coProUpdateFailure": false, + "configPending": false, + "controlsMountingOrientation": null, + "daliBusState": null, + "defaultLinkedGroup": [], + "deviceAliveSignalEnabled": null, + "deviceCommunicationError": null, + "deviceDriveError": null, + "deviceDriveModeError": null, + "deviceId": "3014F7110000000000000CTV", + "deviceOperationMode": null, + "deviceOverheated": false, + "deviceOverloaded": false, + "devicePowerFailureDetected": false, + "deviceUndervoltage": false, + "displayContrast": null, + "displayMode": null, + "displayMountingOrientation": null, + "dutyCycle": false, + "functionalChannelType": "DEVICE_BASE", + "groupIndex": 0, + "groups": [ + "00000000-0000-0000-0000-000000000041", + "00000000-0000-0000-0000-000000000042" + ], + "index": 0, + "invertedDisplayColors": null, + "label": "", + "lockJammed": null, + "lowBat": false, + "mountingOrientation": null, + "multicastRoutingEnabled": false, + "operationDays": null, + "particulateMatterSensorCommunicationError": null, + "particulateMatterSensorError": null, + "powerShortCircuit": null, + "profilePeriodLimitReached": null, + "routerModuleEnabled": false, + "routerModuleSupported": false, + "rssiDeviceValue": -102, + "rssiPeerValue": null, + "sensorCommunicationError": null, + "sensorError": null, + "shortCircuitDataLine": null, + "supportedOptionalFeatures": { + "IFeatureBusConfigMismatch": false, + "IFeatureDeviceCoProError": false, + "IFeatureDeviceCoProRestart": false, + "IFeatureDeviceCoProUpdate": false, + "IFeatureDeviceCommunicationError": false, + "IFeatureDeviceDaliBusError": false, + "IFeatureDeviceDriveError": false, + "IFeatureDeviceDriveModeError": false, + "IFeatureDeviceIdentify": false, + "IFeatureDeviceOverheated": false, + "IFeatureDeviceOverloaded": false, + "IFeatureDeviceParticulateMatterSensorCommunicationError": false, + "IFeatureDeviceParticulateMatterSensorError": false, + "IFeatureDevicePowerFailure": false, + "IFeatureDeviceSensorCommunicationError": false, + "IFeatureDeviceSensorError": false, + "IFeatureDeviceTemperatureHumiditySensorCommunicationError": false, + "IFeatureDeviceTemperatureHumiditySensorError": false, + "IFeatureDeviceTemperatureOutOfRange": false, + "IFeatureDeviceUndervoltage": false, + "IFeatureMulticastRouter": false, + "IFeaturePowerShortCircuit": false, + "IFeatureProfilePeriodLimit": false, + "IFeatureRssiValue": true, + "IFeatureShortCircuitDataLine": false, + "IOptionalFeatureDefaultLinkedGroup": false, + "IOptionalFeatureDeviceAliveSignalEnabled": false, + "IOptionalFeatureDeviceErrorLockJammed": false, + "IOptionalFeatureDeviceOperationMode": false, + "IOptionalFeatureDisplayContrast": false, + "IOptionalFeatureDisplayMode": false, + "IOptionalFeatureDutyCycle": true, + "IOptionalFeatureInvertedDisplayColors": false, + "IOptionalFeatureLowBat": true, + "IOptionalFeatureMountingOrientation": false, + "IOptionalFeatureOperationDays": false + }, + "temperatureHumiditySensorCommunicationError": null, + "temperatureHumiditySensorError": null, + "temperatureOutOfRange": false, + "unreach": false + }, + "1": { + "absoluteAngle": 89, + "accelerationSensorEventFilterPeriod": 3.0, + "accelerationSensorMode": "TILT", + "accelerationSensorNeutralPosition": "VERTICAL", + "accelerationSensorSecondTriggerAngle": 75, + "accelerationSensorSensitivity": "SENSOR_RANGE_2G_2PLUS_SENSE", + "accelerationSensorTriggerAngle": 20, + "accelerationSensorTriggered": false, + "channelRole": "ACCELERATION_SENSOR", + "deviceId": "3014F7110000000000000CTV", + "functionalChannelType": "TILT_VIBRATION_SENSOR_CHANNEL", + "groupIndex": 1, + "groups": [ + "00000000-0000-0000-0000-000000000023", + "00000000-0000-0000-0000-000000000041", + "00000000-0000-0000-0000-000000000043" + ], + "index": 1, + "label": "", + "supportedOptionalFeatures": { + "IFeatureLightGroupSensorChannel": false, + "IOptionalFeatureAbsoluteAngle": true, + "IOptionalFeatureAccelerationSensorTiltTriggerAngle": true, + "IOptionalFeatureTiltDetection": true, + "IOptionalFeatureTiltState": true, + "IOptionalFeatureTiltVisualization": true + }, + "tiltState": "NEUTRAL", + "tiltVisualization": "GARAGE_DOOR" + } + }, + "homeId": "00000000-0000-0000-0000-000000000001", + "id": "3014F7110000000000000CTV", + "label": "Neigungssensor Tor", + "lastStatusUpdate": 1741379260066, + "liveUpdateState": "LIVE_UPDATE_NOT_SUPPORTED", + "manuallyUpdateForced": false, + "manufacturerCode": 9, + "measuredAttributes": {}, + "modelId": 580, + "modelType": "ELV-SH-CTV", + "oem": "eQ-3", + "permanentlyReachable": false, + "serializedGlobalTradeItemNumber": "3014F7110000000000000CTV", + "type": "TILT_VIBRATION_SENSOR_COMPACT", + "updateState": "UP_TO_DATE" + }, "3014F71100000000000SVCTH": { "availableFirmwareVersion": "1.0.10", "connectionType": "HMIP_RF", diff --git a/tests/components/homematicip_cloud/test_device.py b/tests/components/homematicip_cloud/test_device.py index abd0e18b368..aff698cd3d9 100644 --- a/tests/components/homematicip_cloud/test_device.py +++ b/tests/components/homematicip_cloud/test_device.py @@ -22,7 +22,7 @@ async def test_hmip_load_all_supported_devices( test_devices=None, test_groups=None ) - assert len(mock_hap.hmip_device_by_entity_id) == 325 + assert len(mock_hap.hmip_device_by_entity_id) == 331 async def test_hmip_remove_device( diff --git a/tests/components/homematicip_cloud/test_sensor.py b/tests/components/homematicip_cloud/test_sensor.py index 3b5773cfa4d..a107214b373 100644 --- a/tests/components/homematicip_cloud/test_sensor.py +++ b/tests/components/homematicip_cloud/test_sensor.py @@ -13,6 +13,9 @@ from homeassistant.components.homematicip_cloud.entity import ( ) from homeassistant.components.homematicip_cloud.hap import HomematicipHAP from homeassistant.components.homematicip_cloud.sensor import ( + ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION, + ATTR_ACCELERATION_SENSOR_SECOND_TRIGGER_ANGLE, + ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE, ATTR_CURRENT_ILLUMINATION, ATTR_HIGHEST_ILLUMINATION, ATTR_LEFT_COUNTER, @@ -708,6 +711,54 @@ async def test_hmip_esi_led_energy_counter_usage_high_tariff( assert ha_state.state == "23825.748" +async def test_hmip_tilt_vibration_sensor_tilt_state( + hass: HomeAssistant, default_mock_hap_factory: HomeFactory +) -> None: + """Test HomematicipTiltVibrationSensor.""" + entity_id = "sensor.neigungssensor_tor_tilt_state" + entity_name = "Neigungssensor Tor Tilt State" + device_model = "ELV-SH-CTV" + mock_hap = await default_mock_hap_factory.async_get_mock_hap( + test_devices=["Neigungssensor Tor"] + ) + + ha_state, hmip_device = get_and_check_entity_basics( + hass, mock_hap, entity_id, entity_name, device_model + ) + + assert ha_state.state == "neutral" + + await async_manipulate_test_data(hass, hmip_device, "tiltState", "NON_NEUTRAL", 1) + ha_state = hass.states.get(entity_id) + assert ha_state.state == "non_neutral" + + await async_manipulate_test_data(hass, hmip_device, "tiltState", "TILTED", 1) + ha_state = hass.states.get(entity_id) + assert ha_state.state == "tilted" + + assert ha_state.attributes[ATTR_ACCELERATION_SENSOR_NEUTRAL_POSITION] == "VERTICAL" + assert ha_state.attributes[ATTR_ACCELERATION_SENSOR_TRIGGER_ANGLE] == 20 + assert ha_state.attributes[ATTR_ACCELERATION_SENSOR_SECOND_TRIGGER_ANGLE] == 75 + + +async def test_hmip_tilt_vibration_sensor_tilt_angle( + hass: HomeAssistant, default_mock_hap_factory: HomeFactory +) -> None: + """Test HomematicipTiltVibrationSensor.""" + entity_id = "sensor.neigungssensor_tor_tilt_angle" + entity_name = "Neigungssensor Tor Tilt Angle" + device_model = "ELV-SH-CTV" + mock_hap = await default_mock_hap_factory.async_get_mock_hap( + test_devices=["Neigungssensor Tor"] + ) + + ha_state, hmip_device = get_and_check_entity_basics( + hass, mock_hap, entity_id, entity_name, device_model + ) + + assert ha_state.state == "89" + + async def test_hmip_absolute_humidity_sensor( hass: HomeAssistant, default_mock_hap_factory: HomeFactory ) -> None: diff --git a/tests/components/http/test_init.py b/tests/components/http/test_init.py index 7858bbc123d..195a291b140 100644 --- a/tests/components/http/test_init.py +++ b/tests/components/http/test_init.py @@ -522,24 +522,6 @@ async def test_logging( assert "GET /api/states/logging.entity" not in caplog.text -async def test_register_static_paths( - hass: HomeAssistant, - hass_client: ClientSessionGenerator, - caplog: pytest.LogCaptureFixture, -) -> None: - """Test registering a static path with old api.""" - assert await async_setup_component(hass, "frontend", {}) - path = str(Path(__file__).parent) - - match_error = ( - "Detected code that calls hass.http.register_static_path " - "which does blocking I/O in the event loop, instead call " - "`await hass.http.async_register_static_paths" - ) - with pytest.raises(RuntimeError, match=match_error): - hass.http.register_static_path("/something", path) - - async def test_ssl_issue_if_no_urls_configured( hass: HomeAssistant, tmp_path: Path, diff --git a/tests/components/huawei_lte/test_config_flow.py b/tests/components/huawei_lte/test_config_flow.py index 5e018e73f2a..e40a3ca5a01 100644 --- a/tests/components/huawei_lte/test_config_flow.py +++ b/tests/components/huawei_lte/test_config_flow.py @@ -13,7 +13,11 @@ import requests_mock from requests_mock import ANY from homeassistant import config_entries -from homeassistant.components.huawei_lte.const import CONF_UNAUTHENTICATED_MODE, DOMAIN +from homeassistant.components.huawei_lte.const import ( + CONF_UNAUTHENTICATED_MODE, + CONF_UPNP_UDN, + DOMAIN, +) from homeassistant.const import ( CONF_NAME, CONF_PASSWORD, @@ -373,6 +377,7 @@ async def test_ssdp( assert result["type"] == FlowResultType.CREATE_ENTRY assert result["title"] == service_info.upnp[ATTR_UPNP_MODEL_NAME] + assert result["result"].data[CONF_UPNP_UDN] == service_info.upnp[ATTR_UPNP_UDN] @pytest.mark.parametrize( diff --git a/tests/components/husqvarna_automower/snapshots/test_diagnostics.ambr b/tests/components/husqvarna_automower/snapshots/test_diagnostics.ambr index d1e1f08f867..c58a12ad007 100644 --- a/tests/components/husqvarna_automower/snapshots/test_diagnostics.ambr +++ b/tests/components/husqvarna_automower/snapshots/test_diagnostics.ambr @@ -63,7 +63,8 @@ 'stay_out_zones': True, 'work_areas': True, }), - 'messages': None, + 'messages': list([ + ]), 'metadata': dict({ 'connected': True, 'status_dateteime': '2023-06-05T00:00:00+00:00', diff --git a/tests/components/husqvarna_automower/test_init.py b/tests/components/husqvarna_automower/test_init.py index f2b468c4faf..f54250a3336 100644 --- a/tests/components/husqvarna_automower/test_init.py +++ b/tests/components/husqvarna_automower/test_init.py @@ -3,7 +3,7 @@ from asyncio import Event from collections.abc import Callable from copy import deepcopy -from datetime import datetime, timedelta +from datetime import datetime, time as dt_time, timedelta import http import time from unittest.mock import AsyncMock, patch @@ -14,7 +14,7 @@ from aioautomower.exceptions import ( HusqvarnaTimeoutError, HusqvarnaWSServerHandshakeError, ) -from aioautomower.model import MowerAttributes, WorkArea +from aioautomower.model import Calendar, MowerAttributes, WorkArea from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion @@ -262,7 +262,7 @@ async def test_constant_polling( test_values[TEST_MOWER_ID].battery.battery_percent = 77 - freezer.tick(SCAN_INTERVAL - timedelta(seconds=1)) + freezer.tick(SCAN_INTERVAL - timedelta(seconds=10)) async_fire_time_changed(hass) await hass.async_block_till_done() @@ -278,7 +278,7 @@ async def test_constant_polling( test_values[TEST_MOWER_ID].work_areas[123456].progress = 50 mock_automower_client.get_status.return_value = test_values - freezer.tick(timedelta(seconds=4)) + freezer.tick(timedelta(seconds=10)) async_fire_time_changed(hass) await hass.async_block_till_done() mock_automower_client.get_status.assert_awaited() @@ -384,14 +384,45 @@ async def test_add_and_remove_work_area( values: dict[str, MowerAttributes], ) -> None: """Test adding a work area in runtime.""" + websocket_values = deepcopy(values) + callback_holder: dict[str, Callable] = {} + + @callback + def fake_register_websocket_response( + cb: Callable[[dict[str, MowerAttributes]], None], + ) -> None: + callback_holder["cb"] = cb + + mock_automower_client.register_data_callback.side_effect = ( + fake_register_websocket_response + ) await setup_integration(hass, mock_config_entry) entry = hass.config_entries.async_entries(DOMAIN)[0] current_entites_start = len( er.async_entries_for_config_entry(entity_registry, entry.entry_id) ) - values[TEST_MOWER_ID].work_area_names.append("new work area") - values[TEST_MOWER_ID].work_area_dict.update({1: "new work area"}) - values[TEST_MOWER_ID].work_areas.update( + await hass.async_block_till_done() + + assert mock_automower_client.register_data_callback.called + assert "cb" in callback_holder + + new_task = Calendar( + start=dt_time(hour=11), + duration=timedelta(60), + monday=True, + tuesday=True, + wednesday=True, + thursday=True, + friday=True, + saturday=True, + sunday=True, + work_area_id=1, + ) + websocket_values[TEST_MOWER_ID].calendar.tasks.append(new_task) + poll_values = deepcopy(websocket_values) + poll_values[TEST_MOWER_ID].work_area_names.append("new work area") + poll_values[TEST_MOWER_ID].work_area_dict.update({1: "new work area"}) + poll_values[TEST_MOWER_ID].work_areas.update( { 1: WorkArea( name="new work area", @@ -404,10 +435,15 @@ async def test_add_and_remove_work_area( ) } ) - mock_automower_client.get_status.return_value = values - freezer.tick(SCAN_INTERVAL) - async_fire_time_changed(hass) + mock_automower_client.get_status.return_value = poll_values + + callback_holder["cb"](websocket_values) await hass.async_block_till_done() + assert mock_automower_client.get_status.called + + state = hass.states.get("sensor.test_mower_1_new_work_area_progress") + assert state is not None + assert state.state == "12" current_entites_after_addition = len( er.async_entries_for_config_entry(entity_registry, entry.entry_id) ) @@ -419,15 +455,15 @@ async def test_add_and_remove_work_area( + ADDITIONAL_SWITCH_ENTITIES ) - values[TEST_MOWER_ID].work_area_names.remove("new work area") - del values[TEST_MOWER_ID].work_area_dict[1] - del values[TEST_MOWER_ID].work_areas[1] - values[TEST_MOWER_ID].work_area_names.remove("Front lawn") - del values[TEST_MOWER_ID].work_area_dict[123456] - del values[TEST_MOWER_ID].work_areas[123456] - del values[TEST_MOWER_ID].calendar.tasks[:2] - values[TEST_MOWER_ID].mower.work_area_id = 654321 - mock_automower_client.get_status.return_value = values + poll_values[TEST_MOWER_ID].work_area_names.remove("new work area") + del poll_values[TEST_MOWER_ID].work_area_dict[1] + del poll_values[TEST_MOWER_ID].work_areas[1] + poll_values[TEST_MOWER_ID].work_area_names.remove("Front lawn") + del poll_values[TEST_MOWER_ID].work_area_dict[123456] + del poll_values[TEST_MOWER_ID].work_areas[123456] + del poll_values[TEST_MOWER_ID].calendar.tasks[:2] + poll_values[TEST_MOWER_ID].mower.work_area_id = 654321 + mock_automower_client.get_status.return_value = poll_values freezer.tick(SCAN_INTERVAL) async_fire_time_changed(hass) await hass.async_block_till_done() diff --git a/tests/components/imgw_pib/conftest.py b/tests/components/imgw_pib/conftest.py index a10b9b54532..e0b091e5ff3 100644 --- a/tests/components/imgw_pib/conftest.py +++ b/tests/components/imgw_pib/conftest.py @@ -23,6 +23,8 @@ HYDROLOGICAL_DATA = HydrologicalData( flood_warning=None, water_level_measurement_date=datetime(2024, 4, 27, 10, 0, tzinfo=UTC), water_temperature_measurement_date=datetime(2024, 4, 27, 10, 10, tzinfo=UTC), + water_flow=SensorData(name="Water Flow", value=123.45), + water_flow_measurement_date=datetime(2024, 4, 27, 10, 5, tzinfo=UTC), ) diff --git a/tests/components/imgw_pib/snapshots/test_diagnostics.ambr b/tests/components/imgw_pib/snapshots/test_diagnostics.ambr index 97453930c1e..08f3690136e 100644 --- a/tests/components/imgw_pib/snapshots/test_diagnostics.ambr +++ b/tests/components/imgw_pib/snapshots/test_diagnostics.ambr @@ -34,9 +34,17 @@ 'unit': None, 'value': None, }), + 'latitude': None, + 'longitude': None, 'river': 'River Name', 'station': 'Station Name', 'station_id': '123', + 'water_flow': dict({ + 'name': 'Water Flow', + 'unit': None, + 'value': 123.45, + }), + 'water_flow_measurement_date': '2024-04-27T10:05:00+00:00', 'water_level': dict({ 'name': 'Water Level', 'unit': None, diff --git a/tests/components/imgw_pib/snapshots/test_sensor.ambr b/tests/components/imgw_pib/snapshots/test_sensor.ambr index 5b588af4518..97bb6eefef3 100644 --- a/tests/components/imgw_pib/snapshots/test_sensor.ambr +++ b/tests/components/imgw_pib/snapshots/test_sensor.ambr @@ -1,4 +1,61 @@ # serializer version: 1 +# name: test_sensor[sensor.river_name_station_name_water_flow-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.river_name_station_name_water_flow', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 1, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Water flow', + 'platform': 'imgw_pib', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'water_flow', + 'unique_id': '123_water_flow', + 'unit_of_measurement': , + }) +# --- +# name: test_sensor[sensor.river_name_station_name_water_flow-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'attribution': 'Data provided by IMGW-PIB', + 'device_class': 'volume_flow_rate', + 'friendly_name': 'River Name (Station Name) Water flow', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.river_name_station_name_water_flow', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '123.45', + }) +# --- # name: test_sensor[sensor.river_name_station_name_water_level-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/inkbird/__init__.py b/tests/components/inkbird/__init__.py index 7228f64448b..1daadc9ffe8 100644 --- a/tests/components/inkbird/__init__.py +++ b/tests/components/inkbird/__init__.py @@ -29,7 +29,6 @@ def _make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=MONOTONIC_TIME(), advertisement=None, diff --git a/tests/components/integration/test_init.py b/tests/components/integration/test_init.py index 0ce3297a2ff..50243551d37 100644 --- a/tests/components/integration/test_init.py +++ b/tests/components/integration/test_init.py @@ -7,8 +7,8 @@ import pytest from homeassistant.components import integration from homeassistant.components.integration.config_flow import ConfigFlowHandler from homeassistant.components.integration.const import DOMAIN -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -83,6 +83,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -176,6 +177,7 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: # Set up entities, with backing devices and config entries input_entry = _create_mock_entity("sensor", "input") valid_entry = _create_mock_entity("sensor", "valid") + assert input_entry.device_id != valid_entry.device_id # Setup the config entry config_entry = MockConfigEntry( @@ -193,17 +195,21 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() - assert config_entry.entry_id in _get_device_config_entries(input_entry) + assert config_entry.entry_id not in _get_device_config_entries(input_entry) assert config_entry.entry_id not in _get_device_config_entries(valid_entry) + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id == input_entry.device_id hass.config_entries.async_update_entry( config_entry, options={**config_entry.options, "source": "sensor.valid"} ) await hass.async_block_till_done() - # Check that the config entry association has updated + # Check that the device association has updated assert config_entry.entry_id not in _get_device_config_entries(input_entry) - assert config_entry.entry_id in _get_device_config_entries(valid_entry) + assert config_entry.entry_id not in _get_device_config_entries(valid_entry) + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id == valid_entry.device_id async def test_device_cleaning( @@ -276,7 +282,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( integration_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(integration_config_entry.entry_id) @@ -291,7 +297,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( integration_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 async def test_async_handle_source_entity_changes_source_entity_removed( @@ -302,6 +308,54 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the integration config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(integration_config_entry.entry_id) + await hass.async_block_till_done() + + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert integration_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, integration_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.integration.async_unload_entry", + wraps=integration.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the entity is no longer linked to the source device + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id is None + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the integration config entry is not removed + assert integration_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["update"] + + +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + integration_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the integration config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -318,7 +372,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert integration_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert integration_config_entry.entry_id in sensor_device.config_entries + assert integration_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, integration_entity_entry.entity_id) @@ -335,7 +389,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() - # Check that the integration config entry is removed from the device + # Check that the entity is no longer linked to the source device + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id is None + + # Check that the integration config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert integration_config_entry.entry_id not in sensor_device.config_entries @@ -362,7 +420,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert integration_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert integration_config_entry.entry_id in sensor_device.config_entries + assert integration_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, integration_entity_entry.entity_id) @@ -377,7 +435,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the integration config entry is removed from the device + # Check that the entity is no longer linked to the source device + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id is None + + # Check that the integration config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert integration_config_entry.entry_id not in sensor_device.config_entries @@ -410,7 +472,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert integration_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert integration_config_entry.entry_id in sensor_device.config_entries + assert integration_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert integration_config_entry.entry_id not in sensor_device_2.config_entries @@ -427,11 +489,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the integration config entry is moved to the other device + # Check that the entity is linked to the other device + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id == sensor_device_2.id + + # Check that the derivative config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert integration_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert integration_config_entry.entry_id in sensor_device_2.config_entries + assert integration_config_entry.entry_id not in sensor_device_2.config_entries # Check that the integration config entry is not removed assert integration_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -456,7 +522,7 @@ async def test_async_handle_source_entity_new_entity_id( assert integration_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert integration_config_entry.entry_id in sensor_device.config_entries + assert integration_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, integration_entity_entry.entity_id) @@ -474,12 +540,91 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the integration config entry is updated with the new entity ID assert integration_config_entry.options["source"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert integration_config_entry.entry_id in sensor_device.config_entries + assert integration_config_entry.entry_id not in sensor_device.config_entries # Check that the integration config entry is not removed assert integration_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, +) -> None: + """Test migration from v1.1 removes integration config entry from device.""" + + integration_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "method": "trapezoidal", + "name": "My integration", + "round": 1.0, + "source": sensor_entity_entry.entity_id, + "unit_prefix": "k", + "unit_time": "min", + "max_sub_interval": {"minutes": 1}, + }, + title="My integration", + version=1, + minor_version=1, + ) + integration_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=integration_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert integration_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(integration_config_entry.entry_id) + await hass.async_block_till_done() + + assert integration_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert integration_config_entry.entry_id not in sensor_device.config_entries + integration_entity_entry = entity_registry.async_get("sensor.my_integration") + assert integration_entity_entry.device_id == sensor_entity_entry.device_id + + assert integration_config_entry.version == 1 + assert integration_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "method": "trapezoidal", + "name": "My integration", + "round": 1.0, + "source": "sensor.test", + "unit_prefix": "k", + "unit_time": "min", + "max_sub_interval": {"minutes": 1}, + }, + title="My integration", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/iron_os/conftest.py b/tests/components/iron_os/conftest.py index 479ee2fde7b..60abf8a8008 100644 --- a/tests/components/iron_os/conftest.py +++ b/tests/components/iron_os/conftest.py @@ -131,7 +131,7 @@ def mock_ble_device() -> Generator[MagicMock]: with patch( "homeassistant.components.bluetooth.async_ble_device_from_address", return_value=BLEDevice( - address="c0:ff:ee:c0:ff:ee", name=DEFAULT_NAME, rssi=-50, details={} + address="c0:ff:ee:c0:ff:ee", name=DEFAULT_NAME, details={} ), ) as ble_device: yield ble_device diff --git a/tests/components/jewish_calendar/snapshots/test_diagnostics.ambr b/tests/components/jewish_calendar/snapshots/test_diagnostics.ambr index 3c8acde6e72..0a392e101c5 100644 --- a/tests/components/jewish_calendar/snapshots/test_diagnostics.ambr +++ b/tests/components/jewish_calendar/snapshots/test_diagnostics.ambr @@ -18,25 +18,7 @@ }), }), 'results': dict({ - 'after_shkia_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': False, - 'nusach': 'sephardi', - }), - 'after_tzais_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': False, - 'nusach': 'sephardi', - }), - 'daytime_date': dict({ + 'dateinfo': dict({ 'date': dict({ 'day': 21, 'month': 10, @@ -92,25 +74,7 @@ }), }), 'results': dict({ - 'after_shkia_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': True, - 'nusach': 'sephardi', - }), - 'after_tzais_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': True, - 'nusach': 'sephardi', - }), - 'daytime_date': dict({ + 'dateinfo': dict({ 'date': dict({ 'day': 21, 'month': 10, @@ -166,25 +130,7 @@ }), }), 'results': dict({ - 'after_shkia_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': False, - 'nusach': 'sephardi', - }), - 'after_tzais_date': dict({ - 'date': dict({ - 'day': 21, - 'month': 10, - 'year': 5785, - }), - 'diaspora': False, - 'nusach': 'sephardi', - }), - 'daytime_date': dict({ + 'dateinfo': dict({ 'date': dict({ 'day': 21, 'month': 10, diff --git a/tests/components/jewish_calendar/test_binary_sensor.py b/tests/components/jewish_calendar/test_binary_sensor.py index 46f5fdfcc7d..a4c9fd02be3 100644 --- a/tests/components/jewish_calendar/test_binary_sensor.py +++ b/tests/components/jewish_calendar/test_binary_sensor.py @@ -6,11 +6,8 @@ from typing import Any from freezegun.api import FrozenDateTimeFactory import pytest -from homeassistant.components.binary_sensor import DOMAIN as BINARY_SENSOR_DOMAIN -from homeassistant.components.jewish_calendar.const import DOMAIN -from homeassistant.const import CONF_PLATFORM, STATE_OFF, STATE_ON +from homeassistant.const import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant -from homeassistant.setup import async_setup_component from tests.common import async_fire_time_changed @@ -140,17 +137,3 @@ async def test_issur_melacha_sensor_update( async_fire_time_changed(hass) await hass.async_block_till_done() assert hass.states.get(sensor_id).state == results[1] - - -async def test_no_discovery_info( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture -) -> None: - """Test setup without discovery info.""" - assert BINARY_SENSOR_DOMAIN not in hass.config.components - assert await async_setup_component( - hass, - BINARY_SENSOR_DOMAIN, - {BINARY_SENSOR_DOMAIN: {CONF_PLATFORM: DOMAIN}}, - ) - await hass.async_block_till_done() - assert BINARY_SENSOR_DOMAIN in hass.config.components diff --git a/tests/components/jewish_calendar/test_config_flow.py b/tests/components/jewish_calendar/test_config_flow.py index 7a8b6b8df1e..a63d9abb9a7 100644 --- a/tests/components/jewish_calendar/test_config_flow.py +++ b/tests/components/jewish_calendar/test_config_flow.py @@ -2,7 +2,7 @@ from unittest.mock import AsyncMock -from homeassistant import config_entries, setup +from homeassistant import config_entries from homeassistant.components.jewish_calendar.const import ( CONF_CANDLE_LIGHT_MINUTES, CONF_DIASPORA, @@ -28,19 +28,18 @@ from tests.common import MockConfigEntry async def test_step_user(hass: HomeAssistant, mock_setup_entry: AsyncMock) -> None: """Test user config.""" - await setup.async_setup_component(hass, "persistent_notification", {}) 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" - result2 = await hass.config_entries.flow.async_configure( + result = await hass.config_entries.flow.async_configure( result["flow_id"], {CONF_DIASPORA: DEFAULT_DIASPORA, CONF_LANGUAGE: DEFAULT_LANGUAGE}, ) - assert result2["type"] is FlowResultType.CREATE_ENTRY + assert result["type"] is FlowResultType.CREATE_ENTRY await hass.async_block_till_done() assert len(mock_setup_entry.mock_calls) == 1 diff --git a/tests/components/jewish_calendar/test_sensor.py b/tests/components/jewish_calendar/test_sensor.py index 38a3dd12206..ab24d35f932 100644 --- a/tests/components/jewish_calendar/test_sensor.py +++ b/tests/components/jewish_calendar/test_sensor.py @@ -8,11 +8,7 @@ from hdate.holidays import HolidayDatabase from hdate.parasha import Parasha import pytest -from homeassistant.components.jewish_calendar.const import DOMAIN -from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN -from homeassistant.const import CONF_PLATFORM from homeassistant.core import HomeAssistant -from homeassistant.setup import async_setup_component from homeassistant.util import dt as dt_util from tests.common import MockConfigEntry, async_fire_time_changed @@ -569,17 +565,3 @@ async def test_sensor_does_not_update_on_time_change( async_fire_time_changed(hass) await hass.async_block_till_done() assert hass.states.get(sensor_id).state == results["new_state"] - - -async def test_no_discovery_info( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture -) -> None: - """Test setup without discovery info.""" - assert SENSOR_DOMAIN not in hass.config.components - assert await async_setup_component( - hass, - SENSOR_DOMAIN, - {SENSOR_DOMAIN: {CONF_PLATFORM: DOMAIN}}, - ) - await hass.async_block_till_done() - assert SENSOR_DOMAIN in hass.config.components diff --git a/tests/components/jewish_calendar/test_service.py b/tests/components/jewish_calendar/test_service.py index 4b3f31d11d4..ce5ccf2af37 100644 --- a/tests/components/jewish_calendar/test_service.py +++ b/tests/components/jewish_calendar/test_service.py @@ -4,7 +4,13 @@ import datetime as dt import pytest -from homeassistant.components.jewish_calendar.const import DOMAIN +from homeassistant.components.jewish_calendar.const import ( + ATTR_AFTER_SUNSET, + ATTR_DATE, + ATTR_NUSACH, + DOMAIN, +) +from homeassistant.const import CONF_LANGUAGE from homeassistant.core import HomeAssistant @@ -14,10 +20,10 @@ from homeassistant.core import HomeAssistant pytest.param( dt.datetime(2025, 3, 20, 21, 0), { - "date": dt.date(2025, 3, 20), - "nusach": "sfarad", - "language": "he", - "after_sunset": False, + ATTR_DATE: dt.date(2025, 3, 20), + ATTR_NUSACH: "sfarad", + CONF_LANGUAGE: "he", + ATTR_AFTER_SUNSET: False, }, "", id="no_blessing", @@ -25,10 +31,10 @@ from homeassistant.core import HomeAssistant pytest.param( dt.datetime(2025, 3, 20, 21, 0), { - "date": dt.date(2025, 5, 20), - "nusach": "ashkenaz", - "language": "he", - "after_sunset": False, + ATTR_DATE: dt.date(2025, 5, 20), + ATTR_NUSACH: "ashkenaz", + CONF_LANGUAGE: "he", + ATTR_AFTER_SUNSET: False, }, "היום שבעה ושלושים יום שהם חמישה שבועות ושני ימים בעומר", id="ahskenaz-hebrew", @@ -36,10 +42,10 @@ from homeassistant.core import HomeAssistant pytest.param( dt.datetime(2025, 3, 20, 21, 0), { - "date": dt.date(2025, 5, 20), - "nusach": "sfarad", - "language": "en", - "after_sunset": True, + ATTR_DATE: dt.date(2025, 5, 20), + ATTR_NUSACH: "sfarad", + CONF_LANGUAGE: "en", + ATTR_AFTER_SUNSET: True, }, "Today is the thirty-eighth day, which are five weeks and three days of the Omer", id="sefarad-english-after-sunset", @@ -47,23 +53,23 @@ from homeassistant.core import HomeAssistant pytest.param( dt.datetime(2025, 3, 20, 21, 0), { - "date": dt.date(2025, 5, 20), - "nusach": "sfarad", - "language": "en", - "after_sunset": False, + ATTR_DATE: dt.date(2025, 5, 20), + ATTR_NUSACH: "sfarad", + CONF_LANGUAGE: "en", + ATTR_AFTER_SUNSET: False, }, "Today is the thirty-seventh day, which are five weeks and two days of the Omer", id="sefarad-english-before-sunset", ), pytest.param( dt.datetime(2025, 5, 20, 21, 0), - {"nusach": "sfarad", "language": "en"}, + {ATTR_NUSACH: "sfarad", CONF_LANGUAGE: "en"}, "Today is the thirty-eighth day, which are five weeks and three days of the Omer", id="sefarad-english-after-sunset-without-date", ), pytest.param( dt.datetime(2025, 5, 20, 6, 0), - {"nusach": "sfarad"}, + {ATTR_NUSACH: "sfarad"}, "היום שבעה ושלושים יום שהם חמישה שבועות ושני ימים לעומר", id="sefarad-english-before-sunset-without-date", ), diff --git a/tests/components/knx/test_events.py b/tests/components/knx/test_events.py index 2228781ba89..a40109d167e 100644 --- a/tests/components/knx/test_events.py +++ b/tests/components/knx/test_events.py @@ -4,7 +4,8 @@ import logging import pytest -from homeassistant.components.knx import CONF_EVENT, CONF_TYPE, KNX_ADDRESS +from homeassistant.components.knx.const import KNX_ADDRESS +from homeassistant.const import CONF_EVENT, CONF_TYPE from homeassistant.core import HomeAssistant from .conftest import KNXTestKit diff --git a/tests/components/knx/test_expose.py b/tests/components/knx/test_expose.py index f7a3f4e94f2..331678f0683 100644 --- a/tests/components/knx/test_expose.py +++ b/tests/components/knx/test_expose.py @@ -6,7 +6,7 @@ from freezegun import freeze_time from freezegun.api import FrozenDateTimeFactory import pytest -from homeassistant.components.knx import CONF_KNX_EXPOSE, DOMAIN, KNX_ADDRESS +from homeassistant.components.knx.const import CONF_KNX_EXPOSE, DOMAIN, KNX_ADDRESS from homeassistant.components.knx.schema import ExposeSchema from homeassistant.const import ( CONF_ATTRIBUTE, diff --git a/tests/components/kulersky/test_light.py b/tests/components/kulersky/test_light.py index bde60579af7..9521f98f523 100644 --- a/tests/components/kulersky/test_light.py +++ b/tests/components/kulersky/test_light.py @@ -40,9 +40,7 @@ def mock_ble_device() -> Generator[MagicMock]: """Mock BLEDevice.""" with patch( "homeassistant.components.kulersky.async_ble_device_from_address", - return_value=BLEDevice( - address="AA:BB:CC:11:22:33", name="Bedroom", rssi=-50, details={} - ), + return_value=BLEDevice(address="AA:BB:CC:11:22:33", name="Bedroom", details={}), ) as ble_device: yield ble_device diff --git a/tests/components/leaone/__init__.py b/tests/components/leaone/__init__.py index befc0a81028..900fe100940 100644 --- a/tests/components/leaone/__init__.py +++ b/tests/components/leaone/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/lifx/__init__.py b/tests/components/lifx/__init__.py index 81b913da6ce..95f6154030b 100644 --- a/tests/components/lifx/__init__.py +++ b/tests/components/lifx/__init__.py @@ -199,6 +199,17 @@ def _mocked_ceiling() -> Light: return bulb +def _mocked_128zone_ceiling() -> Light: + bulb = _mocked_bulb() + bulb.product = 201 # LIFX 26"x13" Ceiling + bulb.effect = {"effect": "OFF"} + bulb.get_tile_effect = MockLifxCommand(bulb) + bulb.set_tile_effect = MockLifxCommand(bulb) + bulb.get64 = MockLifxCommand(bulb) + bulb.get_device_chain = MockLifxCommand(bulb) + return bulb + + def _mocked_bulb_old_firmware() -> Light: bulb = _mocked_bulb() bulb.host_firmware_version = "2.77" diff --git a/tests/components/lifx/snapshots/test_diagnostics.ambr b/tests/components/lifx/snapshots/test_diagnostics.ambr new file mode 100644 index 00000000000..3e095252159 --- /dev/null +++ b/tests/components/lifx/snapshots/test_diagnostics.ambr @@ -0,0 +1,1568 @@ +# serializer version: 1 +# name: test_128zone_matrix_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': False, + 'infrared': False, + 'matrix': True, + 'max_kelvin': 9000, + 'min_kelvin': 1500, + 'multizone': False, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'kelvin': 4, + 'matrix': dict({ + 'chain': dict({ + '0': list([ + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + ]), + }), + 'chain_length': 1, + 'effect': dict({ + 'effect': 'OFF', + }), + 'tile_device_width': 16, + 'tile_devices': list([ + dict({ + 'accel_meas_x': 0, + 'accel_meas_y': 0, + 'accel_meas_z': 2000, + 'device_version_product': 201, + 'device_version_vendor': 1, + 'firmware_build': 1729829374000000000, + 'firmware_version_major': 4, + 'firmware_version_minor': 10, + 'height': 16, + 'supported_frame_buffers': 5, + 'user_x': 0.0, + 'user_y': 0.0, + 'width': 8, + }), + ]), + 'tile_devices_count': 1, + }), + 'power': 0, + 'product_id': 201, + 'saturation': 2, + 'vendor': None, + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_bulb_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': False, + 'infrared': False, + 'matrix': False, + 'max_kelvin': 9000, + 'min_kelvin': 2500, + 'multizone': False, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'kelvin': 4, + 'power': 0, + 'product_id': 1, + 'saturation': 2, + 'vendor': None, + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_clean_bulb_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': True, + 'infrared': False, + 'matrix': False, + 'max_kelvin': 9000, + 'min_kelvin': 1500, + 'multizone': False, + 'relays': False, + }), + 'firmware': '3.00', + 'hev': dict({ + 'hev_config': dict({ + 'duration': 7200, + 'indication': False, + }), + 'hev_cycle': dict({ + 'duration': 7200, + 'last_power': False, + 'remaining': 30, + }), + 'last_result': 0, + }), + 'hue': 1, + 'kelvin': 4, + 'power': 0, + 'product_id': 90, + 'saturation': 2, + 'vendor': None, + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_infrared_bulb_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': False, + 'infrared': True, + 'matrix': False, + 'max_kelvin': 9000, + 'min_kelvin': 1500, + 'multizone': False, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'infrared': dict({ + 'brightness': 65535, + }), + 'kelvin': 4, + 'power': 0, + 'product_id': 29, + 'saturation': 2, + 'vendor': None, + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_legacy_multizone_bulb_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': False, + 'infrared': False, + 'matrix': False, + 'max_kelvin': 9000, + 'min_kelvin': 2500, + 'multizone': True, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'kelvin': 4, + 'power': 0, + 'product_id': 31, + 'saturation': 2, + 'vendor': None, + 'zones': dict({ + 'count': 8, + 'state': dict({ + '0': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '1': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '2': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '3': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '4': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '5': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '6': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '7': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + }), + }), + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_matrix_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': False, + 'hev': False, + 'infrared': False, + 'matrix': True, + 'max_kelvin': 9000, + 'min_kelvin': 1500, + 'multizone': False, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'kelvin': 4, + 'matrix': dict({ + 'chain': dict({ + '0': list([ + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + list([ + 0, + 0, + 0, + 3500, + ]), + ]), + }), + 'chain_length': 1, + 'effect': dict({ + 'effect': 'OFF', + }), + 'tile_device_width': 8, + 'tile_devices': list([ + dict({ + 'accel_meas_x': 0, + 'accel_meas_y': 0, + 'accel_meas_z': 2000, + 'device_version_product': 176, + 'device_version_vendor': 1, + 'firmware_build': 1729829374000000000, + 'firmware_version_major': 4, + 'firmware_version_minor': 10, + 'height': 8, + 'supported_frame_buffers': 5, + 'user_x': 0.0, + 'user_y': 0.0, + 'width': 8, + }), + ]), + 'tile_devices_count': 1, + }), + 'power': 0, + 'product_id': 176, + 'saturation': 2, + 'vendor': None, + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- +# name: test_multizone_bulb_diagnostics + dict({ + 'data': dict({ + 'brightness': 3, + 'features': dict({ + 'buttons': False, + 'chain': False, + 'color': True, + 'extended_multizone': True, + 'hev': False, + 'infrared': False, + 'matrix': False, + 'max_kelvin': 9000, + 'min_ext_mz_firmware': 1532997580, + 'min_ext_mz_firmware_components': list([ + 2, + 77, + ]), + 'min_kelvin': 1500, + 'multizone': True, + 'relays': False, + }), + 'firmware': '3.00', + 'hue': 1, + 'kelvin': 4, + 'power': 0, + 'product_id': 38, + 'saturation': 2, + 'vendor': None, + 'zones': dict({ + 'count': 8, + 'state': dict({ + '0': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '1': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '2': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '3': dict({ + 'brightness': 65535, + 'hue': 54612, + 'kelvin': 3500, + 'saturation': 65535, + }), + '4': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '5': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '6': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + '7': dict({ + 'brightness': 65535, + 'hue': 46420, + 'kelvin': 3500, + 'saturation': 65535, + }), + }), + }), + }), + 'entry': dict({ + 'data': dict({ + 'host': '**REDACTED**', + }), + 'title': 'My Bulb', + }), + }) +# --- diff --git a/tests/components/lifx/test_diagnostics.py b/tests/components/lifx/test_diagnostics.py index 22e335612f8..830dc26829a 100644 --- a/tests/components/lifx/test_diagnostics.py +++ b/tests/components/lifx/test_diagnostics.py @@ -1,5 +1,7 @@ """Test LIFX diagnostics.""" +from syrupy.assertion import SnapshotAssertion + from homeassistant.components import lifx from homeassistant.const import CONF_HOST from homeassistant.core import HomeAssistant @@ -10,7 +12,9 @@ from . import ( IP_ADDRESS, SERIAL, MockLifxCommand, + _mocked_128zone_ceiling, _mocked_bulb, + _mocked_ceiling, _mocked_clean_bulb, _mocked_infrared_bulb, _mocked_light_strip, @@ -25,7 +29,9 @@ from tests.typing import ClientSessionGenerator async def test_bulb_diagnostics( - hass: HomeAssistant, hass_client: ClientSessionGenerator + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, ) -> None: """Test diagnostics for a standard bulb.""" config_entry = MockConfigEntry( @@ -45,36 +51,13 @@ async def test_bulb_diagnostics( await hass.async_block_till_done() diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert diag == { - "data": { - "brightness": 3, - "features": { - "buttons": False, - "chain": False, - "color": True, - "extended_multizone": False, - "hev": False, - "infrared": False, - "matrix": False, - "max_kelvin": 9000, - "min_kelvin": 2500, - "multizone": False, - "relays": False, - }, - "firmware": "3.00", - "hue": 1, - "kelvin": 4, - "power": 0, - "product_id": 1, - "saturation": 2, - "vendor": None, - }, - "entry": {"data": {"host": "**REDACTED**"}, "title": "My Bulb"}, - } + assert diag == snapshot async def test_clean_bulb_diagnostics( - hass: HomeAssistant, hass_client: ClientSessionGenerator + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, ) -> None: """Test diagnostics for a standard bulb.""" config_entry = MockConfigEntry( @@ -94,41 +77,13 @@ async def test_clean_bulb_diagnostics( await hass.async_block_till_done() diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert diag == { - "data": { - "brightness": 3, - "features": { - "buttons": False, - "chain": False, - "color": True, - "extended_multizone": False, - "hev": True, - "infrared": False, - "matrix": False, - "max_kelvin": 9000, - "min_kelvin": 1500, - "multizone": False, - "relays": False, - }, - "firmware": "3.00", - "hev": { - "hev_config": {"duration": 7200, "indication": False}, - "hev_cycle": {"duration": 7200, "last_power": False, "remaining": 30}, - "last_result": 0, - }, - "hue": 1, - "kelvin": 4, - "power": 0, - "product_id": 90, - "saturation": 2, - "vendor": None, - }, - "entry": {"data": {"host": "**REDACTED**"}, "title": "My Bulb"}, - } + assert diag == snapshot async def test_infrared_bulb_diagnostics( - hass: HomeAssistant, hass_client: ClientSessionGenerator + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, ) -> None: """Test diagnostics for a standard bulb.""" config_entry = MockConfigEntry( @@ -148,37 +103,13 @@ async def test_infrared_bulb_diagnostics( await hass.async_block_till_done() diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert diag == { - "data": { - "brightness": 3, - "features": { - "buttons": False, - "chain": False, - "color": True, - "extended_multizone": False, - "hev": False, - "infrared": True, - "matrix": False, - "max_kelvin": 9000, - "min_kelvin": 1500, - "multizone": False, - "relays": False, - }, - "firmware": "3.00", - "hue": 1, - "infrared": {"brightness": 65535}, - "kelvin": 4, - "power": 0, - "product_id": 29, - "saturation": 2, - "vendor": None, - }, - "entry": {"data": {"host": "**REDACTED**"}, "title": "My Bulb"}, - } + assert diag == snapshot async def test_legacy_multizone_bulb_diagnostics( - hass: HomeAssistant, hass_client: ClientSessionGenerator + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, ) -> None: """Test diagnostics for a standard bulb.""" config_entry = MockConfigEntry( @@ -225,89 +156,13 @@ async def test_legacy_multizone_bulb_diagnostics( await hass.async_block_till_done() diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert diag == { - "data": { - "brightness": 3, - "features": { - "buttons": False, - "chain": False, - "color": True, - "extended_multizone": False, - "hev": False, - "infrared": False, - "matrix": False, - "max_kelvin": 9000, - "min_kelvin": 2500, - "multizone": True, - "relays": False, - }, - "firmware": "3.00", - "hue": 1, - "kelvin": 4, - "power": 0, - "product_id": 31, - "saturation": 2, - "vendor": None, - "zones": { - "count": 8, - "state": { - "0": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "1": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "2": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "3": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "4": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "5": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "6": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "7": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - }, - }, - }, - "entry": {"data": {"host": "**REDACTED**"}, "title": "My Bulb"}, - } + assert diag == snapshot async def test_multizone_bulb_diagnostics( - hass: HomeAssistant, hass_client: ClientSessionGenerator + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, ) -> None: """Test diagnostics for a standard bulb.""" config_entry = MockConfigEntry( @@ -355,84 +210,102 @@ async def test_multizone_bulb_diagnostics( await hass.async_block_till_done() diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) - assert diag == { - "data": { - "brightness": 3, - "features": { - "buttons": False, - "chain": False, - "color": True, - "extended_multizone": True, - "hev": False, - "infrared": False, - "matrix": False, - "max_kelvin": 9000, - "min_ext_mz_firmware": 1532997580, - "min_ext_mz_firmware_components": [2, 77], - "min_kelvin": 1500, - "multizone": True, - "relays": False, - }, - "firmware": "3.00", - "hue": 1, - "kelvin": 4, - "power": 0, - "product_id": 38, - "saturation": 2, - "vendor": None, - "zones": { - "count": 8, - "state": { - "0": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "1": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "2": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "3": { - "brightness": 65535, - "hue": 54612, - "kelvin": 3500, - "saturation": 65535, - }, - "4": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "5": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "6": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - "7": { - "brightness": 65535, - "hue": 46420, - "kelvin": 3500, - "saturation": 65535, - }, - }, - }, - }, - "entry": {"data": {"host": "**REDACTED**"}, "title": "My Bulb"}, - } + assert diag == snapshot + + +async def test_matrix_diagnostics( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, +) -> None: + """Test diagnostics for a standard bulb.""" + config_entry = MockConfigEntry( + domain=lifx.DOMAIN, + title=DEFAULT_ENTRY_TITLE, + data={CONF_HOST: IP_ADDRESS}, + unique_id=SERIAL, + ) + config_entry.add_to_hass(hass) + bulb = _mocked_ceiling() + bulb.effect = {"effect": "OFF"} + bulb.tile_devices_count = 1 + bulb.tile_device_width = 8 + bulb.tile_devices = [ + { + "accel_meas_x": 0, + "accel_meas_y": 0, + "accel_meas_z": 2000, + "user_x": 0.0, + "user_y": 0.0, + "width": 8, + "height": 8, + "supported_frame_buffers": 5, + "device_version_vendor": 1, + "device_version_product": 176, + "firmware_build": 1729829374000000000, + "firmware_version_minor": 10, + "firmware_version_major": 4, + } + ] + bulb.chain = {0: [(0, 0, 0, 3500)] * 64} + bulb.chain_length = 1 + + with ( + _patch_discovery(device=bulb), + _patch_config_flow_try_connect(device=bulb), + _patch_device(device=bulb), + ): + await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}}) + await hass.async_block_till_done() + + diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) + assert diag == snapshot + + +async def test_128zone_matrix_diagnostics( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, +) -> None: + """Test diagnostics for a standard bulb.""" + config_entry = MockConfigEntry( + domain=lifx.DOMAIN, + title=DEFAULT_ENTRY_TITLE, + data={CONF_HOST: IP_ADDRESS}, + unique_id=SERIAL, + ) + config_entry.add_to_hass(hass) + bulb = _mocked_128zone_ceiling() + bulb.effect = {"effect": "OFF"} + bulb.tile_devices_count = 1 + bulb.tile_device_width = 16 + bulb.tile_devices = [ + { + "accel_meas_x": 0, + "accel_meas_y": 0, + "accel_meas_z": 2000, + "user_x": 0.0, + "user_y": 0.0, + "width": 8, + "height": 16, + "supported_frame_buffers": 5, + "device_version_vendor": 1, + "device_version_product": 201, + "firmware_build": 1729829374000000000, + "firmware_version_minor": 10, + "firmware_version_major": 4, + } + ] + bulb.chain = {0: [(0, 0, 0, 3500)] * 128} + bulb.chain_length = 1 + + with ( + _patch_discovery(device=bulb), + _patch_config_flow_try_connect(device=bulb), + _patch_device(device=bulb), + ): + await async_setup_component(hass, lifx.DOMAIN, {lifx.DOMAIN: {}}) + await hass.async_block_till_done() + + diag = await get_diagnostics_for_config_entry(hass, hass_client, config_entry) + assert diag == snapshot diff --git a/tests/components/litterrobot/common.py b/tests/components/litterrobot/common.py index d96ce06ca59..19c0c3600ea 100644 --- a/tests/components/litterrobot/common.py +++ b/tests/components/litterrobot/common.py @@ -159,6 +159,15 @@ PET_DATA = { "gender": "FEMALE", "lastWeightReading": 9.1, "breeds": ["sphynx"], + "weightHistory": [ + {"weight": 6.48, "timestamp": "2025-06-13T16:12:36"}, + {"weight": 6.6, "timestamp": "2025-06-14T03:52:00"}, + {"weight": 6.59, "timestamp": "2025-06-14T17:20:32"}, + {"weight": 6.5, "timestamp": "2025-06-14T19:22:48"}, + {"weight": 6.35, "timestamp": "2025-06-15T03:12:15"}, + {"weight": 6.45, "timestamp": "2025-06-15T15:27:21"}, + {"weight": 6.25, "timestamp": "2025-06-15T15:29:26"}, + ], } VACUUM_ENTITY_ID = "vacuum.test_litter_box" diff --git a/tests/components/litterrobot/conftest.py b/tests/components/litterrobot/conftest.py index a6058c75bca..aa67db23d89 100644 --- a/tests/components/litterrobot/conftest.py +++ b/tests/components/litterrobot/conftest.py @@ -52,6 +52,20 @@ def create_mock_robot( return robot +def create_mock_pet( + pet_data: dict | None, + account: Account, + side_effect: Any | None = None, +) -> Pet: + """Create a mock Pet.""" + if not pet_data: + pet_data = {} + + pet = Pet(data={**PET_DATA, **pet_data}, session=account.session) + pet.fetch_weight_history = AsyncMock(side_effect=side_effect) + return pet + + def create_mock_account( robot_data: dict | None = None, side_effect: Any | None = None, @@ -69,7 +83,7 @@ def create_mock_account( if skip_robots else [create_mock_robot(robot_data, account, v4, feeder, side_effect)] ) - account.pets = [Pet(PET_DATA, account.session)] if pet else [] + account.pets = [create_mock_pet(PET_DATA, account, side_effect)] if pet else [] return account diff --git a/tests/components/litterrobot/test_sensor.py b/tests/components/litterrobot/test_sensor.py index 76c567f5417..d1101a4231d 100644 --- a/tests/components/litterrobot/test_sensor.py +++ b/tests/components/litterrobot/test_sensor.py @@ -124,6 +124,16 @@ async def test_pet_weight_sensor( assert sensor.attributes["unit_of_measurement"] == UnitOfMass.POUNDS +@pytest.mark.freeze_time("2025-06-15 12:00:00+00:00") +async def test_pet_visits_today_sensor( + hass: HomeAssistant, mock_account_with_pet: MagicMock +) -> None: + """Tests pet visits today sensors.""" + await setup_integration(hass, mock_account_with_pet, PLATFORM_DOMAIN) + sensor = hass.states.get("sensor.kitty_visits_today") + assert sensor.state == "2" + + async def test_litterhopper_sensor( hass: HomeAssistant, mock_account_with_litterhopper: MagicMock ) -> None: diff --git a/tests/components/matter/fixtures/nodes/silabs_evse_charging.json b/tests/components/matter/fixtures/nodes/silabs_evse_charging.json index 3188ba81ad6..3540f376f42 100644 --- a/tests/components/matter/fixtures/nodes/silabs_evse_charging.json +++ b/tests/components/matter/fixtures/nodes/silabs_evse_charging.json @@ -447,6 +447,7 @@ "1/153/37": null, "1/153/38": null, "1/153/39": null, + "1/153/48": 75, "1/153/64": 2, "1/153/65": 0, "1/153/66": 0, diff --git a/tests/components/matter/snapshots/test_number.ambr b/tests/components/matter/snapshots/test_number.ambr index 8d27c4b4691..da709615610 100644 --- a/tests/components/matter/snapshots/test_number.ambr +++ b/tests/components/matter/snapshots/test_number.ambr @@ -750,6 +750,120 @@ 'state': 'unavailable', }) # --- +# name: test_numbers[multi_endpoint_light][number.inovelli_led_off_intensity-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'max': 75, + 'min': 0, + 'mode': , + 'step': 1, + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'number', + 'entity_category': , + 'entity_id': 'number.inovelli_led_off_intensity', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'LED off intensity', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'led_indicator_intensity_off', + 'unique_id': '00000000000004D2-00000000000000C5-MatterNodeDevice-1-InovelliLEDIndicatorIntensityOff-305134641-305070178', + 'unit_of_measurement': None, + }) +# --- +# name: test_numbers[multi_endpoint_light][number.inovelli_led_off_intensity-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Inovelli LED off intensity', + 'max': 75, + 'min': 0, + 'mode': , + 'step': 1, + }), + 'context': , + 'entity_id': 'number.inovelli_led_off_intensity', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '1', + }) +# --- +# name: test_numbers[multi_endpoint_light][number.inovelli_led_on_intensity-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'max': 75, + 'min': 0, + 'mode': , + 'step': 1, + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'number', + 'entity_category': , + 'entity_id': 'number.inovelli_led_on_intensity', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'LED on intensity', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'led_indicator_intensity_on', + 'unique_id': '00000000000004D2-00000000000000C5-MatterNodeDevice-1-InovelliLEDIndicatorIntensityOn-305134641-305070177', + 'unit_of_measurement': None, + }) +# --- +# name: test_numbers[multi_endpoint_light][number.inovelli_led_on_intensity-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Inovelli LED on intensity', + 'max': 75, + 'min': 0, + 'mode': , + 'step': 1, + }), + 'context': , + 'entity_id': 'number.inovelli_led_on_intensity', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '33', + }) +# --- # name: test_numbers[multi_endpoint_light][number.inovelli_off_transition_time-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/matter/snapshots/test_sensor.ambr b/tests/components/matter/snapshots/test_sensor.ambr index 472799b80ae..140384283cc 100644 --- a/tests/components/matter/snapshots/test_sensor.ambr +++ b/tests/components/matter/snapshots/test_sensor.ambr @@ -5022,6 +5022,59 @@ 'state': '2.0', }) # --- +# name: test_sensors[silabs_evse_charging][sensor.evse_state_of_charge-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.evse_state_of_charge', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'State of charge', + 'platform': 'matter', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'evse_soc', + 'unique_id': '00000000000004D2-0000000000000017-MatterNodeDevice-1-EnergyEvseStateOfCharge-153-48', + 'unit_of_measurement': '%', + }) +# --- +# name: test_sensors[silabs_evse_charging][sensor.evse_state_of_charge-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'battery', + 'friendly_name': 'evse State of charge', + 'state_class': , + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.evse_state_of_charge', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '75', + }) +# --- # name: test_sensors[silabs_evse_charging][sensor.evse_user_max_charge_current-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/miele/test_config_flow.py b/tests/components/miele/test_config_flow.py index bbe5844c1cd..5ce129b255d 100644 --- a/tests/components/miele/test_config_flow.py +++ b/tests/components/miele/test_config_flow.py @@ -46,7 +46,6 @@ async def test_full_flow( f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}" f"&redirect_uri={REDIRECT_URL}" f"&state={state}" - "&vg=sv-SE" ) client = await hass_client_no_auth() @@ -118,7 +117,6 @@ async def test_flow_reauth_abort( f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}" f"&redirect_uri={REDIRECT_URL}" f"&state={state}" - "&vg=sv-SE" ) client = await hass_client_no_auth() @@ -187,7 +185,6 @@ async def test_flow_reconfigure_abort( f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}" f"&redirect_uri={REDIRECT_URL}" f"&state={state}" - "&vg=sv-SE" ) client = await hass_client_no_auth() @@ -247,7 +244,6 @@ async def test_zeroconf_flow( f"{OAUTH2_AUTHORIZE}?response_type=code&client_id={CLIENT_ID}" f"&redirect_uri={REDIRECT_URL}" f"&state={state}" - "&vg=sv-SE" ) client = await hass_client_no_auth() diff --git a/tests/components/mqtt/test_config_flow.py b/tests/components/mqtt/test_config_flow.py index 9386f1da32c..77c74001939 100644 --- a/tests/components/mqtt/test_config_flow.py +++ b/tests/components/mqtt/test_config_flow.py @@ -3220,7 +3220,7 @@ async def test_subentry_configflow( "url": learn_more_url(component["platform"]), } - # Process entity details setep + # Process entity details step assert result["step_id"] == "entity_platform_config" # First test validators if set of test @@ -4212,3 +4212,52 @@ async def test_subentry_reconfigure_availablity( "payload_available": "1", "payload_not_available": "0", } + + +async def test_subentry_configflow_section_feature( + hass: HomeAssistant, + mqtt_mock_entry: MqttMockHAClientGenerator, +) -> None: + """Test the subentry ConfigFlow sections are hidden when they have no configurable options.""" + await mqtt_mock_entry() + config_entry = hass.config_entries.async_entries(mqtt.DOMAIN)[0] + + result = await hass.config_entries.subentries.async_init( + (config_entry.entry_id, "device"), + context={"source": config_entries.SOURCE_USER}, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "device" + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], + user_input={"name": "Bla", "mqtt_settings": {"qos": 1}}, + ) + assert result["type"] is FlowResultType.FORM + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], + user_input={"platform": "fan"}, + ) + assert result["type"] is FlowResultType.FORM + assert result["description_placeholders"] == { + "mqtt_device": "Bla", + "platform": "fan", + "entity": "Bla", + "url": learn_more_url("fan"), + } + + # Process entity details step + assert result["step_id"] == "entity_platform_config" + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], + user_input={"fan_feature_speed": True}, + ) + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {} + assert result["step_id"] == "mqtt_platform_config" + + # Check mqtt platform config flow sections from data schema + data_schema = result["data_schema"].schema + assert "fan_speed_settings" in data_schema + assert "fan_preset_mode_settings" not in data_schema diff --git a/tests/components/mqtt/test_discovery.py b/tests/components/mqtt/test_discovery.py index 35a9a0494a6..04b4bda0d79 100644 --- a/tests/components/mqtt/test_discovery.py +++ b/tests/components/mqtt/test_discovery.py @@ -1496,6 +1496,52 @@ async def test_discovery_with_object_id( assert (domain, "object bla") in hass.data["mqtt"].discovery_already_discovered +async def test_discovery_with_object_id_for_previous_deleted_entity( + hass: HomeAssistant, + mqtt_mock_entry: MqttMockHAClientGenerator, +) -> None: + """Test discovering an MQTT entity with object_id and unique_id.""" + + topic = "homeassistant/sensor/object/bla/config" + config = ( + '{ "name": "Hello World 11", "unique_id": "very_unique", ' + '"obj_id": "hello_id", "state_topic": "test-topic" }' + ) + new_config = ( + '{ "name": "Hello World 11", "unique_id": "very_unique", ' + '"obj_id": "updated_hello_id", "state_topic": "test-topic" }' + ) + initial_entity_id = "sensor.hello_id" + new_entity_id = "sensor.updated_hello_id" + name = "Hello World 11" + domain = "sensor" + + await mqtt_mock_entry() + async_fire_mqtt_message(hass, topic, config) + await hass.async_block_till_done() + + state = hass.states.get(initial_entity_id) + + assert state is not None + assert state.name == name + assert (domain, "object bla") in hass.data["mqtt"].discovery_already_discovered + + # Delete the entity + async_fire_mqtt_message(hass, topic, "") + await hass.async_block_till_done() + assert (domain, "object bla") not in hass.data["mqtt"].discovery_already_discovered + + # Rediscover with new object_id + async_fire_mqtt_message(hass, topic, new_config) + await hass.async_block_till_done() + + state = hass.states.get(new_entity_id) + + assert state is not None + assert state.name == name + assert (domain, "object bla") in hass.data["mqtt"].discovery_already_discovered + + async def test_discovery_incl_nodeid( hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator ) -> None: diff --git a/tests/components/nibe_heatpump/__init__.py b/tests/components/nibe_heatpump/__init__.py index 15cd9859d6e..e5ce32b2293 100644 --- a/tests/components/nibe_heatpump/__init__.py +++ b/tests/components/nibe_heatpump/__init__.py @@ -24,6 +24,8 @@ MOCK_ENTRY_DATA = { "connection_type": "nibegw", } +MOCK_UNIQUE_ID = "mock_entry_unique_id" + class MockConnection(Connection): """A mock connection class.""" @@ -59,7 +61,9 @@ class MockConnection(Connection): async def async_add_entry(hass: HomeAssistant, data: dict[str, Any]) -> MockConfigEntry: """Add entry and get the coordinator.""" - entry = MockConfigEntry(domain=DOMAIN, title="Dummy", data=data) + entry = MockConfigEntry( + domain=DOMAIN, title="Dummy", data=data, unique_id=MOCK_UNIQUE_ID + ) entry.add_to_hass(hass) await hass.config_entries.async_setup(entry.entry_id) diff --git a/tests/components/nibe_heatpump/snapshots/test_binary_sensor.ambr b/tests/components/nibe_heatpump/snapshots/test_binary_sensor.ambr new file mode 100644 index 00000000000..37dd7a8679c --- /dev/null +++ b/tests/components/nibe_heatpump/snapshots/test_binary_sensor.ambr @@ -0,0 +1,97 @@ +# serializer version: 1 +# name: test_update[Model.F1255-49239-OFF][binary_sensor.eb101_installed_49239-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.eb101_installed_49239', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'EB101 Installed', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'eb101_installed_49239', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-49239', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-49239-OFF][binary_sensor.eb101_installed_49239-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 EB101 Installed', + }), + 'context': , + 'entity_id': 'binary_sensor.eb101_installed_49239', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_update[Model.F1255-49239-ON][binary_sensor.eb101_installed_49239-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.eb101_installed_49239', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'EB101 Installed', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'eb101_installed_49239', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-49239', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-49239-ON][binary_sensor.eb101_installed_49239-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 EB101 Installed', + }), + 'context': , + 'entity_id': 'binary_sensor.eb101_installed_49239', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/nibe_heatpump/snapshots/test_coordinator.ambr b/tests/components/nibe_heatpump/snapshots/test_coordinator.ambr index 50755533ee5..965d5a3b2bb 100644 --- a/tests/components/nibe_heatpump/snapshots/test_coordinator.ambr +++ b/tests/components/nibe_heatpump/snapshots/test_coordinator.ambr @@ -5,7 +5,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -22,7 +22,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -39,7 +39,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -56,7 +56,7 @@ 'friendly_name': 'S320 Min supply climate system 1', 'max': 80.0, 'min': 5.0, - 'mode': , + 'mode': , 'step': 0.1, 'unit_of_measurement': '°C', }), @@ -77,7 +77,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -94,7 +94,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -111,7 +111,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -128,7 +128,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , diff --git a/tests/components/nibe_heatpump/snapshots/test_number.ambr b/tests/components/nibe_heatpump/snapshots/test_number.ambr index 343d5569a2d..ac6354c902a 100644 --- a/tests/components/nibe_heatpump/snapshots/test_number.ambr +++ b/tests/components/nibe_heatpump/snapshots/test_number.ambr @@ -1,11 +1,29 @@ # serializer version: 1 +# name: test_set_value_same + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1155 Room sensor setpoint S1', + 'max': 30.0, + 'min': 5.0, + 'mode': , + 'step': 0.1, + 'unit_of_measurement': '°C', + }), + 'context': , + 'entity_id': 'number.room_sensor_setpoint_s1_47398', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '25.0', + }) +# --- # name: test_update[Model.F1155-47011-number.heat_offset_s1_47011--10] StateSnapshot({ 'attributes': ReadOnlyDict({ 'friendly_name': 'F1155 Heat Offset S1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -22,7 +40,7 @@ 'friendly_name': 'F1155 Heat Offset S1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -42,7 +60,7 @@ 'friendly_name': 'F750 HW charge offset', 'max': 12.7, 'min': -12.8, - 'mode': , + 'mode': , 'step': 0.1, 'unit_of_measurement': '°C', }), @@ -60,7 +78,7 @@ 'friendly_name': 'F750 HW charge offset', 'max': 12.7, 'min': -12.8, - 'mode': , + 'mode': , 'step': 0.1, 'unit_of_measurement': '°C', }), @@ -78,7 +96,7 @@ 'friendly_name': 'F750 HW charge offset', 'max': 12.7, 'min': -12.8, - 'mode': , + 'mode': , 'step': 0.1, 'unit_of_measurement': '°C', }), @@ -96,7 +114,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -113,7 +131,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , @@ -130,7 +148,7 @@ 'friendly_name': 'S320 Heating offset climate system 1', 'max': 10.0, 'min': -10.0, - 'mode': , + 'mode': , 'step': 1.0, }), 'context': , diff --git a/tests/components/nibe_heatpump/snapshots/test_switch.ambr b/tests/components/nibe_heatpump/snapshots/test_switch.ambr new file mode 100644 index 00000000000..01f35bd8a54 --- /dev/null +++ b/tests/components/nibe_heatpump/snapshots/test_switch.ambr @@ -0,0 +1,193 @@ +# serializer version: 1 +# name: test_update[Model.F1255-48043-ACTIVE][switch.holiday_activated_48043-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.holiday_activated_48043', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Holiday - Activated', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'holiday_activated_48043', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-48043', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-48043-ACTIVE][switch.holiday_activated_48043-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 Holiday - Activated', + }), + 'context': , + 'entity_id': 'switch.holiday_activated_48043', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_update[Model.F1255-48043-INACTIVE][switch.holiday_activated_48043-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.holiday_activated_48043', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Holiday - Activated', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'holiday_activated_48043', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-48043', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-48043-INACTIVE][switch.holiday_activated_48043-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 Holiday - Activated', + }), + 'context': , + 'entity_id': 'switch.holiday_activated_48043', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_update[Model.F1255-48071-OFF][switch.flm_1_accessory_48071-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.flm_1_accessory_48071', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'FLM 1 accessory', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'flm_1_accessory_48071', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-48071', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-48071-OFF][switch.flm_1_accessory_48071-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 FLM 1 accessory', + }), + 'context': , + 'entity_id': 'switch.flm_1_accessory_48071', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_update[Model.F1255-48071-ON][switch.flm_1_accessory_48071-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.flm_1_accessory_48071', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'FLM 1 accessory', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'flm_1_accessory_48071', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-48071', + 'unit_of_measurement': None, + }) +# --- +# name: test_update[Model.F1255-48071-ON][switch.flm_1_accessory_48071-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'F1255 FLM 1 accessory', + }), + 'context': , + 'entity_id': 'switch.flm_1_accessory_48071', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/nibe_heatpump/test_binary_sensor.py b/tests/components/nibe_heatpump/test_binary_sensor.py new file mode 100644 index 00000000000..30010ac61c4 --- /dev/null +++ b/tests/components/nibe_heatpump/test_binary_sensor.py @@ -0,0 +1,49 @@ +"""Test the Nibe Heat Pump binary sensor entities.""" + +from typing import Any +from unittest.mock import patch + +from nibe.heatpump import Model +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 async_add_model + +from tests.common import snapshot_platform + + +@pytest.fixture(autouse=True) +async def fixture_single_platform(): + """Only allow this platform to load.""" + with patch( + "homeassistant.components.nibe_heatpump.PLATFORMS", [Platform.BINARY_SENSOR] + ): + yield + + +@pytest.mark.parametrize( + ("model", "address", "value"), + [ + (Model.F1255, 49239, "OFF"), + (Model.F1255, 49239, "ON"), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_update( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + model: Model, + address: int, + value: Any, + coils: dict[int, Any], + snapshot: SnapshotAssertion, +) -> None: + """Test setting of value.""" + coils[address] = value + + entry = await async_add_model(hass, model) + await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id) diff --git a/tests/components/nibe_heatpump/test_button.py b/tests/components/nibe_heatpump/test_button.py index 5015bba4092..4f2bab7ad0a 100644 --- a/tests/components/nibe_heatpump/test_button.py +++ b/tests/components/nibe_heatpump/test_button.py @@ -1,4 +1,4 @@ -"""Test the Nibe Heat Pump config flow.""" +"""Test the Nibe Heat Pump buttons.""" from typing import Any from unittest.mock import AsyncMock, patch diff --git a/tests/components/nibe_heatpump/test_climate.py b/tests/components/nibe_heatpump/test_climate.py index a9620b5ddb3..85e932f8018 100644 --- a/tests/components/nibe_heatpump/test_climate.py +++ b/tests/components/nibe_heatpump/test_climate.py @@ -1,4 +1,4 @@ -"""Test the Nibe Heat Pump config flow.""" +"""Test the Nibe Heat Pump climate entities.""" from typing import Any from unittest.mock import call, patch diff --git a/tests/components/nibe_heatpump/test_number.py b/tests/components/nibe_heatpump/test_number.py index dc7faf0a80e..6e004a0554e 100644 --- a/tests/components/nibe_heatpump/test_number.py +++ b/tests/components/nibe_heatpump/test_number.py @@ -1,9 +1,10 @@ -"""Test the Nibe Heat Pump config flow.""" +"""Test the Nibe Heat Pump number entities.""" from typing import Any from unittest.mock import AsyncMock, patch from nibe.coil import CoilData +from nibe.exceptions import WriteDeniedException, WriteException, WriteTimeoutException from nibe.heatpump import Model import pytest from syrupy.assertion import SnapshotAssertion @@ -15,6 +16,7 @@ from homeassistant.components.number import ( ) from homeassistant.const import ATTR_ENTITY_ID, Platform from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from . import async_add_model @@ -108,3 +110,101 @@ async def test_set_value( assert isinstance(coil, CoilData) assert coil.coil.address == address assert coil.value == value + + +@pytest.mark.parametrize( + ("exception", "translation_key", "translation_placeholders"), + [ + ( + WriteTimeoutException("timeout writing"), + "write_timeout", + {"address": "47398"}, + ), + ( + WriteException("failed"), + "write_failed", + { + "address": "47398", + "value": "25.0", + "error": "failed", + }, + ), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_set_value_fail( + hass: HomeAssistant, + mock_connection: AsyncMock, + exception: Exception, + translation_key: str, + translation_placeholders: dict[str, Any], + coils: dict[int, Any], +) -> None: + """Test setting of value.""" + + value = 25 + model = Model.F1155 + address = 47398 + entity_id = "number.room_sensor_setpoint_s1_47398" + coils[address] = 0 + + await async_add_model(hass, model) + + await hass.async_block_till_done() + assert hass.states.get(entity_id) + + mock_connection.write_coil.side_effect = exception + + # Write value + with pytest.raises(HomeAssistantError) as exc_info: + await hass.services.async_call( + PLATFORM_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: entity_id, ATTR_VALUE: value}, + blocking=True, + ) + assert exc_info.value.translation_domain == "nibe_heatpump" + assert exc_info.value.translation_key == translation_key + assert exc_info.value.translation_placeholders == translation_placeholders + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_set_value_same( + hass: HomeAssistant, + mock_connection: AsyncMock, + coils: dict[int, Any], + snapshot: SnapshotAssertion, +) -> None: + """Test setting a value, which the pump will reject.""" + + value = 25 + model = Model.F1155 + address = 47398 + entity_id = "number.room_sensor_setpoint_s1_47398" + coils[address] = 0 + + await async_add_model(hass, model) + + await hass.async_block_till_done() + assert hass.states.get(entity_id) + + mock_connection.write_coil.side_effect = WriteDeniedException() + + # Write value + await hass.services.async_call( + PLATFORM_DOMAIN, + SERVICE_SET_VALUE, + {ATTR_ENTITY_ID: entity_id, ATTR_VALUE: value}, + blocking=True, + ) + + # Verify attempt was done + args = mock_connection.write_coil.call_args + assert args + coil = args.args[0] + assert isinstance(coil, CoilData) + assert coil.coil.address == address + assert coil.value == value + + # State should have been set + assert hass.states.get(entity_id) == snapshot diff --git a/tests/components/nibe_heatpump/test_switch.py b/tests/components/nibe_heatpump/test_switch.py new file mode 100644 index 00000000000..4221de52ba1 --- /dev/null +++ b/tests/components/nibe_heatpump/test_switch.py @@ -0,0 +1,133 @@ +"""Test the Nibe Heat Pump switch entities.""" + +from typing import Any +from unittest.mock import AsyncMock, patch + +from nibe.coil import CoilData +from nibe.heatpump import Model +import pytest +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.switch import ( + DOMAIN as SWITCH_PLATFORM, + SERVICE_TURN_OFF, + SERVICE_TURN_ON, +) +from homeassistant.const import ATTR_ENTITY_ID, Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import async_add_model + +from tests.common import snapshot_platform + + +@pytest.fixture(autouse=True) +async def fixture_single_platform(): + """Only allow this platform to load.""" + with patch("homeassistant.components.nibe_heatpump.PLATFORMS", [Platform.SWITCH]): + yield + + +@pytest.mark.parametrize( + ("model", "address", "value"), + [ + (Model.F1255, 48043, "INACTIVE"), + (Model.F1255, 48043, "ACTIVE"), + (Model.F1255, 48071, "OFF"), + (Model.F1255, 48071, "ON"), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_update( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + model: Model, + address: int, + value: Any, + coils: dict[int, Any], + snapshot: SnapshotAssertion, +) -> None: + """Test setting of value.""" + coils[address] = value + + entry = await async_add_model(hass, model) + await snapshot_platform(hass, entity_registry, snapshot, entry.entry_id) + + +@pytest.mark.parametrize( + ("model", "address", "entity_id", "state"), + [ + (Model.F1255, 48043, "switch.holiday_activated_48043", "INACTIVE"), + (Model.F1255, 48071, "switch.flm_1_accessory_48071", "OFF"), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_turn_on( + hass: HomeAssistant, + mock_connection: AsyncMock, + model: Model, + entity_id: str, + address: int, + state: Any, + coils: dict[int, Any], +) -> None: + """Test setting of value.""" + coils[address] = state + + await async_add_model(hass, model) + + # Write value + await hass.services.async_call( + SWITCH_PLATFORM, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + # Verify written + args = mock_connection.write_coil.call_args + assert args + coil = args.args[0] + assert isinstance(coil, CoilData) + assert coil.coil.address == address + assert coil.raw_value == 1 + + +@pytest.mark.parametrize( + ("model", "address", "entity_id", "state"), + [ + (Model.F1255, 48043, "switch.holiday_activated_48043", "INACTIVE"), + (Model.F1255, 48071, "switch.flm_1_accessory_48071", "ON"), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_turn_off( + hass: HomeAssistant, + mock_connection: AsyncMock, + model: Model, + entity_id: str, + address: int, + state: Any, + coils: dict[int, Any], +) -> None: + """Test setting of value.""" + coils[address] = state + + await async_add_model(hass, model) + + # Write value + await hass.services.async_call( + SWITCH_PLATFORM, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + # Verify written + args = mock_connection.write_coil.call_args + assert args + coil = args.args[0] + assert isinstance(coil, CoilData) + assert coil.coil.address == address + assert coil.raw_value == 0 diff --git a/tests/components/nyt_games/fixtures/latest.json b/tests/components/nyt_games/fixtures/latest.json index 73a6f440fc0..16601243052 100644 --- a/tests/components/nyt_games/fixtures/latest.json +++ b/tests/components/nyt_games/fixtures/latest.json @@ -25,43 +25,46 @@ }, "wordle": { "legacyStats": { - "gamesPlayed": 70, - "gamesWon": 51, + "gamesPlayed": 1111, + "gamesWon": 1069, "guesses": { "1": 0, - "2": 1, - "3": 7, - "4": 11, - "5": 20, - "6": 12, - "fail": 19 + "2": 8, + "3": 83, + "4": 440, + "5": 372, + "6": 166, + "fail": 42 }, - "currentStreak": 1, - "maxStreak": 5, - "lastWonDayOffset": 1189, + "currentStreak": 229, + "maxStreak": 229, + "lastWonDayOffset": 1472, "hasPlayed": true, - "autoOptInTimestamp": 1708273168957, - "hasMadeStatsChoice": false, - "timestamp": 1726831978 + "autoOptInTimestamp": 1712205417018, + "hasMadeStatsChoice": true, + "timestamp": 1751255756 }, "calculatedStats": { - "gamesPlayed": 33, - "gamesWon": 26, + "currentStreak": 237, + "maxStreak": 241, + "lastWonPrintDate": "2025-07-08", + "lastCompletedPrintDate": "2025-07-08", + "hasPlayed": true + }, + "totalStats": { + "gamesWon": 1077, + "gamesPlayed": 1119, "guesses": { "1": 0, - "2": 1, - "3": 4, - "4": 7, - "5": 10, - "6": 4, - "fail": 7 + "2": 8, + "3": 83, + "4": 444, + "5": 376, + "6": 166, + "fail": 42 }, - "currentStreak": 1, - "maxStreak": 5, - "lastWonPrintDate": "2024-09-20", - "lastCompletedPrintDate": "2024-09-20", "hasPlayed": true, - "generation": 1 + "hasPlayedArchive": false } } } diff --git a/tests/components/nyt_games/fixtures/new_account.json b/tests/components/nyt_games/fixtures/new_account.json index ad4d8e2e416..d35ce4cdebc 100644 --- a/tests/components/nyt_games/fixtures/new_account.json +++ b/tests/components/nyt_games/fixtures/new_account.json @@ -7,26 +7,6 @@ "stats": { "wordle": { "legacyStats": { - "gamesPlayed": 1, - "gamesWon": 1, - "guesses": { - "1": 0, - "2": 0, - "3": 0, - "4": 0, - "5": 1, - "6": 0, - "fail": 0 - }, - "currentStreak": 0, - "maxStreak": 1, - "lastWonDayOffset": 1118, - "hasPlayed": true, - "autoOptInTimestamp": 1727357874700, - "hasMadeStatsChoice": false, - "timestamp": 1727358123 - }, - "calculatedStats": { "gamesPlayed": 0, "gamesWon": 0, "guesses": { @@ -38,12 +18,35 @@ "6": 0, "fail": 0 }, + "currentStreak": 0, + "maxStreak": 1, + "lastWonDayOffset": 1118, + "hasPlayed": true, + "autoOptInTimestamp": 1727357874700, + "hasMadeStatsChoice": false, + "timestamp": 1727358123 + }, + "calculatedStats": { "currentStreak": 0, "maxStreak": 1, "lastWonPrintDate": "", "lastCompletedPrintDate": "", + "hasPlayed": false + }, + "totalStats": { + "gamesPlayed": 1, + "gamesWon": 1, + "guesses": { + "1": 0, + "2": 0, + "3": 0, + "4": 0, + "5": 1, + "6": 0, + "fail": 0 + }, "hasPlayed": false, - "generation": 1 + "hasPlayedArchive": false } } } diff --git a/tests/components/nyt_games/snapshots/test_sensor.ambr b/tests/components/nyt_games/snapshots/test_sensor.ambr index 5a1aa384f0f..10fddcfa365 100644 --- a/tests/components/nyt_games/snapshots/test_sensor.ambr +++ b/tests/components/nyt_games/snapshots/test_sensor.ambr @@ -473,7 +473,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '1', + 'state': '237', }) # --- # name: test_all_entities[sensor.wordle_highest_streak-entry] @@ -529,7 +529,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '5', + 'state': '241', }) # --- # name: test_all_entities[sensor.wordle_played-entry] @@ -581,7 +581,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '70', + 'state': '1119', }) # --- # name: test_all_entities[sensor.wordle_won-entry] @@ -633,6 +633,6 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '51', + 'state': '1077', }) # --- diff --git a/tests/components/octoprint/__init__.py b/tests/components/octoprint/__init__.py index dd3eda0e81f..3ddae7de587 100644 --- a/tests/components/octoprint/__init__.py +++ b/tests/components/octoprint/__init__.py @@ -21,7 +21,7 @@ from homeassistant.helpers.typing import UNDEFINED, UndefinedType from tests.common import MockConfigEntry DEFAULT_JOB = { - "job": {}, + "job": {"file": {}}, "progress": {"completion": 50}, } diff --git a/tests/components/octoprint/test_sensor.py b/tests/components/octoprint/test_sensor.py index 8c1c0a7712e..87485e46807 100644 --- a/tests/components/octoprint/test_sensor.py +++ b/tests/components/octoprint/test_sensor.py @@ -24,7 +24,7 @@ async def test_sensors( "temperature": {"tool1": {"actual": 18.83136, "target": 37.83136}}, } job = { - "job": {}, + "job": {"file": {}}, "progress": {"completion": 50, "printTime": 600, "printTimeLeft": 6000}, "state": "Printing", } @@ -126,7 +126,7 @@ async def test_sensors_paused( "temperature": {"tool1": {"actual": 18.83136, "target": None}}, } job = { - "job": {}, + "job": {"file": {}}, "progress": {"completion": 50, "printTime": 600, "printTimeLeft": 6000}, "state": "Paused", } @@ -155,7 +155,7 @@ async def test_sensors_printer_disconnected( ) -> None: """Test the underlying sensors.""" job = { - "job": {}, + "job": {"file": {}}, "progress": {"completion": 50, "printTime": 600, "printTimeLeft": 6000}, "state": "Paused", } diff --git a/tests/components/openai_conversation/__init__.py b/tests/components/openai_conversation/__init__.py index dda2fe16a63..11dc978250a 100644 --- a/tests/components/openai_conversation/__init__.py +++ b/tests/components/openai_conversation/__init__.py @@ -1 +1,241 @@ """Tests for the OpenAI Conversation integration.""" + +from openai.types.responses import ( + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseFunctionToolCall, + ResponseFunctionWebSearch, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseOutputMessage, + ResponseOutputText, + ResponseReasoningItem, + ResponseStreamEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, +) +from openai.types.responses.response_function_web_search import ActionSearch + + +def create_message_item( + id: str, text: str | list[str], output_index: int +) -> list[ResponseStreamEvent]: + """Create a message item.""" + if isinstance(text, str): + text = [text] + + content = ResponseOutputText(annotations=[], text="", type="output_text") + events = [ + ResponseOutputItemAddedEvent( + item=ResponseOutputMessage( + id=id, + content=[], + type="message", + role="assistant", + status="in_progress", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.added", + ), + ResponseContentPartAddedEvent( + content_index=0, + item_id=id, + output_index=output_index, + part=content, + sequence_number=0, + type="response.content_part.added", + ), + ] + + content.text = "".join(text) + events.extend( + ResponseTextDeltaEvent( + content_index=0, + delta=delta, + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.output_text.delta", + ) + for delta in text + ) + + events.extend( + [ + ResponseTextDoneEvent( + content_index=0, + item_id=id, + output_index=output_index, + text="".join(text), + sequence_number=0, + type="response.output_text.done", + ), + ResponseContentPartDoneEvent( + content_index=0, + item_id=id, + output_index=output_index, + part=content, + sequence_number=0, + type="response.content_part.done", + ), + ResponseOutputItemDoneEvent( + item=ResponseOutputMessage( + id=id, + content=[content], + role="assistant", + status="completed", + type="message", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.done", + ), + ] + ) + + return events + + +def create_function_tool_call_item( + id: str, arguments: str | list[str], call_id: str, name: str, output_index: int +) -> list[ResponseStreamEvent]: + """Create a function tool call item.""" + if isinstance(arguments, str): + arguments = [arguments] + + events = [ + ResponseOutputItemAddedEvent( + item=ResponseFunctionToolCall( + id=id, + arguments="", + call_id=call_id, + name=name, + type="function_call", + status="in_progress", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.added", + ) + ] + + events.extend( + ResponseFunctionCallArgumentsDeltaEvent( + delta=delta, + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.function_call_arguments.delta", + ) + for delta in arguments + ) + + events.append( + ResponseFunctionCallArgumentsDoneEvent( + arguments="".join(arguments), + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.function_call_arguments.done", + ) + ) + + events.append( + ResponseOutputItemDoneEvent( + item=ResponseFunctionToolCall( + id=id, + arguments="".join(arguments), + call_id=call_id, + name=name, + type="function_call", + status="completed", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.done", + ) + ) + + return events + + +def create_reasoning_item(id: str, output_index: int) -> list[ResponseStreamEvent]: + """Create a reasoning item.""" + return [ + ResponseOutputItemAddedEvent( + item=ResponseReasoningItem( + id=id, + summary=[], + type="reasoning", + status=None, + encrypted_content="AAA", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.added", + ), + ResponseOutputItemDoneEvent( + item=ResponseReasoningItem( + id=id, + summary=[], + type="reasoning", + status=None, + encrypted_content="AAABBB", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.done", + ), + ] + + +def create_web_search_item(id: str, output_index: int) -> list[ResponseStreamEvent]: + """Create a web search call item.""" + return [ + ResponseOutputItemAddedEvent( + item=ResponseFunctionWebSearch( + id=id, + status="in_progress", + action=ActionSearch(query="query", type="search"), + type="web_search_call", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.added", + ), + ResponseWebSearchCallInProgressEvent( + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.web_search_call.in_progress", + ), + ResponseWebSearchCallSearchingEvent( + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.web_search_call.searching", + ), + ResponseWebSearchCallCompletedEvent( + item_id=id, + output_index=output_index, + sequence_number=0, + type="response.web_search_call.completed", + ), + ResponseOutputItemDoneEvent( + item=ResponseFunctionWebSearch( + id=id, + status="completed", + action=ActionSearch(query="query", type="search"), + type="web_search_call", + ), + output_index=output_index, + sequence_number=0, + type="response.output_item.done", + ), + ] diff --git a/tests/components/openai_conversation/conftest.py b/tests/components/openai_conversation/conftest.py index b8944d837be..84c907a7c2e 100644 --- a/tests/components/openai_conversation/conftest.py +++ b/tests/components/openai_conversation/conftest.py @@ -1,11 +1,31 @@ """Tests helpers.""" +from collections.abc import Generator from typing import Any -from unittest.mock import patch +from unittest.mock import AsyncMock, patch +from openai.types import ResponseFormatText +from openai.types.responses import ( + Response, + ResponseCompletedEvent, + ResponseCreatedEvent, + ResponseError, + ResponseErrorEvent, + ResponseFailedEvent, + ResponseIncompleteEvent, + ResponseInProgressEvent, + ResponseOutputItemDoneEvent, + ResponseTextConfig, +) +from openai.types.responses.response import IncompleteDetails import pytest -from homeassistant.components.openai_conversation.const import DEFAULT_CONVERSATION_NAME +from homeassistant.components.openai_conversation.const import ( + CONF_CHAT_MODEL, + DEFAULT_AI_TASK_NAME, + DEFAULT_CONVERSATION_NAME, + RECOMMENDED_AI_TASK_OPTIONS, +) from homeassistant.config_entries import ConfigSubentryData from homeassistant.const import CONF_LLM_HASS_API from homeassistant.core import HomeAssistant @@ -16,14 +36,14 @@ from tests.common import MockConfigEntry @pytest.fixture -def mock_subentry_data() -> dict[str, Any]: +def mock_conversation_subentry_data() -> dict[str, Any]: """Mock subentry data.""" return {} @pytest.fixture def mock_config_entry( - hass: HomeAssistant, mock_subentry_data: dict[str, Any] + hass: HomeAssistant, mock_conversation_subentry_data: dict[str, Any] ) -> MockConfigEntry: """Mock a config entry.""" entry = MockConfigEntry( @@ -33,13 +53,20 @@ def mock_config_entry( "api_key": "bla", }, version=2, + minor_version=3, subentries_data=[ ConfigSubentryData( - data=mock_subentry_data, + data=mock_conversation_subentry_data, subentry_type="conversation", title=DEFAULT_CONVERSATION_NAME, unique_id=None, - ) + ), + ConfigSubentryData( + data=RECOMMENDED_AI_TASK_OPTIONS, + subentry_type="ai_task_data", + title=DEFAULT_AI_TASK_NAME, + unique_id=None, + ), ], ) entry.add_to_hass(hass) @@ -59,6 +86,19 @@ def mock_config_entry_with_assist( return mock_config_entry +@pytest.fixture +def mock_config_entry_with_reasoning_model( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> MockConfigEntry: + """Mock a config entry with assist.""" + hass.config_entries.async_update_subentry( + mock_config_entry, + next(iter(mock_config_entry.subentries.values())), + data={CONF_LLM_HASS_API: llm.LLM_API_ASSIST, CONF_CHAT_MODEL: "o4-mini"}, + ) + return mock_config_entry + + @pytest.fixture async def mock_init_component( hass: HomeAssistant, mock_config_entry: MockConfigEntry @@ -75,3 +115,94 @@ async def mock_init_component( async def setup_ha(hass: HomeAssistant) -> None: """Set up Home Assistant.""" assert await async_setup_component(hass, "homeassistant", {}) + + +@pytest.fixture +def mock_create_stream() -> Generator[AsyncMock]: + """Mock stream response.""" + + async def mock_generator(events, **kwargs): + response = Response( + id="resp_A", + created_at=1700000000, + error=None, + incomplete_details=None, + instructions=kwargs.get("instructions"), + metadata=kwargs.get("metadata", {}), + model=kwargs.get("model", "gpt-4o-mini"), + object="response", + output=[], + parallel_tool_calls=kwargs.get("parallel_tool_calls", True), + temperature=kwargs.get("temperature", 1.0), + tool_choice=kwargs.get("tool_choice", "auto"), + tools=kwargs.get("tools", []), + top_p=kwargs.get("top_p", 1.0), + max_output_tokens=kwargs.get("max_output_tokens", 100000), + previous_response_id=kwargs.get("previous_response_id"), + reasoning=kwargs.get("reasoning"), + status="in_progress", + text=kwargs.get( + "text", ResponseTextConfig(format=ResponseFormatText(type="text")) + ), + truncation=kwargs.get("truncation", "disabled"), + usage=None, + user=kwargs.get("user"), + store=kwargs.get("store", True), + ) + yield ResponseCreatedEvent( + response=response, + sequence_number=0, + type="response.created", + ) + yield ResponseInProgressEvent( + response=response, + sequence_number=0, + type="response.in_progress", + ) + response.status = "completed" + + for value in events: + if isinstance(value, ResponseOutputItemDoneEvent): + response.output.append(value.item) + elif isinstance(value, IncompleteDetails): + response.status = "incomplete" + response.incomplete_details = value + break + if isinstance(value, ResponseError): + response.status = "failed" + response.error = value + break + + yield value + + if isinstance(value, ResponseErrorEvent): + return + + if response.status == "incomplete": + yield ResponseIncompleteEvent( + response=response, + sequence_number=0, + type="response.incomplete", + ) + elif response.status == "failed": + yield ResponseFailedEvent( + response=response, + sequence_number=0, + type="response.failed", + ) + else: + yield ResponseCompletedEvent( + response=response, + sequence_number=0, + type="response.completed", + ) + + with patch( + "openai.resources.responses.AsyncResponses.create", + AsyncMock(), + ) as mock_create: + mock_create.side_effect = lambda **kwargs: mock_generator( + mock_create.return_value.pop(0), **kwargs + ) + + yield mock_create diff --git a/tests/components/openai_conversation/snapshots/test_conversation.ambr b/tests/components/openai_conversation/snapshots/test_conversation.ambr index 48ad0878b2f..77c52ab97e6 100644 --- a/tests/components/openai_conversation/snapshots/test_conversation.ambr +++ b/tests/components/openai_conversation/snapshots/test_conversation.ambr @@ -2,6 +2,7 @@ # name: test_function_call list([ dict({ + 'attachments': None, 'content': 'Please call the test function', 'role': 'user', }), @@ -58,6 +59,7 @@ # name: test_function_call_without_reasoning list([ dict({ + 'attachments': None, 'content': 'Please call the test function', 'role': 'user', }), diff --git a/tests/components/openai_conversation/snapshots/test_init.ambr b/tests/components/openai_conversation/snapshots/test_init.ambr index 8648e47474e..4eff869b016 100644 --- a/tests/components/openai_conversation/snapshots/test_init.ambr +++ b/tests/components/openai_conversation/snapshots/test_init.ambr @@ -1,5 +1,5 @@ # serializer version: 1 -# name: test_devices[mock_subentry_data0] +# name: test_devices[mock_conversation_subentry_data0] DeviceRegistryEntrySnapshot({ 'area_id': None, 'config_entries': , @@ -26,7 +26,7 @@ 'via_device_id': None, }) # --- -# name: test_devices[mock_subentry_data1] +# name: test_devices[mock_conversation_subentry_data1] DeviceRegistryEntrySnapshot({ 'area_id': None, 'config_entries': , diff --git a/tests/components/openai_conversation/test_ai_task.py b/tests/components/openai_conversation/test_ai_task.py new file mode 100644 index 00000000000..14e3056c0e2 --- /dev/null +++ b/tests/components/openai_conversation/test_ai_task.py @@ -0,0 +1,208 @@ +"""Test AI Task platform of OpenAI Conversation integration.""" + +from pathlib import Path +from unittest.mock import AsyncMock, patch + +import pytest +import voluptuous as vol + +from homeassistant.components import ai_task, media_source +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er, selector + +from . import create_message_item + +from tests.common import MockConfigEntry + + +@pytest.mark.usefixtures("mock_init_component") +async def test_generate_data( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_create_stream: AsyncMock, + entity_registry: er.EntityRegistry, +) -> None: + """Test AI Task data generation.""" + entity_id = "ai_task.openai_ai_task" + + # Ensure entity is linked to the subentry + entity_entry = entity_registry.async_get(entity_id) + ai_task_entry = next( + iter( + entry + for entry in mock_config_entry.subentries.values() + if entry.subentry_type == "ai_task_data" + ) + ) + assert entity_entry is not None + assert entity_entry.config_entry_id == mock_config_entry.entry_id + assert entity_entry.config_subentry_id == ai_task_entry.subentry_id + + # Mock the OpenAI response stream + mock_create_stream.return_value = [ + create_message_item(id="msg_A", text="The test data", output_index=0) + ] + + result = await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id=entity_id, + instructions="Generate test data", + ) + + assert result.data == "The test data" + + +@pytest.mark.usefixtures("mock_init_component") +async def test_generate_structured_data( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_create_stream: AsyncMock, + entity_registry: er.EntityRegistry, +) -> None: + """Test AI Task structured data generation.""" + # Mock the OpenAI response stream with JSON data + mock_create_stream.return_value = [ + create_message_item( + id="msg_A", text='{"characters": ["Mario", "Luigi"]}', output_index=0 + ) + ] + + result = await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id="ai_task.openai_ai_task", + instructions="Generate test data", + structure=vol.Schema( + { + vol.Required("characters"): selector.selector( + { + "text": { + "multiple": True, + } + } + ) + }, + ), + ) + + assert result.data == {"characters": ["Mario", "Luigi"]} + + +@pytest.mark.usefixtures("mock_init_component") +async def test_generate_invalid_structured_data( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_create_stream: AsyncMock, + entity_registry: er.EntityRegistry, +) -> None: + """Test AI Task with invalid JSON response.""" + # Mock the OpenAI response stream with invalid JSON + mock_create_stream.return_value = [ + create_message_item(id="msg_A", text="INVALID JSON RESPONSE", output_index=0) + ] + + with pytest.raises( + HomeAssistantError, match="Error with OpenAI structured response" + ): + await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id="ai_task.openai_ai_task", + instructions="Generate test data", + structure=vol.Schema( + { + vol.Required("characters"): selector.selector( + { + "text": { + "multiple": True, + } + } + ) + }, + ), + ) + + +@pytest.mark.usefixtures("mock_init_component") +async def test_generate_data_with_attachments( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_create_stream: AsyncMock, + entity_registry: er.EntityRegistry, +) -> None: + """Test AI Task data generation with attachments.""" + entity_id = "ai_task.openai_ai_task" + + # Mock the OpenAI response stream + mock_create_stream.return_value = [ + create_message_item(id="msg_A", text="Hi there!", output_index=0) + ] + + # Test with attachments + with ( + patch( + "homeassistant.components.media_source.async_resolve_media", + side_effect=[ + media_source.PlayMedia( + url="http://example.com/doorbell_snapshot.jpg", + mime_type="image/jpeg", + path=Path("doorbell_snapshot.jpg"), + ), + media_source.PlayMedia( + url="http://example.com/context.txt", + mime_type="text/plain", + path=Path("context.txt"), + ), + ], + ), + patch("pathlib.Path.exists", return_value=True), + # patch.object(hass.config, "is_allowed_path", return_value=True), + patch( + "homeassistant.components.openai_conversation.entity.guess_file_type", + return_value=("image/jpeg", None), + ), + patch("pathlib.Path.read_bytes", return_value=b"fake_image_data"), + ): + result = await ai_task.async_generate_data( + hass, + task_name="Test Task", + entity_id=entity_id, + instructions="Test prompt", + attachments=[ + {"media_content_id": "media-source://media/doorbell_snapshot.jpg"}, + {"media_content_id": "media-source://media/context.txt"}, + ], + ) + + assert result.data == "Hi there!" + + # Verify that the create stream was called with the correct parameters + # The last call should have the user message with attachments + call_args = mock_create_stream.call_args + assert call_args is not None + + # Check that the input includes the attachments + input_messages = call_args[1]["input"] + assert len(input_messages) > 0 + + # Find the user message with attachments + user_message_with_attachments = input_messages[-2] + + assert user_message_with_attachments is not None + assert isinstance(user_message_with_attachments["content"], list) + assert len(user_message_with_attachments["content"]) == 3 # Text + attachments + assert user_message_with_attachments["content"] == [ + {"type": "input_text", "text": "Test prompt"}, + { + "detail": "auto", + "image_url": "data:image/jpeg;base64,ZmFrZV9pbWFnZV9kYXRh", + "type": "input_image", + }, + { + "detail": "auto", + "image_url": "data:image/jpeg;base64,ZmFrZV9pbWFnZV9kYXRh", + "type": "input_image", + }, + ] diff --git a/tests/components/openai_conversation/test_config_flow.py b/tests/components/openai_conversation/test_config_flow.py index b77542fbab3..0ccbc39160a 100644 --- a/tests/components/openai_conversation/test_config_flow.py +++ b/tests/components/openai_conversation/test_config_flow.py @@ -8,7 +8,9 @@ from openai.types.responses import Response, ResponseOutputMessage, ResponseOutp import pytest from homeassistant import config_entries -from homeassistant.components.openai_conversation.config_flow import RECOMMENDED_OPTIONS +from homeassistant.components.openai_conversation.config_flow import ( + RECOMMENDED_CONVERSATION_OPTIONS, +) from homeassistant.components.openai_conversation.const import ( CONF_CHAT_MODEL, CONF_MAX_TOKENS, @@ -24,8 +26,10 @@ from homeassistant.components.openai_conversation.const import ( CONF_WEB_SEARCH_REGION, CONF_WEB_SEARCH_TIMEZONE, CONF_WEB_SEARCH_USER_LOCATION, + DEFAULT_AI_TASK_NAME, DEFAULT_CONVERSATION_NAME, DOMAIN, + RECOMMENDED_AI_TASK_OPTIONS, RECOMMENDED_CHAT_MODEL, RECOMMENDED_MAX_TOKENS, RECOMMENDED_TOP_P, @@ -77,10 +81,16 @@ async def test_form(hass: HomeAssistant) -> None: assert result2["subentries"] == [ { "subentry_type": "conversation", - "data": RECOMMENDED_OPTIONS, + "data": RECOMMENDED_CONVERSATION_OPTIONS, "title": DEFAULT_CONVERSATION_NAME, "unique_id": None, - } + }, + { + "subentry_type": "ai_task_data", + "data": RECOMMENDED_AI_TASK_OPTIONS, + "title": DEFAULT_AI_TASK_NAME, + "unique_id": None, + }, ] assert len(mock_setup_entry.mock_calls) == 1 @@ -131,14 +141,14 @@ async def test_creating_conversation_subentry( result2 = await hass.config_entries.subentries.async_configure( result["flow_id"], - {"name": "My Custom Agent", **RECOMMENDED_OPTIONS}, + {"name": "My Custom Agent", **RECOMMENDED_CONVERSATION_OPTIONS}, ) await hass.async_block_till_done() assert result2["type"] is FlowResultType.CREATE_ENTRY assert result2["title"] == "My Custom Agent" - processed_options = RECOMMENDED_OPTIONS.copy() + processed_options = RECOMMENDED_CONVERSATION_OPTIONS.copy() processed_options[CONF_PROMPT] = processed_options[CONF_PROMPT].strip() assert result2["data"] == processed_options @@ -286,29 +296,6 @@ async def test_form_invalid_auth(hass: HomeAssistant, side_effect, error) -> Non CONF_PROMPT: "", }, ), - ( # options with no model-specific settings - {}, - ( - { - CONF_RECOMMENDED: False, - CONF_PROMPT: "Speak like a pirate", - }, - { - CONF_TEMPERATURE: 1.0, - CONF_CHAT_MODEL: "gpt-4.5-preview", - CONF_TOP_P: RECOMMENDED_TOP_P, - CONF_MAX_TOKENS: RECOMMENDED_MAX_TOKENS, - }, - ), - { - CONF_RECOMMENDED: False, - CONF_PROMPT: "Speak like a pirate", - CONF_TEMPERATURE: 1.0, - CONF_CHAT_MODEL: "gpt-4.5-preview", - CONF_TOP_P: RECOMMENDED_TOP_P, - CONF_MAX_TOKENS: RECOMMENDED_MAX_TOKENS, - }, - ), ( # options for reasoning models {}, ( @@ -732,3 +719,110 @@ async def test_subentry_web_search_user_location( CONF_WEB_SEARCH_COUNTRY: "US", CONF_WEB_SEARCH_TIMEZONE: "America/Los_Angeles", } + + +async def test_creating_ai_task_subentry( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_init_component, +) -> None: + """Test creating an AI task subentry.""" + old_subentries = set(mock_config_entry.subentries) + # Original conversation + original ai_task + assert len(mock_config_entry.subentries) == 2 + + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, "ai_task_data"), + context={"source": config_entries.SOURCE_USER}, + ) + + assert result.get("type") is FlowResultType.FORM + assert result.get("step_id") == "init" + assert not result.get("errors") + + result2 = await hass.config_entries.subentries.async_configure( + result["flow_id"], + { + "name": "Custom AI Task", + CONF_RECOMMENDED: True, + }, + ) + await hass.async_block_till_done() + + assert result2.get("type") is FlowResultType.CREATE_ENTRY + assert result2.get("title") == "Custom AI Task" + assert result2.get("data") == { + CONF_RECOMMENDED: True, + } + + assert ( + len(mock_config_entry.subentries) == 3 + ) # Original conversation + original ai_task + new ai_task + + new_subentry_id = list(set(mock_config_entry.subentries) - old_subentries)[0] + new_subentry = mock_config_entry.subentries[new_subentry_id] + assert new_subentry.subentry_type == "ai_task_data" + assert new_subentry.title == "Custom AI Task" + + +async def test_ai_task_subentry_not_loaded( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test creating an AI task subentry when entry is not loaded.""" + # Don't call mock_init_component to simulate not loaded state + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, "ai_task_data"), + context={"source": config_entries.SOURCE_USER}, + ) + + assert result.get("type") is FlowResultType.ABORT + assert result.get("reason") == "entry_not_loaded" + + +async def test_creating_ai_task_subentry_advanced( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_init_component, +) -> None: + """Test creating an AI task subentry with advanced settings.""" + result = await hass.config_entries.subentries.async_init( + (mock_config_entry.entry_id, "ai_task_data"), + context={"source": config_entries.SOURCE_USER}, + ) + + assert result.get("type") is FlowResultType.FORM + assert result.get("step_id") == "init" + + # Go to advanced settings + result2 = await hass.config_entries.subentries.async_configure( + result["flow_id"], + { + "name": "Advanced AI Task", + CONF_RECOMMENDED: False, + }, + ) + + assert result2.get("type") is FlowResultType.FORM + assert result2.get("step_id") == "advanced" + + # Configure advanced settings + result3 = await hass.config_entries.subentries.async_configure( + result["flow_id"], + { + CONF_CHAT_MODEL: "gpt-4o", + CONF_MAX_TOKENS: 200, + CONF_TEMPERATURE: 0.5, + CONF_TOP_P: 0.9, + }, + ) + + assert result3.get("type") is FlowResultType.CREATE_ENTRY + assert result3.get("title") == "Advanced AI Task" + assert result3.get("data") == { + CONF_RECOMMENDED: False, + CONF_CHAT_MODEL: "gpt-4o", + CONF_MAX_TOKENS: 200, + CONF_TEMPERATURE: 0.5, + CONF_TOP_P: 0.9, + } diff --git a/tests/components/openai_conversation/test_conversation.py b/tests/components/openai_conversation/test_conversation.py index 8621465bd14..39cd129e1ba 100644 --- a/tests/components/openai_conversation/test_conversation.py +++ b/tests/components/openai_conversation/test_conversation.py @@ -1,38 +1,13 @@ """Tests for the OpenAI integration.""" -from collections.abc import Generator from unittest.mock import AsyncMock, patch import httpx from openai import AuthenticationError, RateLimitError -from openai.types import ResponseFormatText from openai.types.responses import ( - Response, - ResponseCompletedEvent, - ResponseContentPartAddedEvent, - ResponseContentPartDoneEvent, - ResponseCreatedEvent, ResponseError, ResponseErrorEvent, - ResponseFailedEvent, - ResponseFunctionCallArgumentsDeltaEvent, - ResponseFunctionCallArgumentsDoneEvent, - ResponseFunctionToolCall, - ResponseFunctionWebSearch, - ResponseIncompleteEvent, - ResponseInProgressEvent, - ResponseOutputItemAddedEvent, - ResponseOutputItemDoneEvent, - ResponseOutputMessage, - ResponseOutputText, - ResponseReasoningItem, ResponseStreamEvent, - ResponseTextConfig, - ResponseTextDeltaEvent, - ResponseTextDoneEvent, - ResponseWebSearchCallCompletedEvent, - ResponseWebSearchCallInProgressEvent, - ResponseWebSearchCallSearchingEvent, ) from openai.types.responses.response import IncompleteDetails import pytest @@ -54,6 +29,13 @@ from homeassistant.core import Context, HomeAssistant from homeassistant.helpers import intent from homeassistant.setup import async_setup_component +from . import ( + create_function_tool_call_item, + create_message_item, + create_reasoning_item, + create_web_search_item, +) + from tests.common import MockConfigEntry from tests.components.conversation import ( MockChatLog, @@ -61,92 +43,6 @@ from tests.components.conversation import ( ) -@pytest.fixture -def mock_create_stream() -> Generator[AsyncMock]: - """Mock stream response.""" - - async def mock_generator(events, **kwargs): - response = Response( - id="resp_A", - created_at=1700000000, - error=None, - incomplete_details=None, - instructions=kwargs.get("instructions"), - metadata=kwargs.get("metadata", {}), - model=kwargs.get("model", "gpt-4o-mini"), - object="response", - output=[], - parallel_tool_calls=kwargs.get("parallel_tool_calls", True), - temperature=kwargs.get("temperature", 1.0), - tool_choice=kwargs.get("tool_choice", "auto"), - tools=kwargs.get("tools"), - top_p=kwargs.get("top_p", 1.0), - max_output_tokens=kwargs.get("max_output_tokens", 100000), - previous_response_id=kwargs.get("previous_response_id"), - reasoning=kwargs.get("reasoning"), - status="in_progress", - text=kwargs.get( - "text", ResponseTextConfig(format=ResponseFormatText(type="text")) - ), - truncation=kwargs.get("truncation", "disabled"), - usage=None, - user=kwargs.get("user"), - store=kwargs.get("store", True), - ) - yield ResponseCreatedEvent( - response=response, - type="response.created", - ) - yield ResponseInProgressEvent( - response=response, - type="response.in_progress", - ) - response.status = "completed" - - for value in events: - if isinstance(value, ResponseOutputItemDoneEvent): - response.output.append(value.item) - elif isinstance(value, IncompleteDetails): - response.status = "incomplete" - response.incomplete_details = value - break - if isinstance(value, ResponseError): - response.status = "failed" - response.error = value - break - - yield value - - if isinstance(value, ResponseErrorEvent): - return - - if response.status == "incomplete": - yield ResponseIncompleteEvent( - response=response, - type="response.incomplete", - ) - elif response.status == "failed": - yield ResponseFailedEvent( - response=response, - type="response.failed", - ) - else: - yield ResponseCompletedEvent( - response=response, - type="response.completed", - ) - - with patch( - "openai.resources.responses.AsyncResponses.create", - AsyncMock(), - ) as mock_create: - mock_create.side_effect = lambda **kwargs: mock_generator( - mock_create.return_value.pop(0), **kwargs - ) - - yield mock_create - - async def test_entity( hass: HomeAssistant, mock_config_entry: MockConfigEntry, @@ -301,7 +197,7 @@ async def test_incomplete_response( "OpenAI response failed: Rate limit exceeded", ), ( - ResponseErrorEvent(type="error", message="Some error"), + ResponseErrorEvent(type="error", message="Some error", sequence_number=0), "OpenAI response error: Some error", ), ], @@ -341,203 +237,9 @@ async def test_conversation_agent( assert agent.supported_languages == "*" -def create_message_item( - id: str, text: str | list[str], output_index: int -) -> list[ResponseStreamEvent]: - """Create a message item.""" - if isinstance(text, str): - text = [text] - - content = ResponseOutputText(annotations=[], text="", type="output_text") - events = [ - ResponseOutputItemAddedEvent( - item=ResponseOutputMessage( - id=id, - content=[], - type="message", - role="assistant", - status="in_progress", - ), - output_index=output_index, - type="response.output_item.added", - ), - ResponseContentPartAddedEvent( - content_index=0, - item_id=id, - output_index=output_index, - part=content, - type="response.content_part.added", - ), - ] - - content.text = "".join(text) - events.extend( - ResponseTextDeltaEvent( - content_index=0, - delta=delta, - item_id=id, - output_index=output_index, - type="response.output_text.delta", - ) - for delta in text - ) - - events.extend( - [ - ResponseTextDoneEvent( - content_index=0, - item_id=id, - output_index=output_index, - text="".join(text), - type="response.output_text.done", - ), - ResponseContentPartDoneEvent( - content_index=0, - item_id=id, - output_index=output_index, - part=content, - type="response.content_part.done", - ), - ResponseOutputItemDoneEvent( - item=ResponseOutputMessage( - id=id, - content=[content], - role="assistant", - status="completed", - type="message", - ), - output_index=output_index, - type="response.output_item.done", - ), - ] - ) - - return events - - -def create_function_tool_call_item( - id: str, arguments: str | list[str], call_id: str, name: str, output_index: int -) -> list[ResponseStreamEvent]: - """Create a function tool call item.""" - if isinstance(arguments, str): - arguments = [arguments] - - events = [ - ResponseOutputItemAddedEvent( - item=ResponseFunctionToolCall( - id=id, - arguments="", - call_id=call_id, - name=name, - type="function_call", - status="in_progress", - ), - output_index=output_index, - type="response.output_item.added", - ) - ] - - events.extend( - ResponseFunctionCallArgumentsDeltaEvent( - delta=delta, - item_id=id, - output_index=output_index, - type="response.function_call_arguments.delta", - ) - for delta in arguments - ) - - events.append( - ResponseFunctionCallArgumentsDoneEvent( - arguments="".join(arguments), - item_id=id, - output_index=output_index, - type="response.function_call_arguments.done", - ) - ) - - events.append( - ResponseOutputItemDoneEvent( - item=ResponseFunctionToolCall( - id=id, - arguments="".join(arguments), - call_id=call_id, - name=name, - type="function_call", - status="completed", - ), - output_index=output_index, - type="response.output_item.done", - ) - ) - - return events - - -def create_reasoning_item(id: str, output_index: int) -> list[ResponseStreamEvent]: - """Create a reasoning item.""" - return [ - ResponseOutputItemAddedEvent( - item=ResponseReasoningItem( - id=id, - summary=[], - type="reasoning", - status=None, - ), - output_index=output_index, - type="response.output_item.added", - ), - ResponseOutputItemDoneEvent( - item=ResponseReasoningItem( - id=id, - summary=[], - type="reasoning", - status=None, - ), - output_index=output_index, - type="response.output_item.done", - ), - ] - - -def create_web_search_item(id: str, output_index: int) -> list[ResponseStreamEvent]: - """Create a web search call item.""" - return [ - ResponseOutputItemAddedEvent( - item=ResponseFunctionWebSearch( - id=id, status="in_progress", type="web_search_call" - ), - output_index=output_index, - type="response.output_item.added", - ), - ResponseWebSearchCallInProgressEvent( - item_id=id, - output_index=output_index, - type="response.web_search_call.in_progress", - ), - ResponseWebSearchCallSearchingEvent( - item_id=id, - output_index=output_index, - type="response.web_search_call.searching", - ), - ResponseWebSearchCallCompletedEvent( - item_id=id, - output_index=output_index, - type="response.web_search_call.completed", - ), - ResponseOutputItemDoneEvent( - item=ResponseFunctionWebSearch( - id=id, status="completed", type="web_search_call" - ), - output_index=output_index, - type="response.output_item.done", - ), - ] - - async def test_function_call( hass: HomeAssistant, - mock_config_entry_with_assist: MockConfigEntry, + mock_config_entry_with_reasoning_model: MockConfigEntry, mock_init_component, mock_create_stream: AsyncMock, mock_chat_log: MockChatLog, # noqa: F811 @@ -588,6 +290,7 @@ async def test_function_call( "id": "rs_A", "summary": [], "type": "reasoning", + "encrypted_content": "AAABBB", } assert result.response.response_type == intent.IntentResponseType.ACTION_DONE # Don't test the prompt, as it's not deterministic diff --git a/tests/components/openai_conversation/test_entity.py b/tests/components/openai_conversation/test_entity.py new file mode 100644 index 00000000000..58187bd63e9 --- /dev/null +++ b/tests/components/openai_conversation/test_entity.py @@ -0,0 +1,77 @@ +"""Tests for the OpenAI Conversation entity.""" + +import voluptuous as vol + +from homeassistant.components.openai_conversation.entity import ( + _format_structured_output, +) +from homeassistant.helpers import selector + + +async def test_format_structured_output() -> None: + """Test the format_structured_output function.""" + schema = vol.Schema( + { + vol.Required("name"): selector.TextSelector(), + vol.Optional("age"): selector.NumberSelector( + config=selector.NumberSelectorConfig( + min=0, + max=120, + ), + ), + vol.Required("stuff"): selector.ObjectSelector( + { + "multiple": True, + "fields": { + "item_name": { + "selector": {"text": None}, + }, + "item_value": { + "selector": {"text": None}, + }, + }, + } + ), + } + ) + assert _format_structured_output(schema, None) == { + "additionalProperties": False, + "properties": { + "age": { + "maximum": 120.0, + "minimum": 0.0, + "type": [ + "number", + "null", + ], + }, + "name": { + "type": "string", + }, + "stuff": { + "items": { + "properties": { + "item_name": { + "type": ["string", "null"], + }, + "item_value": { + "type": ["string", "null"], + }, + }, + "required": [ + "item_name", + "item_value", + ], + "type": "object", + }, + "type": "array", + }, + }, + "required": [ + "name", + "stuff", + "age", + ], + "strict": True, + "type": "object", + } diff --git a/tests/components/openai_conversation/test_init.py b/tests/components/openai_conversation/test_init.py index d7e8b29cab2..e728d0019b6 100644 --- a/tests/components/openai_conversation/test_init.py +++ b/tests/components/openai_conversation/test_init.py @@ -1,6 +1,6 @@ """Tests for the OpenAI integration.""" -from unittest.mock import AsyncMock, mock_open, patch +from unittest.mock import AsyncMock, Mock, mock_open, patch import httpx from openai import ( @@ -16,8 +16,11 @@ import pytest from syrupy.assertion import SnapshotAssertion from syrupy.filters import props -from homeassistant.components.openai_conversation import CONF_CHAT_MODEL, CONF_FILENAMES -from homeassistant.components.openai_conversation.const import DOMAIN +from homeassistant.components.openai_conversation import CONF_CHAT_MODEL +from homeassistant.components.openai_conversation.const import ( + DEFAULT_AI_TASK_NAME, + DOMAIN, +) from homeassistant.config_entries import ConfigSubentryData from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError @@ -378,7 +381,7 @@ async def test_generate_content_service( """Test generate content service.""" service_data["config_entry"] = mock_config_entry.entry_id expected_args["model"] = "gpt-4o-mini" - expected_args["max_output_tokens"] = 150 + expected_args["max_output_tokens"] = 3000 expected_args["top_p"] = 1.0 expected_args["temperature"] = 1.0 expected_args["user"] = None @@ -394,7 +397,7 @@ async def test_generate_content_service( patch( "base64.b64encode", side_effect=[b"BASE64IMAGE1", b"BASE64IMAGE2"] ) as mock_b64encode, - patch("builtins.open", mock_open(read_data="ABC")) as mock_file, + patch("pathlib.Path.read_bytes", Mock(return_value=b"ABC")) as mock_file, patch("pathlib.Path.exists", return_value=True), patch.object(hass.config, "is_allowed_path", return_value=True), ): @@ -434,15 +437,13 @@ async def test_generate_content_service( assert len(mock_create.mock_calls) == 1 assert mock_create.mock_calls[0][2] == expected_args assert mock_b64encode.call_count == number_of_files - for idx, file in enumerate(service_data[CONF_FILENAMES]): - assert mock_file.call_args_list[idx][0][0] == file + assert mock_file.call_count == number_of_files @pytest.mark.parametrize( ( "service_data", "error", - "number_of_files", "exists_side_effect", "is_allowed_side_effect", ), @@ -450,7 +451,6 @@ async def test_generate_content_service( ( {"prompt": "Picture of a dog", "filenames": ["/a/b/c.jpg"]}, "`/a/b/c.jpg` does not exist", - 0, [False], [True], ), @@ -460,14 +460,12 @@ async def test_generate_content_service( "filenames": ["/a/b/c.jpg", "d/e/f.png"], }, "Cannot read `d/e/f.png`, no access to path; `allowlist_external_dirs` may need to be adjusted in `configuration.yaml`", - 1, [True, True], [True, False], ), ( {"prompt": "Not a picture of a dog", "filenames": ["/a/b/c.mov"]}, "Only images and PDF are supported by the OpenAI API,`/a/b/c.mov` is not an image file or PDF", - 1, [True], [True], ), @@ -479,7 +477,6 @@ async def test_generate_content_service_invalid( mock_init_component, service_data, error, - number_of_files, exists_side_effect, is_allowed_side_effect, ) -> None: @@ -491,9 +488,7 @@ async def test_generate_content_service_invalid( "openai.resources.responses.AsyncResponses.create", new_callable=AsyncMock, ) as mock_create, - patch( - "base64.b64encode", side_effect=[b"BASE64IMAGE1", b"BASE64IMAGE2"] - ) as mock_b64encode, + patch("base64.b64encode", side_effect=[b"BASE64IMAGE1", b"BASE64IMAGE2"]), patch("builtins.open", mock_open(read_data="ABC")), patch("pathlib.Path.exists", side_effect=exists_side_effect), patch.object( @@ -509,7 +504,6 @@ async def test_generate_content_service_invalid( return_response=True, ) assert len(mock_create.mock_calls) == 0 - assert mock_b64encode.call_count == number_of_files @pytest.mark.usefixtures("mock_init_component") @@ -543,7 +537,7 @@ async def test_generate_content_service_error( ) -async def test_migration_from_v1_to_v2( +async def test_migration_from_v1( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, @@ -591,17 +585,33 @@ async def test_migration_from_v1_to_v2( await hass.async_block_till_done() assert mock_config_entry.version == 2 - assert mock_config_entry.minor_version == 2 + assert mock_config_entry.minor_version == 3 assert mock_config_entry.data == {"api_key": "1234"} assert mock_config_entry.options == {} - assert len(mock_config_entry.subentries) == 1 + assert len(mock_config_entry.subentries) == 2 - subentry = next(iter(mock_config_entry.subentries.values())) - assert subentry.unique_id is None - assert subentry.title == "ChatGPT" - assert subentry.subentry_type == "conversation" - assert subentry.data == OPTIONS + # Find the conversation subentry + conversation_subentry = None + ai_task_subentry = None + for subentry in mock_config_entry.subentries.values(): + if subentry.subentry_type == "conversation": + conversation_subentry = subentry + elif subentry.subentry_type == "ai_task_data": + ai_task_subentry = subentry + assert conversation_subentry is not None + assert conversation_subentry.unique_id is None + assert conversation_subentry.title == "ChatGPT" + assert conversation_subentry.subentry_type == "conversation" + assert conversation_subentry.data == OPTIONS + + assert ai_task_subentry is not None + assert ai_task_subentry.unique_id is None + assert ai_task_subentry.title == DEFAULT_AI_TASK_NAME + assert ai_task_subentry.subentry_type == "ai_task_data" + + # Use conversation subentry for the rest of the assertions + subentry = conversation_subentry migrated_entity = entity_registry.async_get(entity.entity_id) assert migrated_entity is not None @@ -626,12 +636,12 @@ async def test_migration_from_v1_to_v2( } -async def test_migration_from_v1_to_v2_with_multiple_keys( +async def test_migration_from_v1_with_multiple_keys( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: - """Test migration from version 1 to version 2 with different API keys.""" + """Test migration from version 1 with different API keys.""" # Create two v1 config entries with different API keys options = { "recommended": True, @@ -704,28 +714,38 @@ async def test_migration_from_v1_to_v2_with_multiple_keys( for idx, entry in enumerate(entries): assert entry.version == 2 - assert entry.minor_version == 2 + assert entry.minor_version == 3 assert not entry.options - assert len(entry.subentries) == 1 - subentry = list(entry.subentries.values())[0] - assert subentry.subentry_type == "conversation" - assert subentry.data == options - assert subentry.title == f"ChatGPT {idx + 1}" + assert len(entry.subentries) == 2 + + conversation_subentry = None + for subentry in entry.subentries.values(): + if subentry.subentry_type == "conversation": + conversation_subentry = subentry + break + + assert conversation_subentry is not None + assert conversation_subentry.subentry_type == "conversation" + assert conversation_subentry.data == options + assert conversation_subentry.title == f"ChatGPT {idx + 1}" + + # Use conversation subentry for device assertions + subentry = conversation_subentry dev = device_registry.async_get_device( - identifiers={(DOMAIN, list(entry.subentries.values())[0].subentry_id)} + identifiers={(DOMAIN, subentry.subentry_id)} ) assert dev is not None assert dev.config_entries == {entry.entry_id} assert dev.config_entries_subentries == {entry.entry_id: {subentry.subentry_id}} -async def test_migration_from_v1_to_v2_with_same_keys( +async def test_migration_from_v1_with_same_keys( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: - """Test migration from version 1 to version 2 with same API keys consolidates entries.""" + """Test migration from version 1 with same API keys consolidates entries.""" # Create two v1 config entries with the same API key options = { "recommended": True, @@ -799,17 +819,28 @@ async def test_migration_from_v1_to_v2_with_same_keys( entry = entries[0] assert entry.version == 2 - assert entry.minor_version == 2 + assert entry.minor_version == 3 assert not entry.options - assert len(entry.subentries) == 2 # Two subentries from the two original entries + assert ( + len(entry.subentries) == 3 + ) # Two conversation subentries + one AI task subentry - # Check both subentries exist with correct data - subentries = list(entry.subentries.values()) - titles = [sub.title for sub in subentries] + # Check both conversation subentries exist with correct data + conversation_subentries = [ + sub for sub in entry.subentries.values() if sub.subentry_type == "conversation" + ] + ai_task_subentries = [ + sub for sub in entry.subentries.values() if sub.subentry_type == "ai_task_data" + ] + + assert len(conversation_subentries) == 2 + assert len(ai_task_subentries) == 1 + + titles = [sub.title for sub in conversation_subentries] assert "ChatGPT" in titles assert "ChatGPT 2" in titles - for subentry in subentries: + for subentry in conversation_subentries: assert subentry.subentry_type == "conversation" assert subentry.data == options @@ -824,12 +855,12 @@ async def test_migration_from_v1_to_v2_with_same_keys( } -async def test_migration_from_v2_1_to_v2_2( +async def test_migration_from_v2_1( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: - """Test migration from version 2.1 to version 2.2. + """Test migration from version 2.1. This tests we clean up the broken migration in Home Assistant Core 2025.7.0b0-2025.7.0b1: @@ -922,16 +953,22 @@ async def test_migration_from_v2_1_to_v2_2( assert len(entries) == 1 entry = entries[0] assert entry.version == 2 - assert entry.minor_version == 2 + assert entry.minor_version == 3 assert not entry.options assert entry.title == "ChatGPT" - assert len(entry.subentries) == 2 + assert len(entry.subentries) == 3 # 2 conversation + 1 AI task conversation_subentries = [ subentry for subentry in entry.subentries.values() if subentry.subentry_type == "conversation" ] + ai_task_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "ai_task_data" + ] assert len(conversation_subentries) == 2 + assert len(ai_task_subentries) == 1 for subentry in conversation_subentries: assert subentry.subentry_type == "conversation" assert subentry.data == options @@ -981,7 +1018,9 @@ async def test_migration_from_v2_1_to_v2_2( } -@pytest.mark.parametrize("mock_subentry_data", [{}, {CONF_CHAT_MODEL: "gpt-1o"}]) +@pytest.mark.parametrize( + "mock_conversation_subentry_data", [{}, {CONF_CHAT_MODEL: "gpt-1o"}] +) async def test_devices( hass: HomeAssistant, mock_config_entry: MockConfigEntry, @@ -989,12 +1028,89 @@ async def test_devices( device_registry: dr.DeviceRegistry, snapshot: SnapshotAssertion, ) -> None: - """Assert exception when invalid config entry is provided.""" + """Test devices are correctly created for subentries.""" devices = dr.async_entries_for_config_entry( device_registry, mock_config_entry.entry_id ) - assert len(devices) == 1 + assert len(devices) == 2 # One for conversation, one for AI task + + # Use the first device for snapshot comparison device = devices[0] assert device == snapshot(exclude=props("identifiers")) - subentry = next(iter(mock_config_entry.subentries.values())) - assert device.identifiers == {(DOMAIN, subentry.subentry_id)} + # Verify the device has identifiers matching one of the subentries + expected_identifiers = [ + {(DOMAIN, subentry.subentry_id)} + for subentry in mock_config_entry.subentries.values() + ] + assert device.identifiers in expected_identifiers + + +async def test_migration_from_v2_2( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test migration from version 2.2.""" + # Create a v2.2 config entry with a conversation subentry + options = { + "recommended": True, + "llm_hass_api": ["assist"], + "prompt": "You are a helpful assistant", + "chat_model": "gpt-4o-mini", + } + mock_config_entry = MockConfigEntry( + domain=DOMAIN, + data={"api_key": "1234"}, + entry_id="mock_entry_id", + version=2, + minor_version=2, + subentries_data=[ + ConfigSubentryData( + data=options, + subentry_id="mock_id_1", + subentry_type="conversation", + title="ChatGPT", + unique_id=None, + ), + ], + title="ChatGPT", + ) + mock_config_entry.add_to_hass(hass) + + # Run migration + with patch( + "homeassistant.components.openai_conversation.async_setup_entry", + return_value=True, + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entries = hass.config_entries.async_entries(DOMAIN) + assert len(entries) == 1 + entry = entries[0] + assert entry.version == 2 + assert entry.minor_version == 3 + assert not entry.options + assert entry.title == "ChatGPT" + assert len(entry.subentries) == 2 + + # Check conversation subentry is still there + conversation_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "conversation" + ] + assert len(conversation_subentries) == 1 + conversation_subentry = conversation_subentries[0] + assert conversation_subentry.data == options + + # Check AI Task subentry was added + ai_task_subentries = [ + subentry + for subentry in entry.subentries.values() + if subentry.subentry_type == "ai_task_data" + ] + assert len(ai_task_subentries) == 1 + ai_task_subentry = ai_task_subentries[0] + assert ai_task_subentry.data == {"recommended": True} + assert ai_task_subentry.title == "OpenAI AI Task" diff --git a/tests/components/pi_hole/__init__.py b/tests/components/pi_hole/__init__.py index 36ee963a16f..c20f22ac58d 100644 --- a/tests/components/pi_hole/__init__.py +++ b/tests/components/pi_hole/__init__.py @@ -185,7 +185,6 @@ CONFIG_ENTRY_WITH_API_KEY = { CONF_API_KEY: API_KEY, CONF_SSL: SSL, CONF_VERIFY_SSL: VERIFY_SSL, - CONF_API_VERSION: API_VERSION, } CONFIG_ENTRY_WITHOUT_API_KEY = { @@ -194,7 +193,6 @@ CONFIG_ENTRY_WITHOUT_API_KEY = { CONF_NAME: NAME, CONF_SSL: SSL, CONF_VERIFY_SSL: VERIFY_SSL, - CONF_API_VERSION: API_VERSION, } SWITCH_ENTITY_ID = "switch.pi_hole" diff --git a/tests/components/pi_hole/test_config_flow.py b/tests/components/pi_hole/test_config_flow.py index e92a845ce1e..e79f65b406e 100644 --- a/tests/components/pi_hole/test_config_flow.py +++ b/tests/components/pi_hole/test_config_flow.py @@ -3,7 +3,7 @@ from homeassistant.components import pi_hole from homeassistant.components.pi_hole.const import DOMAIN from homeassistant.config_entries import SOURCE_USER -from homeassistant.const import CONF_API_KEY, CONF_API_VERSION +from homeassistant.const import CONF_API_KEY from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @@ -104,7 +104,7 @@ async def test_flow_user_with_api_key_v5(hass: HomeAssistant) -> None: assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == NAME - assert result["data"] == {**CONFIG_ENTRY_WITH_API_KEY, CONF_API_VERSION: 5} + assert result["data"] == {**CONFIG_ENTRY_WITH_API_KEY} mock_setup.assert_called_once() # duplicated server @@ -148,7 +148,7 @@ async def test_flow_reauth(hass: HomeAssistant) -> None: mocked_hole = _create_mocked_hole(has_data=False, api_version=5) entry = MockConfigEntry( domain=pi_hole.DOMAIN, - data={**CONFIG_DATA_DEFAULTS, CONF_API_VERSION: 5, CONF_API_KEY: "oldkey"}, + data={**CONFIG_DATA_DEFAULTS, CONF_API_KEY: "oldkey"}, ) entry.add_to_hass(hass) with _patch_init_hole(mocked_hole), _patch_config_flow_hole(mocked_hole): diff --git a/tests/components/pi_hole/test_init.py b/tests/components/pi_hole/test_init.py index b4cc11529d9..94170e967d4 100644 --- a/tests/components/pi_hole/test_init.py +++ b/tests/components/pi_hole/test_init.py @@ -51,7 +51,7 @@ async def test_setup_api_v6( entry.add_to_hass(hass) with _patch_init_hole(mocked_hole) as patched_init_hole: assert await hass.config_entries.async_setup(entry.entry_id) - patched_init_hole.assert_called_once_with( + patched_init_hole.assert_called_with( host=config_entry_data[CONF_HOST], session=ANY, password=expected_api_token, @@ -78,7 +78,7 @@ async def test_setup_api_v5( entry.add_to_hass(hass) with _patch_init_hole(mocked_hole) as patched_init_hole: assert await hass.config_entries.async_setup(entry.entry_id) - patched_init_hole.assert_called_once_with( + patched_init_hole.assert_called_with( host=config_entry_data[CONF_HOST], session=ANY, api_token=expected_api_token, @@ -206,7 +206,7 @@ async def test_setup_without_api_version(hass: HomeAssistant) -> None: with _patch_init_hole(mocked_hole): assert await hass.config_entries.async_setup(entry.entry_id) - assert entry.data[CONF_API_VERSION] == 6 + assert entry.runtime_data.api_version == 6 mocked_hole = _create_mocked_hole(api_version=5) config = {**CONFIG_DATA_DEFAULTS} @@ -216,7 +216,7 @@ async def test_setup_without_api_version(hass: HomeAssistant) -> None: with _patch_init_hole(mocked_hole): assert await hass.config_entries.async_setup(entry.entry_id) - assert entry.data[CONF_API_VERSION] == 5 + assert entry.runtime_data.api_version == 5 async def test_setup_name_config(hass: HomeAssistant) -> None: diff --git a/tests/components/pyload/conftest.py b/tests/components/pyload/conftest.py index 9b410a5fdd6..72fabfa3de1 100644 --- a/tests/components/pyload/conftest.py +++ b/tests/components/pyload/conftest.py @@ -16,6 +16,7 @@ from homeassistant.const import ( CONF_USERNAME, CONF_VERIFY_SSL, ) +from homeassistant.helpers.service_info.hassio import HassioServiceInfo from tests.common import MockConfigEntry @@ -39,6 +40,21 @@ NEW_INPUT = { } +ADDON_DISCOVERY_INFO = { + "addon": "pyLoad-ng", + CONF_URL: "http://539df76c-pyload-ng:8000/", + CONF_USERNAME: "pyload", + CONF_PASSWORD: "pyload", +} + +ADDON_SERVICE_INFO = HassioServiceInfo( + config=ADDON_DISCOVERY_INFO, + name="pyLoad-ng Addon", + slug="p539df76c_pyload-ng", + uuid="1234", +) + + @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock]: """Override async_setup_entry.""" diff --git a/tests/components/pyload/test_config_flow.py b/tests/components/pyload/test_config_flow.py index 492e4a4b652..1eafbd2eb66 100644 --- a/tests/components/pyload/test_config_flow.py +++ b/tests/components/pyload/test_config_flow.py @@ -6,11 +6,18 @@ from pyloadapi.exceptions import CannotConnect, InvalidAuth, ParserError import pytest from homeassistant.components.pyload.const import DEFAULT_NAME, DOMAIN -from homeassistant.config_entries import SOURCE_USER +from homeassistant.config_entries import SOURCE_HASSIO, SOURCE_IGNORE, SOURCE_USER +from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME, CONF_VERIFY_SSL from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType -from .conftest import NEW_INPUT, REAUTH_INPUT, USER_INPUT +from .conftest import ( + ADDON_DISCOVERY_INFO, + ADDON_SERVICE_INFO, + NEW_INPUT, + REAUTH_INPUT, + USER_INPUT, +) from tests.common import MockConfigEntry @@ -245,3 +252,183 @@ async def test_reconfigure_errors( assert result["reason"] == "reconfigure_successful" assert config_entry.data == USER_INPUT assert len(hass.config_entries.async_entries()) == 1 + + +async def test_hassio_discovery( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_pyloadapi: AsyncMock, +) -> None: + """Test flow started from Supervisor discovery.""" + + mock_pyloadapi.login.side_effect = InvalidAuth + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "hassio_confirm" + assert result["errors"] is None + + mock_pyloadapi.login.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "p539df76c_pyload-ng" + assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False} + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.usefixtures("mock_pyloadapi") +async def test_hassio_discovery_confirm_only( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, +) -> None: + """Test flow started from Supervisor discovery. Abort with confirm only.""" + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "hassio_confirm" + + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "p539df76c_pyload-ng" + assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False} + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.parametrize( + ("side_effect", "error_text"), + [ + (InvalidAuth, "invalid_auth"), + (CannotConnect, "cannot_connect"), + (IndexError, "unknown"), + ], +) +async def test_hassio_discovery_errors( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_pyloadapi: AsyncMock, + side_effect: Exception, + error_text: str, +) -> None: + """Test flow started from Supervisor discovery.""" + + mock_pyloadapi.login.side_effect = side_effect + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "hassio_confirm" + assert result["errors"] is None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["errors"] == {"base": error_text} + + mock_pyloadapi.login.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"} + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["title"] == "p539df76c_pyload-ng" + assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False} + assert len(mock_setup_entry.mock_calls) == 1 + + +@pytest.mark.usefixtures("mock_pyloadapi") +async def test_hassio_discovery_already_configured( + hass: HomeAssistant, +) -> None: + """Test we abort discovery flow if already configured.""" + + MockConfigEntry( + domain=DOMAIN, + data={ + CONF_URL: "http://539df76c-pyload-ng:8000/", + CONF_USERNAME: "pyload", + CONF_PASSWORD: "pyload", + }, + ).add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("mock_pyloadapi") +async def test_hassio_discovery_data_update( + hass: HomeAssistant, +) -> None: + """Test we abort discovery flow if already configured and we update entry from discovery data.""" + + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_URL: "http://localhost:8000/", + CONF_USERNAME: "pyload", + CONF_PASSWORD: "pyload", + }, + unique_id="1234", + ) + + entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + assert entry.data[CONF_URL] == "http://539df76c-pyload-ng:8000/" + + +@pytest.mark.usefixtures("mock_pyloadapi") +async def test_hassio_discovery_ignored( + hass: HomeAssistant, +) -> None: + """Test we abort discovery flow if discovery was ignored.""" + + MockConfigEntry( + domain=DOMAIN, + source=SOURCE_IGNORE, + data={}, + unique_id="1234", + ).add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=ADDON_SERVICE_INFO, + context={"source": SOURCE_HASSIO}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" diff --git a/tests/components/reolink/conftest.py b/tests/components/reolink/conftest.py index d34a27045fe..1ca6bb4eb55 100644 --- a/tests/components/reolink/conftest.py +++ b/tests/components/reolink/conftest.py @@ -84,6 +84,8 @@ def _init_host_mock(host_mock: MagicMock) -> None: host_mock.set_whiteled = AsyncMock() host_mock.set_state_light = AsyncMock() host_mock.renew = AsyncMock() + host_mock.get_vod_source = AsyncMock() + host_mock.expire_session = AsyncMock() host_mock.is_nvr = True host_mock.is_hub = False host_mock.mac_address = TEST_MAC diff --git a/tests/components/reolink/test_util.py b/tests/components/reolink/test_util.py index 181249b8bff..8b730bc708b 100644 --- a/tests/components/reolink/test_util.py +++ b/tests/components/reolink/test_util.py @@ -103,12 +103,12 @@ DEV_ID_STANDALONE_CAM = f"{TEST_UID_CAM}" async def test_try_function( hass: HomeAssistant, config_entry: MockConfigEntry, - reolink_connect: MagicMock, + reolink_host: MagicMock, side_effect: ReolinkError, expected: HomeAssistantError, ) -> None: """Test try_function error translations using number entity.""" - reolink_connect.volume.return_value = 80 + reolink_host.volume.return_value = 80 with patch("homeassistant.components.reolink.PLATFORMS", [Platform.NUMBER]): assert await hass.config_entries.async_setup(config_entry.entry_id) @@ -117,7 +117,7 @@ async def test_try_function( entity_id = f"{Platform.NUMBER}.{TEST_NVR_NAME}_volume" - reolink_connect.set_volume.side_effect = side_effect + reolink_host.set_volume.side_effect = side_effect with pytest.raises(expected.__class__) as err: await hass.services.async_call( NUMBER_DOMAIN, @@ -128,8 +128,6 @@ async def test_try_function( assert err.value.translation_key == expected.translation_key - reolink_connect.set_volume.reset_mock(side_effect=True) - @pytest.mark.parametrize( ("identifiers"), @@ -141,12 +139,12 @@ async def test_try_function( async def test_get_device_uid_and_ch( hass: HomeAssistant, config_entry: MockConfigEntry, - reolink_connect: MagicMock, + reolink_host: MagicMock, device_registry: dr.DeviceRegistry, identifiers: set[tuple[str, str]], ) -> None: """Test get_device_uid_and_ch with multiple identifiers.""" - reolink_connect.channels = [0] + reolink_host.channels = [0] dev_entry = device_registry.async_get_or_create( identifiers=identifiers, diff --git a/tests/components/reolink/test_views.py b/tests/components/reolink/test_views.py index 992e47f0575..6da9fbd29ca 100644 --- a/tests/components/reolink/test_views.py +++ b/tests/components/reolink/test_views.py @@ -64,14 +64,14 @@ def get_mock_session( ) async def test_playback_proxy( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, caplog: pytest.LogCaptureFixture, content_type: str, ) -> None: """Test successful playback proxy URL.""" - reolink_connect.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) + reolink_host.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) mock_session = get_mock_session(content_type=content_type) @@ -100,12 +100,12 @@ async def test_playback_proxy( async def test_proxy_get_source_error( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, ) -> None: """Test error while getting source for playback proxy URL.""" - reolink_connect.get_vod_source.side_effect = ReolinkError(TEST_ERROR) + reolink_host.get_vod_source.side_effect = ReolinkError(TEST_ERROR) assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() @@ -123,12 +123,11 @@ async def test_proxy_get_source_error( assert await response.content.read() == bytes(TEST_ERROR, "utf-8") assert response.status == HTTPStatus.BAD_REQUEST - reolink_connect.get_vod_source.side_effect = None async def test_proxy_invalid_config_entry_id( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, ) -> None: @@ -156,12 +155,12 @@ async def test_proxy_invalid_config_entry_id( async def test_playback_proxy_timeout( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, ) -> None: """Test playback proxy URL with a timeout in the second chunk.""" - reolink_connect.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) + reolink_host.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) mock_session = get_mock_session([b"test", TimeoutError()], 4) @@ -190,13 +189,13 @@ async def test_playback_proxy_timeout( @pytest.mark.parametrize(("content_type"), [("video/x-flv"), ("text/html")]) async def test_playback_wrong_content( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, content_type: str, ) -> None: """Test playback proxy URL with a wrong content type in the response.""" - reolink_connect.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) + reolink_host.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) mock_session = get_mock_session(content_type=content_type) @@ -223,12 +222,12 @@ async def test_playback_wrong_content( async def test_playback_connect_error( hass: HomeAssistant, - reolink_connect: MagicMock, + reolink_host: MagicMock, config_entry: MockConfigEntry, hass_client: ClientSessionGenerator, ) -> None: """Test playback proxy URL with a connection error.""" - reolink_connect.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) + reolink_host.get_vod_source.return_value = (TEST_MIME_TYPE_MP4, TEST_URL) mock_session = Mock() mock_session.get = AsyncMock(side_effect=ClientConnectionError(TEST_ERROR)) diff --git a/tests/components/rest/test_sensor.py b/tests/components/rest/test_sensor.py index c688ff1b314..b830d6b7743 100644 --- a/tests/components/rest/test_sensor.py +++ b/tests/components/rest/test_sensor.py @@ -1,6 +1,7 @@ """The tests for the REST sensor platform.""" from http import HTTPStatus +import logging import ssl from unittest.mock import patch @@ -19,6 +20,14 @@ from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT, + CONF_DEVICE_CLASS, + CONF_FORCE_UPDATE, + CONF_METHOD, + CONF_NAME, + CONF_PARAMS, + CONF_RESOURCE, + CONF_UNIT_OF_MEASUREMENT, + CONF_VALUE_TEMPLATE, CONTENT_TYPE_JSON, SERVICE_RELOAD, STATE_UNAVAILABLE, @@ -162,6 +171,94 @@ async def test_setup_encoding( assert hass.states.get("sensor.mysensor").state == "tack själv" +async def test_setup_auto_encoding_from_content_type( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Test setup with encoding auto-detected from Content-Type header.""" + # Test with ISO-8859-1 charset in Content-Type header + aioclient_mock.get( + "http://localhost", + status=HTTPStatus.OK, + content="Björk Guðmundsdóttir".encode("iso-8859-1"), + headers={"Content-Type": "text/plain; charset=iso-8859-1"}, + ) + assert await async_setup_component( + hass, + SENSOR_DOMAIN, + { + SENSOR_DOMAIN: { + "name": "mysensor", + # encoding defaults to UTF-8, but should be ignored when charset present + "platform": DOMAIN, + "resource": "http://localhost", + "method": "GET", + } + }, + ) + await hass.async_block_till_done() + assert len(hass.states.async_all(SENSOR_DOMAIN)) == 1 + assert hass.states.get("sensor.mysensor").state == "Björk Guðmundsdóttir" + + +async def test_setup_encoding_fallback_no_charset( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Test that configured encoding is used when no charset in Content-Type.""" + # No charset in Content-Type header + aioclient_mock.get( + "http://localhost", + status=HTTPStatus.OK, + content="Björk Guðmundsdóttir".encode("iso-8859-1"), + headers={"Content-Type": "text/plain"}, # No charset! + ) + assert await async_setup_component( + hass, + SENSOR_DOMAIN, + { + SENSOR_DOMAIN: { + "name": "mysensor", + "encoding": "iso-8859-1", # This will be used as fallback + "platform": DOMAIN, + "resource": "http://localhost", + "method": "GET", + } + }, + ) + await hass.async_block_till_done() + assert len(hass.states.async_all(SENSOR_DOMAIN)) == 1 + assert hass.states.get("sensor.mysensor").state == "Björk Guðmundsdóttir" + + +async def test_setup_charset_overrides_encoding_config( + hass: HomeAssistant, aioclient_mock: AiohttpClientMocker +) -> None: + """Test that charset in Content-Type overrides configured encoding.""" + # Server sends UTF-8 with correct charset header + aioclient_mock.get( + "http://localhost", + status=HTTPStatus.OK, + content="Björk Guðmundsdóttir".encode(), + headers={"Content-Type": "text/plain; charset=utf-8"}, + ) + assert await async_setup_component( + hass, + SENSOR_DOMAIN, + { + SENSOR_DOMAIN: { + "name": "mysensor", + "encoding": "iso-8859-1", # Config says ISO-8859-1, but charset=utf-8 should win + "platform": DOMAIN, + "resource": "http://localhost", + "method": "GET", + } + }, + ) + await hass.async_block_till_done() + assert len(hass.states.async_all(SENSOR_DOMAIN)) == 1 + # This should work because charset=utf-8 overrides the iso-8859-1 config + assert hass.states.get("sensor.mysensor").state == "Björk Guðmundsdóttir" + + @pytest.mark.parametrize( ("ssl_cipher_list", "ssl_cipher_list_expected"), [ @@ -978,6 +1075,124 @@ async def test_update_with_failed_get( assert "Empty reply" in caplog.text +async def test_query_param_dict_value( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Test dict values in query params are handled for backward compatibility.""" + # Mock response + aioclient_mock.post( + "https://www.envertecportal.com/ApiInverters/QueryTerminalReal", + status=HTTPStatus.OK, + json={"Data": {"QueryResults": [{"POWER": 1500}]}}, + ) + + # This test checks that when template_complex processes a string that looks like + # a dict/list, it converts it to an actual dict/list, which then needs to be + # handled by our backward compatibility code + with caplog.at_level(logging.DEBUG, logger="homeassistant.components.rest.data"): + assert await async_setup_component( + hass, + DOMAIN, + { + DOMAIN: [ + { + CONF_RESOURCE: ( + "https://www.envertecportal.com/ApiInverters/" + "QueryTerminalReal" + ), + CONF_METHOD: "POST", + CONF_PARAMS: { + "page": "1", + "perPage": "20", + "orderBy": "SN", + # When processed by template.render_complex, certain + # strings might be converted to dicts/lists if they + # look like JSON + "whereCondition": ( + "{{ {'STATIONID': 'A6327A17797C1234'} }}" + ), # Template that evaluates to dict + }, + "sensor": [ + { + CONF_NAME: "Solar MPPT1 Power", + CONF_VALUE_TEMPLATE: ( + "{{ value_json.Data.QueryResults[0].POWER }}" + ), + CONF_DEVICE_CLASS: "power", + CONF_UNIT_OF_MEASUREMENT: "W", + CONF_FORCE_UPDATE: True, + "state_class": "measurement", + } + ], + } + ] + }, + ) + await hass.async_block_till_done() + + # The sensor should be created successfully with backward compatibility + assert len(hass.states.async_all(SENSOR_DOMAIN)) == 1 + state = hass.states.get("sensor.solar_mppt1_power") + assert state is not None + assert state.state == "1500" + + # Check that a debug message was logged about the parameter conversion + assert "REST query parameter 'whereCondition' has type" in caplog.text + assert "converting to string" in caplog.text + + +async def test_query_param_json_string_preserved( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Test that JSON strings in query params are preserved and not converted to dicts.""" + # Mock response + aioclient_mock.get( + "https://api.example.com/data", + status=HTTPStatus.OK, + json={"value": 42}, + ) + + # Config with JSON string (quoted) - should remain a string + assert await async_setup_component( + hass, + DOMAIN, + { + DOMAIN: [ + { + CONF_RESOURCE: "https://api.example.com/data", + CONF_METHOD: "GET", + CONF_PARAMS: { + "filter": '{"type": "sensor", "id": 123}', # JSON string + "normal": "value", + }, + "sensor": [ + { + CONF_NAME: "Test Sensor", + CONF_VALUE_TEMPLATE: "{{ value_json.value }}", + } + ], + } + ] + }, + ) + await hass.async_block_till_done() + + # Check the sensor was created + assert len(hass.states.async_all(SENSOR_DOMAIN)) == 1 + state = hass.states.get("sensor.test_sensor") + assert state is not None + assert state.state == "42" + + # Verify the request was made with the JSON string intact + assert len(aioclient_mock.mock_calls) == 1 + method, url, data, headers = aioclient_mock.mock_calls[0] + assert url.query["filter"] == '{"type": "sensor", "id": 123}' + assert url.query["normal"] == "value" + + async def test_reload(hass: HomeAssistant, aioclient_mock: AiohttpClientMocker) -> None: """Verify we can reload reset sensors.""" diff --git a/tests/components/rest_command/test_init.py b/tests/components/rest_command/test_init.py index 97ef29dfaca..b9c1096f26a 100644 --- a/tests/components/rest_command/test_init.py +++ b/tests/components/rest_command/test_init.py @@ -290,6 +290,7 @@ async def test_rest_command_get_response_plaintext( assert len(aioclient_mock.mock_calls) == 1 assert response["content"] == "success" assert response["status"] == 200 + assert response["headers"] == {"content-type": "text/plain"} async def test_rest_command_get_response_json( @@ -314,6 +315,7 @@ async def test_rest_command_get_response_json( assert response["content"]["status"] == "success" assert response["content"]["number"] == 42 assert response["status"] == 200 + assert response["headers"] == {"content-type": "application/json"} async def test_rest_command_get_response_malformed_json( @@ -326,7 +328,7 @@ async def test_rest_command_get_response_malformed_json( aioclient_mock.get( TEST_URL, - content='{"status": "failure", 42', + content=b'{"status": "failure", 42', headers={"content-type": "application/json"}, ) @@ -379,3 +381,27 @@ async def test_rest_command_get_response_none( ) assert not response + + +async def test_rest_command_response_iter_chunked( + hass: HomeAssistant, + setup_component: ComponentSetup, + aioclient_mock: AiohttpClientMocker, +) -> None: + """Ensure response is consumed when return_response is False.""" + await setup_component() + + png = base64.decodebytes( + b"iVBORw0KGgoAAAANSUhEUgAAAAIAAAABCAIAAAB7QOjdAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQ" + b"UAAAAJcEhZcwAAFiUAABYlAUlSJPAAAAAPSURBVBhXY/h/ku////8AECAE1JZPvDAAAAAASUVORK5CYII=" + ) + aioclient_mock.get(TEST_URL, content=png) + + with patch("aiohttp.StreamReader.iter_chunked", autospec=True) as mock_iter_chunked: + response = await hass.services.async_call(DOMAIN, "get_test", {}, blocking=True) + + # Ensure the response is not returned + assert response is None + + # Verify iter_chunked was called with a chunk size + assert mock_iter_chunked.called diff --git a/tests/components/risco/test_alarm_control_panel.py b/tests/components/risco/test_alarm_control_panel.py index 8caef1fbfc4..d27d39071a0 100644 --- a/tests/components/risco/test_alarm_control_panel.py +++ b/tests/components/risco/test_alarm_control_panel.py @@ -35,6 +35,7 @@ FIRST_LOCAL_ENTITY_ID = "alarm_control_panel.name_0" SECOND_LOCAL_ENTITY_ID = "alarm_control_panel.name_1" CODES_REQUIRED_OPTIONS = {"code_arm_required": True, "code_disarm_required": True} +CODES_NOT_REQUIRED_OPTIONS = {"code_arm_required": False, "code_disarm_required": False} TEST_RISCO_TO_HA = { "arm": AlarmControlPanelState.ARMED_AWAY, "partial_arm": AlarmControlPanelState.ARMED_HOME, @@ -388,7 +389,8 @@ async def test_cloud_sets_full_custom_mapping( @pytest.mark.parametrize( - "options", [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}] + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}], ) async def test_cloud_sets_with_correct_code( hass: HomeAssistant, two_part_cloud_alarm, setup_risco_cloud @@ -452,7 +454,58 @@ async def test_cloud_sets_with_correct_code( @pytest.mark.parametrize( - "options", [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}] + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_NOT_REQUIRED_OPTIONS}], +) +async def test_cloud_sets_without_code( + hass: HomeAssistant, two_part_cloud_alarm, setup_risco_cloud +) -> None: + """Test settings the various modes when code is not required.""" + await _test_cloud_service_call( + hass, SERVICE_ALARM_DISARM, "disarm", FIRST_CLOUD_ENTITY_ID, 0 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_DISARM, "disarm", SECOND_CLOUD_ENTITY_ID, 1 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_AWAY, "arm", FIRST_CLOUD_ENTITY_ID, 0 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_AWAY, "arm", SECOND_CLOUD_ENTITY_ID, 1 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_HOME, "partial_arm", FIRST_CLOUD_ENTITY_ID, 0 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_HOME, "partial_arm", SECOND_CLOUD_ENTITY_ID, 1 + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_NIGHT, "group_arm", FIRST_CLOUD_ENTITY_ID, 0, "C" + ) + await _test_cloud_service_call( + hass, SERVICE_ALARM_ARM_NIGHT, "group_arm", SECOND_CLOUD_ENTITY_ID, 1, "C" + ) + with pytest.raises(HomeAssistantError): + await _test_cloud_no_service_call( + hass, + SERVICE_ALARM_ARM_CUSTOM_BYPASS, + "partial_arm", + FIRST_CLOUD_ENTITY_ID, + 0, + ) + with pytest.raises(HomeAssistantError): + await _test_cloud_no_service_call( + hass, + SERVICE_ALARM_ARM_CUSTOM_BYPASS, + "partial_arm", + SECOND_CLOUD_ENTITY_ID, + 1, + ) + + +@pytest.mark.parametrize( + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}], ) async def test_cloud_sets_with_incorrect_code( hass: HomeAssistant, two_part_cloud_alarm, setup_risco_cloud @@ -837,7 +890,8 @@ async def test_local_sets_full_custom_mapping( @pytest.mark.parametrize( - "options", [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}] + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}], ) async def test_local_sets_with_correct_code( hass: HomeAssistant, two_part_local_alarm, setup_risco_local @@ -931,7 +985,8 @@ async def test_local_sets_with_correct_code( @pytest.mark.parametrize( - "options", [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}] + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_REQUIRED_OPTIONS}], ) async def test_local_sets_with_incorrect_code( hass: HomeAssistant, two_part_local_alarm, setup_risco_local @@ -1020,3 +1075,87 @@ async def test_local_sets_with_incorrect_code( two_part_local_alarm[1], **code, ) + + +@pytest.mark.parametrize( + "options", + [{**CUSTOM_MAPPING_OPTIONS, **CODES_NOT_REQUIRED_OPTIONS}], +) +async def test_local_sets_without_code( + hass: HomeAssistant, two_part_local_alarm, setup_risco_local +) -> None: + """Test settings the various modes when code is not required.""" + await _test_local_service_call( + hass, + SERVICE_ALARM_DISARM, + "disarm", + FIRST_LOCAL_ENTITY_ID, + two_part_local_alarm[0], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_DISARM, + "disarm", + SECOND_LOCAL_ENTITY_ID, + two_part_local_alarm[1], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_AWAY, + "arm", + FIRST_LOCAL_ENTITY_ID, + two_part_local_alarm[0], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_AWAY, + "arm", + SECOND_LOCAL_ENTITY_ID, + two_part_local_alarm[1], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_HOME, + "partial_arm", + FIRST_LOCAL_ENTITY_ID, + two_part_local_alarm[0], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_HOME, + "partial_arm", + SECOND_LOCAL_ENTITY_ID, + two_part_local_alarm[1], + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_NIGHT, + "group_arm", + FIRST_LOCAL_ENTITY_ID, + two_part_local_alarm[0], + "C", + ) + await _test_local_service_call( + hass, + SERVICE_ALARM_ARM_NIGHT, + "group_arm", + SECOND_LOCAL_ENTITY_ID, + two_part_local_alarm[1], + "C", + ) + with pytest.raises(HomeAssistantError): + await _test_local_no_service_call( + hass, + SERVICE_ALARM_ARM_CUSTOM_BYPASS, + "partial_arm", + FIRST_LOCAL_ENTITY_ID, + two_part_local_alarm[0], + ) + with pytest.raises(HomeAssistantError): + await _test_local_no_service_call( + hass, + SERVICE_ALARM_ARM_CUSTOM_BYPASS, + "partial_arm", + SECOND_LOCAL_ENTITY_ID, + two_part_local_alarm[1], + ) diff --git a/tests/components/russound_rio/conftest.py b/tests/components/russound_rio/conftest.py index 81091e1d5a8..15922f76b9f 100644 --- a/tests/components/russound_rio/conftest.py +++ b/tests/components/russound_rio/conftest.py @@ -84,6 +84,7 @@ def mock_russound_client() -> Generator[AsyncMock]: zone.set_treble = AsyncMock() zone.set_turn_on_volume = AsyncMock() zone.set_loudness = AsyncMock() + zone.restore_preset = AsyncMock() client.controllers = { 1: Controller( diff --git a/tests/components/russound_rio/fixtures/get_sources.json b/tests/components/russound_rio/fixtures/get_sources.json index e39d702b8a1..a9f4b4e14af 100644 --- a/tests/components/russound_rio/fixtures/get_sources.json +++ b/tests/components/russound_rio/fixtures/get_sources.json @@ -1,7 +1,14 @@ { "1": { "name": "Aux", - "type": "Miscellaneous Audio" + "type": "RNET AM/FM Tuner (Internal)", + "presets": { + "1": "WOOD", + "2": "89.7 MHz FM", + "7": "WWKR", + "8": "WKLA", + "11": "WGN" + } }, "2": { "name": "Spotify", diff --git a/tests/components/russound_rio/test_media_player.py b/tests/components/russound_rio/test_media_player.py index 04e1057565d..d8eacd5f30b 100644 --- a/tests/components/russound_rio/test_media_player.py +++ b/tests/components/russound_rio/test_media_player.py @@ -9,10 +9,13 @@ import pytest from homeassistant.components.media_player import ( ATTR_INPUT_SOURCE, + ATTR_MEDIA_CONTENT_ID, + ATTR_MEDIA_CONTENT_TYPE, ATTR_MEDIA_SEEK_POSITION, ATTR_MEDIA_VOLUME_LEVEL, ATTR_MEDIA_VOLUME_MUTED, DOMAIN as MP_DOMAIN, + SERVICE_PLAY_MEDIA, SERVICE_SELECT_SOURCE, ) from homeassistant.const import ( @@ -32,7 +35,7 @@ from homeassistant.const import ( STATE_PLAYING, ) from homeassistant.core import HomeAssistant -from homeassistant.exceptions import HomeAssistantError +from homeassistant.exceptions import HomeAssistantError, ServiceValidationError from . import mock_state_update, setup_integration from .const import ENTITY_ID_ZONE_1 @@ -253,3 +256,94 @@ async def test_media_seek( mock_russound_client.controllers[1].zones[1].set_seek_time.assert_called_once_with( 100 ) + + +async def test_play_media_preset_item_id( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_russound_client: AsyncMock, +) -> None: + """Test playing media with a preset item id.""" + await setup_integration(hass, mock_config_entry) + + await hass.services.async_call( + MP_DOMAIN, + SERVICE_PLAY_MEDIA, + { + ATTR_ENTITY_ID: ENTITY_ID_ZONE_1, + ATTR_MEDIA_CONTENT_TYPE: "preset", + ATTR_MEDIA_CONTENT_ID: "1", + }, + blocking=True, + ) + mock_russound_client.controllers[1].zones[1].restore_preset.assert_called_once_with( + 1 + ) + + await hass.services.async_call( + MP_DOMAIN, + SERVICE_PLAY_MEDIA, + { + ATTR_ENTITY_ID: ENTITY_ID_ZONE_1, + ATTR_MEDIA_CONTENT_TYPE: "preset", + ATTR_MEDIA_CONTENT_ID: "1,2", + }, + blocking=True, + ) + mock_russound_client.controllers[1].zones[1].select_source.assert_called_once_with( + 1 + ) + mock_russound_client.controllers[1].zones[1].restore_preset.assert_called_with(2) + + with pytest.raises( + ServiceValidationError, + match="The specified preset is not available for this source: 10", + ): + await hass.services.async_call( + MP_DOMAIN, + SERVICE_PLAY_MEDIA, + { + ATTR_ENTITY_ID: ENTITY_ID_ZONE_1, + ATTR_MEDIA_CONTENT_TYPE: "preset", + ATTR_MEDIA_CONTENT_ID: "10", + }, + blocking=True, + ) + + with pytest.raises( + ServiceValidationError, match="Preset must be an integer, got: UNKNOWN_PRESET" + ): + await hass.services.async_call( + MP_DOMAIN, + SERVICE_PLAY_MEDIA, + { + ATTR_ENTITY_ID: ENTITY_ID_ZONE_1, + ATTR_MEDIA_CONTENT_TYPE: "preset", + ATTR_MEDIA_CONTENT_ID: "UNKNOWN_PRESET", + }, + blocking=True, + ) + + +async def test_play_media_unknown_type( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_russound_client: AsyncMock, +) -> None: + """Test playing media with an unsupported content type.""" + await setup_integration(hass, mock_config_entry) + + with pytest.raises( + HomeAssistantError, + match="Unsupported media type for Russound zone: unsupported_content_type", + ): + await hass.services.async_call( + MP_DOMAIN, + SERVICE_PLAY_MEDIA, + { + ATTR_ENTITY_ID: ENTITY_ID_ZONE_1, + ATTR_MEDIA_CONTENT_TYPE: "unsupported_content_type", + ATTR_MEDIA_CONTENT_ID: "1", + }, + blocking=True, + ) diff --git a/tests/components/sensor/common.py b/tests/components/sensor/common.py index 2df13b697da..1b9810a8250 100644 --- a/tests/components/sensor/common.py +++ b/tests/components/sensor/common.py @@ -7,6 +7,7 @@ from homeassistant.components.sensor import ( ) from homeassistant.components.sensor.const import DEVICE_CLASS_STATE_CLASSES from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_MILLION, DEGREE, @@ -44,6 +45,7 @@ from homeassistant.const import ( from tests.common import MockEntity UNITS_OF_MEASUREMENT = { + SensorDeviceClass.ABSOLUTE_HUMIDITY: CONCENTRATION_GRAMS_PER_CUBIC_METER, SensorDeviceClass.APPARENT_POWER: UnitOfApparentPower.VOLT_AMPERE, SensorDeviceClass.AQI: None, SensorDeviceClass.AREA: UnitOfArea.SQUARE_METERS, diff --git a/tests/components/sensor/test_device_condition.py b/tests/components/sensor/test_device_condition.py index 1c87845c2c7..da69610f4c5 100644 --- a/tests/components/sensor/test_device_condition.py +++ b/tests/components/sensor/test_device_condition.py @@ -125,7 +125,7 @@ async def test_get_conditions( conditions = await async_get_device_automations( hass, DeviceAutomationType.CONDITION, device_entry.id ) - assert len(conditions) == 54 + assert len(conditions) == 55 assert conditions == unordered(expected_conditions) diff --git a/tests/components/sensor/test_device_trigger.py b/tests/components/sensor/test_device_trigger.py index bb57797e6dd..c39a5216f0f 100644 --- a/tests/components/sensor/test_device_trigger.py +++ b/tests/components/sensor/test_device_trigger.py @@ -126,7 +126,7 @@ async def test_get_triggers( triggers = await async_get_device_automations( hass, DeviceAutomationType.TRIGGER, device_entry.id ) - assert len(triggers) == 54 + assert len(triggers) == 55 assert triggers == unordered(expected_triggers) diff --git a/tests/components/sensorpro/__init__.py b/tests/components/sensorpro/__init__.py index a63bdbe08dc..7f2a7b1f33e 100644 --- a/tests/components/sensorpro/__init__.py +++ b/tests/components/sensorpro/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/sensorpush/__init__.py b/tests/components/sensorpush/__init__.py index 88fb2072961..6f1f80d777e 100644 --- a/tests/components/sensorpush/__init__.py +++ b/tests/components/sensorpush/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/smartthings/conftest.py b/tests/components/smartthings/conftest.py index e8cde67122b..93f505872f4 100644 --- a/tests/components/smartthings/conftest.py +++ b/tests/components/smartthings/conftest.py @@ -130,6 +130,7 @@ def mock_smartthings() -> Generator[AsyncMock]: "da_wm_wm_000001_1", "da_wm_sc_000001", "da_rvc_normal_000001", + "da_rvc_map_01011", "da_ks_microwave_0101x", "da_ks_cooktop_31001", "da_ks_range_0101x", diff --git a/tests/components/smartthings/fixtures/device_status/da_rvc_map_01011.json b/tests/components/smartthings/fixtures/device_status/da_rvc_map_01011.json new file mode 100644 index 00000000000..14244935308 --- /dev/null +++ b/tests/components/smartthings/fixtures/device_status/da_rvc_map_01011.json @@ -0,0 +1,994 @@ +{ + "components": { + "refill-drainage-kit": { + "samsungce.connectionState": { + "connectionState": { + "value": null + } + }, + "samsungce.activationState": { + "activationState": { + "value": null + } + }, + "custom.disabledCapabilities": { + "disabledCapabilities": { + "value": [ + "samsungce.drainFilter", + "samsungce.connectionState", + "samsungce.activationState" + ], + "timestamp": "2025-06-20T14:12:57.135Z" + } + }, + "samsungce.drainFilter": { + "drainFilterUsageStep": { + "value": null + }, + "drainFilterStatus": { + "value": null + }, + "drainFilterLastResetDate": { + "value": null + }, + "drainFilterResetType": { + "value": null + }, + "drainFilterUsage": { + "value": null + } + } + }, + "station": { + "custom.hepaFilter": { + "hepaFilterCapacity": { + "value": null + }, + "hepaFilterStatus": { + "value": "normal", + "timestamp": "2025-07-02T04:35:14.449Z" + }, + "hepaFilterResetType": { + "value": ["replaceable"], + "timestamp": "2025-07-02T04:35:14.449Z" + }, + "hepaFilterUsageStep": { + "value": null + }, + "hepaFilterUsage": { + "value": null + }, + "hepaFilterLastResetDate": { + "value": null + } + }, + "samsungce.robotCleanerDustBag": { + "supportedStatus": { + "value": ["full", "normal"], + "timestamp": "2025-07-02T04:35:14.620Z" + }, + "status": { + "value": "normal", + "timestamp": "2025-07-02T04:35:14.620Z" + } + } + }, + "main": { + "mediaPlayback": { + "supportedPlaybackCommands": { + "value": null + }, + "playbackStatus": { + "value": null + } + }, + "robotCleanerTurboMode": { + "robotCleanerTurboMode": { + "value": "extraSilence", + "timestamp": "2025-07-10T11:00:38.909Z" + } + }, + "ocf": { + "st": { + "value": "2024-01-01T09:00:15Z", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mndt": { + "value": "", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnfv": { + "value": "20250123.105306", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnhw": { + "value": "", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "di": { + "value": "05accb39-2017-c98b-a5ab-04a81f4d3d9a", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnsl": { + "value": "", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "dmv": { + "value": "res.1.1.0,sh.1.1.0", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "n": { + "value": "[robot vacuum] Samsung", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnmo": { + "value": "JETBOT_COMBO_9X00_24K|50029141|80010b0002d8411f0100000000000000", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "vid": { + "value": "DA-RVC-MAP-01011", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnmn": { + "value": "Samsung Electronics", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnml": { + "value": "", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnpv": { + "value": "1.0", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "mnos": { + "value": "Tizen", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "pi": { + "value": "05accb39-2017-c98b-a5ab-04a81f4d3d9a", + "timestamp": "2025-06-20T14:12:57.924Z" + }, + "icv": { + "value": "core.1.1.0", + "timestamp": "2025-06-20T14:12:57.924Z" + } + }, + "custom.disabledCapabilities": { + "disabledCapabilities": { + "value": [ + "samsungce.robotCleanerAudioClip", + "custom.hepaFilter", + "imageCapture", + "mediaPlaybackRepeat", + "mediaPlayback", + "mediaTrackControl", + "samsungce.robotCleanerPatrol", + "samsungce.musicPlaylist", + "audioVolume", + "audioMute", + "videoCapture", + "samsungce.robotCleanerWelcome", + "samsungce.microphoneSettings", + "samsungce.robotCleanerGuidedPatrol", + "samsungce.robotCleanerSafetyPatrol", + "soundDetection", + "samsungce.soundDetectionSensitivity", + "audioTrackAddressing", + "samsungce.robotCleanerMonitoringAutomation" + ], + "timestamp": "2025-06-20T14:12:58.125Z" + } + }, + "logTrigger": { + "logState": { + "value": "idle", + "timestamp": "2025-07-02T04:35:14.401Z" + }, + "logRequestState": { + "value": "idle", + "timestamp": "2025-07-02T04:35:14.401Z" + }, + "logInfo": { + "value": null + } + }, + "samsungce.driverVersion": { + "versionNumber": { + "value": 25040102, + "timestamp": "2025-06-20T14:12:57.135Z" + } + }, + "sec.diagnosticsInformation": { + "logType": { + "value": ["errCode", "dump"], + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "endpoint": { + "value": "PIPER", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "minVersion": { + "value": "3.0", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "signinPermission": { + "value": null + }, + "setupId": { + "value": "VR0", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "protocolType": { + "value": "ble_ocf", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "tsId": { + "value": "DA10", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "mnId": { + "value": "0AJT", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "dumpType": { + "value": "file", + "timestamp": "2025-07-02T04:35:13.556Z" + } + }, + "custom.hepaFilter": { + "hepaFilterCapacity": { + "value": null + }, + "hepaFilterStatus": { + "value": null + }, + "hepaFilterResetType": { + "value": null + }, + "hepaFilterUsageStep": { + "value": null + }, + "hepaFilterUsage": { + "value": null + }, + "hepaFilterLastResetDate": { + "value": null + } + }, + "samsungce.robotCleanerMapCleaningInfo": { + "area": { + "value": "None", + "timestamp": "2025-07-10T09:37:08.648Z" + }, + "cleanedExtent": { + "value": -1, + "unit": "m\u00b2", + "timestamp": "2025-07-10T09:37:08.648Z" + }, + "nearObject": { + "value": "None", + "timestamp": "2025-07-02T04:35:13.567Z" + }, + "remainingTime": { + "value": -1, + "unit": "minute", + "timestamp": "2025-07-10T06:42:57.820Z" + } + }, + "audioVolume": { + "volume": { + "value": null + } + }, + "powerConsumptionReport": { + "powerConsumption": { + "value": { + "energy": 981, + "deltaEnergy": 21, + "power": 0, + "powerEnergy": 0.0, + "persistedEnergy": 0, + "energySaved": 0, + "start": "2025-07-10T11:11:22Z", + "end": "2025-07-10T11:20:22Z" + }, + "timestamp": "2025-07-10T11:20:22.600Z" + } + }, + "samsungce.robotCleanerMapList": { + "maps": { + "value": [ + { + "id": "1", + "name": "Map1", + "userEdited": false, + "createdTime": "2025-07-01T08:23:29Z", + "updatedTime": "2025-07-01T08:23:29Z", + "areaInfo": [ + { + "id": "1", + "name": "Room", + "userEdited": false + }, + { + "id": "2", + "name": "Room 2", + "userEdited": false + }, + { + "id": "3", + "name": "Room 3", + "userEdited": false + }, + { + "id": "4", + "name": "Room 4", + "userEdited": false + } + ], + "objectInfo": [] + } + ], + "timestamp": "2025-07-02T04:35:14.204Z" + } + }, + "samsungce.robotCleanerPatrol": { + "timezone": { + "value": null + }, + "patrolStatus": { + "value": null + }, + "areaIds": { + "value": null + }, + "timeOffset": { + "value": null + }, + "waypoints": { + "value": null + }, + "enabled": { + "value": null + }, + "dayOfWeek": { + "value": null + }, + "blockingStatus": { + "value": null + }, + "mapId": { + "value": null + }, + "startTime": { + "value": null + }, + "interval": { + "value": null + }, + "endTime": { + "value": null + }, + "obsoleted": { + "value": null + } + }, + "samsungce.robotCleanerAudioClip": { + "enabled": { + "value": null + } + }, + "samsungce.musicPlaylist": { + "currentTrack": { + "value": null + }, + "playlist": { + "value": null + } + }, + "audioNotification": {}, + "samsungce.robotCleanerPetMonitorReport": { + "report": { + "value": null + } + }, + "execute": { + "data": { + "value": null + } + }, + "samsungce.energyPlanner": { + "data": { + "value": null + }, + "plan": { + "value": "none", + "timestamp": "2025-07-02T04:35:14.341Z" + } + }, + "samsungce.robotCleanerFeatureVisibility": { + "invisibleFeatures": { + "value": [ + "Start", + "Dock", + "SelectRoom", + "DustEmit", + "SelectSpot", + "CleaningMethod", + "MopWash", + "MopDry" + ], + "timestamp": "2025-07-10T09:52:40.298Z" + }, + "visibleFeatures": { + "value": [ + "Stop", + "Suction", + "Repeat", + "MapMerge", + "MapDivide", + "MySchedule", + "Homecare", + "CleanReport", + "CleanHistory", + "DND", + "Sound", + "NoEntryZone", + "RenameRoom", + "ResetMap", + "Accessory", + "CleaningOption", + "ObjectEdit", + "WaterLevel", + "ClimbZone" + ], + "timestamp": "2025-07-10T09:52:40.298Z" + } + }, + "sec.wifiConfiguration": { + "autoReconnection": { + "value": true, + "timestamp": "2025-07-02T04:35:14.461Z" + }, + "minVersion": { + "value": "1.0", + "timestamp": "2025-07-02T04:35:14.461Z" + }, + "supportedWiFiFreq": { + "value": ["2.4G", "5G"], + "timestamp": "2025-07-02T04:35:14.461Z" + }, + "supportedAuthType": { + "value": ["OPEN", "WEP", "WPA-PSK", "WPA2-PSK", "SAE"], + "timestamp": "2025-07-02T04:35:14.461Z" + }, + "protocolType": { + "value": ["helper_hotspot", "ble_ocf"], + "timestamp": "2025-07-02T04:35:14.461Z" + } + }, + "samsungce.softwareVersion": { + "versions": { + "value": [ + { + "id": "0", + "swType": "Software", + "versionNumber": "25012310" + }, + { + "id": "1", + "swType": "Software", + "versionNumber": "25012310" + }, + { + "id": "2", + "swType": "Firmware", + "versionNumber": "25012100" + }, + { + "id": "3", + "swType": "Firmware", + "versionNumber": "24012200" + }, + { + "id": "4", + "swType": "Bixby", + "versionNumber": "(null)" + }, + { + "id": "5", + "swType": "Firmware", + "versionNumber": "25012200" + } + ], + "timestamp": "2025-07-02T04:35:13.556Z" + } + }, + "samsungce.softwareUpdate": { + "targetModule": { + "value": { + "newVersion": "00000000", + "currentVersion": "00000000", + "moduleType": "mainController" + }, + "timestamp": "2025-07-09T23:00:32.385Z" + }, + "otnDUID": { + "value": "JHCDM7UU7UJWQ", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "lastUpdatedDate": { + "value": null + }, + "availableModules": { + "value": [], + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "newVersionAvailable": { + "value": false, + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "operatingState": { + "value": "none", + "timestamp": "2025-07-02T04:35:19.823Z" + }, + "progress": { + "value": 0, + "unit": "%", + "timestamp": "2025-07-02T04:35:19.823Z" + } + }, + "samsungce.robotCleanerReservation": { + "reservations": { + "value": [ + { + "id": "2", + "enabled": true, + "dayOfWeek": ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + "startTime": "02:32", + "repeatMode": "weekly", + "cleaningMode": "auto" + } + ], + "timestamp": "2025-07-02T04:35:13.844Z" + }, + "maxNumberOfReservations": { + "value": null + } + }, + "audioMute": { + "mute": { + "value": null + } + }, + "mediaTrackControl": { + "supportedTrackControlCommands": { + "value": null + } + }, + "samsungce.robotCleanerMotorFilter": { + "motorFilterResetType": { + "value": ["washable"], + "timestamp": "2025-07-02T04:35:13.496Z" + }, + "motorFilterStatus": { + "value": "normal", + "timestamp": "2025-07-02T04:35:13.496Z" + } + }, + "samsungce.robotCleanerCleaningType": { + "cleaningType": { + "value": "vacuumAndMopTogether", + "timestamp": "2025-07-09T12:44:06.437Z" + }, + "supportedCleaningTypes": { + "value": ["vacuum", "mop", "vacuumAndMopTogether", "mopAfterVacuum"], + "timestamp": "2025-07-02T04:35:13.646Z" + } + }, + "soundDetection": { + "soundDetectionState": { + "value": null + }, + "supportedSoundTypes": { + "value": null + }, + "soundDetected": { + "value": null + } + }, + "samsungce.robotCleanerWelcome": { + "coordinates": { + "value": null + } + }, + "samsungce.robotCleanerPetMonitor": { + "areaIds": { + "value": null + }, + "originator": { + "value": null + }, + "waypoints": { + "value": null + }, + "enabled": { + "value": null + }, + "excludeHolidays": { + "value": null + }, + "dayOfWeek": { + "value": null + }, + "monitoringStatus": { + "value": null + }, + "blockingStatus": { + "value": null + }, + "mapId": { + "value": null + }, + "startTime": { + "value": null + }, + "interval": { + "value": null + }, + "endTime": { + "value": null + }, + "obsoleted": { + "value": null + } + }, + "battery": { + "quantity": { + "value": null + }, + "battery": { + "value": 59, + "unit": "%", + "timestamp": "2025-07-10T11:24:13.441Z" + }, + "type": { + "value": null + } + }, + "samsungce.deviceIdentification": { + "micomAssayCode": { + "value": "50029141", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "modelName": { + "value": null + }, + "serialNumber": { + "value": null + }, + "serialNumberExtra": { + "value": null + }, + "modelClassificationCode": { + "value": "80010b0002d8411f0100000000000000", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "description": { + "value": "Jet Bot V/C", + "timestamp": "2025-07-02T04:35:13.556Z" + }, + "releaseYear": { + "value": null + }, + "binaryId": { + "value": "JETBOT_COMBO_9X00_24K", + "timestamp": "2025-07-09T23:00:26.764Z" + } + }, + "samsungce.robotCleanerSystemSoundMode": { + "soundMode": { + "value": "mute", + "timestamp": "2025-07-05T18:17:55.940Z" + }, + "supportedSoundModes": { + "value": ["mute", "beep", "voice"], + "timestamp": "2025-07-02T04:35:13.646Z" + } + }, + "switch": { + "switch": { + "value": "on", + "timestamp": "2025-07-09T23:00:26.829Z" + } + }, + "samsungce.robotCleanerPetCleaningSchedule": { + "excludeHolidays": { + "value": null + }, + "dayOfWeek": { + "value": null + }, + "mapId": { + "value": null + }, + "areaIds": { + "value": null + }, + "startTime": { + "value": null + }, + "originator": { + "value": null + }, + "obsoleted": { + "value": true, + "timestamp": "2025-07-02T04:35:14.317Z" + }, + "enabled": { + "value": null + } + }, + "samsungce.quickControl": { + "version": { + "value": "1.0", + "timestamp": "2025-07-02T04:35:14.234Z" + } + }, + "samsungce.microphoneSettings": { + "mute": { + "value": null + } + }, + "samsungce.robotCleanerMapAreaInfo": { + "areaInfo": { + "value": [ + { + "id": "1", + "name": "Room" + }, + { + "id": "2", + "name": "Room 2" + }, + { + "id": "3", + "name": "Room 3" + }, + { + "id": "4", + "name": "Room 4" + } + ], + "timestamp": "2025-07-03T02:33:15.133Z" + } + }, + "samsungce.audioVolumeLevel": { + "volumeLevel": { + "value": 0, + "timestamp": "2025-07-05T18:17:55.915Z" + }, + "volumeLevelRange": { + "value": { + "minimum": 0, + "maximum": 3, + "step": 1 + }, + "timestamp": "2025-07-02T04:35:13.837Z" + } + }, + "robotCleanerMovement": { + "robotCleanerMovement": { + "value": "cleaning", + "timestamp": "2025-07-10T09:38:52.938Z" + } + }, + "samsungce.robotCleanerSafetyPatrol": { + "personDetection": { + "value": null + } + }, + "sec.calmConnectionCare": { + "role": { + "value": ["things"], + "timestamp": "2025-07-02T04:35:14.461Z" + }, + "protocols": { + "value": null + }, + "version": { + "value": "1.0", + "timestamp": "2025-07-02T04:35:14.461Z" + } + }, + "custom.disabledComponents": { + "disabledComponents": { + "value": ["refill-drainage-kit"], + "timestamp": "2025-06-20T14:12:57.135Z" + } + }, + "videoCapture": { + "stream": { + "value": null + }, + "clip": { + "value": null + } + }, + "samsungce.robotCleanerWaterSprayLevel": { + "availableWaterSprayLevels": { + "value": null + }, + "waterSprayLevel": { + "value": "mediumLow", + "timestamp": "2025-07-10T11:00:35.545Z" + }, + "supportedWaterSprayLevels": { + "value": ["high", "mediumHigh", "medium", "mediumLow", "low"], + "timestamp": "2025-07-02T04:35:13.646Z" + } + }, + "samsungce.robotCleanerMapMetadata": { + "cellSize": { + "value": 20, + "unit": "mm", + "timestamp": "2025-06-20T14:12:57.135Z" + } + }, + "samsungce.robotCleanerGuidedPatrol": { + "mapId": { + "value": null + }, + "waypoints": { + "value": null + } + }, + "audioTrackAddressing": {}, + "refresh": {}, + "samsungce.robotCleanerOperatingState": { + "supportedOperatingState": { + "value": [ + "homing", + "charging", + "charged", + "chargingForRemainingJob", + "moving", + "cleaning", + "paused", + "idle", + "error", + "powerSaving", + "factoryReset", + "relocal", + "exploring", + "processing", + "emitDust", + "washingMop", + "sterilizingMop", + "dryingMop", + "supplyingWater", + "preparingWater", + "spinDrying", + "flexCharged", + "descaling", + "drainingWater", + "waitingForDescaling" + ], + "timestamp": "2025-06-20T14:12:58.012Z" + }, + "operatingState": { + "value": "dryingMop", + "timestamp": "2025-07-10T09:52:40.510Z" + }, + "cleaningStep": { + "value": "none", + "timestamp": "2025-07-10T09:37:07.214Z" + }, + "homingReason": { + "value": "none", + "timestamp": "2025-07-10T09:37:45.152Z" + }, + "isMapBasedOperationAvailable": { + "value": false, + "timestamp": "2025-07-10T09:37:55.690Z" + } + }, + "samsungce.soundDetectionSensitivity": { + "level": { + "value": null + }, + "supportedLevels": { + "value": null + } + }, + "samsungce.robotCleanerMonitoringAutomation": {}, + "mediaPlaybackRepeat": { + "playbackRepeatMode": { + "value": null + } + }, + "imageCapture": { + "image": { + "value": null + }, + "encrypted": { + "value": null + }, + "captureTime": { + "value": null + } + }, + "samsungce.robotCleanerCleaningMode": { + "supportedCleaningMode": { + "value": [ + "auto", + "area", + "spot", + "stop", + "uncleanedObject", + "patternMap" + ], + "timestamp": "2025-06-20T14:12:58.012Z" + }, + "repeatModeEnabled": { + "value": true, + "timestamp": "2025-07-02T04:35:13.646Z" + }, + "supportRepeatMode": { + "value": true, + "timestamp": "2025-07-02T04:35:13.646Z" + }, + "cleaningMode": { + "value": "stop", + "timestamp": "2025-07-10T09:37:07.214Z" + } + }, + "samsungce.robotCleanerAvpRegistration": { + "registrationStatus": { + "value": null + } + }, + "samsungce.robotCleanerDrivingMode": { + "drivingMode": { + "value": "areaThenWalls", + "timestamp": "2025-07-02T04:35:13.646Z" + }, + "supportedDrivingModes": { + "value": ["areaThenWalls", "wallFirst", "quickCleaningZigzagPattern"], + "timestamp": "2025-07-02T04:35:13.646Z" + } + }, + "robotCleanerCleaningMode": { + "robotCleanerCleaningMode": { + "value": "stop", + "timestamp": "2025-07-10T09:37:07.214Z" + } + }, + "custom.doNotDisturbMode": { + "doNotDisturb": { + "value": "off", + "timestamp": "2025-07-02T04:35:13.622Z" + }, + "startTime": { + "value": "0000", + "timestamp": "2025-07-02T04:35:13.622Z" + }, + "endTime": { + "value": "0000", + "timestamp": "2025-07-02T04:35:13.622Z" + } + }, + "samsungce.lamp": { + "brightnessLevel": { + "value": "on", + "timestamp": "2025-07-10T11:20:40.419Z" + }, + "supportedBrightnessLevel": { + "value": ["on", "off"], + "timestamp": "2025-06-20T14:12:57.383Z" + } + } + } + } +} diff --git a/tests/components/smartthings/fixtures/devices/da_rvc_map_01011.json b/tests/components/smartthings/fixtures/devices/da_rvc_map_01011.json new file mode 100644 index 00000000000..f25797f2dcf --- /dev/null +++ b/tests/components/smartthings/fixtures/devices/da_rvc_map_01011.json @@ -0,0 +1,353 @@ +{ + "items": [ + { + "deviceId": "05accb39-2017-c98b-a5ab-04a81f4d3d9a", + "name": "[robot vacuum] Samsung", + "label": "Robot vacuum", + "manufacturerName": "Samsung Electronics", + "presentationId": "DA-RVC-MAP-01011", + "deviceManufacturerCode": "Samsung Electronics", + "locationId": "d31d0982-9bf9-4f0c-afd4-ad3d78842541", + "ownerId": "85532262-6537-54d9-179a-333db98dbcc0", + "roomId": "572f5713-53a9-4fb8-85fd-60515e44f1ed", + "deviceTypeName": "Samsung OCF Robot Vacuum", + "components": [ + { + "id": "main", + "label": "main", + "capabilities": [ + { + "id": "audioMute", + "version": 1 + }, + { + "id": "audioNotification", + "version": 1 + }, + { + "id": "audioTrackAddressing", + "version": 1 + }, + { + "id": "audioVolume", + "version": 1 + }, + { + "id": "battery", + "version": 1 + }, + { + "id": "execute", + "version": 1 + }, + { + "id": "imageCapture", + "version": 1 + }, + { + "id": "logTrigger", + "version": 1 + }, + { + "id": "mediaPlayback", + "version": 1 + }, + { + "id": "mediaPlaybackRepeat", + "version": 1 + }, + { + "id": "mediaTrackControl", + "version": 1 + }, + { + "id": "ocf", + "version": 1 + }, + { + "id": "powerConsumptionReport", + "version": 1 + }, + { + "id": "refresh", + "version": 1 + }, + { + "id": "robotCleanerCleaningMode", + "version": 1 + }, + { + "id": "robotCleanerMovement", + "version": 1 + }, + { + "id": "robotCleanerTurboMode", + "version": 1 + }, + { + "id": "soundDetection", + "version": 1 + }, + { + "id": "switch", + "version": 1 + }, + { + "id": "videoCapture", + "version": 1 + }, + { + "id": "custom.disabledCapabilities", + "version": 1 + }, + { + "id": "custom.disabledComponents", + "version": 1 + }, + { + "id": "custom.doNotDisturbMode", + "version": 1 + }, + { + "id": "custom.hepaFilter", + "version": 1 + }, + { + "id": "samsungce.audioVolumeLevel", + "version": 1 + }, + { + "id": "samsungce.deviceIdentification", + "version": 1 + }, + { + "id": "samsungce.driverVersion", + "version": 1 + }, + { + "id": "samsungce.lamp", + "version": 1 + }, + { + "id": "samsungce.microphoneSettings", + "version": 1 + }, + { + "id": "samsungce.softwareUpdate", + "version": 1 + }, + { + "id": "samsungce.musicPlaylist", + "version": 1 + }, + { + "id": "samsungce.robotCleanerDrivingMode", + "version": 1 + }, + { + "id": "samsungce.robotCleanerCleaningMode", + "version": 1 + }, + { + "id": "samsungce.robotCleanerCleaningType", + "version": 1 + }, + { + "id": "samsungce.robotCleanerOperatingState", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMapAreaInfo", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMapCleaningInfo", + "version": 1 + }, + { + "id": "samsungce.robotCleanerPatrol", + "version": 1 + }, + { + "id": "samsungce.robotCleanerPetCleaningSchedule", + "version": 1 + }, + { + "id": "samsungce.robotCleanerPetMonitor", + "version": 1 + }, + { + "id": "samsungce.robotCleanerPetMonitorReport", + "version": 1 + }, + { + "id": "samsungce.robotCleanerReservation", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMotorFilter", + "version": 1 + }, + { + "id": "samsungce.robotCleanerAvpRegistration", + "version": 1 + }, + { + "id": "samsungce.soundDetectionSensitivity", + "version": 1 + }, + { + "id": "samsungce.robotCleanerWaterSprayLevel", + "version": 1 + }, + { + "id": "samsungce.robotCleanerWelcome", + "version": 1 + }, + { + "id": "samsungce.robotCleanerAudioClip", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMonitoringAutomation", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMapMetadata", + "version": 1 + }, + { + "id": "samsungce.robotCleanerMapList", + "version": 1 + }, + { + "id": "samsungce.robotCleanerSystemSoundMode", + "version": 1 + }, + { + "id": "samsungce.energyPlanner", + "version": 1 + }, + { + "id": "samsungce.quickControl", + "version": 1 + }, + { + "id": "samsungce.robotCleanerFeatureVisibility", + "version": 1 + }, + { + "id": "samsungce.softwareVersion", + "version": 1 + }, + { + "id": "samsungce.robotCleanerGuidedPatrol", + "version": 1 + }, + { + "id": "samsungce.robotCleanerSafetyPatrol", + "version": 1 + }, + { + "id": "sec.calmConnectionCare", + "version": 1 + }, + { + "id": "sec.diagnosticsInformation", + "version": 1 + }, + { + "id": "sec.wifiConfiguration", + "version": 1 + } + ], + "categories": [ + { + "name": "RobotCleaner", + "categoryType": "manufacturer" + } + ], + "optional": false + }, + { + "id": "station", + "label": "station", + "capabilities": [ + { + "id": "custom.hepaFilter", + "version": 1 + }, + { + "id": "samsungce.robotCleanerDustBag", + "version": 1 + } + ], + "categories": [ + { + "name": "Other", + "categoryType": "manufacturer" + } + ], + "optional": false + }, + { + "id": "refill-drainage-kit", + "label": "refill-drainage-kit", + "capabilities": [ + { + "id": "custom.disabledCapabilities", + "version": 1 + }, + { + "id": "samsungce.drainFilter", + "version": 1 + }, + { + "id": "samsungce.connectionState", + "version": 1 + }, + { + "id": "samsungce.activationState", + "version": 1 + } + ], + "categories": [ + { + "name": "Other", + "categoryType": "manufacturer" + } + ], + "optional": false + } + ], + "createTime": "2025-06-20T14:12:56.260Z", + "profile": { + "id": "5d345d41-a497-3fc7-84fe-eaaee50f0509" + }, + "ocf": { + "ocfDeviceType": "oic.d.robotcleaner", + "name": "[robot vacuum] Samsung", + "specVersion": "core.1.1.0", + "verticalDomainSpecVersion": "res.1.1.0,sh.1.1.0", + "manufacturerName": "Samsung Electronics", + "modelNumber": "JETBOT_COMBO_9X00_24K|50029141|80010b0002d8411f0100000000000000", + "platformVersion": "1.0", + "platformOS": "Tizen", + "hwVersion": "", + "firmwareVersion": "20250123.105306", + "vendorId": "DA-RVC-MAP-01011", + "vendorResourceClientServerVersion": "4.0.38", + "lastSignupTime": "2025-06-20T14:12:56.202953160Z", + "transferCandidate": false, + "additionalAuthCodeRequired": false, + "modelCode": "NONE" + }, + "type": "OCF", + "restrictionTier": 0, + "allowed": null, + "executionContext": "CLOUD", + "relationships": [] + } + ], + "_links": {} +} diff --git a/tests/components/smartthings/snapshots/test_init.ambr b/tests/components/smartthings/snapshots/test_init.ambr index 446eca63fb2..6ce3992d2b4 100644 --- a/tests/components/smartthings/snapshots/test_init.ambr +++ b/tests/components/smartthings/snapshots/test_init.ambr @@ -728,6 +728,39 @@ 'via_device_id': None, }) # --- +# name: test_devices[da_rvc_map_01011] + DeviceRegistryEntrySnapshot({ + 'area_id': None, + 'config_entries': , + 'config_entries_subentries': , + 'configuration_url': 'https://account.smartthings.com', + 'connections': set({ + }), + 'disabled_by': None, + 'entry_type': None, + 'hw_version': '', + 'id': , + 'identifiers': set({ + tuple( + 'smartthings', + '05accb39-2017-c98b-a5ab-04a81f4d3d9a', + ), + }), + 'is_new': False, + 'labels': set({ + }), + 'manufacturer': 'Samsung Electronics', + 'model': 'JETBOT_COMBO_9X00_24K', + 'model_id': None, + 'name': 'Robot vacuum', + 'name_by_user': None, + 'primary_config_entry': , + 'serial_number': None, + 'suggested_area': None, + 'sw_version': '20250123.105306', + 'via_device_id': None, + }) +# --- # name: test_devices[da_rvc_normal_000001] DeviceRegistryEntrySnapshot({ 'area_id': 'theater', diff --git a/tests/components/smartthings/snapshots/test_select.ambr b/tests/components/smartthings/snapshots/test_select.ambr index 7dd57e89c6a..d36132cc1ef 100644 --- a/tests/components/smartthings/snapshots/test_select.ambr +++ b/tests/components/smartthings/snapshots/test_select.ambr @@ -55,7 +55,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'unknown', + 'state': 'off', }) # --- # name: test_all_entities[da_ks_oven_01061][select.oven_lamp-entry] @@ -112,7 +112,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'unknown', + 'state': 'high', }) # --- # name: test_all_entities[da_ks_range_0101x][select.vulcan_lamp-entry] @@ -172,6 +172,63 @@ 'state': 'extra_high', }) # --- +# name: test_all_entities[da_rvc_map_01011][select.robot_vacuum_lamp-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'on', + 'off', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.robot_vacuum_lamp', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Lamp', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'lamp', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_samsungce.lamp_brightnessLevel_brightnessLevel', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[da_rvc_map_01011][select.robot_vacuum_lamp-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Robot vacuum Lamp', + 'options': list([ + 'on', + 'off', + ]), + }), + 'context': , + 'entity_id': 'select.robot_vacuum_lamp', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- # name: test_all_entities[da_wm_dw_000001][select.dishwasher-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/smartthings/snapshots/test_sensor.ambr b/tests/components/smartthings/snapshots/test_sensor.ambr index f88524116ee..169359118da 100644 --- a/tests/components/smartthings/snapshots/test_sensor.ambr +++ b/tests/components/smartthings/snapshots/test_sensor.ambr @@ -6066,6 +6066,540 @@ 'state': '97', }) # --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_battery-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.robot_vacuum_battery', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Battery', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_battery_battery_battery', + 'unit_of_measurement': '%', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_battery-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'battery', + 'friendly_name': 'Robot vacuum Battery', + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_battery', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '59', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_cleaning_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'auto', + 'part', + 'repeat', + 'manual', + 'stop', + 'map', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.robot_vacuum_cleaning_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Cleaning mode', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'robot_cleaner_cleaning_mode', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_robotCleanerCleaningMode_robotCleanerCleaningMode_robotCleanerCleaningMode', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_cleaning_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'enum', + 'friendly_name': 'Robot vacuum Cleaning mode', + 'options': list([ + 'auto', + 'part', + 'repeat', + 'manual', + 'stop', + 'map', + ]), + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_cleaning_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'stop', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_energy', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Energy', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_powerConsumptionReport_powerConsumption_energy_meter', + 'unit_of_measurement': , + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'energy', + 'friendly_name': 'Robot vacuum Energy', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_energy', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.981', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy_difference-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_energy_difference', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Energy difference', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'energy_difference', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_powerConsumptionReport_powerConsumption_deltaEnergy_meter', + 'unit_of_measurement': , + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy_difference-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'energy', + 'friendly_name': 'Robot vacuum Energy difference', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_energy_difference', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.021', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy_saved-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_energy_saved', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Energy saved', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'energy_saved', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_powerConsumptionReport_powerConsumption_energySaved_meter', + 'unit_of_measurement': , + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_energy_saved-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'energy', + 'friendly_name': 'Robot vacuum Energy saved', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_energy_saved', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_movement-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'homing', + 'idle', + 'charging', + 'alarm', + 'off', + 'reserve', + 'point', + 'after', + 'cleaning', + 'pause', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_movement', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Movement', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'robot_cleaner_movement', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_robotCleanerMovement_robotCleanerMovement_robotCleanerMovement', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_movement-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'enum', + 'friendly_name': 'Robot vacuum Movement', + 'options': list([ + 'homing', + 'idle', + 'charging', + 'alarm', + 'off', + 'reserve', + 'point', + 'after', + 'cleaning', + 'pause', + ]), + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_movement', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'cleaning', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Power', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_powerConsumptionReport_powerConsumption_power_meter', + 'unit_of_measurement': , + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Robot vacuum Power', + 'power_consumption_end': '2025-07-10T11:20:22Z', + 'power_consumption_start': '2025-07-10T11:11:22Z', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_power_energy-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.robot_vacuum_power_energy', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Power energy', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'power_energy', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_powerConsumptionReport_powerConsumption_powerEnergy_meter', + 'unit_of_measurement': , + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_power_energy-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'energy', + 'friendly_name': 'Robot vacuum Power energy', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_power_energy', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_turbo_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'on', + 'off', + 'silence', + 'extra_silence', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.robot_vacuum_turbo_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Turbo mode', + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'robot_cleaner_turbo_mode', + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_robotCleanerTurboMode_robotCleanerTurboMode_robotCleanerTurboMode', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[da_rvc_map_01011][sensor.robot_vacuum_turbo_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'enum', + 'friendly_name': 'Robot vacuum Turbo mode', + 'options': list([ + 'on', + 'off', + 'silence', + 'extra_silence', + ]), + }), + 'context': , + 'entity_id': 'sensor.robot_vacuum_turbo_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'extra_silence', + }) +# --- # name: test_all_entities[da_rvc_normal_000001][sensor.robot_vacuum_battery-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/smartthings/snapshots/test_switch.ambr b/tests/components/smartthings/snapshots/test_switch.ambr index d0ea3dbcdad..1aaeb35205f 100644 --- a/tests/components/smartthings/snapshots/test_switch.ambr +++ b/tests/components/smartthings/snapshots/test_switch.ambr @@ -623,6 +623,54 @@ 'state': 'off', }) # --- +# name: test_all_entities[da_rvc_map_01011][switch.robot_vacuum-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.robot_vacuum', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'smartthings', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': '05accb39-2017-c98b-a5ab-04a81f4d3d9a_main_switch_switch_switch', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[da_rvc_map_01011][switch.robot_vacuum-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Robot vacuum', + }), + 'context': , + 'entity_id': 'switch.robot_vacuum', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- # name: test_all_entities[da_rvc_normal_000001][switch.robot_vacuum-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ diff --git a/tests/components/snapcast/__init__.py b/tests/components/snapcast/__init__.py index a325bd41bd7..69bf252f53a 100644 --- a/tests/components/snapcast/__init__.py +++ b/tests/components/snapcast/__init__.py @@ -1 +1,13 @@ """Tests for the Snapcast integration.""" + +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry + + +async def setup_integration(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: + """Set up the Snapcast integration in Home Assistant.""" + config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() diff --git a/tests/components/snapcast/conftest.py b/tests/components/snapcast/conftest.py index bcc0ac5bc30..c2c4ffa7997 100644 --- a/tests/components/snapcast/conftest.py +++ b/tests/components/snapcast/conftest.py @@ -1,9 +1,18 @@ """Test the snapcast config flow.""" from collections.abc import Generator -from unittest.mock import AsyncMock, MagicMock, patch +from unittest.mock import AsyncMock, patch import pytest +from snapcast.control.client import Snapclient +from snapcast.control.group import Snapgroup +from snapcast.control.server import CONTROL_PORT +from snapcast.control.stream import Snapstream + +from homeassistant.components.snapcast.const import DOMAIN +from homeassistant.const import CONF_HOST, CONF_PORT + +from tests.common import MockConfigEntry @pytest.fixture @@ -16,10 +25,145 @@ def mock_setup_entry() -> Generator[AsyncMock]: @pytest.fixture -def mock_create_server() -> Generator[AsyncMock]: +def mock_server(mock_create_server: AsyncMock) -> Generator[AsyncMock]: + """Override async_setup_entry.""" + with patch( + "homeassistant.components.snapcast.config_flow.snapcast.control.create_server", + return_value=mock_create_server, + ) as mock_server: + yield mock_server + + +@pytest.fixture +def mock_create_server( + mock_group: AsyncMock, + mock_client: AsyncMock, + mock_stream_1: AsyncMock, + mock_stream_2: AsyncMock, +) -> Generator[AsyncMock]: """Create mock snapcast connection.""" - mock_connection = AsyncMock() - mock_connection.start = AsyncMock(return_value=None) - mock_connection.stop = MagicMock() - with patch("snapcast.control.create_server", return_value=mock_connection): - yield mock_connection + with patch( + "homeassistant.components.snapcast.coordinator.Snapserver", autospec=True + ) as mock_snapserver: + mock_server = mock_snapserver.return_value + mock_server.groups = [mock_group] + mock_server.clients = [mock_client] + mock_server.streams = [mock_stream_1, mock_stream_2] + mock_server.group.return_value = mock_group + mock_server.client.return_value = mock_client + + def get_stream(identifier: str) -> AsyncMock: + return {s.identifier: s for s in mock_server.streams}[identifier] + + mock_server.stream = get_stream + yield mock_server + + +@pytest.fixture +async def mock_config_entry() -> MockConfigEntry: + """Return a mock config entry.""" + + # Create a mock config entry + return MockConfigEntry( + domain=DOMAIN, + data={ + CONF_HOST: "127.0.0.1", + CONF_PORT: CONTROL_PORT, + }, + ) + + +@pytest.fixture +def mock_group(stream: str, streams: dict[str, AsyncMock]) -> AsyncMock: + """Create a mock Snapgroup.""" + group = AsyncMock(spec=Snapgroup) + group.identifier = "4dcc4e3b-c699-a04b-7f0c-8260d23c43e1" + group.name = "test_group" + group.friendly_name = "test_group" + group.stream = stream + group.muted = False + group.stream_status = streams[stream].status + group.volume = 48 + group.streams_by_name.return_value = {s.friendly_name: s for s in streams.values()} + return group + + +@pytest.fixture +def mock_client(mock_group: AsyncMock) -> AsyncMock: + """Create a mock Snapclient.""" + client = AsyncMock(spec=Snapclient) + client.identifier = "00:21:6a:7d:74:fc#2" + client.friendly_name = "test_client" + client.version = "0.10.0" + client.connected = True + client.name = "Snapclient" + client.latency = 6 + client.muted = False + client.volume = 48 + client.group = mock_group + mock_group.clients = [client.identifier] + return client + + +@pytest.fixture +def mock_stream_1() -> AsyncMock: + """Create a mock stream.""" + stream = AsyncMock(spec=Snapstream) + stream.identifier = "test_stream_1" + stream.status = "playing" + stream.name = "Test Stream 1" + stream.friendly_name = "Test Stream 1" + stream.metadata = { + "album": "Test Album", + "artist": ["Test Artist 1", "Test Artist 2"], + "title": "Test Title", + "artUrl": "http://localhost/test_art.jpg", + "albumArtist": [ + "Test Album Artist 1", + "Test Album Artist 2", + ], + "trackNumber": 10, + "duration": 60.0, + } + stream.meta = stream.metadata + stream.properties = { + "position": 30.0, + **stream.metadata, + } + stream.path = None + return stream + + +@pytest.fixture +def mock_stream_2() -> AsyncMock: + """Create a mock stream.""" + stream = AsyncMock(spec=Snapstream) + stream.identifier = "test_stream_2" + stream.status = "idle" + stream.name = "Test Stream 2" + stream.friendly_name = "Test Stream 2" + stream.metadata = None + stream.meta = None + stream.properties = None + stream.path = None + return stream + + +@pytest.fixture( + params=[ + "test_stream_1", + "test_stream_2", + ] +) +def stream(request: pytest.FixtureRequest) -> Generator[str]: + """Return every device.""" + return request.param + + +@pytest.fixture +def streams(mock_stream_1: AsyncMock, mock_stream_2: AsyncMock) -> dict[str, AsyncMock]: + """Return a dictionary of mock streams.""" + return { + mock_stream_1.identifier: mock_stream_1, + mock_stream_2.identifier: mock_stream_2, + } diff --git a/tests/components/snapcast/const.py b/tests/components/snapcast/const.py new file mode 100644 index 00000000000..0fbd5a05460 --- /dev/null +++ b/tests/components/snapcast/const.py @@ -0,0 +1,4 @@ +"""Constants for Snapcast tests.""" + +TEST_CLIENT_ENTITY_ID = "media_player.test_client_snapcast_client" +TEST_GROUP_ENTITY_ID = "media_player.test_group_snapcast_group" diff --git a/tests/components/snapcast/snapshots/test_media_player.ambr b/tests/components/snapcast/snapshots/test_media_player.ambr new file mode 100644 index 00000000000..c497cdd861b --- /dev/null +++ b/tests/components/snapcast/snapshots/test_media_player.ambr @@ -0,0 +1,271 @@ +# serializer version: 1 +# name: test_state[test_stream_1][media_player.test_client_snapcast_client-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'media_player', + 'entity_category': None, + 'entity_id': 'media_player.test_client_snapcast_client', + 'has_entity_name': False, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'test_client Snapcast Client', + 'platform': 'snapcast', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'snapcast_client_127.0.0.1:1705_00:21:6a:7d:74:fc#2', + 'unit_of_measurement': None, + }) +# --- +# name: test_state[test_stream_1][media_player.test_client_snapcast_client-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'speaker', + 'entity_picture': '/api/media_player_proxy/media_player.test_client_snapcast_client?token=mock_token&cache=6e2dee674d9d1dc7', + 'friendly_name': 'test_client Snapcast Client', + 'is_volume_muted': False, + 'latency': 6, + 'media_album_artist': 'Test Album Artist 1, Test Album Artist 2', + 'media_album_name': 'Test Album', + 'media_artist': 'Test Artist 1, Test Artist 2', + 'media_content_type': , + 'media_duration': 60, + 'media_position': 30, + 'media_title': 'Test Title', + 'media_track': 10, + 'source': 'test_stream_1', + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + 'supported_features': , + 'volume_level': 0.48, + }), + 'context': , + 'entity_id': 'media_player.test_client_snapcast_client', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'playing', + }) +# --- +# name: test_state[test_stream_1][media_player.test_group_snapcast_group-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'media_player', + 'entity_category': None, + 'entity_id': 'media_player.test_group_snapcast_group', + 'has_entity_name': False, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'test_group Snapcast Group', + 'platform': 'snapcast', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'snapcast_group_127.0.0.1:1705_4dcc4e3b-c699-a04b-7f0c-8260d23c43e1', + 'unit_of_measurement': None, + }) +# --- +# name: test_state[test_stream_1][media_player.test_group_snapcast_group-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'speaker', + 'entity_picture': '/api/media_player_proxy/media_player.test_group_snapcast_group?token=mock_token&cache=6e2dee674d9d1dc7', + 'friendly_name': 'test_group Snapcast Group', + 'is_volume_muted': False, + 'media_album_artist': 'Test Album Artist 1, Test Album Artist 2', + 'media_album_name': 'Test Album', + 'media_artist': 'Test Artist 1, Test Artist 2', + 'media_content_type': , + 'media_duration': 60, + 'media_position': 30, + 'media_title': 'Test Title', + 'media_track': 10, + 'source': 'test_stream_1', + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + 'supported_features': , + 'volume_level': 0.48, + }), + 'context': , + 'entity_id': 'media_player.test_group_snapcast_group', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'playing', + }) +# --- +# name: test_state[test_stream_2][media_player.test_client_snapcast_client-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'media_player', + 'entity_category': None, + 'entity_id': 'media_player.test_client_snapcast_client', + 'has_entity_name': False, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'test_client Snapcast Client', + 'platform': 'snapcast', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'snapcast_client_127.0.0.1:1705_00:21:6a:7d:74:fc#2', + 'unit_of_measurement': None, + }) +# --- +# name: test_state[test_stream_2][media_player.test_client_snapcast_client-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'speaker', + 'friendly_name': 'test_client Snapcast Client', + 'is_volume_muted': False, + 'latency': 6, + 'media_content_type': , + 'source': 'test_stream_2', + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + 'supported_features': , + 'volume_level': 0.48, + }), + 'context': , + 'entity_id': 'media_player.test_client_snapcast_client', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'idle', + }) +# --- +# name: test_state[test_stream_2][media_player.test_group_snapcast_group-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'media_player', + 'entity_category': None, + 'entity_id': 'media_player.test_group_snapcast_group', + 'has_entity_name': False, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'test_group Snapcast Group', + 'platform': 'snapcast', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'snapcast_group_127.0.0.1:1705_4dcc4e3b-c699-a04b-7f0c-8260d23c43e1', + 'unit_of_measurement': None, + }) +# --- +# name: test_state[test_stream_2][media_player.test_group_snapcast_group-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'speaker', + 'friendly_name': 'test_group Snapcast Group', + 'is_volume_muted': False, + 'media_content_type': , + 'source': 'test_stream_2', + 'source_list': list([ + 'Test Stream 1', + 'Test Stream 2', + ]), + 'supported_features': , + 'volume_level': 0.48, + }), + 'context': , + 'entity_id': 'media_player.test_group_snapcast_group', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'idle', + }) +# --- diff --git a/tests/components/snapcast/test_config_flow.py b/tests/components/snapcast/test_config_flow.py index 3bdba8b4c58..5b7d30211e1 100644 --- a/tests/components/snapcast/test_config_flow.py +++ b/tests/components/snapcast/test_config_flow.py @@ -1,95 +1,103 @@ """Test the Snapcast module.""" import socket -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock import pytest -from homeassistant import config_entries, setup from homeassistant.components.snapcast.const import DOMAIN +from homeassistant.config_entries import SOURCE_USER from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from tests.common import MockConfigEntry -TEST_CONNECTION = {CONF_HOST: "snapserver.test", CONF_PORT: 1705} - -pytestmark = pytest.mark.usefixtures("mock_setup_entry", "mock_create_server") +TEST_CONNECTION = {CONF_HOST: "127.0.0.1", CONF_PORT: 1705} -async def test_form( - hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_create_server: AsyncMock +async def test_full_flow( + hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_server: AsyncMock ) -> None: - """Test we get the form and handle errors and successful connection.""" - await setup.async_setup_component(hass, "persistent_notification", {}) + """Test the full flow.""" result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": config_entries.SOURCE_USER} + DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert not result["errors"] - # test invalid host error - with patch("snapcast.control.create_server", side_effect=socket.gaierror): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - TEST_CONNECTION, - ) - await hass.async_block_till_done() - - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" - assert result["errors"] == {"base": "invalid_host"} - - # test connection error - with patch("snapcast.control.create_server", side_effect=ConnectionRefusedError): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - TEST_CONNECTION, - ) - await hass.async_block_till_done() - - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "user" - assert result["errors"] == {"base": "cannot_connect"} - - # test success result = await hass.config_entries.flow.async_configure( - result["flow_id"], TEST_CONNECTION + result["flow_id"], + TEST_CONNECTION, ) - await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "Snapcast" - assert result["data"] == {CONF_HOST: "snapserver.test", CONF_PORT: 1705} - assert len(mock_create_server.mock_calls) == 1 + assert result["data"] == {CONF_HOST: "127.0.0.1", CONF_PORT: 1705} assert len(mock_setup_entry.mock_calls) == 1 -async def test_abort( - hass: HomeAssistant, mock_setup_entry: AsyncMock, mock_create_server: AsyncMock +@pytest.mark.parametrize( + ("exception", "error"), + [ + (socket.gaierror, "invalid_host"), + (ConnectionRefusedError, "cannot_connect"), + ], +) +async def test_exceptions( + hass: HomeAssistant, + mock_setup_entry: AsyncMock, + mock_server: AsyncMock, + exception: Exception, + error: str, ) -> None: - """Test config flow abort if device is already configured.""" - entry = MockConfigEntry( - domain=DOMAIN, - data=TEST_CONNECTION, - ) - entry.add_to_hass(hass) + """Test we get the form and handle errors and successful connection.""" + mock_server.side_effect = exception result = await hass.config_entries.flow.async_init( - DOMAIN, context={"source": config_entries.SOURCE_USER} + DOMAIN, context={"source": SOURCE_USER} ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" assert not result["errors"] - with patch("snapcast.control.create_server", side_effect=socket.gaierror): - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - TEST_CONNECTION, - ) - await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + TEST_CONNECTION, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["errors"] == {"base": error} + + mock_server.side_effect = None + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + TEST_CONNECTION, + ) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + +async def test_already_setup( + hass: HomeAssistant, mock_config_entry: MockConfigEntry +) -> None: + """Test config flow abort if device is already configured.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert not result["errors"] + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + TEST_CONNECTION, + ) assert result["type"] is FlowResultType.ABORT assert result["reason"] == "already_configured" diff --git a/tests/components/snapcast/test_media_player.py b/tests/components/snapcast/test_media_player.py new file mode 100644 index 00000000000..57a8a865ddf --- /dev/null +++ b/tests/components/snapcast/test_media_player.py @@ -0,0 +1,30 @@ +"""Test the snapcast media player implementation.""" + +from unittest.mock import AsyncMock, patch + +from syrupy.assertion import SnapshotAssertion + +from homeassistant.config_entries import ConfigEntryState +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_state( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_create_server: AsyncMock, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test basic state information.""" + + # Setup and verify the integration is loaded + with patch("secrets.token_hex", return_value="mock_token"): + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.LOADED + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) diff --git a/tests/components/snmp/test_float_sensor.py b/tests/components/snmp/test_float_sensor.py index a4f6e21dad7..032a89e8be8 100644 --- a/tests/components/snmp/test_float_sensor.py +++ b/tests/components/snmp/test_float_sensor.py @@ -16,7 +16,7 @@ def hlapi_mock(): """Mock out 3rd party API.""" mock_data = Opaque(value=b"\x9fx\x04=\xa4\x00\x00") with patch( - "homeassistant.components.snmp.sensor.getCmd", + "homeassistant.components.snmp.sensor.get_cmd", return_value=(None, None, None, [[mock_data]]), ): yield diff --git a/tests/components/snmp/test_init.py b/tests/components/snmp/test_init.py index 0aa97dcc475..37039444aa0 100644 --- a/tests/components/snmp/test_init.py +++ b/tests/components/snmp/test_init.py @@ -2,8 +2,8 @@ from unittest.mock import patch -from pysnmp.hlapi.asyncio import SnmpEngine -from pysnmp.hlapi.asyncio.cmdgen import lcd +from pysnmp.hlapi.v3arch.asyncio import SnmpEngine +from pysnmp.hlapi.v3arch.asyncio.cmdgen import LCD from homeassistant.components import snmp from homeassistant.const import EVENT_HOMEASSISTANT_STOP @@ -16,7 +16,7 @@ async def test_async_get_snmp_engine(hass: HomeAssistant) -> None: assert isinstance(engine, SnmpEngine) engine2 = await snmp.async_get_snmp_engine(hass) assert engine is engine2 - with patch.object(lcd, "unconfigure") as mock_unconfigure: + with patch.object(LCD, "unconfigure") as mock_unconfigure: hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() assert mock_unconfigure.called diff --git a/tests/components/snmp/test_integer_sensor.py b/tests/components/snmp/test_integer_sensor.py index 8e7e0f166ef..8a7d3b91138 100644 --- a/tests/components/snmp/test_integer_sensor.py +++ b/tests/components/snmp/test_integer_sensor.py @@ -16,7 +16,7 @@ def hlapi_mock(): """Mock out 3rd party API.""" mock_data = Integer32(13) with patch( - "homeassistant.components.snmp.sensor.getCmd", + "homeassistant.components.snmp.sensor.get_cmd", return_value=(None, None, None, [[mock_data]]), ): yield diff --git a/tests/components/snmp/test_negative_sensor.py b/tests/components/snmp/test_negative_sensor.py index 66a111b68d0..512cd536df9 100644 --- a/tests/components/snmp/test_negative_sensor.py +++ b/tests/components/snmp/test_negative_sensor.py @@ -16,7 +16,7 @@ def hlapi_mock(): """Mock out 3rd party API.""" mock_data = Integer32(-13) with patch( - "homeassistant.components.snmp.sensor.getCmd", + "homeassistant.components.snmp.sensor.get_cmd", return_value=(None, None, None, [[mock_data]]), ): yield diff --git a/tests/components/snmp/test_string_sensor.py b/tests/components/snmp/test_string_sensor.py index 5362e79c98d..b51fae0afe5 100644 --- a/tests/components/snmp/test_string_sensor.py +++ b/tests/components/snmp/test_string_sensor.py @@ -16,7 +16,7 @@ def hlapi_mock(): """Mock out 3rd party API.""" mock_data = OctetString("98F") with patch( - "homeassistant.components.snmp.sensor.getCmd", + "homeassistant.components.snmp.sensor.get_cmd", return_value=(None, None, None, [[mock_data]]), ): yield diff --git a/tests/components/snmp/test_switch.py b/tests/components/snmp/test_switch.py index fe1c3922ff0..a70428934ac 100644 --- a/tests/components/snmp/test_switch.py +++ b/tests/components/snmp/test_switch.py @@ -27,7 +27,7 @@ async def test_snmp_integer_switch_off(hass: HomeAssistant) -> None: mock_data = Integer32(0) with patch( - "homeassistant.components.snmp.switch.getCmd", + "homeassistant.components.snmp.switch.get_cmd", return_value=(None, None, None, [[mock_data]]), ): assert await async_setup_component(hass, SWITCH_DOMAIN, config) @@ -41,7 +41,7 @@ async def test_snmp_integer_switch_on(hass: HomeAssistant) -> None: mock_data = Integer32(1) with patch( - "homeassistant.components.snmp.switch.getCmd", + "homeassistant.components.snmp.switch.get_cmd", return_value=(None, None, None, [[mock_data]]), ): assert await async_setup_component(hass, SWITCH_DOMAIN, config) @@ -57,7 +57,7 @@ async def test_snmp_integer_switch_unknown( mock_data = Integer32(3) with patch( - "homeassistant.components.snmp.switch.getCmd", + "homeassistant.components.snmp.switch.get_cmd", return_value=(None, None, None, [[mock_data]]), ): assert await async_setup_component(hass, SWITCH_DOMAIN, config) diff --git a/tests/components/switch_as_x/__init__.py b/tests/components/switch_as_x/__init__.py index 2addb832462..dbf1afa54ac 100644 --- a/tests/components/switch_as_x/__init__.py +++ b/tests/components/switch_as_x/__init__.py @@ -1,6 +1,11 @@ """The tests for Switch as X platforms.""" +from homeassistant.components.cover import CoverEntityFeature +from homeassistant.components.fan import FanEntityFeature +from homeassistant.components.light import ATTR_SUPPORTED_COLOR_MODES, ColorMode from homeassistant.components.lock import LockState +from homeassistant.components.siren import SirenEntityFeature +from homeassistant.components.valve import ValveEntityFeature from homeassistant.const import STATE_CLOSED, STATE_OFF, STATE_ON, STATE_OPEN, Platform PLATFORMS_TO_TEST = ( @@ -12,6 +17,15 @@ PLATFORMS_TO_TEST = ( Platform.VALVE, ) +CAPABILITY_MAP = { + Platform.COVER: None, + Platform.FAN: {}, + Platform.LIGHT: {ATTR_SUPPORTED_COLOR_MODES: [ColorMode.ONOFF]}, + Platform.LOCK: None, + Platform.SIREN: None, + Platform.VALVE: None, +} + STATE_MAP = { False: { Platform.COVER: {STATE_ON: STATE_OPEN, STATE_OFF: STATE_CLOSED}, @@ -30,3 +44,12 @@ STATE_MAP = { Platform.VALVE: {STATE_ON: STATE_CLOSED, STATE_OFF: STATE_OPEN}, }, } + +SUPPORTED_FEATURE_MAP = { + Platform.COVER: CoverEntityFeature.OPEN | CoverEntityFeature.CLOSE, + Platform.FAN: FanEntityFeature.TURN_ON | FanEntityFeature.TURN_OFF, + Platform.LIGHT: 0, + Platform.LOCK: 0, + Platform.SIREN: SirenEntityFeature.TURN_ON | SirenEntityFeature.TURN_OFF, + Platform.VALVE: ValveEntityFeature.OPEN | ValveEntityFeature.CLOSE, +} diff --git a/tests/components/switch_as_x/test_init.py b/tests/components/switch_as_x/test_init.py index 2c87b0e3a92..a201cb258d6 100644 --- a/tests/components/switch_as_x/test_init.py +++ b/tests/components/switch_as_x/test_init.py @@ -25,12 +25,12 @@ from homeassistant.const import ( EntityCategory, Platform, ) -from homeassistant.core import Event, HomeAssistant +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event from homeassistant.setup import async_setup_component -from . import PLATFORMS_TO_TEST +from . import CAPABILITY_MAP, PLATFORMS_TO_TEST, SUPPORTED_FEATURE_MAP from tests.common import MockConfigEntry @@ -79,6 +79,22 @@ def switch_as_x_config_entry( return config_entry +def track_entity_registry_actions( + hass: HomeAssistant, entity_id: str +) -> list[er.EventEntityRegistryUpdatedData]: + """Track entity registry actions for an entity.""" + events = [] + + @callback + def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: + """Add entity registry updated event to the list.""" + events.append(event.data) + + async_track_entity_registry_updated_event(hass, entity_id, add_event) + + return events + + @pytest.mark.parametrize("target_domain", PLATFORMS_TO_TEST) async def test_config_entry_unregistered_uuid( hass: HomeAssistant, target_domain: str @@ -222,7 +238,7 @@ async def test_device_registry_config_entry_1( assert entity_entry.device_id == switch_entity_entry.device_id device_entry = device_registry.async_get(device_entry.id) - assert switch_as_x_config_entry.entry_id in device_entry.config_entries + assert switch_as_x_config_entry.entry_id not in device_entry.config_entries events = [] @@ -304,7 +320,7 @@ async def test_device_registry_config_entry_2( assert entity_entry.device_id == switch_entity_entry.device_id device_entry = device_registry.async_get(device_entry.id) - assert switch_as_x_config_entry.entry_id in device_entry.config_entries + assert switch_as_x_config_entry.entry_id not in device_entry.config_entries events = [] @@ -386,7 +402,7 @@ async def test_device_registry_config_entry_3( assert entity_entry.device_id == switch_entity_entry.device_id device_entry = device_registry.async_get(device_entry.id) - assert switch_as_x_config_entry.entry_id in device_entry.config_entries + assert switch_as_x_config_entry.entry_id not in device_entry.config_entries device_entry_2 = device_registry.async_get(device_entry_2.id) assert switch_as_x_config_entry.entry_id not in device_entry_2.config_entries @@ -413,7 +429,7 @@ async def test_device_registry_config_entry_3( device_entry = device_registry.async_get(device_entry.id) assert switch_as_x_config_entry.entry_id not in device_entry.config_entries device_entry_2 = device_registry.async_get(device_entry_2.id) - assert switch_as_x_config_entry.entry_id in device_entry_2.config_entries + assert switch_as_x_config_entry.entry_id not in device_entry_2.config_entries # Check that the switch_as_x config entry is not removed assert switch_as_x_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -1083,11 +1099,31 @@ async def test_restore_expose_settings( @pytest.mark.parametrize("target_domain", PLATFORMS_TO_TEST) async def test_migrate( hass: HomeAssistant, + device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, target_domain: Platform, ) -> None: """Test migration.""" - # Setup the config entry + # Switch config entry, device and entity + switch_config_entry = MockConfigEntry() + switch_config_entry.add_to_hass(hass) + + device_entry = device_registry.async_get_or_create( + config_entry_id=switch_config_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, + ) + switch_entity_entry = entity_registry.async_get_or_create( + "switch", + "test", + "unique", + config_entry=switch_config_entry, + device_id=device_entry.id, + original_name="ABC", + suggested_object_id="test", + ) + assert switch_entity_entry.entity_id == "switch.test" + + # Switch_as_x config entry, device and entity config_entry = MockConfigEntry( data={}, domain=DOMAIN, @@ -1100,9 +1136,37 @@ async def test_migrate( minor_version=1, ) config_entry.add_to_hass(hass) + device_registry.async_update_device( + device_entry.id, add_config_entry_id=config_entry.entry_id + ) + switch_as_x_entity_entry = entity_registry.async_get_or_create( + target_domain, + "switch_as_x", + config_entry.entry_id, + capabilities=CAPABILITY_MAP[target_domain], + config_entry=config_entry, + device_id=device_entry.id, + original_name="ABC", + suggested_object_id="abc", + supported_features=SUPPORTED_FEATURE_MAP[target_domain], + ) + entity_registry.async_update_entity_options( + switch_as_x_entity_entry.entity_id, + DOMAIN, + {"entity_id": "switch.test", "invert": False}, + ) + + events = track_entity_registry_actions(hass, switch_as_x_entity_entry.entity_id) + + # Setup the switch_as_x config entry assert await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() + assert set(entity_registry.entities) == { + switch_entity_entry.entity_id, + switch_as_x_entity_entry.entity_id, + } + # Check migration was successful and added invert option assert config_entry.state is ConfigEntryState.LOADED assert config_entry.options == { @@ -1117,6 +1181,20 @@ async def test_migrate( assert hass.states.get(f"{target_domain}.abc") is not None assert entity_registry.async_get(f"{target_domain}.abc") is not None + # Entity removed from device to prevent deletion, then added back to device + assert events == [ + { + "action": "update", + "changes": {"device_id": device_entry.id}, + "entity_id": switch_as_x_entity_entry.entity_id, + }, + { + "action": "update", + "changes": {"device_id": None}, + "entity_id": switch_as_x_entity_entry.entity_id, + }, + ] + @pytest.mark.parametrize("target_domain", PLATFORMS_TO_TEST) async def test_migrate_from_future( diff --git a/tests/components/template/conftest.py b/tests/components/template/conftest.py index c69c9e9e9a4..c57d1dcbfab 100644 --- a/tests/components/template/conftest.py +++ b/tests/components/template/conftest.py @@ -4,11 +4,15 @@ from enum import Enum import pytest +from homeassistant.components import template +from homeassistant.config_entries import SOURCE_USER from homeassistant.core import HomeAssistant, ServiceCall +from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers.typing import ConfigType from homeassistant.setup import async_setup_component from tests.common import assert_setup_component, async_mock_service +from tests.conftest import WebSocketGenerator class ConfigurationStyle(Enum): @@ -19,6 +23,88 @@ class ConfigurationStyle(Enum): TRIGGER = "Trigger" +def make_test_trigger(*entities: str) -> dict: + """Make a test state trigger.""" + return { + "trigger": [ + { + "trigger": "state", + "entity_id": list(entities), + }, + {"platform": "event", "event_type": "test_event"}, + ], + "variables": {"triggering_entity": "{{ trigger.entity_id }}"}, + "action": [ + {"event": "action_event", "event_data": {"what": "{{ triggering_entity }}"}} + ], + } + + +async def async_setup_legacy_platforms( + hass: HomeAssistant, + domain: str, + slug: str, + count: int, + config: ConfigType, +) -> None: + """Do setup of any legacy platform that supports a keyed dictionary of template entities.""" + with assert_setup_component(count, domain): + assert await async_setup_component( + hass, + domain, + {domain: {"platform": "template", slug: config}}, + ) + + await hass.async_block_till_done() + await hass.async_start() + await hass.async_block_till_done() + + +async def async_setup_modern_state_format( + hass: HomeAssistant, + domain: str, + count: int, + config: ConfigType, + extra_config: ConfigType | None = None, +) -> None: + """Do setup of template integration via modern format.""" + extra = extra_config or {} + with assert_setup_component(count, template.DOMAIN): + assert await async_setup_component( + hass, + template.DOMAIN, + {"template": {domain: config, **extra}}, + ) + + await hass.async_block_till_done() + await hass.async_start() + await hass.async_block_till_done() + + +async def async_setup_modern_trigger_format( + hass: HomeAssistant, + domain: str, + trigger: dict, + count: int, + config: ConfigType, + extra_config: ConfigType | None = None, +) -> None: + """Do setup of template integration via trigger format.""" + extra = extra_config or {} + config = {"template": {domain: config, **trigger, **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() + + @pytest.fixture def calls(hass: HomeAssistant) -> list[ServiceCall]: """Track calls to a mock service.""" @@ -51,3 +137,43 @@ async def caplog_setup_text(caplog: pytest.LogCaptureFixture) -> str: @pytest.fixture(autouse=True, name="stub_blueprint_populate") def stub_blueprint_populate_autouse(stub_blueprint_populate: None) -> None: """Stub copying the blueprints to the config folder.""" + + +async def async_get_flow_preview_state( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + domain: str, + user_input: ConfigType, +) -> ConfigType: + """Test the config flow preview.""" + client = await hass_ws_client(hass) + + result = await hass.config_entries.flow.async_init( + template.DOMAIN, context={"source": SOURCE_USER} + ) + assert result["type"] is FlowResultType.MENU + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {"next_step_id": domain}, + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == domain + assert result["errors"] is None + assert result["preview"] == "template" + + await client.send_json_auto_id( + { + "type": "template/start_preview", + "flow_id": result["flow_id"], + "flow_type": "config_flow", + "user_input": user_input, + } + ) + msg = await client.receive_json() + assert msg["success"] + assert msg["result"] is None + + msg = await client.receive_json() + return msg["event"] diff --git a/tests/components/template/test_binary_sensor.py b/tests/components/template/test_binary_sensor.py index a3b7edea919..75a9e2c9689 100644 --- a/tests/components/template/test_binary_sensor.py +++ b/tests/components/template/test_binary_sensor.py @@ -1,9 +1,9 @@ """The tests for the Template Binary sensor platform.""" from collections.abc import Generator -from copy import deepcopy from datetime import UTC, datetime, timedelta import logging +from typing import Any from unittest.mock import Mock, patch from freezegun.api import FrozenDateTimeFactory @@ -23,16 +23,26 @@ from homeassistant.const import ( from homeassistant.core import Context, CoreState, HomeAssistant, State from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.entity_component import async_update_entity +from homeassistant.helpers.restore_state import STORAGE_KEY as RESTORE_STATE_KEY from homeassistant.helpers.typing import ConfigType -from homeassistant.setup import async_setup_component + +from .conftest import ( + ConfigurationStyle, + async_get_flow_preview_state, + async_setup_legacy_platforms, + async_setup_modern_state_format, + async_setup_modern_trigger_format, + make_test_trigger, +) from tests.common import ( MockConfigEntry, - assert_setup_component, async_fire_time_changed, + async_mock_restore_state_shutdown_restart, mock_restore_cache, mock_restore_cache_with_extra_data, ) +from tests.typing import WebSocketGenerator _BEER_TRIGGER_VALUE_TEMPLATE = ( "{% if trigger.event.data.beer < 0 %}" @@ -45,94 +55,202 @@ _BEER_TRIGGER_VALUE_TEMPLATE = ( ) -@pytest.mark.parametrize("count", [1]) -@pytest.mark.parametrize( - ("config", "domain", "entity_id", "name", "attributes"), - [ - ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "value_template": "{{ True }}", - } - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test", - "test", - {"friendly_name": "test"}, - ), - ( - { - "template": { - "binary_sensor": { - "state": "{{ True }}", - } - }, - }, - template.DOMAIN, - "binary_sensor.unnamed_device", - "unnamed device", - {}, - ), - ], +TEST_OBJECT_ID = "test_binary_sensor" +TEST_ENTITY_ID = f"binary_sensor.{TEST_OBJECT_ID}" +TEST_STATE_ENTITY_ID = "binary_sensor.test_state" +TEST_ATTRIBUTE_ENTITY_ID = "sensor.test_attribute" +TEST_AVAILABILITY_ENTITY_ID = "binary_sensor.test_availability" +TEST_STATE_TRIGGER = make_test_trigger( + TEST_STATE_ENTITY_ID, TEST_AVAILABILITY_ENTITY_ID, TEST_ATTRIBUTE_ENTITY_ID ) -@pytest.mark.usefixtures("start_ha") -async def test_setup_minimal( - hass: HomeAssistant, entity_id: str, name: str, attributes: dict[str, str] +UNIQUE_ID_CONFIG = { + "unique_id": "not-so-unique-anymore", +} + + +async def async_setup_legacy_format( + hass: HomeAssistant, count: int, config: ConfigType ) -> None: - """Test the setup.""" - state = hass.states.get(entity_id) - assert state is not None - assert state.name == name - assert state.state == STATE_ON - assert state.attributes == attributes + """Do setup of binary sensor integration via legacy format.""" + await async_setup_legacy_platforms( + hass, binary_sensor.DOMAIN, "sensors", count, config + ) + + +async def async_setup_modern_format( + hass: HomeAssistant, + count: int, + config: ConfigType, + extra_config: ConfigType | None = None, +) -> None: + """Do setup of binary sensor integration via modern format.""" + await async_setup_modern_state_format( + hass, binary_sensor.DOMAIN, count, config, extra_config + ) + + +async def async_setup_trigger_format( + hass: HomeAssistant, + count: int, + config: ConfigType, + extra_config: ConfigType | None = None, +) -> None: + """Do setup of binary sensor integration via trigger format.""" + await async_setup_modern_trigger_format( + hass, binary_sensor.DOMAIN, TEST_STATE_TRIGGER, count, config, extra_config + ) + + +@pytest.fixture +async def setup_base_binary_sensor( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + config: ConfigType | list[dict], + extra_template_options: ConfigType, +) -> None: + """Do setup of binary sensor integration.""" + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_format(hass, count, config) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format(hass, count, config, extra_template_options) + elif style == ConfigurationStyle.TRIGGER: + await async_setup_trigger_format(hass, count, config, extra_template_options) + + +async def async_setup_binary_sensor( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + state_template: str, + extra_config: ConfigType, +) -> None: + """Do setup of binary sensor integration.""" + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_format( + hass, + count, + {TEST_OBJECT_ID: {"value_template": state_template, **extra_config}}, + ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format( + hass, + count, + {"name": TEST_OBJECT_ID, "state": state_template, **extra_config}, + ) + elif style == ConfigurationStyle.TRIGGER: + await async_setup_trigger_format( + hass, + count, + {"name": TEST_OBJECT_ID, "state": state_template, **extra_config}, + ) + + +@pytest.fixture +async def setup_binary_sensor( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + state_template: str, + extra_config: dict[str, Any], +) -> None: + """Do setup of binary sensor integration.""" + await async_setup_binary_sensor(hass, count, style, state_template, extra_config) + + +@pytest.fixture +async def setup_single_attribute_binary_sensor( + hass: HomeAssistant, + count: int, + style: ConfigurationStyle, + attribute: str, + attribute_value: str | dict, + state_template: str, + extra_config: dict, +) -> None: + """Do setup of binary sensor integration testing a single attribute.""" + extra = {attribute: attribute_value} if attribute and attribute_value else {} + if style == ConfigurationStyle.LEGACY: + await async_setup_legacy_format( + hass, + count, + { + TEST_OBJECT_ID: { + "value_template": state_template, + **extra, + **extra_config, + } + }, + ) + elif style == ConfigurationStyle.MODERN: + await async_setup_modern_format( + hass, + count, + { + "name": TEST_OBJECT_ID, + "state": state_template, + **extra, + **extra_config, + }, + ) + elif style == ConfigurationStyle.TRIGGER: + await async_setup_trigger_format( + hass, + count, + { + "name": TEST_OBJECT_ID, + "state": state_template, + **extra, + **extra_config, + }, + ) -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "extra_config"), [(1, "{{ True }}", {})] +) +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], +) +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_setup_minimal(hass: HomeAssistant) -> None: + """Test the setup.""" + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state is not None + assert state.name == TEST_OBJECT_ID + assert state.state == STATE_ON + assert state.attributes == {"friendly_name": TEST_OBJECT_ID} + + +@pytest.mark.parametrize( + ("count", "state_template", "extra_config"), [ ( + 1, + "{{ True }}", { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "friendly_name": "virtual thingy", - "value_template": "{{ True }}", - "device_class": "motion", - } - }, - }, + "device_class": "motion", }, - binary_sensor.DOMAIN, - "binary_sensor.test", - ), - ( - { - "template": { - "binary_sensor": { - "name": "virtual thingy", - "state": "{{ True }}", - "device_class": "motion", - } - }, - }, - template.DOMAIN, - "binary_sensor.virtual_thingy", - ), + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_setup(hass: HomeAssistant, entity_id: str) -> None: +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], +) +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_setup(hass: HomeAssistant) -> None: """Test the setup.""" - state = hass.states.get(entity_id) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) assert state is not None - assert state.name == "virtual thingy" + assert state.name == TEST_OBJECT_ID assert state.state == STATE_ON assert state.attributes["device_class"] == "motion" @@ -298,162 +416,144 @@ async def test_state( assert state.state == expected_result -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "attribute_value", "extra_config"), [ ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_template_sensor": { - "value_template": "{{ states.sensor.xyz.state }}", - "icon_template": "{% if " - "states.binary_sensor.test_state.state == " - "'on' %}" - "mdi:check" - "{% endif %}", - }, - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test_template_sensor", - ), - ( - { - "template": { - "binary_sensor": { - "state": "{{ states.sensor.xyz.state }}", - "icon": "{% if " - "states.binary_sensor.test_state.state == " - "'on' %}" - "mdi:check" - "{% endif %}", - }, - }, - }, - template.DOMAIN, - "binary_sensor.unnamed_device", - ), + 1, + "{{ 1 == 1 }}", + "{% if is_state('binary_sensor.test_state', 'on') %}mdi:check{% endif %}", + {}, + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_icon_template(hass: HomeAssistant, entity_id: str) -> None: +@pytest.mark.parametrize( + ("style", "attribute", "initial_state"), + [ + (ConfigurationStyle.LEGACY, "icon_template", ""), + (ConfigurationStyle.MODERN, "icon", ""), + (ConfigurationStyle.TRIGGER, "icon", None), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_icon_template(hass: HomeAssistant, initial_state: str | None) -> None: """Test icon template.""" - state = hass.states.get(entity_id) - assert state.attributes.get("icon") == "" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("icon") == initial_state - hass.states.async_set("binary_sensor.test_state", STATE_ON) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - state = hass.states.get(entity_id) + + state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["icon"] == "mdi:check" -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "attribute_value", "extra_config"), [ ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_template_sensor": { - "value_template": "{{ states.sensor.xyz.state }}", - "entity_picture_template": "{% if " - "states.binary_sensor.test_state.state == " - "'on' %}" - "/local/sensor.png" - "{% endif %}", - }, - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test_template_sensor", - ), - ( - { - "template": { - "binary_sensor": { - "state": "{{ states.sensor.xyz.state }}", - "picture": "{% if " - "states.binary_sensor.test_state.state == " - "'on' %}" - "/local/sensor.png" - "{% endif %}", - }, - }, - }, - template.DOMAIN, - "binary_sensor.unnamed_device", - ), + 1, + "{{ 1 == 1 }}", + "{% if is_state('binary_sensor.test_state', 'on') %}/local/sensor.png{% endif %}", + {}, + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_entity_picture_template(hass: HomeAssistant, entity_id: str) -> None: +@pytest.mark.parametrize( + ("style", "attribute", "initial_state"), + [ + (ConfigurationStyle.LEGACY, "entity_picture_template", ""), + (ConfigurationStyle.MODERN, "picture", ""), + (ConfigurationStyle.TRIGGER, "picture", None), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_entity_picture_template( + hass: HomeAssistant, initial_state: str | None +) -> None: """Test entity_picture template.""" - state = hass.states.get(entity_id) - assert state.attributes.get("entity_picture") == "" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("entity_picture") == initial_state - hass.states.async_set("binary_sensor.test_state", STATE_ON) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - state = hass.states.get(entity_id) + + state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["entity_picture"] == "/local/sensor.png" -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "attribute_value", "extra_config"), [ ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_template_sensor": { - "value_template": "{{ states.sensor.xyz.state }}", - "attribute_templates": { - "test_attribute": "It {{ states.sensor.test_state.state }}." - }, - }, - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test_template_sensor", - ), - ( - { - "template": { - "binary_sensor": { - "state": "{{ states.sensor.xyz.state }}", - "attributes": { - "test_attribute": "It {{ states.sensor.test_state.state }}." - }, - }, - }, - }, - template.DOMAIN, - "binary_sensor.unnamed_device", - ), + 1, + "{{ True }}", + {"test_attribute": "It {{ states.sensor.test_attribute.state }}."}, + {}, + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_attribute_templates(hass: HomeAssistant, entity_id: str) -> None: +@pytest.mark.parametrize( + ("style", "attribute", "initial_value"), + [ + (ConfigurationStyle.LEGACY, "attribute_templates", "It ."), + (ConfigurationStyle.MODERN, "attributes", "It ."), + (ConfigurationStyle.TRIGGER, "attributes", None), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_attribute_templates( + hass: HomeAssistant, initial_value: str | None +) -> None: """Test attribute_templates template.""" - state = hass.states.get(entity_id) - assert state.attributes.get("test_attribute") == "It ." - hass.states.async_set("sensor.test_state", "Works2") + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("test_attribute") == initial_value + + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, "Works2") await hass.async_block_till_done() - hass.states.async_set("sensor.test_state", "Works") + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, "Works") await hass.async_block_till_done() - state = hass.states.get(entity_id) + + state = hass.states.get(TEST_ENTITY_ID) assert state.attributes["test_attribute"] == "It Works." +@pytest.mark.parametrize( + ("count", "state_template", "attribute_value", "extra_config"), + [ + ( + 1, + "{{ states.binary_sensor.test_sensor }}", + {"test_attribute": "{{ states.binary_sensor.unknown.attributes.picture }}"}, + {}, + ) + ], +) +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "attribute_templates"), + (ConfigurationStyle.MODERN, "attributes"), + (ConfigurationStyle.TRIGGER, "attributes"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_invalid_attribute_template( + hass: HomeAssistant, + style: ConfigurationStyle, + caplog_setup_text: str, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that errors are logged if rendering template fails.""" + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + assert len(hass.states.async_all()) == 2 + text = ( + "Template variable error: 'None' has no attribute 'attributes' when rendering" + ) + assert text in caplog_setup_text or text in caplog.text + + @pytest.fixture def setup_mock() -> Generator[Mock]: """Do setup of sensor mock.""" @@ -496,338 +596,261 @@ async def test_match_all(hass: HomeAssistant, setup_mock: Mock) -> None: assert len(setup_mock.mock_calls) == init_calls -@pytest.mark.parametrize(("count", "domain"), [(1, binary_sensor.DOMAIN)]) @pytest.mark.parametrize( - "config", + ("count", "state_template", "extra_config"), [ - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - }, - }, - }, - }, + ( + 1, + "{{ is_state('binary_sensor.test_state', 'on') }}", + {"device_class": "motion"}, + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_event(hass: HomeAssistant) -> None: +@pytest.mark.parametrize( + ("style", "initial_state"), + [ + (ConfigurationStyle.LEGACY, STATE_OFF), + (ConfigurationStyle.MODERN, STATE_OFF), + (ConfigurationStyle.TRIGGER, STATE_UNKNOWN), + ], +) +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_binary_sensor_state(hass: HomeAssistant, initial_state: str) -> None: """Test the event.""" - state = hass.states.get("binary_sensor.test") - assert state.state == STATE_OFF + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == initial_state - hass.states.async_set("sensor.test_state", STATE_ON) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_ON @pytest.mark.parametrize( - ("config", "count", "domain"), + ("count", "state_template", "extra_config", "attribute"), [ ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_on": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_on": 5, - }, - "test_off": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_off": 5, - }, - }, - }, - }, 1, - binary_sensor.DOMAIN, - ), - ( - { - "template": [ - { - "binary_sensor": { - "name": "test on", - "state": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_on": 5, - }, - }, - { - "binary_sensor": { - "name": "test off", - "state": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_off": 5, - }, - }, - ] - }, - 2, - template.DOMAIN, - ), - ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_on": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_on": '{{ ({ "seconds": 10 / 2 }) }}', - }, - "test_off": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_off": '{{ ({ "seconds": 10 / 2 }) }}', - }, - }, - }, - }, - 1, - binary_sensor.DOMAIN, - ), - ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test_on": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_on": '{{ ({ "seconds": states("input_number.delay")|int }) }}', - }, - "test_off": { - "friendly_name": "virtual thingy", - "value_template": "{{ states.sensor.test_state.state == 'on' }}", - "device_class": "motion", - "delay_off": '{{ ({ "seconds": states("input_number.delay")|int }) }}', - }, - }, - }, - }, - 1, - binary_sensor.DOMAIN, - ), + "{{ is_state('binary_sensor.test_state', 'on') }}", + {"device_class": "motion"}, + "delay_on", + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_template_delay_on_off( - hass: HomeAssistant, freezer: FrozenDateTimeFactory +@pytest.mark.parametrize( + ("style", "initial_state"), + [ + (ConfigurationStyle.LEGACY, STATE_OFF), + (ConfigurationStyle.MODERN, STATE_OFF), + (ConfigurationStyle.TRIGGER, STATE_UNKNOWN), + ], +) +@pytest.mark.parametrize( + "attribute_value", + [ + 5, + "{{ dict(seconds=10 / 2) }}", + '{{ dict(seconds=states("sensor.test_attribute") | int(0)) }}', + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_delay_on( + hass: HomeAssistant, initial_state: str, freezer: FrozenDateTimeFactory ) -> None: """Test binary sensor template delay on.""" # Ensure the initial state is not on - assert hass.states.get("binary_sensor.test_on").state != STATE_ON - assert hass.states.get("binary_sensor.test_off").state != STATE_ON + assert hass.states.get(TEST_ENTITY_ID).state == initial_state - hass.states.async_set("input_number.delay", 5) - hass.states.async_set("sensor.test_state", STATE_ON) + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, 5) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_OFF - assert hass.states.get("binary_sensor.test_off").state == STATE_ON + + assert hass.states.get(TEST_ENTITY_ID).state == initial_state freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_ON - assert hass.states.get("binary_sensor.test_off").state == STATE_ON - # check with time changes - hass.states.async_set("sensor.test_state", STATE_OFF) - await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_OFF - assert hass.states.get("binary_sensor.test_off").state == STATE_ON + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON - hass.states.async_set("sensor.test_state", STATE_ON) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_OFF) await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_OFF - assert hass.states.get("binary_sensor.test_off").state == STATE_ON - hass.states.async_set("sensor.test_state", STATE_OFF) + assert hass.states.get(TEST_ENTITY_ID).state == STATE_OFF + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_OFF - assert hass.states.get("binary_sensor.test_off").state == STATE_ON + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_OFF + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_OFF) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_OFF freezer.tick(timedelta(seconds=5)) async_fire_time_changed(hass) await hass.async_block_till_done() - assert hass.states.get("binary_sensor.test_on").state == STATE_OFF - assert hass.states.get("binary_sensor.test_off").state == STATE_OFF + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_OFF -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "extra_config", "attribute"), [ ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "friendly_name": "virtual thingy", - "value_template": "true", - "device_class": "motion", - "delay_off": 5, - }, - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test", - ), - ( - { - "template": { - "binary_sensor": { - "name": "virtual thingy", - "state": "true", - "device_class": "motion", - "delay_off": 5, - }, - }, - }, - template.DOMAIN, - "binary_sensor.virtual_thingy", - ), + 1, + "{{ is_state('binary_sensor.test_state', 'on') }}", + {"device_class": "motion"}, + "delay_off", + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_available_without_availability_template( - hass: HomeAssistant, entity_id: str -) -> None: +@pytest.mark.parametrize( + "style", + [ + ConfigurationStyle.LEGACY, + ConfigurationStyle.MODERN, + ConfigurationStyle.TRIGGER, + ], +) +@pytest.mark.parametrize( + "attribute_value", + [ + 5, + "{{ dict(seconds=10 / 2) }}", + '{{ dict(seconds=states("sensor.test_attribute") | int(0)) }}', + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_delay_off(hass: HomeAssistant, freezer: FrozenDateTimeFactory) -> None: + """Test binary sensor template delay off.""" + assert hass.states.get(TEST_ENTITY_ID).state != STATE_ON + + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, 5) + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON + + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_OFF) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_OFF) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_ON + + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state == STATE_OFF + + +@pytest.mark.parametrize( + ("count", "state_template", "extra_config"), + [ + ( + 1, + "{{ True }}", + { + "device_class": "motion", + "delay_off": 5, + }, + ) + ], +) +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], +) +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_available_without_availability_template(hass: HomeAssistant) -> None: """Ensure availability is true without an availability_template.""" - state = hass.states.get(entity_id) + state = hass.states.get(TEST_ENTITY_ID) assert state.state != STATE_UNAVAILABLE assert state.attributes[ATTR_DEVICE_CLASS] == "motion" -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), + ("count", "state_template", "attribute_value", "extra_config"), [ ( + 1, + "{{ True }}", + "{{ is_state('binary_sensor.test_availability','on') }}", { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "friendly_name": "virtual thingy", - "value_template": "true", - "device_class": "motion", - "delay_off": 5, - "availability_template": "{{ is_state('sensor.test_state','on') }}", - }, - }, - }, + "device_class": "motion", + "delay_off": 5, }, - binary_sensor.DOMAIN, - "binary_sensor.test", - ), - ( - { - "template": { - "binary_sensor": { - "name": "virtual thingy", - "state": "true", - "device_class": "motion", - "delay_off": 5, - "availability": "{{ is_state('sensor.test_state','on') }}", - }, - }, - }, - template.DOMAIN, - "binary_sensor.virtual_thingy", - ), + ) ], ) -@pytest.mark.usefixtures("start_ha") -async def test_availability_template(hass: HomeAssistant, entity_id: str) -> None: +@pytest.mark.parametrize( + ("style", "attribute"), + [ + (ConfigurationStyle.LEGACY, "availability_template"), + (ConfigurationStyle.MODERN, "availability"), + (ConfigurationStyle.TRIGGER, "availability"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_availability_template(hass: HomeAssistant) -> None: """Test availability template.""" - hass.states.async_set("sensor.test_state", STATE_OFF) + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, STATE_OFF) await hass.async_block_till_done() - assert hass.states.get(entity_id).state == STATE_UNAVAILABLE + assert hass.states.get(TEST_ENTITY_ID).state == STATE_UNAVAILABLE - hass.states.async_set("sensor.test_state", STATE_ON) + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, STATE_ON) await hass.async_block_till_done() - state = hass.states.get(entity_id) + state = hass.states.get(TEST_ENTITY_ID) assert state.state != STATE_UNAVAILABLE assert state.attributes[ATTR_DEVICE_CLASS] == "motion" -@pytest.mark.parametrize(("count", "domain"), [(1, binary_sensor.DOMAIN)]) @pytest.mark.parametrize( - "config", + ("count", "state_template", "attribute_value", "extra_config"), + [(1, "{{ True }}", "{{ x - 12 }}", {})], +) +@pytest.mark.parametrize( + ("style", "attribute"), [ - { - "binary_sensor": { - "platform": "template", - "sensors": { - "invalid_template": { - "value_template": "{{ states.binary_sensor.test_sensor }}", - "attribute_templates": { - "test_attribute": "{{ states.binary_sensor.unknown.attributes.picture }}" - }, - } - }, - }, - }, + (ConfigurationStyle.LEGACY, "availability_template"), + (ConfigurationStyle.MODERN, "availability"), + (ConfigurationStyle.TRIGGER, "availability"), ], ) -@pytest.mark.usefixtures("start_ha") -async def test_invalid_attribute_template( - hass: HomeAssistant, caplog_setup_text: str -) -> None: - """Test that errors are logged if rendering template fails.""" - hass.states.async_set("binary_sensor.test_sensor", STATE_ON) - assert len(hass.states.async_all()) == 2 - assert ("test_attribute") in caplog_setup_text - assert ("TemplateError") in caplog_setup_text - - -@pytest.mark.parametrize(("count", "domain"), [(1, binary_sensor.DOMAIN)]) -@pytest.mark.parametrize( - "config", - [ - { - "binary_sensor": { - "platform": "template", - "sensors": { - "my_sensor": { - "value_template": "{{ states.binary_sensor.test_sensor }}", - "availability_template": "{{ x - 12 }}", - }, - }, - }, - }, - ], -) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") async def test_invalid_availability_template_keeps_component_available( - hass: HomeAssistant, caplog_setup_text: str + hass: HomeAssistant, caplog_setup_text: str, caplog: pytest.LogCaptureFixture ) -> None: """Test that an invalid availability keeps the device available.""" - assert hass.states.get("binary_sensor.my_sensor").state != STATE_UNAVAILABLE - assert "UndefinedError: 'x' is undefined" in caplog_setup_text + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, STATE_OFF) + await hass.async_block_till_done() + + assert hass.states.get(TEST_ENTITY_ID).state != STATE_UNAVAILABLE + text = "UndefinedError: 'x' is undefined" + assert text in caplog_setup_text or text in caplog.text async def test_no_update_template_match_all(hass: HomeAssistant) -> None: @@ -896,172 +919,145 @@ async def test_no_update_template_match_all(hass: HomeAssistant) -> None: assert hass.states.get("binary_sensor.all_attribute").state == STATE_OFF -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) +@pytest.mark.parametrize(("count", "extra_template_options"), [(1, {})]) @pytest.mark.parametrize( - "config", + ("config", "style"), [ - { - "template": { - "unique_id": "group-id", - "binary_sensor": { - "name": "top-level", - "unique_id": "sensor-id", - "state": STATE_ON, + ( + { + "test_template_01": { + "value_template": "{{ True }}", + **UNIQUE_ID_CONFIG, + }, + "test_template_02": { + "value_template": "{{ True }}", + **UNIQUE_ID_CONFIG, }, }, - "binary_sensor": { - "platform": "template", - "sensors": { - "test_template_cover_01": { - "unique_id": "not-so-unique-anymore", - "value_template": "{{ true }}", - }, - "test_template_cover_02": { - "unique_id": "not-so-unique-anymore", - "value_template": "{{ false }}", - }, + ConfigurationStyle.LEGACY, + ), + ( + [ + { + "name": "test_template_01", + "state": "{{ True }}", + **UNIQUE_ID_CONFIG, }, - }, - }, + { + "name": "test_template_02", + "state": "{{ True }}", + **UNIQUE_ID_CONFIG, + }, + ], + ConfigurationStyle.MODERN, + ), + ( + [ + { + "name": "test_template_01", + "state": "{{ True }}", + **UNIQUE_ID_CONFIG, + }, + { + "name": "test_template_02", + "state": "{{ True }}", + **UNIQUE_ID_CONFIG, + }, + ], + ConfigurationStyle.TRIGGER, + ), ], ) -@pytest.mark.usefixtures("start_ha") -async def test_unique_id( +@pytest.mark.usefixtures("setup_base_binary_sensor") +async def test_unique_id(hass: HomeAssistant) -> None: + """Test unique_id option only creates one fan per id.""" + assert len(hass.states.async_all()) == 1 + + +@pytest.mark.parametrize( + ("count", "config", "extra_template_options"), + [ + ( + 1, + [ + { + "name": "test_a", + "state": "{{ True }}", + "unique_id": "a", + }, + { + "name": "test_b", + "state": "{{ True }}", + "unique_id": "b", + }, + ], + {"unique_id": "x"}, + ) + ], +) +@pytest.mark.parametrize( + "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] +) +@pytest.mark.usefixtures("setup_base_binary_sensor") +async def test_nested_unique_id( hass: HomeAssistant, entity_registry: er.EntityRegistry ) -> None: - """Test unique_id option only creates one binary sensor per id.""" - assert len(hass.states.async_all()) == 2 + """Test a template unique_id propagates to switch unique_ids.""" + assert len(hass.states.async_all("binary_sensor")) == 2 - assert len(entity_registry.entities) == 2 - assert entity_registry.async_get_entity_id( - "binary_sensor", "template", "group-id-sensor-id" - ) - assert entity_registry.async_get_entity_id( - "binary_sensor", "template", "not-so-unique-anymore" - ) + entry = entity_registry.async_get("binary_sensor.test_a") + assert entry + assert entry.unique_id == "x-a" + + entry = entity_registry.async_get("binary_sensor.test_b") + assert entry + assert entry.unique_id == "x-b" -@pytest.mark.parametrize(("count", "domain"), [(1, binary_sensor.DOMAIN)]) @pytest.mark.parametrize( - "config", + ("count", "state_template", "attribute_value", "extra_config"), + [(1, "{{ 1 == 1 }}", "{{ states.sensor.test_attribute.state }}", {})], +) +@pytest.mark.parametrize( + ("style", "attribute", "initial_state"), [ - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "friendly_name": "virtual thingy", - "value_template": "True", - "icon_template": "{{ states.sensor.test_state.state }}", - "device_class": "motion", - "delay_on": 5, - }, - }, - }, - }, + (ConfigurationStyle.LEGACY, "icon_template", ""), + (ConfigurationStyle.MODERN, "icon", ""), ], ) -@pytest.mark.usefixtures("start_ha") -async def test_template_validation_error( - hass: HomeAssistant, caplog: pytest.LogCaptureFixture +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_template_icon_validation_error( + hass: HomeAssistant, initial_state: str, caplog: pytest.LogCaptureFixture ) -> None: """Test binary sensor template delay on.""" caplog.set_level(logging.ERROR) - state = hass.states.get("binary_sensor.test") - assert state.attributes.get("icon") == "" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes.get("icon") == initial_state - hass.states.async_set("sensor.test_state", "mdi:check") + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, "mdi:check") await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") - assert state.attributes.get("icon") == "mdi:check" + state = hass.states.get(TEST_ENTITY_ID) + assert state.attributes["icon"] == "mdi:check" - hass.states.async_set("sensor.test_state", "invalid_icon") + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, "invalid_icon") await hass.async_block_till_done() + assert len(caplog.records) == 1 assert caplog.records[0].message.startswith( "Error validating template result 'invalid_icon' from template" ) - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.attributes.get("icon") is None -@pytest.mark.parametrize("count", [1]) @pytest.mark.parametrize( - ("config", "domain", "entity_id"), - [ - ( - { - "binary_sensor": { - "platform": "template", - "sensors": { - "test": { - "availability_template": "{{ is_state('sensor.bla', 'available') }}", - "entity_picture_template": "{{ 'blib' + 'blub' }}", - "icon_template": "mdi:{{ 1+2 }}", - "friendly_name": "{{ 'My custom ' + 'sensor' }}", - "value_template": "{{ true }}", - }, - }, - }, - }, - binary_sensor.DOMAIN, - "binary_sensor.test", - ), - ( - { - "template": { - "binary_sensor": { - "availability": "{{ is_state('sensor.bla', 'available') }}", - "picture": "{{ 'blib' + 'blub' }}", - "icon": "mdi:{{ 1+2 }}", - "name": "{{ 'My custom ' + 'sensor' }}", - "state": "{{ true }}", - }, - }, - }, - template.DOMAIN, - "binary_sensor.my_custom_sensor", - ), - ], + ("count", "state_template"), [(1, "{{ states.binary_sensor.test_state.state }}")] ) -@pytest.mark.usefixtures("start_ha") -async def test_availability_icon_picture(hass: HomeAssistant, entity_id: str) -> None: - """Test name, icon and picture templates are rendered at setup.""" - state = hass.states.get(entity_id) - assert state.state == "unavailable" - assert state.attributes == { - "entity_picture": "blibblub", - "friendly_name": "My custom sensor", - "icon": "mdi:3", - } - - hass.states.async_set("sensor.bla", "available") - await hass.async_block_till_done() - - state = hass.states.get(entity_id) - assert state.state == "on" - assert state.attributes == { - "entity_picture": "blibblub", - "friendly_name": "My custom sensor", - "icon": "mdi:3", - } - - -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) @pytest.mark.parametrize( - "config", - [ - { - "template": { - "binary_sensor": { - "name": "test", - "state": "{{ states.sensor.test_state.state }}", - }, - }, - }, - ], + "style", + [ConfigurationStyle.LEGACY, ConfigurationStyle.MODERN], ) @pytest.mark.parametrize( ("extra_config", "source_state", "restored_state", "initial_state"), @@ -1107,8 +1103,8 @@ async def test_availability_icon_picture(hass: HomeAssistant, entity_id: str) -> async def test_restore_state( hass: HomeAssistant, count: int, - domain: str, - config: ConfigType, + style: ConfigurationStyle, + state_template: str, extra_config: ConfigType, source_state: str | None, restored_state: str, @@ -1116,199 +1112,33 @@ async def test_restore_state( ) -> None: """Test restoring template binary sensor.""" - hass.states.async_set("sensor.test_state", source_state) - fake_state = State( - "binary_sensor.test", - restored_state, - {}, - ) + hass.states.async_set(TEST_STATE_ENTITY_ID, source_state) + await hass.async_block_till_done() + + fake_state = State(TEST_ENTITY_ID, restored_state, {}) mock_restore_cache(hass, (fake_state,)) - config = deepcopy(config) - config["template"]["binary_sensor"].update(**extra_config) - with assert_setup_component(count, domain): - assert await async_setup_component( - hass, - domain, - config, - ) - await hass.async_block_till_done() + await async_setup_binary_sensor(hass, count, style, state_template, extra_config) - context = Context() - hass.bus.async_fire("test_event", {"beer": 2}, context=context) - await hass.async_block_till_done() - - await hass.async_start() - await hass.async_block_till_done() - - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == initial_state -@pytest.mark.parametrize(("count", "domain"), [(2, "template")]) @pytest.mark.parametrize( - "config", + ("count", "style", "state_template", "extra_config"), [ - { - "template": [ - {"invalid": "config"}, - # Config after invalid should still be set up - { - "unique_id": "listening-test-event", - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensors": { - "hello": { - "friendly_name": "Hello Name", - "unique_id": "hello_name-id", - "device_class": "battery", - "value_template": _BEER_TRIGGER_VALUE_TEMPLATE, - "entity_picture_template": "{{ '/local/dogs.png' }}", - "icon_template": "{{ 'mdi:pirate' }}", - "attribute_templates": { - "plus_one": "{{ trigger.event.data.beer + 1 }}" - }, - }, - }, - "binary_sensor": [ - { - "name": "via list", - "unique_id": "via_list-id", - "device_class": "battery", - "state": _BEER_TRIGGER_VALUE_TEMPLATE, - "picture": "{{ '/local/dogs.png' }}", - "icon": "{{ 'mdi:pirate' }}", - "attributes": { - "plus_one": "{{ trigger.event.data.beer + 1 }}", - "another": "{{ trigger.event.data.uno_mas or 1 }}", - }, - } - ], - }, - { - "trigger": [], - "binary_sensors": { - "bare_minimum": { - "value_template": "{{ trigger.event.data.beer == 1 }}" - }, - }, - }, - ], - }, - ], -) -@pytest.mark.parametrize( - ( - "beer_count", - "final_state", - "icon_attr", - "entity_picture_attr", - "plus_one_attr", - "another_attr", - "another_attr_update", - ), - [ - (2, STATE_ON, "mdi:pirate", "/local/dogs.png", 3, 1, "si"), - (1, STATE_OFF, "mdi:pirate", "/local/dogs.png", 2, 1, "si"), - (0, STATE_UNKNOWN, "mdi:pirate", "/local/dogs.png", 1, 1, "si"), - (-1, STATE_UNAVAILABLE, None, None, None, None, None), - ], -) -@pytest.mark.usefixtures("start_ha") -async def test_trigger_entity( - hass: HomeAssistant, - beer_count: int, - final_state: str, - icon_attr: str | None, - entity_picture_attr: str | None, - plus_one_attr: int | None, - another_attr: int | None, - another_attr_update: str | None, - entity_registry: er.EntityRegistry, -) -> None: - """Test trigger entity works.""" - await hass.async_block_till_done() - state = hass.states.get("binary_sensor.hello_name") - assert state is not None - assert state.state == STATE_UNKNOWN - - state = hass.states.get("binary_sensor.bare_minimum") - assert state is not None - assert state.state == STATE_UNKNOWN - - context = Context() - hass.bus.async_fire("test_event", {"beer": beer_count}, context=context) - await hass.async_block_till_done() - - state = hass.states.get("binary_sensor.hello_name") - assert state.state == final_state - assert state.attributes.get("device_class") == "battery" - assert state.attributes.get("icon") == icon_attr - assert state.attributes.get("entity_picture") == entity_picture_attr - assert state.attributes.get("plus_one") == plus_one_attr - assert state.context is context - - assert len(entity_registry.entities) == 2 - assert ( - entity_registry.entities["binary_sensor.hello_name"].unique_id - == "listening-test-event-hello_name-id" - ) - assert ( - entity_registry.entities["binary_sensor.via_list"].unique_id - == "listening-test-event-via_list-id" - ) - - state = hass.states.get("binary_sensor.via_list") - assert state.state == final_state - assert state.attributes.get("device_class") == "battery" - assert state.attributes.get("icon") == icon_attr - assert state.attributes.get("entity_picture") == entity_picture_attr - assert state.attributes.get("plus_one") == plus_one_attr - assert state.attributes.get("another") == another_attr - assert state.context is context - - # Even if state itself didn't change, attributes might have changed - hass.bus.async_fire("test_event", {"beer": beer_count, "uno_mas": "si"}) - await hass.async_block_till_done() - state = hass.states.get("binary_sensor.via_list") - assert state.state == final_state - assert state.attributes.get("another") == another_attr_update - - # Check None values - hass.bus.async_fire("test_event", {"beer": 0}) - await hass.async_block_till_done() - state = hass.states.get("binary_sensor.hello_name") - assert state.state == STATE_UNKNOWN - state = hass.states.get("binary_sensor.via_list") - assert state.state == STATE_UNKNOWN - - # Check impossible values - hass.bus.async_fire("test_event", {"beer": -1}) - await hass.async_block_till_done() - state = hass.states.get("binary_sensor.hello_name") - assert state.state == STATE_UNAVAILABLE - state = hass.states.get("binary_sensor.via_list") - assert state.state == STATE_UNAVAILABLE - - -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) -@pytest.mark.parametrize( - "config", - [ - { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": _BEER_TRIGGER_VALUE_TEMPLATE, - "device_class": "motion", - "delay_on": '{{ ({ "seconds": 6 / 2 }) }}', - "auto_off": '{{ ({ "seconds": 1 + 1 }) }}', - }, + ( + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + { + "device_class": "motion", + "delay_on": '{{ ({ "seconds": 6 / 2 }) }}', + "auto_off": '{{ ({ "seconds": 1 + 1 }) }}', }, - }, + ) ], ) -@pytest.mark.usefixtures("start_ha") @pytest.mark.parametrize( ("beer_count", "first_state", "second_state", "final_state"), [ @@ -1318,7 +1148,8 @@ async def test_trigger_entity( (-1, STATE_UNAVAILABLE, STATE_UNAVAILABLE, STATE_UNAVAILABLE), ], ) -async def test_template_with_trigger_templated_delay_on( +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_template_with_trigger_templated_auto_off( hass: HomeAssistant, beer_count: int, first_state: str, @@ -1326,8 +1157,8 @@ async def test_template_with_trigger_templated_delay_on( final_state: str, freezer: FrozenDateTimeFactory, ) -> None: - """Test binary sensor template with template delay on.""" - state = hass.states.get("binary_sensor.test") + """Test binary sensor template with template auto off.""" + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_UNKNOWN context = Context() @@ -1335,7 +1166,7 @@ async def test_template_with_trigger_templated_delay_on( await hass.async_block_till_done() # State should still be unknown - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == first_state # Now wait for the on delay @@ -1343,7 +1174,7 @@ async def test_template_with_trigger_templated_delay_on( async_fire_time_changed(hass) await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == second_state # Now wait for the auto-off @@ -1351,52 +1182,128 @@ async def test_template_with_trigger_templated_delay_on( async_fire_time_changed(hass) await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == final_state -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) @pytest.mark.parametrize( - ("config", "delay_state"), + ("count", "style", "state_template", "extra_config"), [ ( + 1, + ConfigurationStyle.TRIGGER, + "{{ True }}", { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": "{{ trigger.event.data.beer == 2 }}", - "device_class": "motion", - "delay_on": '{{ ({ "seconds": 10 }) }}', - }, - }, + "device_class": "motion", + "auto_off": '{{ ({ "seconds": 5 }) }}', }, - STATE_ON, - ), - ( - { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": "{{ trigger.event.data.beer != 2 }}", - "device_class": "motion", - "delay_off": '{{ ({ "seconds": 10 }) }}', - }, - }, - }, - STATE_OFF, - ), + ) ], ) -@pytest.mark.usefixtures("start_ha") +@pytest.mark.usefixtures("setup_binary_sensor") +async def test_template_with_trigger_auto_off_cancel( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, +) -> None: + """Test binary sensor template with template auto off.""" + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_UNKNOWN + + context = Context() + hass.bus.async_fire("test_event", {}, context=context) + await hass.async_block_till_done() + + # State should still be unknown + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_ON + + # Now wait for the on delay + freezer.tick(timedelta(seconds=4)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_ON + + hass.bus.async_fire("test_event", {}, context=context) + await hass.async_block_till_done() + + # Now wait for the on delay + freezer.tick(timedelta(seconds=4)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_ON + + # Now wait for the auto-off + freezer.tick(timedelta(seconds=2)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_OFF + + +@pytest.mark.parametrize( + ("count", "style", "extra_config", "attribute_value"), + [ + ( + 1, + ConfigurationStyle.TRIGGER, + {"device_class": "motion"}, + "{{ states('sensor.test_attribute') }}", + ) + ], +) +@pytest.mark.parametrize( + ("state_template", "attribute"), + [ + ("{{ True }}", "delay_on"), + ("{{ False }}", "delay_off"), + ("{{ True }}", "auto_off"), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") +async def test_trigger_with_negative_time_periods( + hass: HomeAssistant, attribute: str, caplog: pytest.LogCaptureFixture +) -> None: + """Test binary sensor template with template negative time periods.""" + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_UNKNOWN + + hass.states.async_set(TEST_ATTRIBUTE_ENTITY_ID, "-5") + await hass.async_block_till_done() + + assert f"Error rendering {attribute} template: " in caplog.text + + +@pytest.mark.parametrize( + ("count", "style", "extra_config", "attribute_value"), + [ + ( + 1, + ConfigurationStyle.TRIGGER, + {"device_class": "motion"}, + "{{ ({ 'seconds': 10 }) }}", + ) + ], +) +@pytest.mark.parametrize( + ("state_template", "attribute", "delay_state"), + [ + ("{{ trigger.event.data.beer == 2 }}", "delay_on", STATE_ON), + ("{{ trigger.event.data.beer != 2 }}", "delay_off", STATE_OFF), + ], +) +@pytest.mark.usefixtures("setup_single_attribute_binary_sensor") async def test_trigger_template_delay_with_multiple_triggers( hass: HomeAssistant, delay_state: str, freezer: FrozenDateTimeFactory ) -> None: """Test trigger based binary sensor with multiple triggers occurring during the delay.""" for _ in range(10): # State should still be unknown - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_UNKNOWN hass.bus.async_fire("test_event", {"beer": 2}, context=Context()) @@ -1406,32 +1313,10 @@ async def test_trigger_template_delay_with_multiple_triggers( async_fire_time_changed(hass) await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == delay_state -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) -@pytest.mark.parametrize( - "config", - [ - { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": _BEER_TRIGGER_VALUE_TEMPLATE, - "device_class": "motion", - "picture": "{{ '/local/dogs.png' }}", - "icon": "{{ 'mdi:pirate' }}", - "attributes": { - "plus_one": "{{ trigger.event.data.beer + 1 }}", - "another": "{{ trigger.event.data.uno_mas or 1 }}", - }, - }, - }, - }, - ], -) @pytest.mark.parametrize( ("restored_state", "initial_state", "initial_attributes"), [ @@ -1443,9 +1328,6 @@ async def test_trigger_template_delay_with_multiple_triggers( ) async def test_trigger_entity_restore_state( hass: HomeAssistant, - count: int, - domain: str, - config: ConfigType, restored_state: str, initial_state: str, initial_attributes: list[str], @@ -1459,7 +1341,7 @@ async def test_trigger_entity_restore_state( } fake_state = State( - "binary_sensor.test", + TEST_ENTITY_ID, restored_state, restored_attributes, ) @@ -1467,18 +1349,23 @@ async def test_trigger_entity_restore_state( "auto_off_time": None, } 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 async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + { + "device_class": "motion", + "picture": "{{ '/local/dogs.png' }}", + "icon": "{{ 'mdi:pirate' }}", + "attributes": { + "plus_one": "{{ trigger.event.data.beer + 1 }}", + "another": "{{ trigger.event.data.uno_mas or 1 }}", + }, + }, + ) - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == initial_state for attr, value in restored_attributes.items(): if attr in initial_attributes: @@ -1490,7 +1377,7 @@ async def test_trigger_entity_restore_state( hass.bus.async_fire("test_event", {"beer": 2}) await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_ON assert state.attributes["icon"] == "mdi:pirate" assert state.attributes["entity_picture"] == "/local/dogs.png" @@ -1498,40 +1385,16 @@ async def test_trigger_entity_restore_state( assert state.attributes["another"] == 1 -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) -@pytest.mark.parametrize( - "config", - [ - { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": _BEER_TRIGGER_VALUE_TEMPLATE, - "device_class": "motion", - "auto_off": '{{ ({ "seconds": 1 + 1 }) }}', - }, - }, - }, - ], -) @pytest.mark.parametrize("restored_state", [STATE_ON, STATE_OFF]) async def test_trigger_entity_restore_state_auto_off( hass: HomeAssistant, - count: int, - domain: str, - config: ConfigType, restored_state: str, freezer: FrozenDateTimeFactory, ) -> None: """Test restoring trigger template binary sensor.""" freezer.move_to("2022-02-02 12:02:00+00:00") - fake_state = State( - "binary_sensor.test", - restored_state, - {}, - ) + fake_state = State(TEST_ENTITY_ID, restored_state, {}) fake_extra_data = { "auto_off_time": { "__type": "", @@ -1539,18 +1402,15 @@ async def test_trigger_entity_restore_state_auto_off( }, } 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 async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + {"device_class": "motion", "auto_off": '{{ ({ "seconds": 1 + 1 }) }}'}, + ) - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == restored_state # Now wait for the auto-off @@ -1558,42 +1418,18 @@ async def test_trigger_entity_restore_state_auto_off( await hass.async_block_till_done() await hass.async_block_till_done() - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_OFF -@pytest.mark.parametrize(("count", "domain"), [(1, "template")]) -@pytest.mark.parametrize( - "config", - [ - { - "template": { - "trigger": {"platform": "event", "event_type": "test_event"}, - "binary_sensor": { - "name": "test", - "state": _BEER_TRIGGER_VALUE_TEMPLATE, - "device_class": "motion", - "auto_off": '{{ ({ "seconds": 1 + 1 }) }}', - }, - }, - }, - ], -) async def test_trigger_entity_restore_state_auto_off_expired( hass: HomeAssistant, - count: int, - domain: str, - config: ConfigType, freezer: FrozenDateTimeFactory, ) -> None: """Test restoring trigger template binary sensor.""" freezer.move_to("2022-02-02 12:02:00+00:00") - fake_state = State( - "binary_sensor.test", - STATE_ON, - {}, - ) + fake_state = State(TEST_ENTITY_ID, STATE_ON, {}) fake_extra_data = { "auto_off_time": { "__type": "", @@ -1601,21 +1437,132 @@ async def test_trigger_entity_restore_state_auto_off_expired( }, } 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 async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + {"device_class": "motion", "auto_off": '{{ ({ "seconds": 1 + 1 }) }}'}, + ) - await hass.async_block_till_done() - await hass.async_start() - await hass.async_block_till_done() - - state = hass.states.get("binary_sensor.test") + state = hass.states.get(TEST_ENTITY_ID) assert state.state == STATE_OFF +async def test_saving_auto_off( + hass: HomeAssistant, + hass_storage: dict[str, Any], + freezer: FrozenDateTimeFactory, +) -> None: + """Test we restore state integration.""" + restored_attributes = { + "entity_picture": "/local/cats.png", + "icon": "mdi:ship", + "plus_one": 55, + } + + freezer.move_to("2022-02-02 02:02:00+00:00") + fake_extra_data = { + "auto_off_time": { + "__type": "", + "isoformat": "2022-02-02T02:02:02+00:00", + }, + } + await async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + "{{ True }}", + { + "device_class": "motion", + "auto_off": '{{ ({ "seconds": 1 + 1 }) }}', + "attributes": restored_attributes, + }, + ) + + hass.states.async_set(TEST_STATE_ENTITY_ID, STATE_ON) + await hass.async_block_till_done() + + await async_mock_restore_state_shutdown_restart(hass) + + assert len(hass_storage[RESTORE_STATE_KEY]["data"]) == 1 + state = hass_storage[RESTORE_STATE_KEY]["data"][0]["state"] + assert state["entity_id"] == TEST_ENTITY_ID + + for attr, value in restored_attributes.items(): + assert state["attributes"][attr] == value + + extra_data = hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"] + assert extra_data == fake_extra_data + + +async def test_trigger_entity_restore_invalid_auto_off_time_data( + hass: HomeAssistant, + hass_storage: dict[str, Any], + freezer: FrozenDateTimeFactory, +) -> None: + """Test restoring trigger template binary sensor.""" + + freezer.move_to("2022-02-02 12:02:00+00:00") + fake_state = State(TEST_ENTITY_ID, STATE_ON, {}) + fake_extra_data = { + "auto_off_time": { + "_type": "", + "isoformat": datetime(2022, 2, 2, 12, 2, 0, tzinfo=UTC).isoformat(), + }, + } + mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) + await async_mock_restore_state_shutdown_restart(hass) + + extra_data = hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"] + assert extra_data == fake_extra_data + + await async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + {"device_class": "motion", "auto_off": '{{ ({ "seconds": 1 + 1 }) }}'}, + ) + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_UNKNOWN + + +async def test_trigger_entity_restore_invalid_auto_off_time_key( + hass: HomeAssistant, + hass_storage: dict[str, Any], + freezer: FrozenDateTimeFactory, +) -> None: + """Test restoring trigger template binary sensor.""" + + freezer.move_to("2022-02-02 12:02:00+00:00") + fake_state = State(TEST_ENTITY_ID, STATE_ON, {}) + fake_extra_data = { + "auto_off_timex": { + "__type": "", + "isoformat": datetime(2022, 2, 2, 12, 2, 0, tzinfo=UTC).isoformat(), + }, + } + mock_restore_cache_with_extra_data(hass, ((fake_state, fake_extra_data),)) + await async_mock_restore_state_shutdown_restart(hass) + + extra_data = hass_storage[RESTORE_STATE_KEY]["data"][0]["extra_data"] + assert "auto_off_timex" in extra_data + assert extra_data == fake_extra_data + + await async_setup_binary_sensor( + hass, + 1, + ConfigurationStyle.TRIGGER, + _BEER_TRIGGER_VALUE_TEMPLATE, + {"device_class": "motion", "auto_off": '{{ ({ "seconds": 1 + 1 }) }}'}, + ) + + state = hass.states.get(TEST_ENTITY_ID) + assert state.state == STATE_UNKNOWN + + async def test_device_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, @@ -1653,3 +1600,16 @@ async def test_device_id( template_entity = entity_registry.async_get("binary_sensor.my_template") assert template_entity is not None assert template_entity.device_id == device_entry.id + + +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, + binary_sensor.DOMAIN, + {"name": "My template", "state": "{{ 'on' }}"}, + ) + assert state["state"] == "on" diff --git a/tests/components/template/test_number.py b/tests/components/template/test_number.py index a15ae1e46c0..21dea28b73f 100644 --- a/tests/components/template/test_number.py +++ b/tests/components/template/test_number.py @@ -35,9 +35,10 @@ from homeassistant.core import Context, HomeAssistant, ServiceCall from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.setup import async_setup_component -from .conftest import ConfigurationStyle +from .conftest import ConfigurationStyle, async_get_flow_preview_state from tests.common import MockConfigEntry, assert_setup_component, async_capture_events +from tests.typing import WebSocketGenerator _TEST_OBJECT_ID = "template_number" _TEST_NUMBER = f"number.{_TEST_OBJECT_ID}" @@ -608,3 +609,24 @@ async def test_empty_action_config(hass: HomeAssistant, setup_number) -> None: state = hass.states.get(_TEST_NUMBER) assert float(state.state) == 4 + + +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, + number.DOMAIN, + { + "name": "My template", + "min": 0.0, + "max": 100.0, + **TEST_REQUIRED, + }, + ) + + assert state["state"] == "0.0" diff --git a/tests/components/template/test_select.py b/tests/components/template/test_select.py index 5e29993f0f6..6971d41750d 100644 --- a/tests/components/template/test_select.py +++ b/tests/components/template/test_select.py @@ -28,6 +28,7 @@ from homeassistant.const import ( ATTR_ICON, CONF_ENTITY_ID, CONF_ICON, + STATE_UNAVAILABLE, STATE_UNKNOWN, ) from homeassistant.core import Context, HomeAssistant, ServiceCall @@ -43,11 +44,15 @@ _TEST_SELECT = f"select.{_TEST_OBJECT_ID}" # Represent for select's current_option _OPTION_INPUT_SELECT = "input_select.option" TEST_STATE_ENTITY_ID = "select.test_state" - +TEST_AVAILABILITY_ENTITY_ID = "binary_sensor.test_availability" TEST_STATE_TRIGGER = { "trigger": { "trigger": "state", - "entity_id": [_OPTION_INPUT_SELECT, TEST_STATE_ENTITY_ID], + "entity_id": [ + _OPTION_INPUT_SELECT, + TEST_STATE_ENTITY_ID, + TEST_AVAILABILITY_ENTITY_ID, + ], }, "variables": {"triggering_entity": "{{ trigger.entity_id }}"}, "action": [ @@ -201,20 +206,6 @@ async def test_multiple_configs(hass: HomeAssistant) -> None: async def test_missing_required_keys(hass: HomeAssistant) -> None: """Test: missing required fields will fail.""" - with assert_setup_component(0, "template"): - assert await setup.async_setup_component( - hass, - "template", - { - "template": { - "select": { - "select_option": {"service": "script.select_option"}, - "options": "{{ ['a', 'b'] }}", - } - } - }, - ) - with assert_setup_component(0, "select"): assert await setup.async_setup_component( hass, @@ -559,3 +550,98 @@ async def test_empty_action_config(hass: HomeAssistant, setup_select) -> None: state = hass.states.get(_TEST_SELECT) assert state.state == "a" + + +@pytest.mark.parametrize( + ("count", "select_config"), + [ + ( + 1, + { + "options": "{{ ['test', 'yes', 'no'] }}", + "select_option": [], + }, + ) + ], +) +@pytest.mark.parametrize( + "style", + [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER], +) +@pytest.mark.usefixtures("setup_select") +async def test_optimistic(hass: HomeAssistant) -> None: + """Test configuration with optimistic state.""" + + state = hass.states.get(_TEST_SELECT) + assert state.state == STATE_UNKNOWN + + # Ensure Trigger template entities update. + hass.states.async_set(TEST_STATE_ENTITY_ID, "anything") + await hass.async_block_till_done() + + await hass.services.async_call( + select.DOMAIN, + select.SERVICE_SELECT_OPTION, + {ATTR_ENTITY_ID: _TEST_SELECT, "option": "test"}, + blocking=True, + ) + + state = hass.states.get(_TEST_SELECT) + assert state.state == "test" + + await hass.services.async_call( + select.DOMAIN, + select.SERVICE_SELECT_OPTION, + {ATTR_ENTITY_ID: _TEST_SELECT, "option": "yes"}, + blocking=True, + ) + + state = hass.states.get(_TEST_SELECT) + assert state.state == "yes" + + +@pytest.mark.parametrize( + ("count", "select_config"), + [ + ( + 1, + { + "options": "{{ ['test', 'yes', 'no'] }}", + "select_option": [], + "state": "{{ states('select.test_state') }}", + "availability": "{{ is_state('binary_sensor.test_availability', 'on') }}", + }, + ) + ], +) +@pytest.mark.parametrize( + "style", [ConfigurationStyle.MODERN, ConfigurationStyle.TRIGGER] +) +@pytest.mark.usefixtures("setup_select") +async def test_availability(hass: HomeAssistant) -> None: + """Test configuration with optimistic state.""" + + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, "on") + hass.states.async_set(TEST_STATE_ENTITY_ID, "test") + await hass.async_block_till_done() + + state = hass.states.get(_TEST_SELECT) + assert state.state == "test" + + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, "off") + await hass.async_block_till_done() + + state = hass.states.get(_TEST_SELECT) + assert state.state == STATE_UNAVAILABLE + + hass.states.async_set(TEST_STATE_ENTITY_ID, "yes") + await hass.async_block_till_done() + + state = hass.states.get(_TEST_SELECT) + assert state.state == STATE_UNAVAILABLE + + hass.states.async_set(TEST_AVAILABILITY_ENTITY_ID, "on") + await hass.async_block_till_done() + + state = hass.states.get(_TEST_SELECT) + assert state.state == "yes" diff --git a/tests/components/template/test_sensor.py b/tests/components/template/test_sensor.py index eb4f6c3596b..e89e98601d6 100644 --- a/tests/components/template/test_sensor.py +++ b/tests/components/template/test_sensor.py @@ -30,6 +30,8 @@ from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.setup import ATTR_COMPONENT, async_setup_component from homeassistant.util import dt as dt_util +from .conftest import async_get_flow_preview_state + from tests.common import ( MockConfigEntry, assert_setup_component, @@ -37,6 +39,7 @@ from tests.common import ( async_fire_time_changed, mock_restore_cache_with_extra_data, ) +from tests.conftest import WebSocketGenerator TEST_NAME = "sensor.test_template_sensor" @@ -2434,3 +2437,19 @@ async def test_device_id( template_entity = entity_registry.async_get("sensor.my_template") assert template_entity is not None assert template_entity.device_id == device_entry.id + + +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, + sensor.DOMAIN, + {"name": "My template", "state": "{{ 0.0 }}"}, + ) + + assert state["state"] == "0.0" diff --git a/tests/components/template/test_switch.py b/tests/components/template/test_switch.py index de6894c73a8..c6ed303af7b 100644 --- a/tests/components/template/test_switch.py +++ b/tests/components/template/test_switch.py @@ -8,7 +8,6 @@ from syrupy.assertion import SnapshotAssertion from homeassistant.components import switch, template from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN from homeassistant.components.template.switch import rewrite_legacy_to_modern_conf -from homeassistant.config_entries import SOURCE_USER from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, @@ -18,12 +17,11 @@ from homeassistant.const import ( STATE_UNAVAILABLE, ) from homeassistant.core import CoreState, HomeAssistant, ServiceCall, State -from homeassistant.data_entry_flow import FlowResultType from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.template import Template from homeassistant.setup import async_setup_component -from .conftest import ConfigurationStyle +from .conftest import ConfigurationStyle, async_get_flow_preview_state from tests.common import ( MockConfigEntry, @@ -396,37 +394,15 @@ async def test_flow_preview( hass_ws_client: WebSocketGenerator, ) -> None: """Test the config flow preview.""" - client = await hass_ws_client(hass) - result = await hass.config_entries.flow.async_init( - template.DOMAIN, context={"source": SOURCE_USER} + state = await async_get_flow_preview_state( + hass, + hass_ws_client, + switch.DOMAIN, + {"name": "My template", state_key: "{{ 'on' }}"}, ) - assert result["type"] is FlowResultType.MENU - result = await hass.config_entries.flow.async_configure( - result["flow_id"], - {"next_step_id": SWITCH_DOMAIN}, - ) - await hass.async_block_till_done() - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == SWITCH_DOMAIN - assert result["errors"] is None - assert result["preview"] == "template" - - await client.send_json_auto_id( - { - "type": "template/start_preview", - "flow_id": result["flow_id"], - "flow_type": "config_flow", - "user_input": {"name": "My template", state_key: "{{ 'on' }}"}, - } - ) - msg = await client.receive_json() - assert msg["success"] - assert msg["result"] is None - - msg = await client.receive_json() - assert msg["event"]["state"] == "on" + assert state["state"] == STATE_ON @pytest.mark.parametrize( diff --git a/tests/components/tesla_fleet/test_config_flow.py b/tests/components/tesla_fleet/test_config_flow.py index 4a8142a2d85..98806a27268 100644 --- a/tests/components/tesla_fleet/test_config_flow.py +++ b/tests/components/tesla_fleet/test_config_flow.py @@ -713,8 +713,11 @@ async def test_reauth_confirm_form(hass: HomeAssistant) -> None: ("domain", "expected_valid"), [ ("example.com", True), + ("exa-mple.com", True), ("test.example.com", True), + ("tes-t.example.com", True), ("sub.domain.example.org", True), + ("su-b.dom-ain.exam-ple.org", True), ("https://example.com", False), ("invalid-domain", False), ("", False), @@ -722,6 +725,8 @@ async def test_reauth_confirm_form(hass: HomeAssistant) -> None: ("example.", False), (".example.com", False), ("exam ple.com", False), + ("-example.com", False), + ("domain-.example.com", False), ], ) def test_is_valid_domain(domain: str, expected_valid: bool) -> None: diff --git a/tests/components/teslemetry/snapshots/test_sensor.ambr b/tests/components/teslemetry/snapshots/test_sensor.ambr index 57a0f49d949..1db8cf9612f 100644 --- a/tests/components/teslemetry/snapshots/test_sensor.ambr +++ b/tests/components/teslemetry/snapshots/test_sensor.ambr @@ -55,7 +55,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.684', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_charged-statealt] @@ -130,7 +130,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.036', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_discharged-statealt] @@ -205,7 +205,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.036', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_exported-statealt] @@ -280,7 +280,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_imported_from_generator-statealt] @@ -355,7 +355,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_imported_from_grid-statealt] @@ -430,7 +430,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.684', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_battery_imported_from_solar-statealt] @@ -580,7 +580,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.036', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_consumer_imported_from_battery-statealt] @@ -655,7 +655,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_consumer_imported_from_generator-statealt] @@ -730,7 +730,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_consumer_imported_from_grid-statealt] @@ -805,7 +805,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.038', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_consumer_imported_from_solar-statealt] @@ -955,7 +955,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_generator_exported-statealt] @@ -1105,7 +1105,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.002', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_exported-statealt] @@ -1180,7 +1180,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_exported_from_battery-statealt] @@ -1255,7 +1255,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_exported_from_generator-statealt] @@ -1330,7 +1330,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.002', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_exported_from_solar-statealt] @@ -1405,7 +1405,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_imported-statealt] @@ -1555,7 +1555,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_services_exported-statealt] @@ -1630,7 +1630,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.0', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_grid_services_imported-statealt] @@ -1780,7 +1780,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.074', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_home_usage-statealt] @@ -2087,7 +2087,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.724', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_solar_exported-statealt] @@ -2162,7 +2162,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '0.724', + 'state': 'unknown', }) # --- # name: test_sensors[sensor.energy_site_solar_generated-statealt] diff --git a/tests/components/teslemetry/test_diagnostics.py b/tests/components/teslemetry/test_diagnostics.py index fb8eb79a918..18182b14321 100644 --- a/tests/components/teslemetry/test_diagnostics.py +++ b/tests/components/teslemetry/test_diagnostics.py @@ -1,11 +1,14 @@ """Test the Telemetry Diagnostics.""" +from freezegun.api import FrozenDateTimeFactory from syrupy.assertion import SnapshotAssertion +from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL from homeassistant.core import HomeAssistant from . import setup_platform +from tests.common import async_fire_time_changed from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator @@ -14,10 +17,16 @@ async def test_diagnostics( hass: HomeAssistant, hass_client: ClientSessionGenerator, snapshot: SnapshotAssertion, + freezer: FrozenDateTimeFactory, ) -> None: """Test diagnostics.""" entry = await setup_platform(hass) + # Wait for coordinator refresh + freezer.tick(VEHICLE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + diag = await get_diagnostics_for_config_entry(hass, hass_client, entry) assert diag == snapshot diff --git a/tests/components/teslemetry/test_init.py b/tests/components/teslemetry/test_init.py index d2ef5c38893..54c9ca0dad9 100644 --- a/tests/components/teslemetry/test_init.py +++ b/tests/components/teslemetry/test_init.py @@ -107,20 +107,6 @@ async def test_energy_site_refresh_error( assert entry.state is state -# Test Energy History Coordinator -@pytest.mark.parametrize(("side_effect", "state"), ERRORS) -async def test_energy_history_refresh_error( - hass: HomeAssistant, - mock_energy_history: AsyncMock, - side_effect: TeslaFleetError, - state: ConfigEntryState, -) -> None: - """Test coordinator refresh with an error.""" - mock_energy_history.side_effect = side_effect - entry = await setup_platform(hass) - assert entry.state is state - - async def test_vehicle_stream( hass: HomeAssistant, mock_add_listener: AsyncMock, diff --git a/tests/components/teslemetry/test_sensor.py b/tests/components/teslemetry/test_sensor.py index d2d6d88b3e3..296f9e8bff4 100644 --- a/tests/components/teslemetry/test_sensor.py +++ b/tests/components/teslemetry/test_sensor.py @@ -9,7 +9,7 @@ from teslemetry_stream import Signal from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL from homeassistant.config_entries import ConfigEntryState -from homeassistant.const import STATE_UNAVAILABLE, Platform +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -30,6 +30,8 @@ async def test_sensors( """Tests that the sensor entities with the legacy polling are correct.""" freezer.move_to("2024-01-01 00:00:00+00:00") + async_fire_time_changed(hass) + await hass.async_block_till_done() # Force the vehicle to use polling with patch("tesla_fleet_api.teslemetry.Vehicle.pre2021", return_value=True): @@ -117,7 +119,7 @@ async def test_energy_history_no_time_series( entity_id = "sensor.energy_site_battery_discharged" state = hass.states.get(entity_id) - assert state.state == "0.036" + assert state.state == STATE_UNKNOWN mock_energy_history.return_value = ENERGY_HISTORY_EMPTY diff --git a/tests/components/tessie/snapshots/test_update.ambr b/tests/components/tessie/snapshots/test_update.ambr index 8780f64bb09..ff298f97ecd 100644 --- a/tests/components/tessie/snapshots/test_update.ambr +++ b/tests/components/tessie/snapshots/test_update.ambr @@ -45,7 +45,7 @@ 'installed_version': '2023.38.6', 'latest_version': '2023.44.30.4', 'release_summary': None, - 'release_url': None, + 'release_url': 'https://stats.tessie.com/versions/2023.44.30.4', 'skipped_version': None, 'supported_features': , 'title': None, diff --git a/tests/components/thermobeacon/__init__.py b/tests/components/thermobeacon/__init__.py index 32b6d823ec2..9b43e3b33f2 100644 --- a/tests/components/thermobeacon/__init__.py +++ b/tests/components/thermobeacon/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/thermopro/__init__.py b/tests/components/thermopro/__init__.py index 7ac593e6336..6971d72c460 100644 --- a/tests/components/thermopro/__init__.py +++ b/tests/components/thermopro/__init__.py @@ -32,7 +32,6 @@ def make_bluetooth_service_info( name=name, address=address, details={}, - rssi=rssi, ), time=monotonic_time_coarse(), advertisement=None, diff --git a/tests/components/threshold/test_init.py b/tests/components/threshold/test_init.py index 599612ce0b7..fed35bc6502 100644 --- a/tests/components/threshold/test_init.py +++ b/tests/components/threshold/test_init.py @@ -7,8 +7,8 @@ import pytest from homeassistant.components import threshold from homeassistant.components.threshold.config_flow import ConfigFlowHandler from homeassistant.components.threshold.const import DOMAIN -from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -81,6 +81,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -174,6 +175,7 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: # Set up entities, with backing devices and config entries run1_entry = _create_mock_entity("sensor", "initial") run2_entry = _create_mock_entity("sensor", "changed") + assert run1_entry.device_id != run2_entry.device_id # Setup the config entry config_entry = MockConfigEntry( @@ -186,23 +188,27 @@ async def test_entry_changed(hass: HomeAssistant, platform) -> None: "name": "My threshold", "upper": None, }, - title="My integration", + title="My threshold", ) 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.entry_id in _get_device_config_entries(run1_entry) + assert config_entry.entry_id not in _get_device_config_entries(run1_entry) assert config_entry.entry_id not in _get_device_config_entries(run2_entry) + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == run1_entry.device_id hass.config_entries.async_update_entry( config_entry, options={**config_entry.options, "entity_id": "sensor.changed"} ) await hass.async_block_till_done() - # Check that the config entry association has updated + # Check that the device association has updated assert config_entry.entry_id not in _get_device_config_entries(run1_entry) - assert config_entry.entry_id in _get_device_config_entries(run2_entry) + assert config_entry.entry_id not in _get_device_config_entries(run2_entry) + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == run2_entry.device_id async def test_device_cleaning( @@ -273,7 +279,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( threshold_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(threshold_config_entry.entry_id) @@ -288,7 +294,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( threshold_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 async def test_async_handle_source_entity_changes_source_entity_removed( @@ -299,6 +305,54 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the threshold config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(threshold_config_entry.entry_id) + await hass.async_block_till_done() + + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.threshold.async_unload_entry", + wraps=threshold.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the threshold config entry is not removed + assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["update"] + + +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + threshold_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the threshold config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -315,7 +369,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -332,7 +386,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() - # Check that the threshold config entry is removed from the device + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the threshold config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries @@ -359,7 +417,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -374,7 +432,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the threshold config entry is removed from the device + # Check that the entity is no longer linked to the source device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id is None + + # Check that the threshold config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries @@ -407,7 +469,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert threshold_config_entry.entry_id not in sensor_device_2.config_entries @@ -424,11 +486,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the threshold config entry is moved to the other device + # Check that the entity is linked to the other device + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_device_2.id + + # Check that the derivative config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert threshold_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert threshold_config_entry.entry_id in sensor_device_2.config_entries + assert threshold_config_entry.entry_id not in sensor_device_2.config_entries # Check that the threshold config entry is not removed assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -453,7 +519,7 @@ async def test_async_handle_source_entity_new_entity_id( assert threshold_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, threshold_entity_entry.entity_id) @@ -471,12 +537,87 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the threshold config entry is updated with the new entity ID assert threshold_config_entry.options["entity_id"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert threshold_config_entry.entry_id in sensor_device.config_entries + assert threshold_config_entry.entry_id not in sensor_device.config_entries # Check that the threshold config entry is not removed assert threshold_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, +) -> None: + """Test migration from v1.1 removes threshold config entry from device.""" + + threshold_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "entity_id": sensor_entity_entry.entity_id, + "hysteresis": 0.0, + "lower": -2.0, + "name": "My threshold", + "upper": None, + }, + title="My threshold", + version=1, + minor_version=1, + ) + threshold_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=threshold_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(threshold_config_entry.entry_id) + await hass.async_block_till_done() + + assert threshold_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert threshold_config_entry.entry_id not in sensor_device.config_entries + threshold_entity_entry = entity_registry.async_get("binary_sensor.my_threshold") + assert threshold_entity_entry.device_id == sensor_entity_entry.device_id + + assert threshold_config_entry.version == 1 + assert threshold_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "entity_id": "sensor.test", + "hysteresis": 0.0, + "lower": -2.0, + "name": "My threshold", + "upper": None, + }, + title="My threshold", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/trend/test_init.py b/tests/components/trend/test_init.py index 4ff6213d082..22700376b26 100644 --- a/tests/components/trend/test_init.py +++ b/tests/components/trend/test_init.py @@ -8,7 +8,7 @@ from homeassistant.components import trend from homeassistant.components.trend.config_flow import ConfigFlowHandler from homeassistant.components.trend.const import DOMAIN from homeassistant.config_entries import ConfigEntry, ConfigEntryState -from homeassistant.core import Event, HomeAssistant +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event @@ -81,6 +81,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -199,7 +200,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( trend_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(trend_config_entry.entry_id) @@ -214,7 +215,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( trend_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 async def test_async_handle_source_entity_changes_source_entity_removed( @@ -225,6 +226,53 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_config_entry: ConfigEntry, sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, +) -> None: + """Test the trend config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(trend_config_entry.entry_id) + await hass.async_block_till_done() + + trend_entity_entry = entity_registry.async_get("binary_sensor.my_trend") + assert trend_entity_entry.device_id == sensor_entity_entry.device_id + + sensor_device = device_registry.async_get(sensor_device.id) + assert trend_config_entry.entry_id not in sensor_device.config_entries + + events = track_entity_registry_actions(hass, trend_entity_entry.entity_id) + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.trend.async_unload_entry", + wraps=trend.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_called_once() + + # Check that the helper entity is removed + assert not entity_registry.async_get("binary_sensor.my_trend") + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the trend config entry is removed + assert trend_config_entry.entry_id not in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["remove"] + + +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + trend_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, ) -> None: """Test the trend config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -241,7 +289,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert trend_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert trend_config_entry.entry_id in sensor_device.config_entries + assert trend_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, trend_entity_entry.entity_id) @@ -258,7 +306,10 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the trend config entry is removed from the device + # Check that the helper entity is removed + assert not entity_registry.async_get("binary_sensor.my_trend") + + # Check that the trend config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert trend_config_entry.entry_id not in sensor_device.config_entries @@ -285,7 +336,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert trend_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert trend_config_entry.entry_id in sensor_device.config_entries + assert trend_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, trend_entity_entry.entity_id) @@ -300,7 +351,11 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the trend config entry is removed from the device + # Check that the entity is no longer linked to the source device + trend_entity_entry = entity_registry.async_get("binary_sensor.my_trend") + assert trend_entity_entry.device_id is None + + # Check that the trend config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert trend_config_entry.entry_id not in sensor_device.config_entries @@ -333,7 +388,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert trend_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert trend_config_entry.entry_id in sensor_device.config_entries + assert trend_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert trend_config_entry.entry_id not in sensor_device_2.config_entries @@ -350,11 +405,15 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the trend config entry is moved to the other device + # Check that the entity is linked to the other device + trend_entity_entry = entity_registry.async_get("binary_sensor.my_trend") + assert trend_entity_entry.device_id == sensor_device_2.id + + # Check that the trend config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert trend_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert trend_config_entry.entry_id in sensor_device_2.config_entries + assert trend_config_entry.entry_id not in sensor_device_2.config_entries # Check that the trend config entry is not removed assert trend_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -379,7 +438,7 @@ async def test_async_handle_source_entity_new_entity_id( assert trend_entity_entry.device_id == sensor_entity_entry.device_id sensor_device = device_registry.async_get(sensor_device.id) - assert trend_config_entry.entry_id in sensor_device.config_entries + assert trend_config_entry.entry_id not in sensor_device.config_entries events = track_entity_registry_actions(hass, trend_entity_entry.entity_id) @@ -397,12 +456,83 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the trend config entry is updated with the new entity ID assert trend_config_entry.options["entity_id"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert trend_config_entry.entry_id in sensor_device.config_entries + assert trend_config_entry.entry_id not in sensor_device.config_entries # Check that the trend config entry is not removed assert trend_config_entry.entry_id in hass.config_entries.async_entry_ids() # Check we got the expected events assert events == [] + + +async def test_migration_1_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, +) -> None: + """Test migration from v1.1 removes trend config entry from device.""" + + trend_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My trend", + "entity_id": sensor_entity_entry.entity_id, + "invert": False, + }, + title="My trend", + version=1, + minor_version=1, + ) + trend_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=trend_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert trend_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(trend_config_entry.entry_id) + await hass.async_block_till_done() + + assert trend_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entity is linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert trend_config_entry.entry_id not in sensor_device.config_entries + trend_entity_entry = entity_registry.async_get("binary_sensor.my_trend") + assert trend_entity_entry.device_id == sensor_entity_entry.device_id + + assert trend_config_entry.version == 1 + assert trend_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "name": "My trend", + "entity_id": "sensor.test", + "invert": False, + }, + title="My trend", + version=2, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py index 22fb10209b0..db42da5de0e 100644 --- a/tests/components/tts/test_init.py +++ b/tests/components/tts/test_init.py @@ -1835,7 +1835,7 @@ async def test_async_convert_audio_error(hass: HomeAssistant) -> None: async def bad_data_gen(): yield bytes(0) - with pytest.raises(RuntimeError): + with pytest.raises(HomeAssistantError): # Simulate a bad WAV file async for _chunk in tts._async_convert_audio( hass, "wav", bad_data_gen(), "mp3" diff --git a/tests/components/tuya/__init__.py b/tests/components/tuya/__init__.py index 1d468a46814..09606c7e116 100644 --- a/tests/components/tuya/__init__.py +++ b/tests/components/tuya/__init__.py @@ -7,10 +7,108 @@ from unittest.mock import patch from tuya_sharing import CustomerDevice from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform from homeassistant.core import HomeAssistant from tests.common import MockConfigEntry +DEVICE_MOCKS = { + "am43_corded_motor_zigbee_cover": [ + # https://github.com/home-assistant/core/issues/71242 + Platform.SELECT, + Platform.COVER, + ], + "clkg_curtain_switch": [ + # https://github.com/home-assistant/core/issues/136055 + Platform.COVER, + Platform.LIGHT, + ], + "cs_arete_two_12l_dehumidifier_air_purifier": [ + Platform.BINARY_SENSOR, + Platform.FAN, + Platform.HUMIDIFIER, + Platform.SELECT, + Platform.SENSOR, + Platform.SWITCH, + ], + "cwwsq_cleverio_pf100": [ + # https://github.com/home-assistant/core/issues/144745 + Platform.NUMBER, + Platform.SENSOR, + ], + "cwysj_pixi_smart_drinking_fountain": [ + # https://github.com/home-assistant/core/pull/146599 + Platform.SENSOR, + Platform.SWITCH, + ], + "cz_dual_channel_metering": [ + # https://github.com/home-assistant/core/issues/147149 + Platform.SENSOR, + Platform.SWITCH, + ], + "dlq_earu_electric_eawcpt": [ + # https://github.com/home-assistant/core/issues/102769 + Platform.SENSOR, + Platform.SWITCH, + ], + "dlq_metering_3pn_wifi": [ + # https://github.com/home-assistant/core/issues/143499 + Platform.SENSOR, + ], + "kg_smart_valve": [ + # https://github.com/home-assistant/core/issues/148347 + Platform.SWITCH, + ], + "kj_bladeless_tower_fan": [ + # https://github.com/orgs/home-assistant/discussions/61 + Platform.FAN, + Platform.SELECT, + Platform.SWITCH, + ], + "mal_alarm_host": [ + # Alarm Host support + Platform.ALARM_CONTROL_PANEL, + Platform.SWITCH, + ], + "mcs_door_sensor": [ + # https://github.com/home-assistant/core/issues/108301 + Platform.BINARY_SENSOR, + Platform.SENSOR, + ], + "rqbj_gas_sensor": [ + # https://github.com/orgs/home-assistant/discussions/100 + Platform.BINARY_SENSOR, + Platform.SENSOR, + ], + "sfkzq_valve_controller": [ + # https://github.com/home-assistant/core/issues/148116 + Platform.SWITCH, + ], + "tdq_4_443": [ + # https://github.com/home-assistant/core/issues/146845 + Platform.SELECT, + Platform.SWITCH, + ], + "wk_wifi_smart_gas_boiler_thermostat": [ + # https://github.com/orgs/home-assistant/discussions/243 + Platform.CLIMATE, + Platform.SWITCH, + ], + "wsdcg_temperature_humidity": [ + # https://github.com/home-assistant/core/issues/102769 + Platform.SENSOR, + ], + "wxkg_wireless_switch": [ + # https://github.com/home-assistant/core/issues/93975 + Platform.EVENT, + Platform.SENSOR, + ], + "zndb_smart_meter": [ + # https://github.com/home-assistant/core/issues/138372 + Platform.SENSOR, + ], +} + async def initialize_entry( hass: HomeAssistant, diff --git a/tests/components/tuya/conftest.py b/tests/components/tuya/conftest.py index 017c6f00241..3d89e1d6f92 100644 --- a/tests/components/tuya/conftest.py +++ b/tests/components/tuya/conftest.py @@ -6,7 +6,7 @@ from collections.abc import Generator from unittest.mock import MagicMock, patch import pytest -from tuya_sharing import CustomerDevice +from tuya_sharing import CustomerApi, CustomerDevice, DeviceFunction, DeviceStatusRange from homeassistant.components.tuya import ManagerCompat from homeassistant.components.tuya.const import ( @@ -18,6 +18,8 @@ from homeassistant.components.tuya.const import ( DOMAIN, ) from homeassistant.core import HomeAssistant +from homeassistant.helpers.json import json_dumps +from homeassistant.util import dt as dt_util from tests.common import MockConfigEntry, async_load_json_object_fixture @@ -115,6 +117,12 @@ def mock_manager() -> ManagerCompat: manager = MagicMock(spec=ManagerCompat) manager.device_map = {} manager.mq = MagicMock() + manager.mq.client = MagicMock() + manager.mq.client.is_connected = MagicMock(return_value=True) + manager.customer_api = MagicMock(spec=CustomerApi) + # Meaningless URL / UUIDs + manager.customer_api.endpoint = "https://apigw.tuyaeu.com" + manager.terminal_id = "7cd96aff-6ec8-4006-b093-3dbff7947591" return manager @@ -135,18 +143,40 @@ async def mock_device(hass: HomeAssistant, mock_device_code: str) -> CustomerDev hass, f"{mock_device_code}.json", DOMAIN ) device = MagicMock(spec=CustomerDevice) - device.id = details["id"] + device.id = details.get("id", "mocked_device_id") device.name = details["name"] device.category = details["category"] device.product_id = details["product_id"] device.product_name = details["product_name"] device.online = details["online"] + device.sub = details.get("sub") + device.time_zone = details.get("time_zone") + device.active_time = details.get("active_time") + if device.active_time: + device.active_time = int(dt_util.as_timestamp(device.active_time)) + device.create_time = details.get("create_time") + if device.create_time: + device.create_time = int(dt_util.as_timestamp(device.create_time)) + device.update_time = details.get("update_time") + if device.update_time: + device.update_time = int(dt_util.as_timestamp(device.update_time)) + device.support_local = details.get("support_local") + device.mqtt_connected = details.get("mqtt_connected") + device.function = { - key: MagicMock(type=value["type"], values=value["values"]) + key: DeviceFunction( + code=value.get("code"), + type=value["type"], + values=json_dumps(value["value"]), + ) for key, value in details["function"].items() } device.status_range = { - key: MagicMock(type=value["type"], values=value["values"]) + key: DeviceStatusRange( + code=value.get("code"), + type=value["type"], + values=json_dumps(value["value"]), + ) for key, value in details["status_range"].items() } device.status = details["status"] diff --git a/tests/components/tuya/fixtures/am43_corded_motor_zigbee_cover.json b/tests/components/tuya/fixtures/am43_corded_motor_zigbee_cover.json new file mode 100644 index 00000000000..14d1c39fc94 --- /dev/null +++ b/tests/components/tuya/fixtures/am43_corded_motor_zigbee_cover.json @@ -0,0 +1,61 @@ +{ + "id": "zah67ekd", + "name": "Kitchen Blinds", + "category": "cl", + "product_id": "zah67ekd", + "product_name": "AM43拉绳电机-Zigbee", + "online": true, + "function": { + "control": { + "type": "Enum", + "value": { "range": ["open", "stop", "close", "continue"] } + }, + "percent_control": { + "type": "Integer", + "value": { "unit": "%", "min": 0, "max": 100, "scale": 0, "step": 1 } + }, + "control_back_mode": { + "type": "Enum", + "value": { "range": ["forward", "back"] } + } + }, + "status_range": { + "control": { + "type": "Enum", + "value": { "range": ["open", "stop", "close", "continue"] } + }, + "percent_control": { + "type": "Integer", + "value": { "unit": "%", "min": 0, "max": 100, "scale": 0, "step": 1 } + }, + "percent_state": { + "type": "Integer", + "value": { "unit": "%", "min": 0, "max": 100, "scale": 0, "step": 1 } + }, + "control_back_mode": { + "type": "Enum", + "value": { "range": ["forward", "back"] } + }, + "work_state": { + "type": "Enum", + "value": { "range": ["opening", "closing"] } + }, + "situation_set": { + "type": "Enum", + "value": { "range": ["fully_open", "fully_close"] } + }, + "fault": { + "type": "Bitmap", + "value": { "label": ["motor_fault"] } + } + }, + "status": { + "control": "stop", + "percent_control": 100, + "percent_state": 52, + "control_back_mode": "forward", + "work_state": "closing", + "situation_set": "fully_open", + "fault": 0 + } +} diff --git a/tests/components/tuya/fixtures/clkg_curtain_switch.json b/tests/components/tuya/fixtures/clkg_curtain_switch.json new file mode 100644 index 00000000000..28e3248f8b5 --- /dev/null +++ b/tests/components/tuya/fixtures/clkg_curtain_switch.json @@ -0,0 +1,95 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1729466466688hgsTp2", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bf1fa053e0ba4e002c6we8", + "name": "Tapparelle studio", + "category": "clkg", + "product_id": "nhyj64w2", + "product_name": "Curtain switch", + "online": true, + "sub": true, + "time_zone": "+02:00", + "active_time": "2025-01-13T23:37:14+00:00", + "create_time": "2025-01-13T23:37:14+00:00", + "update_time": "2025-01-13T23:37:14+00:00", + "function": { + "control": { + "type": "Enum", + "value": { + "range": ["open", "stop", "close"] + } + }, + "percent_control": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 10 + } + }, + "cur_calibration": { + "type": "Enum", + "value": { + "range": ["start", "end"] + } + }, + "switch_backlight": { + "type": "Boolean", + "value": {} + }, + "control_back_mode": { + "type": "Enum", + "value": { + "range": ["forward", "back"] + } + } + }, + "status_range": { + "control": { + "type": "Enum", + "value": { + "range": ["open", "stop", "close"] + } + }, + "percent_control": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 10 + } + }, + "cur_calibration": { + "type": "Enum", + "value": { + "range": ["start", "end"] + } + }, + "switch_backlight": { + "type": "Boolean", + "value": {} + }, + "control_back_mode": { + "type": "Enum", + "value": { + "range": ["forward", "back"] + } + } + }, + "status": { + "control": "stop", + "percent_control": 100, + "cur_calibration": "end", + "switch_backlight": true, + "control_back_mode": "forward" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/cs_arete_two_12l_dehumidifier_air_purifier.json b/tests/components/tuya/fixtures/cs_arete_two_12l_dehumidifier_air_purifier.json index 1e50e7e3fec..5574153a439 100644 --- a/tests/components/tuya/fixtures/cs_arete_two_12l_dehumidifier_air_purifier.json +++ b/tests/components/tuya/fixtures/cs_arete_two_12l_dehumidifier_air_purifier.json @@ -6,39 +6,41 @@ "product_name": "Arete\u00ae Two 12L Dehumidifier/Air Purifier", "online": true, "function": { - "switch": { "type": "Boolean", "values": "{}" }, + "switch": { "type": "Boolean", "value": {} }, "dehumidify_set_value": { "type": "Integer", - "values": "{\"unit\": \"%\", \"min\": 35, \"max\": 70, \"scale\": 0, \"step\": 5}" + "value": { "unit": "%", "min": 35, "max": 70, "scale": 0, "step": 5 } }, - "child_lock": { "type": "Boolean", "values": "{}" }, + "child_lock": { "type": "Boolean", "value": {} }, "countdown_set": { "type": "Enum", - "values": "{\"range\": [\"cancel\", \"1h\", \"2h\", \"3h\"]}" + "value": { "range": ["cancel", "1h", "2h", "3h"] } } }, "status_range": { - "switch": { "type": "Boolean", "values": "{}" }, + "switch": { "type": "Boolean", "value": {} }, "dehumidify_set_value": { "type": "Integer", - "values": "{\"unit\": \"%\", \"min\": 35, \"max\": 70, \"scale\": 0, \"step\": 5}" + "value": { "unit": "%", "min": 35, "max": 70, "scale": 0, "step": 5 } }, - "child_lock": { "type": "Boolean", "values": "{}" }, + "child_lock": { "type": "Boolean", "value": {} }, "humidity_indoor": { "type": "Integer", - "values": "{\"unit\": \"%\", \"min\": 0, \"max\": 100, \"scale\": 0, \"step\": 1}" + "value": { "unit": "%", "min": 0, "max": 100, "scale": 0, "step": 1 } }, "countdown_set": { "type": "Enum", - "values": "{\"range\": [\"cancel\", \"1h\", \"2h\", \"3h\"]}" + "value": { "range": ["cancel", "1h", "2h", "3h"] } }, "countdown_left": { "type": "Integer", - "values": "{\"unit\": \"h\", \"min\": 0, \"max\": 24, \"scale\": 0, \"step\": 1}" + "value": { "unit": "h", "min": 0, "max": 24, "scale": 0, "step": 1 } }, "fault": { "type": "Bitmap", - "values": "{\"label\": [\"tankfull\", \"defrost\", \"E1\", \"E2\", \"L2\", \"L3\", \"L4\", \"wet\"]}" + "value": { + "label": ["tankfull", "defrost", "E1", "E2", "L2", "L3", "L4", "wet"] + } } }, "status": { diff --git a/tests/components/tuya/fixtures/cwwsq_cleverio_pf100.json b/tests/components/tuya/fixtures/cwwsq_cleverio_pf100.json new file mode 100644 index 00000000000..ec6f3ce5122 --- /dev/null +++ b/tests/components/tuya/fixtures/cwwsq_cleverio_pf100.json @@ -0,0 +1,101 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1747045731408d0tb5M", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bfd0273e59494eb34esvrx", + "name": "Cleverio PF100", + "category": "cwwsq", + "product_id": "wfkzyy0evslzsmoi", + "product_name": "Cleverio PF100", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2024-10-20T13:09:34+00:00", + "create_time": "2024-10-20T13:09:34+00:00", + "update_time": "2024-10-20T13:09:34+00:00", + "function": { + "meal_plan": { + "type": "Raw", + "value": {} + }, + "manual_feed": { + "type": "Integer", + "value": { + "unit": "", + "min": 1, + "max": 20, + "scale": 0, + "step": 1 + } + }, + "factory_reset": { + "type": "Boolean", + "value": {} + }, + "light": { + "type": "Boolean", + "value": {} + } + }, + "status_range": { + "meal_plan": { + "type": "Raw", + "value": {} + }, + "manual_feed": { + "type": "Integer", + "value": { + "unit": "", + "min": 1, + "max": 20, + "scale": 0, + "step": 1 + } + }, + "factory_reset": { + "type": "Boolean", + "value": {} + }, + "battery_percentage": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "charge_state": { + "type": "Boolean", + "value": {} + }, + "feed_report": { + "type": "Integer", + "value": { + "unit": "", + "min": 0, + "max": 20, + "scale": 0, + "step": 1 + } + }, + "light": { + "type": "Boolean", + "value": {} + } + }, + "status": { + "meal_plan": "fwQAAgB/BgABAH8JAAIBfwwAAQB/DwACAX8VAAIBfxcAAQAIEgABAQ==", + "manual_feed": 1, + "factory_reset": false, + "battery_percentage": 90, + "charge_state": false, + "feed_report": 2, + "light": true + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/cwysj_pixi_smart_drinking_fountain.json b/tests/components/tuya/fixtures/cwysj_pixi_smart_drinking_fountain.json new file mode 100644 index 00000000000..0f5e5e5f241 --- /dev/null +++ b/tests/components/tuya/fixtures/cwysj_pixi_smart_drinking_fountain.json @@ -0,0 +1,132 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1751729689584Vh0VoL", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "23536058083a8dc57d96", + "name": "PIXI Smart Drinking Fountain", + "category": "cwysj", + "product_id": "z3rpyvznfcch99aa", + "product_name": "", + "online": true, + "sub": false, + "time_zone": "+01:00", + "active_time": "2025-06-17T13:29:17+00:00", + "create_time": "2025-06-17T13:29:17+00:00", + "update_time": "2025-06-17T13:29:17+00:00", + "function": { + "switch": { + "type": "Boolean", + "value": {} + }, + "water_reset": { + "type": "Boolean", + "value": {} + }, + "filter_reset": { + "type": "Boolean", + "value": {} + }, + "pump_reset": { + "type": "Boolean", + "value": {} + }, + "uv": { + "type": "Boolean", + "value": {} + }, + "uv_runtime": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 10800, + "scale": 0, + "step": 1 + } + } + }, + "status_range": { + "switch": { + "type": "Boolean", + "value": {} + }, + "water_time": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 7200, + "scale": 0, + "step": 1 + } + }, + "filter_life": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 43200, + "scale": 0, + "step": 1 + } + }, + "pump_time": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "water_reset": { + "type": "Boolean", + "value": {} + }, + "filter_reset": { + "type": "Boolean", + "value": {} + }, + "pump_reset": { + "type": "Boolean", + "value": {} + }, + "uv": { + "type": "Boolean", + "value": {} + }, + "uv_runtime": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 10800, + "scale": 0, + "step": 1 + } + }, + "water_level": { + "type": "Enum", + "value": { + "range": ["level_1", "level_2", "level_3"] + } + } + }, + "status": { + "switch": true, + "water_time": 0, + "filter_life": 18965, + "pump_time": 18965, + "water_reset": false, + "filter_reset": false, + "pump_reset": false, + "uv": false, + "uv_runtime": 0, + "water_level": "level_3" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/cz_dual_channel_metering.json b/tests/components/tuya/fixtures/cz_dual_channel_metering.json new file mode 100644 index 00000000000..9cd3c4ffd6f --- /dev/null +++ b/tests/components/tuya/fixtures/cz_dual_channel_metering.json @@ -0,0 +1,88 @@ +{ + "endpoint": "https://apigw.tuyaus.com", + "terminal_id": "1742695000703Ozq34h", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "eb0c772dabbb19d653ssi5", + "name": "HVAC Meter", + "category": "cz", + "product_id": "2jxesipczks0kdct", + "product_name": "Dual channel metering", + "online": true, + "sub": false, + "time_zone": "-07:00", + "active_time": "2025-06-19T14:19:08+00:00", + "create_time": "2025-06-19T14:19:08+00:00", + "update_time": "2025-06-19T14:19:08+00:00", + "function": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "switch_2": { + "type": "Boolean", + "value": {} + } + }, + "status_range": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "switch_2": { + "type": "Boolean", + "value": {} + }, + "add_ele": { + "type": "Integer", + "value": { + "unit": "kwh", + "min": 0, + "max": 50000, + "scale": 3, + "step": 100 + } + }, + "cur_current": { + "type": "Integer", + "value": { + "unit": "A", + "min": 0, + "max": 80000, + "scale": 3, + "step": 1 + } + }, + "cur_power": { + "type": "Integer", + "value": { + "unit": "W", + "min": 0, + "max": 200000, + "scale": 1, + "step": 1 + } + }, + "cur_voltage": { + "type": "Integer", + "value": { + "unit": "V", + "min": 0, + "max": 5000, + "scale": 1, + "step": 1 + } + } + }, + "status": { + "switch_1": true, + "switch_2": true, + "add_ele": 190, + "cur_current": 83, + "cur_power": 64, + "cur_voltage": 1217 + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/dlq_earu_electric_eawcpt.json b/tests/components/tuya/fixtures/dlq_earu_electric_eawcpt.json new file mode 100644 index 00000000000..32535964a7e --- /dev/null +++ b/tests/components/tuya/fixtures/dlq_earu_electric_eawcpt.json @@ -0,0 +1,247 @@ +{ + "endpoint": "https://openapi.tuyaeu.com", + "auth_type": 0, + "country_code": "48", + "app_type": "tuyaSmart", + "mqtt_connected": null, + "disabled_by": null, + "disabled_polling": false, + "name": "\u4e00\u8def\u5e26\u8ba1\u91cf\u78c1\u4fdd\u6301\u901a\u65ad\u5668", + "model": "", + "category": "dlq", + "product_id": "0tnvg2xaisqdadcf", + "product_name": "\u4e00\u8def\u5e26\u8ba1\u91cf\u78c1\u4fdd\u6301\u901a\u65ad\u5668", + "online": true, + "sub": false, + "time_zone": "+01:00", + "active_time": "2023-11-25T21:50:37+00:00", + "create_time": "2023-11-25T21:49:06+00:00", + "update_time": "2023-11-28T16:32:28+00:00", + "function": { + "switch": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "relay_status": { + "type": "Enum", + "value": { + "range": ["power_off", "power_on", "last"] + } + }, + "light_mode": { + "type": "Enum", + "value": { + "range": ["relay", "pos", "none", "on"] + } + }, + "child_lock": { + "type": "Boolean", + "value": {} + }, + "cycle_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "alarm_set_1": { + "type": "Raw", + "value": {} + }, + "alarm_set_2": { + "type": "Raw", + "value": {} + } + }, + "status_range": { + "switch": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "add_ele": { + "type": "Integer", + "value": { + "min": 0, + "max": 50000, + "scale": 3, + "step": 100 + } + }, + "cur_current": { + "type": "Integer", + "value": { + "unit": "mA", + "min": 0, + "max": 100000, + "scale": 0, + "step": 1 + } + }, + "cur_power": { + "type": "Integer", + "value": { + "unit": "W", + "min": 0, + "max": 99999, + "scale": 1, + "step": 1 + } + }, + "cur_voltage": { + "type": "Integer", + "value": { + "unit": "V", + "min": 0, + "max": 5000, + "scale": 1, + "step": 1 + } + }, + "test_bit": { + "type": "Integer", + "value": { + "min": 0, + "max": 5, + "scale": 0, + "step": 1 + } + }, + "voltage_coe": { + "type": "Integer", + "value": { + "min": 0, + "max": 1000000, + "scale": 0, + "step": 1 + } + }, + "electric_coe": { + "type": "Integer", + "value": { + "min": 0, + "max": 1000000, + "scale": 0, + "step": 1 + } + }, + "power_coe": { + "type": "Integer", + "value": { + "min": 0, + "max": 1000000, + "scale": 0, + "step": 1 + } + }, + "electricity_coe": { + "type": "Integer", + "value": { + "min": 0, + "max": 1000000, + "scale": 0, + "step": 1 + } + }, + "fault": { + "type": "Bitmap", + "value": { + "label": [ + "ov_cr", + "ov_vol", + "ov_pwr", + "ls_cr", + "ls_vol", + "ls_pow", + "short_circuit_alarm", + "overload_alarm", + "leakagecurr_alarm", + "self_test_alarm", + "high_temp", + "unbalance_alarm", + "miss_phase_alarm" + ] + } + }, + "relay_status": { + "type": "Enum", + "value": { + "range": ["power_off", "power_on", "last"] + } + }, + "light_mode": { + "type": "Enum", + "value": { + "range": ["relay", "pos", "none", "on"] + } + }, + "child_lock": { + "type": "Boolean", + "value": {} + }, + "cycle_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "temp_value": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "alarm_set_1": { + "type": "Raw", + "value": {} + }, + "alarm_set_2": { + "type": "Raw", + "value": {} + } + }, + "status": { + "switch": true, + "countdown_1": 0, + "add_ele": 100, + "cur_current": 2198, + "cur_power": 4953, + "cur_voltage": 2314, + "test_bit": 2, + "voltage_coe": 0, + "electric_coe": 0, + "power_coe": 0, + "electricity_coe": 0, + "fault": 0, + "relay_status": "last", + "light_mode": "relay", + "child_lock": false, + "cycle_time": "", + "temp_value": 0, + "alarm_set_1": "", + "alarm_set_2": "AQAAAAMAAAAEAAAA" + } +} diff --git a/tests/components/tuya/fixtures/dlq_metering_3pn_wifi.json b/tests/components/tuya/fixtures/dlq_metering_3pn_wifi.json new file mode 100644 index 00000000000..8e9a06cc9a9 --- /dev/null +++ b/tests/components/tuya/fixtures/dlq_metering_3pn_wifi.json @@ -0,0 +1,137 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1733006572651YokbqV", + "mqtt_connected": null, + "disabled_by": null, + "disabled_polling": false, + "id": "bf5e5bde2c52cb5994cd27", + "name": "Metering_3PN_WiFi_stable", + "category": "dlq", + "product_id": "kxdr6su0c55p7bbo", + "product_name": "Metering_3PN_WiFi", + "online": true, + "sub": false, + "time_zone": "+03:00", + "active_time": "2024-12-08T17:37:45+00:00", + "create_time": "2024-12-08T17:37:45+00:00", + "update_time": "2024-12-08T17:37:45+00:00", + "function": { + "clear_energy": { + "type": "Boolean", + "value": {} + }, + "alarm_set_1": { + "type": "Raw", + "value": {} + }, + "alarm_set_2": { + "type": "Raw", + "value": {} + }, + "online_state": { + "type": "Enum", + "value": { + "range": ["online", "offline"] + } + } + }, + "status_range": { + "forward_energy_total": { + "type": "Integer", + "value": { + "unit": "kW.h", + "min": 0, + "max": 999999999, + "scale": 2, + "step": 1 + } + }, + "phase_a": { + "type": "Raw", + "value": {} + }, + "phase_b": { + "type": "Raw", + "value": {} + }, + "phase_c": { + "type": "Raw", + "value": {} + }, + "fault": { + "type": "Bitmap", + "value": { + "label": [ + "short_circuit_alarm", + "surge_alarm", + "overload_alarm", + "leakagecurr_alarm", + "temp_dif_fault", + "fire_alarm", + "high_power_alarm", + "self_test_alarm", + "ov_cr", + "unbalance_alarm", + "ov_vol", + "undervoltage_alarm", + "miss_phase_alarm", + "outage_alarm", + "magnetism_alarm", + "credit_alarm", + "no_balance_alarm" + ] + } + }, + "energy_reset": { + "type": "Enum", + "value": { + "range": ["empty"] + } + }, + "alarm_set_1": { + "type": "Raw", + "value": {} + }, + "alarm_set_2": { + "type": "Raw", + "value": {} + }, + "breaker_number": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "supply_frequency": { + "type": "Integer", + "value": { + "unit": "Hz", + "min": 0, + "max": 9999, + "scale": 2, + "step": 1 + } + }, + "online_state": { + "type": "Enum", + "value": { + "range": ["online", "offline"] + } + } + }, + "status": { + "forward_energy_total": 2435416, + "phase_a": "CKMAAn0AAGw=", + "phase_b": "CIsAK8MACWo=", + "phase_c": "CJwAA5EAAFw=", + "fault": 0, + "energy_reset": "", + "alarm_set_1": "BwEADQ==", + "alarm_set_2": "AQEAPAMBAP0EAQC0BQEAAAcBAAAIAQAeCQAAAA==", + "breaker_number": "SPM02_6588", + "supply_frequency": 5000, + "online_state": "online" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/kg_smart_valve.json b/tests/components/tuya/fixtures/kg_smart_valve.json new file mode 100644 index 00000000000..63d9148afbf --- /dev/null +++ b/tests/components/tuya/fixtures/kg_smart_valve.json @@ -0,0 +1,56 @@ +{ + "endpoint": "https://apigw.tuyaus.com", + "terminal_id": "1750526976566fMhqJs", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": true, + "id": "0665305284f3ebe9fdc1", + "name": "QT-Switch", + "category": "kg", + "product_id": "gbm9ata1zrzaez4a", + "product_name": "Smart Valve", + "online": false, + "sub": false, + "time_zone": "-05:00", + "active_time": "2020-01-27T23:37:47+00:00", + "create_time": "2020-01-27T23:37:47+00:00", + "update_time": "2020-01-27T23:37:47+00:00", + "function": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + } + }, + "status_range": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + } + }, + "status": { + "switch_1": false, + "countdown_1": 0 + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/kj_bladeless_tower_fan.json b/tests/components/tuya/fixtures/kj_bladeless_tower_fan.json new file mode 100644 index 00000000000..909022793ba --- /dev/null +++ b/tests/components/tuya/fixtures/kj_bladeless_tower_fan.json @@ -0,0 +1,79 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "CENSORED", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "CENSORED", + "name": "Bree", + "category": "kj", + "product_id": "yrzylxax1qspdgpp", + "product_name": "40\" Bladeless Tower Fan", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2025-06-22T07:35:33+00:00", + "create_time": "2025-06-22T07:35:33+00:00", + "update_time": "2025-06-22T07:35:33+00:00", + "function": { + "switch": { + "type": "Boolean", + "value": {} + }, + "mode": { + "type": "Enum", + "value": { + "range": ["sleep"] + } + }, + "countdown_set": { + "type": "Enum", + "value": { + "range": ["cancel", "1h", "2h", "3h", "4h", "5h"] + } + } + }, + "status_range": { + "switch": { + "type": "Boolean", + "value": {} + }, + "mode": { + "type": "Enum", + "value": { + "range": ["sleep"] + } + }, + "countdown_set": { + "type": "Enum", + "value": { + "range": ["cancel", "1h", "2h", "3h", "4h", "5h"] + } + }, + "countdown_left": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 1440, + "scale": 0, + "step": 1 + } + }, + "fault": { + "type": "Bitmap", + "value": { + "label": ["E1", "E2"] + } + } + }, + "status": { + "switch": false, + "mode": "normal", + "countdown_set": "cancel", + "countdown_left": 0, + "fault": 0 + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/mal_alarm_host.json b/tests/components/tuya/fixtures/mal_alarm_host.json new file mode 100644 index 00000000000..1a25a84ec2c --- /dev/null +++ b/tests/components/tuya/fixtures/mal_alarm_host.json @@ -0,0 +1,225 @@ +{ + "id": "123123aba12312312dazub", + "name": "Multifunction alarm", + "category": "mal", + "product_id": "gyitctrjj1kefxp2", + "product_name": "Multifunction alarm", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2024-12-02T20:08:56+00:00", + "create_time": "2024-12-02T20:08:56+00:00", + "update_time": "2024-12-02T20:08:56+00:00", + "function": { + "master_mode": { + "type": "Enum", + "value": { + "range": ["disarmed", "arm", "home", "sos"] + } + }, + "delay_set": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "alarm_time": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "switch_alarm_sound": { + "type": "Boolean", + "value": {} + }, + "switch_alarm_light": { + "type": "Boolean", + "value": {} + }, + "switch_mode_sound": { + "type": "Boolean", + "value": {} + }, + "switch_kb_sound": { + "type": "Boolean", + "value": {} + }, + "switch_kb_light": { + "type": "Boolean", + "value": {} + }, + "muffling": { + "type": "Boolean", + "value": {} + }, + "switch_alarm_propel": { + "type": "Boolean", + "value": {} + }, + "alarm_delay_time": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "master_state": { + "type": "Enum", + "value": { + "range": ["normal", "alarm"] + } + }, + "sub_class": { + "type": "Enum", + "value": { + "range": ["remote_controller", "detector"] + } + }, + "sub_admin": { + "type": "Raw", + "value": {} + } + }, + "status_range": { + "master_mode": { + "type": "Enum", + "value": { + "range": ["disarmed", "arm", "home", "sos"] + } + }, + "delay_set": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "alarm_time": { + "type": "Integer", + "value": { + "unit": "min", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "switch_alarm_sound": { + "type": "Boolean", + "value": {} + }, + "switch_alarm_light": { + "type": "Boolean", + "value": {} + }, + "switch_mode_sound": { + "type": "Boolean", + "value": {} + }, + "switch_kb_sound": { + "type": "Boolean", + "value": {} + }, + "switch_kb_light": { + "type": "Boolean", + "value": {} + }, + "telnet_state": { + "type": "Enum", + "value": { + "range": [ + "normal", + "network_no", + "phone_no", + "sim_card_no", + "network_search", + "signal_level_1", + "signal_level_2", + "signal_level_3", + "signal_level_4", + "signal_level_5" + ] + } + }, + "muffling": { + "type": "Boolean", + "value": {} + }, + "alarm_msg": { + "type": "Raw", + "value": {} + }, + "switch_alarm_propel": { + "type": "Boolean", + "value": {} + }, + "alarm_delay_time": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "master_state": { + "type": "Enum", + "value": { + "range": ["normal", "alarm"] + } + }, + "sub_class": { + "type": "Enum", + "value": { + "range": ["remote_controller", "detector"] + } + }, + "sub_admin": { + "type": "Raw", + "value": {} + }, + "sub_state": { + "type": "Enum", + "value": { + "range": ["normal", "alarm", "fault", "others"] + } + } + }, + "status": { + "master_mode": "disarmed", + "delay_set": 15, + "alarm_time": 3, + "switch_alarm_sound": true, + "switch_alarm_light": true, + "switch_mode_sound": true, + "switch_kb_sound": false, + "switch_kb_light": false, + "telnet_state": "sim_card_no", + "muffling": false, + "alarm_msg": "AFMAZQBuAHMAbwByACAATABvAHcAIABCAGEAdAB0AGUAcgB5AAoAWgBvAG4AZQA6ADAAMAA1AEUAbgB0AHIAYQBuAGMAZQ==", + "switch_alarm_propel": true, + "alarm_delay_time": 20, + "master_state": "normal", + "sub_class": "remote_controller", + "sub_admin": "AgEFCggC////HABLAGkAdABjAGgAZQBuACAAUwBtAG8AawBlACBjAAL///8gAHUAbgBkAGUAbABlAHQAYQBiAGwAZQA6AEUATwBMADFkAAL///8gAHUAbgBkAGUAbABlAHQAYQBiAGwAZQA6AEUATwBMADJlAAL///8gAHUAbgBkAGUAbABlAHQAYQBiAGwAZQA6AEUATwBMADNmAAL///8gAHUAbgBkAGUAbABlAHQAYQBiAGwAZQA6AEUATwBMADQ=", + "sub_state": "normal" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/mcs_door_sensor.json b/tests/components/tuya/fixtures/mcs_door_sensor.json index cec9547c2ea..c73b6c34878 100644 --- a/tests/components/tuya/fixtures/mcs_door_sensor.json +++ b/tests/components/tuya/fixtures/mcs_door_sensor.json @@ -1,16 +1,38 @@ { + "endpoint": "https://openapi.tuyaeu.com", + "auth_type": 0, + "country_code": "380", + "app_type": "smartlife", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, "id": "bf5cccf9027080e2dbb9w3", - "name": "Door Sensor", + "name": "Door Garage ", + "model": "", "category": "mcs", "product_id": "7jIGJAymiH8OsFFb", "product_name": "Door Sensor", "online": true, + "sub": true, + "time_zone": "+01:00", + "active_time": "2024-01-18T12:27:56+00:00", + "create_time": "2024-01-18T12:27:56+00:00", + "update_time": "2024-01-18T12:29:19+00:00", "function": {}, "status_range": { - "switch": { "type": "Boolean", "values": "{}" }, + "switch": { + "type": "Boolean", + "value": {} + }, "battery": { "type": "Integer", - "values": "{\"unit\": \"\", \"min\": 0, \"max\": 500, \"scale\": 0, \"step\": 1}" + "value": { + "unit": "", + "min": 0, + "max": 500, + "scale": 0, + "step": 1 + } } }, "status": { diff --git a/tests/components/tuya/fixtures/rqbj_gas_sensor.json b/tests/components/tuya/fixtures/rqbj_gas_sensor.json new file mode 100644 index 00000000000..58cbaedb0f1 --- /dev/null +++ b/tests/components/tuya/fixtures/rqbj_gas_sensor.json @@ -0,0 +1,90 @@ +{ + "endpoint": "https://apigw.tuyaus.com", + "terminal_id": "17421891051898r7yM6", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "ebb9d0eb5014f98cfboxbz", + "name": "Gas sensor", + "category": "rqbj", + "product_id": "4iqe2hsfyd86kwwc", + "product_name": "Gas sensor", + "online": true, + "sub": false, + "time_zone": "-04:00", + "active_time": "2025-06-24T20:33:10+00:00", + "create_time": "2025-06-24T20:33:10+00:00", + "update_time": "2025-06-24T20:33:10+00:00", + "function": { + "alarm_time": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 3600, + "scale": 0, + "step": 1 + } + }, + "self_checking": { + "type": "Boolean", + "value": {} + }, + "muffling": { + "type": "Boolean", + "value": {} + } + }, + "status_range": { + "checking_result": { + "type": "Enum", + "value": { + "range": ["checking", "check_success", "check_failure", "others"] + } + }, + "gas_sensor_status": { + "type": "Enum", + "value": { + "range": ["alarm", "normal"] + } + }, + "alarm_time": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 3600, + "scale": 0, + "step": 1 + } + }, + "gas_sensor_value": { + "type": "Integer", + "value": { + "unit": "ppm", + "min": 0, + "max": 999, + "scale": 0, + "step": 1 + } + }, + "self_checking": { + "type": "Boolean", + "value": {} + }, + "muffling": { + "type": "Boolean", + "value": {} + } + }, + "status": { + "checking_result": "check_success", + "gas_sensor_status": "normal", + "alarm_time": 300, + "gas_sensor_value": 0, + "self_checking": false, + "muffling": true + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/sfkzq_valve_controller.json b/tests/components/tuya/fixtures/sfkzq_valve_controller.json new file mode 100644 index 00000000000..dd95050e2bf --- /dev/null +++ b/tests/components/tuya/fixtures/sfkzq_valve_controller.json @@ -0,0 +1,56 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1739471569144tcmeiO", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bfb9bfc18eeaed2d85yt5m", + "name": "Sprinkler Cesare", + "category": "sfkzq", + "product_id": "o6dagifntoafakst", + "product_name": "Valve Controller", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2025-06-19T07:56:02+00:00", + "create_time": "2025-06-19T07:56:02+00:00", + "update_time": "2025-06-19T07:56:02+00:00", + "function": { + "switch": { + "type": "Boolean", + "value": {} + }, + "countdown": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + } + }, + "status_range": { + "switch": { + "type": "Boolean", + "value": {} + }, + "countdown": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + } + }, + "status": { + "switch": false, + "countdown": 0 + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/tdq_4_443.json b/tests/components/tuya/fixtures/tdq_4_443.json new file mode 100644 index 00000000000..c139e79d19b --- /dev/null +++ b/tests/components/tuya/fixtures/tdq_4_443.json @@ -0,0 +1,248 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1748383912663Y2lvlm", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bf082711d275c0c883vb4p", + "name": "4-433", + "category": "tdq", + "product_id": "cq1p0nt0a4rixnex", + "product_name": "4-433", + "online": false, + "sub": false, + "time_zone": "+02:00", + "active_time": "2025-06-12T16:57:13+00:00", + "create_time": "2025-06-12T16:57:13+00:00", + "update_time": "2025-06-12T16:57:13+00:00", + "function": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "switch_2": { + "type": "Boolean", + "value": {} + }, + "switch_3": { + "type": "Boolean", + "value": {} + }, + "switch_4": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_2": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_3": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_4": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "relay_status": { + "type": "Enum", + "value": { + "range": ["0", "1", "2"] + } + }, + "random_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "cycle_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "switch_inching": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "switch_type": { + "type": "Enum", + "value": { + "range": ["flip", "sync", "button"] + } + }, + "switch_interlock": { + "type": "Raw", + "value": {} + }, + "remote_add": { + "type": "Raw", + "value": {} + }, + "remote_list": { + "type": "Raw", + "value": {} + } + }, + "status_range": { + "switch_1": { + "type": "Boolean", + "value": {} + }, + "switch_2": { + "type": "Boolean", + "value": {} + }, + "switch_3": { + "type": "Boolean", + "value": {} + }, + "switch_4": { + "type": "Boolean", + "value": {} + }, + "countdown_1": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_2": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_3": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "countdown_4": { + "type": "Integer", + "value": { + "unit": "s", + "min": 0, + "max": 86400, + "scale": 0, + "step": 1 + } + }, + "test_bit": { + "type": "Integer", + "value": { + "min": 0, + "max": 5, + "scale": 0, + "step": 1 + } + }, + "relay_status": { + "type": "Enum", + "value": { + "range": ["0", "1", "2"] + } + }, + "random_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "cycle_time": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "switch_inching": { + "type": "String", + "value": { + "maxlen": 255 + } + }, + "switch_type": { + "type": "Enum", + "value": { + "range": ["flip", "sync", "button"] + } + }, + "switch_interlock": { + "type": "Raw", + "value": {} + }, + "remote_add": { + "type": "Raw", + "value": {} + }, + "remote_list": { + "type": "Raw", + "value": {} + } + }, + "status": { + "switch_1": false, + "switch_2": false, + "switch_3": false, + "switch_4": true, + "countdown_1": 0, + "countdown_2": 0, + "countdown_3": 0, + "countdown_4": 0, + "test_bit": 0, + "relay_status": 2, + "random_time": "", + "cycle_time": "", + "switch_inching": "AQAjAwAeBAACBgAC", + "switch_type": "button", + "switch_interlock": "", + "remote_add": "AAA=", + "remote_list": "AA==" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/wk_wifi_smart_gas_boiler_thermostat.json b/tests/components/tuya/fixtures/wk_wifi_smart_gas_boiler_thermostat.json new file mode 100644 index 00000000000..e96389ca215 --- /dev/null +++ b/tests/components/tuya/fixtures/wk_wifi_smart_gas_boiler_thermostat.json @@ -0,0 +1,188 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "xxxxxxxxxxxxxxxxxxx", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bfb45cb8a9452fba66lexg", + "name": "WiFi Smart Gas Boiler Thermostat ", + "category": "wk", + "product_id": "fi6dne5tu4t1nm6j", + "product_name": "WiFi Smart Gas Boiler Thermostat ", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2025-07-05T17:50:52+00:00", + "create_time": "2025-07-05T17:50:52+00:00", + "update_time": "2025-07-05T17:50:52+00:00", + "function": { + "switch": { + "type": "Boolean", + "value": {} + }, + "mode": { + "type": "Enum", + "value": { + "range": ["auto"] + } + }, + "temp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 50, + "max": 350, + "scale": 1, + "step": 5 + } + }, + "temp_correction": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -99, + "max": 99, + "scale": 1, + "step": 1 + } + }, + "upper_temp": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 150, + "max": 350, + "scale": 1, + "step": 5 + } + }, + "lower_temp": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 50, + "max": 140, + "scale": 1, + "step": 5 + } + }, + "child_lock": { + "type": "Boolean", + "value": {} + }, + "frost": { + "type": "Boolean", + "value": {} + }, + "factory_reset": { + "type": "Boolean", + "value": {} + } + }, + "status_range": { + "switch": { + "type": "Boolean", + "value": {} + }, + "mode": { + "type": "Enum", + "value": { + "range": ["auto"] + } + }, + "temp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 50, + "max": 350, + "scale": 1, + "step": 5 + } + }, + "temp_current": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 0, + "max": 800, + "scale": 1, + "step": 1 + } + }, + "temp_correction": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -99, + "max": 99, + "scale": 1, + "step": 1 + } + }, + "fault": { + "type": "Bitmap", + "value": { + "label": ["battery_temp_fault"] + } + }, + "upper_temp": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 150, + "max": 350, + "scale": 1, + "step": 5 + } + }, + "lower_temp": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": 50, + "max": 140, + "scale": 1, + "step": 5 + } + }, + "battery_percentage": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "child_lock": { + "type": "Boolean", + "value": {} + }, + "frost": { + "type": "Boolean", + "value": {} + }, + "factory_reset": { + "type": "Boolean", + "value": {} + } + }, + "status": { + "switch": true, + "mode": "auto", + "temp_set": 220, + "temp_current": 249, + "temp_correction": -15, + "fault": 0, + "upper_temp": 350, + "lower_temp": 50, + "battery_percentage": 100, + "child_lock": false, + "frost": false, + "factory_reset": false + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/wsdcg_temperature_humidity.json b/tests/components/tuya/fixtures/wsdcg_temperature_humidity.json new file mode 100644 index 00000000000..06d07a4c506 --- /dev/null +++ b/tests/components/tuya/fixtures/wsdcg_temperature_humidity.json @@ -0,0 +1,158 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "17150293164666xhFUk", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + + "id": "bf316b8707b061f044th18", + "name": "NP DownStairs North", + "category": "wsdcg", + "product_id": "g2y6z3p3ja2qhyav", + "product_name": "\u6e29\u6e7f\u5ea6\u4f20\u611f\u5668wifi", + "online": true, + "sub": false, + "time_zone": "+10:30", + "active_time": "2023-12-22T03:38:57+00:00", + "create_time": "2023-12-22T03:38:57+00:00", + "update_time": "2023-12-22T03:38:57+00:00", + "function": { + "maxtemp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -200, + "max": 600, + "scale": 1, + "step": 1 + } + }, + "minitemp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -200, + "max": 600, + "scale": 1, + "step": 1 + } + }, + "maxhum_set": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "minihum_set": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + } + }, + "status_range": { + "va_temperature": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -200, + "max": 600, + "scale": 1, + "step": 1 + } + }, + "va_humidity": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "battery_percentage": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "maxtemp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -200, + "max": 600, + "scale": 1, + "step": 1 + } + }, + "minitemp_set": { + "type": "Integer", + "value": { + "unit": "\u2103", + "min": -200, + "max": 600, + "scale": 1, + "step": 1 + } + }, + "maxhum_set": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "minihum_set": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + }, + "temp_alarm": { + "type": "Enum", + "value": { + "range": ["loweralarm", "upperalarm", "cancel"] + } + }, + "hum_alarm": { + "type": "Enum", + "value": { + "range": ["loweralarm", "upperalarm", "cancel"] + } + } + }, + "status": { + "va_temperature": 185, + "va_humidity": 47, + "battery_percentage": 0, + "maxtemp_set": 600, + "minitemp_set": -100, + "maxhum_set": 100, + "minihum_set": 0, + "temp_alarm": "cancel", + "hum_alarm": "cancel" + }, + "set_up": true, + "support_local": true +} diff --git a/tests/components/tuya/fixtures/wxkg_wireless_switch.json b/tests/components/tuya/fixtures/wxkg_wireless_switch.json new file mode 100644 index 00000000000..376276099cc --- /dev/null +++ b/tests/components/tuya/fixtures/wxkg_wireless_switch.json @@ -0,0 +1,50 @@ +{ + "endpoint": "https://openapi.tuyaeu.com", + "auth_type": 0, + "country_code": "44", + "app_type": "smartlife", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "name": "Bathroom Smart Switch", + "model": "LKWSW201", + "category": "wxkg", + "product_id": "l8yaz4um5b3pwyvf", + "product_name": "Wireless Switch", + "online": true, + "sub": false, + "time_zone": "+00:00", + "active_time": "2023-01-05T20:12:39+00:00", + "create_time": "2023-01-05T20:12:39+00:00", + "update_time": "2023-05-30T17:17:47+00:00", + "function": {}, + "status_range": { + "switch_mode1": { + "type": "Enum", + "value": { + "range": ["click", "press"] + } + }, + "switch_mode2": { + "type": "Enum", + "value": { + "range": ["click", "press"] + } + }, + "battery_percentage": { + "type": "Integer", + "value": { + "unit": "%", + "min": 0, + "max": 100, + "scale": 0, + "step": 1 + } + } + }, + "status": { + "switch_mode1": "click", + "switch_mode2": "click", + "battery_percentage": 100 + } +} diff --git a/tests/components/tuya/fixtures/zndb_smart_meter.json b/tests/components/tuya/fixtures/zndb_smart_meter.json new file mode 100644 index 00000000000..139cf814347 --- /dev/null +++ b/tests/components/tuya/fixtures/zndb_smart_meter.json @@ -0,0 +1,79 @@ +{ + "endpoint": "https://apigw.tuyaeu.com", + "terminal_id": "1739198173271wpFacM", + "mqtt_connected": true, + "disabled_by": null, + "disabled_polling": false, + "id": "bfe33b4c74661f1f1bgacy", + "name": "Meter", + "category": "zndb", + "product_id": "ze8faryrxr0glqnn", + "product_name": "PJ2101A 1P WiFi Smart Meter ", + "online": true, + "sub": false, + "time_zone": "+02:00", + "active_time": "2024-08-24T11:22:33+00:00", + "create_time": "2024-08-24T11:22:33+00:00", + "update_time": "2024-08-24T11:22:33+00:00", + "function": { + "forward_energy_total": { + "type": "Integer", + "value": { + "unit": "kW\u00b7h", + "min": 0, + "max": 99999999, + "scale": 2, + "step": 1 + } + }, + "energy_month": { + "type": "raw", + "value": {} + }, + "energy_daily": { + "type": "raw", + "value": {} + } + }, + "status_range": { + "energy_month": { + "type": "raw", + "value": {} + }, + "energy_daily": { + "type": "raw", + "value": {} + }, + "phase_a": { + "type": "raw", + "value": {} + }, + "forward_energy_total": { + "type": "Integer", + "value": { + "unit": "kW\u00b7h", + "min": 0, + "max": 99999999, + "scale": 2, + "step": 1 + } + }, + "reverse_energy_total": { + "type": "Integer", + "value": { + "unit": "kW\u00b7h", + "min": 0, + "max": 99999999, + "scale": 2, + "step": 1 + } + } + }, + "status": { + "energy_month": "GAkYCQAAANQ=", + "energy_daily": "", + "phase_a": "CSIAFfQABKE=" + }, + "set_up": true, + "support_local": false +} diff --git a/tests/components/tuya/snapshots/test_alarm_control_panel.ambr b/tests/components/tuya/snapshots/test_alarm_control_panel.ambr new file mode 100644 index 00000000000..97076d5e467 --- /dev/null +++ b/tests/components/tuya/snapshots/test_alarm_control_panel.ambr @@ -0,0 +1,53 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[mal_alarm_host][alarm_control_panel.multifunction_alarm-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'alarm_control_panel', + 'entity_category': None, + 'entity_id': 'alarm_control_panel.multifunction_alarm', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'tuya.123123aba12312312dazubmaster_mode', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[mal_alarm_host][alarm_control_panel.multifunction_alarm-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'changed_by': None, + 'code_arm_required': False, + 'code_format': None, + 'friendly_name': 'Multifunction alarm', + 'supported_features': , + }), + 'context': , + 'entity_id': 'alarm_control_panel.multifunction_alarm', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'disarmed', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_binary_sensor.ambr b/tests/components/tuya/snapshots/test_binary_sensor.ambr new file mode 100644 index 00000000000..efd995b3280 --- /dev/null +++ b/tests/components/tuya/snapshots/test_binary_sensor.ambr @@ -0,0 +1,246 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_defrost-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.dehumidifier_defrost', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Defrost', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'defrost', + 'unique_id': 'tuya.bf3fce6af592f12df3gbgqdefrost', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_defrost-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'problem', + 'friendly_name': 'Dehumidifier Defrost', + }), + 'context': , + 'entity_id': 'binary_sensor.dehumidifier_defrost', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_tank_full-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.dehumidifier_tank_full', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Tank full', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'tankfull', + 'unique_id': 'tuya.bf3fce6af592f12df3gbgqtankfull', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_tank_full-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'problem', + 'friendly_name': 'Dehumidifier Tank full', + }), + 'context': , + 'entity_id': 'binary_sensor.dehumidifier_tank_full', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_wet-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': , + 'entity_id': 'binary_sensor.dehumidifier_wet', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Wet', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'wet', + 'unique_id': 'tuya.bf3fce6af592f12df3gbgqwet', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][binary_sensor.dehumidifier_wet-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'problem', + 'friendly_name': 'Dehumidifier Wet', + }), + 'context': , + 'entity_id': 'binary_sensor.dehumidifier_wet', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[mcs_door_sensor][binary_sensor.door_garage_door-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': None, + 'entity_id': 'binary_sensor.door_garage_door', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Door', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'tuya.bf5cccf9027080e2dbb9w3switch', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[mcs_door_sensor][binary_sensor.door_garage_door-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'door', + 'friendly_name': 'Door Garage Door', + }), + 'context': , + 'entity_id': 'binary_sensor.door_garage_door', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[rqbj_gas_sensor][binary_sensor.gas_sensor_gas-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'binary_sensor', + 'entity_category': None, + 'entity_id': 'binary_sensor.gas_sensor_gas', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Gas', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'tuya.ebb9d0eb5014f98cfboxbzgas_sensor_status', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[rqbj_gas_sensor][binary_sensor.gas_sensor_gas-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'gas', + 'friendly_name': 'Gas sensor Gas', + }), + 'context': , + 'entity_id': 'binary_sensor.gas_sensor_gas', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_climate.ambr b/tests/components/tuya/snapshots/test_climate.ambr new file mode 100644 index 00000000000..4360ef7f436 --- /dev/null +++ b/tests/components/tuya/snapshots/test_climate.ambr @@ -0,0 +1,67 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[wk_wifi_smart_gas_boiler_thermostat][climate.wifi_smart_gas_boiler_thermostat-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'hvac_modes': list([ + , + , + ]), + 'max_temp': 35.0, + 'min_temp': 5.0, + 'target_temp_step': 0.5, + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'climate', + 'entity_category': None, + 'entity_id': 'climate.wifi_smart_gas_boiler_thermostat', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'tuya.bfb45cb8a9452fba66lexg', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[wk_wifi_smart_gas_boiler_thermostat][climate.wifi_smart_gas_boiler_thermostat-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'current_temperature': 24.9, + 'friendly_name': 'WiFi Smart Gas Boiler Thermostat ', + 'hvac_modes': list([ + , + , + ]), + 'max_temp': 35.0, + 'min_temp': 5.0, + 'supported_features': , + 'target_temp_step': 0.5, + 'temperature': 22.0, + }), + 'context': , + 'entity_id': 'climate.wifi_smart_gas_boiler_thermostat', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'heat_cool', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_cover.ambr b/tests/components/tuya/snapshots/test_cover.ambr new file mode 100644 index 00000000000..1ab635919ca --- /dev/null +++ b/tests/components/tuya/snapshots/test_cover.ambr @@ -0,0 +1,103 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[am43_corded_motor_zigbee_cover][cover.kitchen_blinds_curtain-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'cover', + 'entity_category': None, + 'entity_id': 'cover.kitchen_blinds_curtain', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Curtain', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'curtain', + 'unique_id': 'tuya.zah67ekdcontrol', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[am43_corded_motor_zigbee_cover][cover.kitchen_blinds_curtain-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'current_position': 48, + 'device_class': 'curtain', + 'friendly_name': 'Kitchen Blinds Curtain', + 'supported_features': , + }), + 'context': , + 'entity_id': 'cover.kitchen_blinds_curtain', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'open', + }) +# --- +# name: test_platform_setup_and_discovery[clkg_curtain_switch][cover.tapparelle_studio_curtain-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'cover', + 'entity_category': None, + 'entity_id': 'cover.tapparelle_studio_curtain', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Curtain', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'curtain', + 'unique_id': 'tuya.bf1fa053e0ba4e002c6we8control', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[clkg_curtain_switch][cover.tapparelle_studio_curtain-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'current_position': 0, + 'device_class': 'curtain', + 'friendly_name': 'Tapparelle studio Curtain', + 'supported_features': , + }), + 'context': , + 'entity_id': 'cover.tapparelle_studio_curtain', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'closed', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_diagnostics.ambr b/tests/components/tuya/snapshots/test_diagnostics.ambr new file mode 100644 index 00000000000..5fc3796d109 --- /dev/null +++ b/tests/components/tuya/snapshots/test_diagnostics.ambr @@ -0,0 +1,183 @@ +# serializer version: 1 +# name: test_device_diagnostics[rqbj_gas_sensor] + dict({ + 'active_time': '2025-06-24T20:33:10+00:00', + 'category': 'rqbj', + 'create_time': '2025-06-24T20:33:10+00:00', + 'disabled_by': None, + 'disabled_polling': False, + 'endpoint': 'https://apigw.tuyaeu.com', + 'function': dict({ + 'null': dict({ + 'type': 'Boolean', + 'value': dict({ + }), + }), + }), + 'home_assistant': dict({ + 'disabled': False, + 'disabled_by': None, + 'entities': list([ + dict({ + 'device_class': None, + 'disabled': False, + 'disabled_by': None, + 'entity_category': None, + 'icon': None, + 'original_device_class': 'gas', + 'original_icon': None, + 'state': dict({ + 'attributes': dict({ + 'device_class': 'gas', + 'friendly_name': 'Gas sensor Gas', + }), + 'entity_id': 'binary_sensor.gas_sensor_gas', + 'state': 'off', + }), + 'unit_of_measurement': None, + }), + dict({ + 'device_class': None, + 'disabled': False, + 'disabled_by': None, + 'entity_category': None, + 'icon': None, + 'original_device_class': None, + 'original_icon': None, + 'state': dict({ + 'attributes': dict({ + 'friendly_name': 'Gas sensor Gas', + 'state_class': 'measurement', + 'unit_of_measurement': 'ppm', + }), + 'entity_id': 'sensor.gas_sensor_gas', + 'state': '0.0', + }), + 'unit_of_measurement': 'ppm', + }), + ]), + 'name': 'Gas sensor', + 'name_by_user': None, + }), + 'id': 'ebb9d0eb5014f98cfboxbz', + 'mqtt_connected': True, + 'name': 'Gas sensor', + 'online': True, + 'product_id': '4iqe2hsfyd86kwwc', + 'product_name': 'Gas sensor', + 'set_up': True, + 'status': dict({ + 'alarm_time': 300, + 'checking_result': 'check_success', + 'gas_sensor_status': 'normal', + 'gas_sensor_value': 0, + 'muffling': True, + 'self_checking': False, + }), + 'status_range': dict({ + 'null': dict({ + 'type': 'Boolean', + 'value': dict({ + }), + }), + }), + 'sub': False, + 'support_local': True, + 'terminal_id': '7cd96aff-6ec8-4006-b093-3dbff7947591', + 'time_zone': '-04:00', + 'update_time': '2025-06-24T20:33:10+00:00', + }) +# --- +# name: test_entry_diagnostics[rqbj_gas_sensor] + dict({ + 'devices': list([ + dict({ + 'active_time': '2025-06-24T20:33:10+00:00', + 'category': 'rqbj', + 'create_time': '2025-06-24T20:33:10+00:00', + 'function': dict({ + 'null': dict({ + 'type': 'Boolean', + 'value': dict({ + }), + }), + }), + 'home_assistant': dict({ + 'disabled': False, + 'disabled_by': None, + 'entities': list([ + dict({ + 'device_class': None, + 'disabled': False, + 'disabled_by': None, + 'entity_category': None, + 'icon': None, + 'original_device_class': 'gas', + 'original_icon': None, + 'state': dict({ + 'attributes': dict({ + 'device_class': 'gas', + 'friendly_name': 'Gas sensor Gas', + }), + 'entity_id': 'binary_sensor.gas_sensor_gas', + 'state': 'off', + }), + 'unit_of_measurement': None, + }), + dict({ + 'device_class': None, + 'disabled': False, + 'disabled_by': None, + 'entity_category': None, + 'icon': None, + 'original_device_class': None, + 'original_icon': None, + 'state': dict({ + 'attributes': dict({ + 'friendly_name': 'Gas sensor Gas', + 'state_class': 'measurement', + 'unit_of_measurement': 'ppm', + }), + 'entity_id': 'sensor.gas_sensor_gas', + 'state': '0.0', + }), + 'unit_of_measurement': 'ppm', + }), + ]), + 'name': 'Gas sensor', + 'name_by_user': None, + }), + 'id': 'ebb9d0eb5014f98cfboxbz', + 'name': 'Gas sensor', + 'online': True, + 'product_id': '4iqe2hsfyd86kwwc', + 'product_name': 'Gas sensor', + 'set_up': True, + 'status': dict({ + 'alarm_time': 300, + 'checking_result': 'check_success', + 'gas_sensor_status': 'normal', + 'gas_sensor_value': 0, + 'muffling': True, + 'self_checking': False, + }), + 'status_range': dict({ + 'null': dict({ + 'type': 'Boolean', + 'value': dict({ + }), + }), + }), + 'sub': False, + 'support_local': True, + 'time_zone': '-04:00', + 'update_time': '2025-06-24T20:33:10+00:00', + }), + ]), + 'disabled_by': None, + 'disabled_polling': False, + 'endpoint': 'https://apigw.tuyaeu.com', + 'mqtt_connected': True, + 'terminal_id': '7cd96aff-6ec8-4006-b093-3dbff7947591', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_event.ambr b/tests/components/tuya/snapshots/test_event.ambr new file mode 100644 index 00000000000..085ebd3ec8b --- /dev/null +++ b/tests/components/tuya/snapshots/test_event.ambr @@ -0,0 +1,119 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][event.bathroom_smart_switch_button_1-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'event_types': list([ + 'click', + 'press', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.bathroom_smart_switch_button_1', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Button 1', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'numbered_button', + 'unique_id': 'tuya.mocked_device_idswitch_mode1', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][event.bathroom_smart_switch_button_1-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'button', + 'event_type': None, + 'event_types': list([ + 'click', + 'press', + ]), + 'friendly_name': 'Bathroom Smart Switch Button 1', + }), + 'context': , + 'entity_id': 'event.bathroom_smart_switch_button_1', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][event.bathroom_smart_switch_button_2-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'event_types': list([ + 'click', + 'press', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.bathroom_smart_switch_button_2', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Button 2', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'numbered_button', + 'unique_id': 'tuya.mocked_device_idswitch_mode2', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][event.bathroom_smart_switch_button_2-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'button', + 'event_type': None, + 'event_types': list([ + 'click', + 'press', + ]), + 'friendly_name': 'Bathroom Smart Switch Button 2', + }), + 'context': , + 'entity_id': 'event.bathroom_smart_switch_button_2', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_fan.ambr b/tests/components/tuya/snapshots/test_fan.ambr index 399056e7665..cbd3c997625 100644 --- a/tests/components/tuya/snapshots/test_fan.ambr +++ b/tests/components/tuya/snapshots/test_fan.ambr @@ -49,3 +49,60 @@ 'state': 'on', }) # --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][fan.bree-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'preset_modes': list([ + 'sleep', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'fan', + 'entity_category': None, + 'entity_id': 'fan.bree', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': None, + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': None, + 'unique_id': 'tuya.CENSORED', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][fan.bree-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Bree', + 'preset_mode': 'normal', + 'preset_modes': list([ + 'sleep', + ]), + 'supported_features': , + }), + 'context': , + 'entity_id': 'fan.bree', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_light.ambr b/tests/components/tuya/snapshots/test_light.ambr new file mode 100644 index 00000000000..b9395b3d682 --- /dev/null +++ b/tests/components/tuya/snapshots/test_light.ambr @@ -0,0 +1,58 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[clkg_curtain_switch][light.tapparelle_studio_backlight-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'supported_color_modes': list([ + , + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'light', + 'entity_category': , + 'entity_id': 'light.tapparelle_studio_backlight', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Backlight', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'backlight', + 'unique_id': 'tuya.bf1fa053e0ba4e002c6we8switch_backlight', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[clkg_curtain_switch][light.tapparelle_studio_backlight-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'color_mode': , + 'friendly_name': 'Tapparelle studio Backlight', + 'supported_color_modes': list([ + , + ]), + 'supported_features': , + }), + 'context': , + 'entity_id': 'light.tapparelle_studio_backlight', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_number.ambr b/tests/components/tuya/snapshots/test_number.ambr new file mode 100644 index 00000000000..6d741e4e76c --- /dev/null +++ b/tests/components/tuya/snapshots/test_number.ambr @@ -0,0 +1,58 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[cwwsq_cleverio_pf100][number.cleverio_pf100_feed-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'max': 20.0, + 'min': 1.0, + 'mode': , + 'step': 1.0, + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'number', + 'entity_category': None, + 'entity_id': 'number.cleverio_pf100_feed', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Feed', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'feed', + 'unique_id': 'tuya.bfd0273e59494eb34esvrxmanual_feed', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwwsq_cleverio_pf100][number.cleverio_pf100_feed-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Cleverio PF100 Feed', + 'max': 20.0, + 'min': 1.0, + 'mode': , + 'step': 1.0, + }), + 'context': , + 'entity_id': 'number.cleverio_pf100_feed', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '1.0', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_select.ambr b/tests/components/tuya/snapshots/test_select.ambr index a9daca637b5..e8337fb4fbf 100644 --- a/tests/components/tuya/snapshots/test_select.ambr +++ b/tests/components/tuya/snapshots/test_select.ambr @@ -1,4 +1,61 @@ # serializer version: 1 +# name: test_platform_setup_and_discovery[am43_corded_motor_zigbee_cover][select.kitchen_blinds_motor_mode-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'forward', + 'back', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.kitchen_blinds_motor_mode', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Motor mode', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'curtain_motor_mode', + 'unique_id': 'tuya.zah67ekdcontrol_back_mode', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[am43_corded_motor_zigbee_cover][select.kitchen_blinds_motor_mode-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Kitchen Blinds Motor mode', + 'options': list([ + 'forward', + 'back', + ]), + }), + 'context': , + 'entity_id': 'select.kitchen_blinds_motor_mode', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'forward', + }) +# --- # name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][select.dehumidifier_countdown-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ @@ -60,3 +117,127 @@ 'state': 'cancel', }) # --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][select.bree_countdown-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + 'cancel', + '1h', + '2h', + '3h', + '4h', + '5h', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.bree_countdown', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Countdown', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'countdown', + 'unique_id': 'tuya.CENSOREDcountdown_set', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][select.bree_countdown-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Bree Countdown', + 'options': list([ + 'cancel', + '1h', + '2h', + '3h', + '4h', + '5h', + ]), + }), + 'context': , + 'entity_id': 'select.bree_countdown', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'cancel', + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][select.4_433_power_on_behavior-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'options': list([ + '0', + '1', + '2', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'select', + 'entity_category': , + 'entity_id': 'select.4_433_power_on_behavior', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Power on behavior', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'relay_status', + 'unique_id': 'tuya.bf082711d275c0c883vb4prelay_status', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][select.4_433_power_on_behavior-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': '4-433 Power on behavior', + 'options': list([ + '0', + '1', + '2', + ]), + }), + 'context': , + 'entity_id': 'select.4_433_power_on_behavior', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_sensor.ambr b/tests/components/tuya/snapshots/test_sensor.ambr index 47709b03a5e..3704aa4f067 100644 --- a/tests/components/tuya/snapshots/test_sensor.ambr +++ b/tests/components/tuya/snapshots/test_sensor.ambr @@ -52,7 +52,1155 @@ 'state': '47.0', }) # --- -# name: test_platform_setup_and_discovery[mcs_door_sensor][sensor.door_sensor_battery-entry] +# name: test_platform_setup_and_discovery[cwwsq_cleverio_pf100][sensor.cleverio_pf100_last_amount-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.cleverio_pf100_last_amount', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Last amount', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'last_amount', + 'unique_id': 'tuya.bfd0273e59494eb34esvrxfeed_report', + 'unit_of_measurement': '', + }) +# --- +# name: test_platform_setup_and_discovery[cwwsq_cleverio_pf100][sensor.cleverio_pf100_last_amount-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Cleverio PF100 Last amount', + 'state_class': , + 'unit_of_measurement': '', + }), + 'context': , + 'entity_id': 'sensor.cleverio_pf100_last_amount', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '2.0', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_filter_duration-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.pixi_smart_drinking_fountain_filter_duration', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Filter duration', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'filter_duration', + 'unique_id': 'tuya.23536058083a8dc57d96filter_life', + 'unit_of_measurement': 'min', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_filter_duration-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Filter duration', + 'state_class': , + 'unit_of_measurement': 'min', + }), + 'context': , + 'entity_id': 'sensor.pixi_smart_drinking_fountain_filter_duration', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '18965.0', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_uv_runtime-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.pixi_smart_drinking_fountain_uv_runtime', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'UV runtime', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'uv_runtime', + 'unique_id': 'tuya.23536058083a8dc57d96uv_runtime', + 'unit_of_measurement': 's', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_uv_runtime-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain UV runtime', + 'state_class': , + 'unit_of_measurement': 's', + }), + 'context': , + 'entity_id': 'sensor.pixi_smart_drinking_fountain_uv_runtime', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_level-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_level', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Water level', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'water_level_state', + 'unique_id': 'tuya.23536058083a8dc57d96water_level', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_level-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Water level', + }), + 'context': , + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_level', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'level_3', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_pump_duration-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_pump_duration', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Water pump duration', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'pump_time', + 'unique_id': 'tuya.23536058083a8dc57d96pump_time', + 'unit_of_measurement': 'min', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_pump_duration-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Water pump duration', + 'state_class': , + 'unit_of_measurement': 'min', + }), + 'context': , + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_pump_duration', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '18965.0', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_usage_duration-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_usage_duration', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Water usage duration', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'water_time', + 'unique_id': 'tuya.23536058083a8dc57d96water_time', + 'unit_of_measurement': 'min', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][sensor.pixi_smart_drinking_fountain_water_usage_duration-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Water usage duration', + 'state_class': , + 'unit_of_measurement': 'min', + }), + 'context': , + 'entity_id': 'sensor.pixi_smart_drinking_fountain_water_usage_duration', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.hvac_meter_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'current', + 'unique_id': 'tuya.eb0c772dabbb19d653ssi5cur_current', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': 'HVAC Meter Current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.hvac_meter_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.083', + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.hvac_meter_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'power', + 'unique_id': 'tuya.eb0c772dabbb19d653ssi5cur_power', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'HVAC Meter Power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.hvac_meter_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '6.4', + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.hvac_meter_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'voltage', + 'unique_id': 'tuya.eb0c772dabbb19d653ssi5cur_voltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][sensor.hvac_meter_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': 'HVAC Meter Voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.hvac_meter_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '121.7', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'current', + 'unique_id': 'tuya.mocked_device_idcur_current', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': '一路带计量磁保持通断器 Current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '2.198', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'power', + 'unique_id': 'tuya.mocked_device_idcur_power', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': '一路带计量磁保持通断器 Power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '495.3', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'voltage', + 'unique_id': 'tuya.mocked_device_idcur_voltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': '一路带计量磁保持通断器 Voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '231.4', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_current', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_aelectriccurrent', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase A current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.637', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_power', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_apower', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase A power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.108', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_voltage', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_avoltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_a_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase A voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_a_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '221.1', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase B current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_b_current', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_belectriccurrent', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase B current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '11.203', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase B power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_b_power', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_bpower', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase B power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '2.41', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase B voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_b_voltage', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_bvoltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_b_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase B voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_b_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '218.7', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase C current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_c_current', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_celectriccurrent', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase C current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.913', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase C power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_c_power', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_cpower', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase C power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.092', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase C voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_c_voltage', + 'unique_id': 'tuya.bf5e5bde2c52cb5994cd27phase_cvoltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[dlq_metering_3pn_wifi][sensor.metering_3pn_wifi_stable_phase_c_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': 'Metering_3PN_WiFi_stable Phase C voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.metering_3pn_wifi_stable_phase_c_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '220.4', + }) +# --- +# name: test_platform_setup_and_discovery[mcs_door_sensor][sensor.door_garage_battery-entry] EntityRegistryEntrySnapshot({ 'aliases': set({ }), @@ -67,7 +1215,7 @@ 'disabled_by': None, 'domain': 'sensor', 'entity_category': , - 'entity_id': 'sensor.door_sensor_battery', + 'entity_id': 'sensor.door_garage_battery', 'has_entity_name': True, 'hidden_by': None, 'icon': None, @@ -89,19 +1237,454 @@ 'unit_of_measurement': '%', }) # --- -# name: test_platform_setup_and_discovery[mcs_door_sensor][sensor.door_sensor_battery-state] +# name: test_platform_setup_and_discovery[mcs_door_sensor][sensor.door_garage_battery-state] StateSnapshot({ 'attributes': ReadOnlyDict({ 'device_class': 'battery', - 'friendly_name': 'Door Sensor Battery', + 'friendly_name': 'Door Garage Battery', 'state_class': , 'unit_of_measurement': '%', }), 'context': , - 'entity_id': 'sensor.door_sensor_battery', + 'entity_id': 'sensor.door_garage_battery', 'last_changed': , 'last_reported': , 'last_updated': , 'state': '100.0', }) # --- +# name: test_platform_setup_and_discovery[rqbj_gas_sensor][sensor.gas_sensor_gas-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.gas_sensor_gas', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Gas', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'gas', + 'unique_id': 'tuya.ebb9d0eb5014f98cfboxbzgas_sensor_value', + 'unit_of_measurement': 'ppm', + }) +# --- +# name: test_platform_setup_and_discovery[rqbj_gas_sensor][sensor.gas_sensor_gas-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Gas sensor Gas', + 'state_class': , + 'unit_of_measurement': 'ppm', + }), + 'context': , + 'entity_id': 'sensor.gas_sensor_gas', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_battery-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.np_downstairs_north_battery', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Battery', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'battery', + 'unique_id': 'tuya.bf316b8707b061f044th18battery_percentage', + 'unit_of_measurement': '%', + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_battery-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'battery', + 'friendly_name': 'NP DownStairs North Battery', + 'state_class': , + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.np_downstairs_north_battery', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '0.0', + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_humidity-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.np_downstairs_north_humidity', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Humidity', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'humidity', + 'unique_id': 'tuya.bf316b8707b061f044th18va_humidity', + 'unit_of_measurement': '%', + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_humidity-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'humidity', + 'friendly_name': 'NP DownStairs North Humidity', + 'state_class': , + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.np_downstairs_north_humidity', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '47.0', + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_temperature-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.np_downstairs_north_temperature', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 1, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Temperature', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'temperature', + 'unique_id': 'tuya.bf316b8707b061f044th18va_temperature', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[wsdcg_temperature_humidity][sensor.np_downstairs_north_temperature-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'temperature', + 'friendly_name': 'NP DownStairs North Temperature', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.np_downstairs_north_temperature', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '18.5', + }) +# --- +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][sensor.bathroom_smart_switch_battery-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': , + 'entity_id': 'sensor.bathroom_smart_switch_battery', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Battery', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'battery', + 'unique_id': 'tuya.mocked_device_idbattery_percentage', + 'unit_of_measurement': '%', + }) +# --- +# name: test_platform_setup_and_discovery[wxkg_wireless_switch][sensor.bathroom_smart_switch_battery-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'battery', + 'friendly_name': 'Bathroom Smart Switch Battery', + 'state_class': , + 'unit_of_measurement': '%', + }), + 'context': , + 'entity_id': 'sensor.bathroom_smart_switch_battery', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '100.0', + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_current-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.meter_phase_a_current', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A current', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_current', + 'unique_id': 'tuya.bfe33b4c74661f1f1bgacyphase_aelectriccurrent', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_current-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'current', + 'friendly_name': 'Meter Phase A current', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.meter_phase_a_current', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '5.62', + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.meter_phase_a_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 2, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_power', + 'unique_id': 'tuya.bfe33b4c74661f1f1bgacyphase_apower', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'power', + 'friendly_name': 'Meter Phase A power', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.meter_phase_a_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '1.185', + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_voltage-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': dict({ + 'state_class': , + }), + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'sensor', + 'entity_category': None, + 'entity_id': 'sensor.meter_phase_a_voltage', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + 'sensor': dict({ + 'suggested_display_precision': 0, + }), + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Phase A voltage', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'phase_a_voltage', + 'unique_id': 'tuya.bfe33b4c74661f1f1bgacyphase_avoltage', + 'unit_of_measurement': , + }) +# --- +# name: test_platform_setup_and_discovery[zndb_smart_meter][sensor.meter_phase_a_voltage-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'voltage', + 'friendly_name': 'Meter Phase A voltage', + 'state_class': , + 'unit_of_measurement': , + }), + 'context': , + 'entity_id': 'sensor.meter_phase_a_voltage', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': '233.8', + }) +# --- diff --git a/tests/components/tuya/snapshots/test_switch.ambr b/tests/components/tuya/snapshots/test_switch.ambr new file mode 100644 index 00000000000..bf970a6ffbb --- /dev/null +++ b/tests/components/tuya/snapshots/test_switch.ambr @@ -0,0 +1,969 @@ +# serializer version: 1 +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][switch.dehumidifier_child_lock-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.dehumidifier_child_lock', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': 'mdi:account-lock', + 'original_name': 'Child lock', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'child_lock', + 'unique_id': 'tuya.bf3fce6af592f12df3gbgqchild_lock', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cs_arete_two_12l_dehumidifier_air_purifier][switch.dehumidifier_child_lock-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Dehumidifier Child lock', + 'icon': 'mdi:account-lock', + }), + 'context': , + 'entity_id': 'switch.dehumidifier_child_lock', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_filter_reset-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_filter_reset', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Filter reset', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'filter_reset', + 'unique_id': 'tuya.23536058083a8dc57d96filter_reset', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_filter_reset-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Filter reset', + }), + 'context': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_filter_reset', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.pixi_smart_drinking_fountain_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'power', + 'unique_id': 'tuya.23536058083a8dc57d96switch', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Power', + }), + 'context': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_reset_of_water_usage_days-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_reset_of_water_usage_days', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Reset of water usage days', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'reset_of_water_usage_days', + 'unique_id': 'tuya.23536058083a8dc57d96water_reset', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_reset_of_water_usage_days-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Reset of water usage days', + }), + 'context': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_reset_of_water_usage_days', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_uv_sterilization-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_uv_sterilization', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'UV sterilization', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'uv_sterilization', + 'unique_id': 'tuya.23536058083a8dc57d96uv', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_uv_sterilization-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain UV sterilization', + }), + 'context': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_uv_sterilization', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_water_pump_reset-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_water_pump_reset', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Water pump reset', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'water_pump_reset', + 'unique_id': 'tuya.23536058083a8dc57d96pump_reset', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cwysj_pixi_smart_drinking_fountain][switch.pixi_smart_drinking_fountain_water_pump_reset-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'PIXI Smart Drinking Fountain Water pump reset', + }), + 'context': , + 'entity_id': 'switch.pixi_smart_drinking_fountain_water_pump_reset', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][switch.hvac_meter_socket_1-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.hvac_meter_socket_1', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Socket 1', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'socket_1', + 'unique_id': 'tuya.eb0c772dabbb19d653ssi5switch_1', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][switch.hvac_meter_socket_1-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': 'HVAC Meter Socket 1', + }), + 'context': , + 'entity_id': 'switch.hvac_meter_socket_1', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][switch.hvac_meter_socket_2-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.hvac_meter_socket_2', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Socket 2', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'socket_2', + 'unique_id': 'tuya.eb0c772dabbb19d653ssi5switch_2', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[cz_dual_channel_metering][switch.hvac_meter_socket_2-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': 'HVAC Meter Socket 2', + }), + 'context': , + 'entity_id': 'switch.hvac_meter_socket_2', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_child_lock-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_child_lock', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Child lock', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'child_lock', + 'unique_id': 'tuya.mocked_device_idchild_lock', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_child_lock-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': '一路带计量磁保持通断器 Child lock', + }), + 'context': , + 'entity_id': 'switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_child_lock', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_switch-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_switch', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Switch', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch', + 'unique_id': 'tuya.mocked_device_idswitch', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[dlq_earu_electric_eawcpt][switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_switch-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': '一路带计量磁保持通断器 Switch', + }), + 'context': , + 'entity_id': 'switch.yi_lu_dai_ji_liang_ci_bao_chi_tong_duan_qi_switch', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[kg_smart_valve][switch.qt_switch_switch_1-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.qt_switch_switch_1', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Switch 1', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch_1', + 'unique_id': 'tuya.0665305284f3ebe9fdc1switch_1', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[kg_smart_valve][switch.qt_switch_switch_1-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': 'QT-Switch Switch 1', + }), + 'context': , + 'entity_id': 'switch.qt_switch_switch_1', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][switch.bree_power-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.bree_power', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Power', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'power', + 'unique_id': 'tuya.CENSOREDswitch', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[kj_bladeless_tower_fan][switch.bree_power-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Bree Power', + }), + 'context': , + 'entity_id': 'switch.bree_power', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[mal_alarm_host][switch.multifunction_alarm_arm_beep-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.multifunction_alarm_arm_beep', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Arm beep', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'arm_beep', + 'unique_id': 'tuya.123123aba12312312dazubswitch_alarm_sound', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[mal_alarm_host][switch.multifunction_alarm_arm_beep-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Multifunction alarm Arm beep', + }), + 'context': , + 'entity_id': 'switch.multifunction_alarm_arm_beep', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[mal_alarm_host][switch.multifunction_alarm_siren-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.multifunction_alarm_siren', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Siren', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'siren', + 'unique_id': 'tuya.123123aba12312312dazubswitch_alarm_light', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[mal_alarm_host][switch.multifunction_alarm_siren-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Multifunction alarm Siren', + }), + 'context': , + 'entity_id': 'switch.multifunction_alarm_siren', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_platform_setup_and_discovery[sfkzq_valve_controller][switch.sprinkler_cesare_switch-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.sprinkler_cesare_switch', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Switch', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch', + 'unique_id': 'tuya.bfb9bfc18eeaed2d85yt5mswitch', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[sfkzq_valve_controller][switch.sprinkler_cesare_switch-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'Sprinkler Cesare Switch', + }), + 'context': , + 'entity_id': 'switch.sprinkler_cesare_switch', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_1-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.4_433_switch_1', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Switch 1', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch_1', + 'unique_id': 'tuya.bf082711d275c0c883vb4pswitch_1', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_1-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': '4-433 Switch 1', + }), + 'context': , + 'entity_id': 'switch.4_433_switch_1', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_2-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.4_433_switch_2', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Switch 2', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch_2', + 'unique_id': 'tuya.bf082711d275c0c883vb4pswitch_2', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_2-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': '4-433 Switch 2', + }), + 'context': , + 'entity_id': 'switch.4_433_switch_2', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_3-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.4_433_switch_3', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Switch 3', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch_3', + 'unique_id': 'tuya.bf082711d275c0c883vb4pswitch_3', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_3-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': '4-433 Switch 3', + }), + 'context': , + 'entity_id': 'switch.4_433_switch_3', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_4-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': None, + 'entity_id': 'switch.4_433_switch_4', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Switch 4', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'switch_4', + 'unique_id': 'tuya.bf082711d275c0c883vb4pswitch_4', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[tdq_4_443][switch.4_433_switch_4-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'device_class': 'outlet', + 'friendly_name': '4-433 Switch 4', + }), + 'context': , + 'entity_id': 'switch.4_433_switch_4', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unavailable', + }) +# --- +# name: test_platform_setup_and_discovery[wk_wifi_smart_gas_boiler_thermostat][switch.wifi_smart_gas_boiler_thermostat_child_lock-entry] + EntityRegistryEntrySnapshot({ + 'aliases': set({ + }), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'switch', + 'entity_category': , + 'entity_id': 'switch.wifi_smart_gas_boiler_thermostat_child_lock', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Child lock', + 'platform': 'tuya', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'child_lock', + 'unique_id': 'tuya.bfb45cb8a9452fba66lexgchild_lock', + 'unit_of_measurement': None, + }) +# --- +# name: test_platform_setup_and_discovery[wk_wifi_smart_gas_boiler_thermostat][switch.wifi_smart_gas_boiler_thermostat_child_lock-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + 'friendly_name': 'WiFi Smart Gas Boiler Thermostat Child lock', + }), + 'context': , + 'entity_id': 'switch.wifi_smart_gas_boiler_thermostat_child_lock', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- diff --git a/tests/components/tuya/test_alarm_control_panel.py b/tests/components/tuya/test_alarm_control_panel.py new file mode 100644 index 00000000000..71527bd83eb --- /dev/null +++ b/tests/components/tuya/test_alarm_control_panel.py @@ -0,0 +1,57 @@ +"""Test Tuya Alarm Control Panel platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.ALARM_CONTROL_PANEL in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.ALARM_CONTROL_PANEL]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.ALARM_CONTROL_PANEL not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.ALARM_CONTROL_PANEL]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_binary_sensor.py b/tests/components/tuya/test_binary_sensor.py new file mode 100644 index 00000000000..f59e325b6cc --- /dev/null +++ b/tests/components/tuya/test_binary_sensor.py @@ -0,0 +1,93 @@ +"""Test Tuya binary sensor platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.BINARY_SENSOR in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR]) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.BINARY_SENSOR not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) + + +@pytest.mark.parametrize( + "mock_device_code", + ["cs_arete_two_12l_dehumidifier_air_purifier"], +) +@pytest.mark.parametrize( + ("fault_value", "tankfull", "defrost", "wet"), + [ + (0, "off", "off", "off"), + (0x1, "on", "off", "off"), + (0x2, "off", "on", "off"), + (0x80, "off", "off", "on"), + (0x83, "on", "on", "on"), + ], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.BINARY_SENSOR]) +async def test_bitmap( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + fault_value: int, + tankfull: str, + defrost: str, + wet: str, +) -> None: + """Test BITMAP fault sensor on cs_arete_two_12l_dehumidifier_air_purifier.""" + mock_device.status["fault"] = fault_value + + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert hass.states.get("binary_sensor.dehumidifier_tank_full").state == tankfull + assert hass.states.get("binary_sensor.dehumidifier_defrost").state == defrost + assert hass.states.get("binary_sensor.dehumidifier_wet").state == wet diff --git a/tests/components/tuya/test_climate.py b/tests/components/tuya/test_climate.py new file mode 100644 index 00000000000..a5117983000 --- /dev/null +++ b/tests/components/tuya/test_climate.py @@ -0,0 +1,57 @@ +"""Test Tuya climate platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.CLIMATE in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.CLIMATE]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.CLIMATE not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.CLIMATE]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_cover.py b/tests/components/tuya/test_cover.py new file mode 100644 index 00000000000..4550ed9d6f4 --- /dev/null +++ b/tests/components/tuya/test_cover.py @@ -0,0 +1,90 @@ +"""Test Tuya cover platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.COVER in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.COVER not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) + + +@pytest.mark.parametrize( + "mock_device_code", + ["am43_corded_motor_zigbee_cover"], +) +@pytest.mark.parametrize( + ("percent_control", "percent_state"), + [ + (100, 52), + (0, 100), + (50, 25), + ], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.COVER]) +async def test_percent_state_on_cover( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + percent_control: int, + percent_state: int, +) -> None: + """Test percent_state attribute on the cover entity.""" + mock_device.status["percent_control"] = percent_control + # 100 is closed and 0 is open for Tuya covers + mock_device.status["percent_state"] = 100 - percent_state + + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + cover_state = hass.states.get("cover.kitchen_blinds_curtain") + assert cover_state is not None, "cover.kitchen_blinds_curtain does not exist" + assert cover_state.attributes["current_position"] == percent_state diff --git a/tests/components/tuya/test_diagnostics.py b/tests/components/tuya/test_diagnostics.py new file mode 100644 index 00000000000..2009f117efb --- /dev/null +++ b/tests/components/tuya/test_diagnostics.py @@ -0,0 +1,67 @@ +"""Test Tuya diagnostics platform.""" + +from __future__ import annotations + +import pytest +from syrupy.assertion import SnapshotAssertion +from syrupy.filters import props +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.components.tuya.const import DOMAIN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr + +from . import initialize_entry + +from tests.common import MockConfigEntry +from tests.components.diagnostics import ( + get_diagnostics_for_config_entry, + get_diagnostics_for_device, +) +from tests.typing import ClientSessionGenerator + + +@pytest.mark.parametrize("mock_device_code", ["rqbj_gas_sensor"]) +async def test_entry_diagnostics( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + hass_client: ClientSessionGenerator, + snapshot: SnapshotAssertion, +) -> None: + """Test config entry diagnostics.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + result = await get_diagnostics_for_config_entry( + hass, hass_client, mock_config_entry + ) + + assert result == snapshot( + exclude=props("last_changed", "last_reported", "last_updated") + ) + + +@pytest.mark.parametrize("mock_device_code", ["rqbj_gas_sensor"]) +async def test_device_diagnostics( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + hass_client: ClientSessionGenerator, + device_registry: dr.DeviceRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test device diagnostics.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + device = device_registry.async_get_device(identifiers={(DOMAIN, mock_device.id)}) + assert device, repr(device_registry.devices) + + result = await get_diagnostics_for_device( + hass, hass_client, mock_config_entry, device + ) + assert result == snapshot( + exclude=props("last_changed", "last_reported", "last_updated") + ) diff --git a/tests/components/tuya/test_event.py b/tests/components/tuya/test_event.py new file mode 100644 index 00000000000..3a332dbe5c7 --- /dev/null +++ b/tests/components/tuya/test_event.py @@ -0,0 +1,57 @@ +"""Test Tuya event platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.EVENT in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.EVENT]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.EVENT not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.EVENT]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_fan.py b/tests/components/tuya/test_fan.py index f8a2c5bbee8..f6b9a6956bf 100644 --- a/tests/components/tuya/test_fan.py +++ b/tests/components/tuya/test_fan.py @@ -13,13 +13,13 @@ from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from . import initialize_entry +from . import DEVICE_MOCKS, initialize_entry from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.parametrize( - "mock_device_code", ["cs_arete_two_12l_dehumidifier_air_purifier"] + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.FAN in v] ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.FAN]) async def test_platform_setup_and_discovery( @@ -34,3 +34,22 @@ async def test_platform_setup_and_discovery( await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.FAN not in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.FAN]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_humidifier.py b/tests/components/tuya/test_humidifier.py index aad5782ee13..f4cd264a03c 100644 --- a/tests/components/tuya/test_humidifier.py +++ b/tests/components/tuya/test_humidifier.py @@ -13,13 +13,13 @@ from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from . import initialize_entry +from . import DEVICE_MOCKS, initialize_entry from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.parametrize( - "mock_device_code", ["cs_arete_two_12l_dehumidifier_air_purifier"] + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.HUMIDIFIER in v] ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.HUMIDIFIER]) async def test_platform_setup_and_discovery( @@ -34,3 +34,23 @@ async def test_platform_setup_and_discovery( await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.HUMIDIFIER not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.HUMIDIFIER]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_light.py b/tests/components/tuya/test_light.py new file mode 100644 index 00000000000..33d0e36715e --- /dev/null +++ b/tests/components/tuya/test_light.py @@ -0,0 +1,57 @@ +"""Test Tuya light platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.LIGHT in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.LIGHT]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", + [k for k, v in DEVICE_MOCKS.items() if Platform.LIGHT not in v], +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.LIGHT]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_number.py b/tests/components/tuya/test_number.py new file mode 100644 index 00000000000..7da514964aa --- /dev/null +++ b/tests/components/tuya/test_number.py @@ -0,0 +1,55 @@ +"""Test Tuya number platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.NUMBER in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.NUMBER]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.NUMBER not in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.NUMBER]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_select.py b/tests/components/tuya/test_select.py index 5f1111a0fd3..c295a07d83f 100644 --- a/tests/components/tuya/test_select.py +++ b/tests/components/tuya/test_select.py @@ -13,13 +13,13 @@ from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from . import initialize_entry +from . import DEVICE_MOCKS, initialize_entry from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.parametrize( - "mock_device_code", ["cs_arete_two_12l_dehumidifier_air_purifier"] + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SELECT in v] ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.SELECT]) async def test_platform_setup_and_discovery( @@ -34,3 +34,22 @@ async def test_platform_setup_and_discovery( await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SELECT not in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SELECT]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_sensor.py b/tests/components/tuya/test_sensor.py index bf424e289ef..d0c6054c135 100644 --- a/tests/components/tuya/test_sensor.py +++ b/tests/components/tuya/test_sensor.py @@ -13,16 +13,16 @@ from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from . import initialize_entry +from . import DEVICE_MOCKS, initialize_entry from tests.common import MockConfigEntry, snapshot_platform @pytest.mark.parametrize( - "mock_device_code", - ["cs_arete_two_12l_dehumidifier_air_purifier", "mcs_door_sensor"], + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SENSOR in v] ) @patch("homeassistant.components.tuya.PLATFORMS", [Platform.SENSOR]) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_platform_setup_and_discovery( hass: HomeAssistant, mock_manager: ManagerCompat, @@ -35,3 +35,22 @@ async def test_platform_setup_and_discovery( await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SENSOR not in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SENSOR]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/tuya/test_switch.py b/tests/components/tuya/test_switch.py new file mode 100644 index 00000000000..6164a5c7af8 --- /dev/null +++ b/tests/components/tuya/test_switch.py @@ -0,0 +1,55 @@ +"""Test Tuya switch platform.""" + +from __future__ import annotations + +from unittest.mock import patch + +import pytest +from syrupy.assertion import SnapshotAssertion +from tuya_sharing import CustomerDevice + +from homeassistant.components.tuya import ManagerCompat +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from . import DEVICE_MOCKS, initialize_entry + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SWITCH in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH]) +async def test_platform_setup_and_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, +) -> None: + """Test platform setup and discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.parametrize( + "mock_device_code", [k for k, v in DEVICE_MOCKS.items() if Platform.SWITCH not in v] +) +@patch("homeassistant.components.tuya.PLATFORMS", [Platform.SWITCH]) +async def test_platform_setup_no_discovery( + hass: HomeAssistant, + mock_manager: ManagerCompat, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + entity_registry: er.EntityRegistry, +) -> None: + """Test platform setup without discovery.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + + assert not er.async_entries_for_config_entry( + entity_registry, mock_config_entry.entry_id + ) diff --git a/tests/components/utility_meter/snapshots/test_diagnostics.ambr b/tests/components/utility_meter/snapshots/test_diagnostics.ambr index ef235bba99d..024fd1aaa7b 100644 --- a/tests/components/utility_meter/snapshots/test_diagnostics.ambr +++ b/tests/components/utility_meter/snapshots/test_diagnostics.ambr @@ -8,7 +8,7 @@ 'discovery_keys': dict({ }), 'domain': 'utility_meter', - 'minor_version': 1, + 'minor_version': 2, 'options': dict({ 'cycle': 'monthly', 'delta_values': False, diff --git a/tests/components/utility_meter/test_config_flow.py b/tests/components/utility_meter/test_config_flow.py index 01fd80acc0e..0aa73d6d123 100644 --- a/tests/components/utility_meter/test_config_flow.py +++ b/tests/components/utility_meter/test_config_flow.py @@ -403,11 +403,19 @@ async def test_change_device_source( assert await hass.config_entries.async_setup(utility_meter_config_entry.entry_id) await hass.async_block_till_done() - # Confirm that the configuration entry has been added to the source entity 1 (current) device registry + # Confirm that the configuration entry has not been added to the source entity 1 (current) device registry current_device = device_registry.async_get( device_id=current_entity_source.device_id ) - assert utility_meter_config_entry.entry_id in current_device.config_entries + assert utility_meter_config_entry.entry_id not in current_device.config_entries + + # Check that the entities are linked to the expected device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id == source_entity_1.device_id # Change configuration options to use source entity 2 (with a linked device) and reload the integration previous_entity_source = source_entity_1 @@ -427,17 +435,25 @@ async def test_change_device_source( assert result["type"] is FlowResultType.CREATE_ENTRY await hass.async_block_till_done() - # Confirm that the configuration entry has been removed from the source entity 1 (previous) device registry + # Confirm that the configuration entry is not in the source entity 1 (previous) device registry previous_device = device_registry.async_get( device_id=previous_entity_source.device_id ) assert utility_meter_config_entry.entry_id not in previous_device.config_entries - # Confirm that the configuration entry has been added to the source entity 2 (current) device registry + # Confirm that the configuration entry is not in to the source entity 2 (current) device registry current_device = device_registry.async_get( device_id=current_entity_source.device_id ) - assert utility_meter_config_entry.entry_id in current_device.config_entries + assert utility_meter_config_entry.entry_id not in current_device.config_entries + + # Check that the entities are linked to the expected device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id == source_entity_2.device_id # Change configuration options to use source entity 3 (without a device) and reload the integration previous_entity_source = source_entity_2 @@ -457,12 +473,20 @@ async def test_change_device_source( assert result["type"] is FlowResultType.CREATE_ENTRY await hass.async_block_till_done() - # Confirm that the configuration entry has been removed from the source entity 2 (previous) device registry + # Confirm that the configuration entry has is not in the source entity 2 (previous) device registry previous_device = device_registry.async_get( device_id=previous_entity_source.device_id ) assert utility_meter_config_entry.entry_id not in previous_device.config_entries + # Check that the entities are no longer linked to a device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id is None + # Confirm that there is no device with the helper configuration entry assert ( dr.async_entries_for_config_entry( @@ -489,8 +513,16 @@ async def test_change_device_source( assert result["type"] is FlowResultType.CREATE_ENTRY await hass.async_block_till_done() - # Confirm that the configuration entry has been added to the source entity 2 (current) device registry + # Confirm that the configuration entry is not in the source entity 2 (current) device registry current_device = device_registry.async_get( device_id=current_entity_source.device_id ) - assert utility_meter_config_entry.entry_id in current_device.config_entries + assert utility_meter_config_entry.entry_id not in current_device.config_entries + + # Check that the entities are linked to the expected device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id == source_entity_2.device_id diff --git a/tests/components/utility_meter/test_init.py b/tests/components/utility_meter/test_init.py index ea4af741e19..ec7fdd1db87 100644 --- a/tests/components/utility_meter/test_init.py +++ b/tests/components/utility_meter/test_init.py @@ -20,7 +20,7 @@ from homeassistant.components.utility_meter import ( ) from homeassistant.components.utility_meter.config_flow import ConfigFlowHandler from homeassistant.components.utility_meter.const import DOMAIN, SERVICE_RESET -from homeassistant.config_entries import ConfigEntry +from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_UNIT_OF_MEASUREMENT, @@ -29,7 +29,7 @@ from homeassistant.const import ( Platform, UnitOfEnergy, ) -from homeassistant.core import Event, HomeAssistant, State +from homeassistant.core import Event, HomeAssistant, State, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event from homeassistant.setup import async_setup_component @@ -108,6 +108,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -601,7 +602,7 @@ async def test_device_cleaning( devices_before_reload = device_registry.devices.get_devices_for_config_entry_id( utility_meter_config_entry.entry_id ) - assert len(devices_before_reload) == 3 + assert len(devices_before_reload) == 2 # Config entry reload await hass.config_entries.async_reload(utility_meter_config_entry.entry_id) @@ -616,7 +617,7 @@ async def test_device_cleaning( devices_after_reload = device_registry.devices.get_devices_for_config_entry_id( utility_meter_config_entry.entry_id ) - assert len(devices_after_reload) == 1 + assert len(devices_after_reload) == 0 @pytest.mark.parametrize( @@ -642,6 +643,81 @@ async def test_async_handle_source_entity_changes_source_entity_removed( sensor_device: dr.DeviceEntry, sensor_entity_entry: er.RegistryEntry, expected_entities: set[str], +) -> None: + """Test the utility_meter config entry is removed when the source entity is removed.""" + assert await hass.config_entries.async_setup(utility_meter_config_entry.entry_id) + await hass.async_block_till_done() + + events = {} + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id == sensor_entity_entry.device_id + events[utility_meter_entity.entity_id] = track_entity_registry_actions( + hass, utility_meter_entity.entity_id + ) + assert set(events) == expected_entities + + sensor_device = device_registry.async_get(sensor_device.id) + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries + + # Remove the source sensor's config entry from the device, this removes the + # source sensor + with patch( + "homeassistant.components.utility_meter.async_unload_entry", + wraps=utility_meter.async_unload_entry, + ) as mock_unload_entry: + device_registry.async_update_device( + sensor_device.id, remove_config_entry_id=sensor_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + mock_unload_entry.assert_not_called() + + # Check that the entities are no longer linked to the source device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id is None + + # Check that the device is removed + assert not device_registry.async_get(sensor_device.id) + + # Check that the utility_meter config entry is not removed + assert utility_meter_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + for entity_events in events.values(): + assert entity_events == ["update"] + + +@pytest.mark.parametrize( + ("tariffs", "expected_entities"), + [ + ([], {"sensor.my_utility_meter"}), + ( + ["peak", "offpeak"], + { + "select.my_utility_meter", + "sensor.my_utility_meter_offpeak", + "sensor.my_utility_meter_peak", + }, + ), + ], +) +async def test_async_handle_source_entity_changes_source_entity_removed_shared_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + utility_meter_config_entry: MockConfigEntry, + sensor_config_entry: ConfigEntry, + sensor_device: dr.DeviceEntry, + sensor_entity_entry: er.RegistryEntry, + expected_entities: set[str], ) -> None: """Test the utility_meter config entry is removed when the source entity is removed.""" # Add another config entry to the sensor device @@ -667,7 +743,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed( assert set(events) == expected_entities sensor_device = device_registry.async_get(sensor_device.id) - assert utility_meter_config_entry.entry_id in sensor_device.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries # Remove the source sensor's config entry from the device, this removes the # source sensor @@ -682,7 +758,15 @@ async def test_async_handle_source_entity_changes_source_entity_removed( await hass.async_block_till_done() mock_unload_entry.assert_not_called() - # Check that the utility_meter config entry is removed from the device + # Check that the entities are no longer linked to the source device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id is None + + # Check that the utility_meter config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert utility_meter_config_entry.entry_id not in sensor_device.config_entries @@ -734,7 +818,7 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev assert set(events) == expected_entities sensor_device = device_registry.async_get(sensor_device.id) - assert utility_meter_config_entry.entry_id in sensor_device.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries # Remove the source sensor from the device with patch( @@ -747,7 +831,15 @@ async def test_async_handle_source_entity_changes_source_entity_removed_from_dev await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the utility_meter config entry is removed from the device + # Check that the entities are no longer linked to the source device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id is None + + # Check that the utility_meter config entry is not in the device sensor_device = device_registry.async_get(sensor_device.id) assert utility_meter_config_entry.entry_id not in sensor_device.config_entries @@ -805,7 +897,7 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi assert set(events) == expected_entities sensor_device = device_registry.async_get(sensor_device.id) - assert utility_meter_config_entry.entry_id in sensor_device.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) assert utility_meter_config_entry.entry_id not in sensor_device_2.config_entries @@ -820,11 +912,19 @@ async def test_async_handle_source_entity_changes_source_entity_moved_other_devi await hass.async_block_till_done() mock_unload_entry.assert_called_once() - # Check that the utility_meter config entry is moved to the other device + # Check that the entities are linked to the other device + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + assert utility_meter_entity.device_id == sensor_device_2.id + + # Check that the derivative config entry is not in any of the devices sensor_device = device_registry.async_get(sensor_device.id) assert utility_meter_config_entry.entry_id not in sensor_device.config_entries sensor_device_2 = device_registry.async_get(sensor_device_2.id) - assert utility_meter_config_entry.entry_id in sensor_device_2.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device_2.config_entries # Check that the utility_meter config entry is not removed assert utility_meter_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -874,7 +974,7 @@ async def test_async_handle_source_entity_new_entity_id( assert set(events) == expected_entities sensor_device = device_registry.async_get(sensor_device.id) - assert utility_meter_config_entry.entry_id in sensor_device.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries # Change the source entity's entity ID with patch( @@ -890,9 +990,9 @@ async def test_async_handle_source_entity_new_entity_id( # Check that the utility_meter config entry is updated with the new entity ID assert utility_meter_config_entry.options["source"] == "sensor.new_entity_id" - # Check that the helper config is still in the device + # Check that the helper config is not in the device sensor_device = device_registry.async_get(sensor_device.id) - assert utility_meter_config_entry.entry_id in sensor_device.config_entries + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries # Check that the utility_meter config entry is not removed assert utility_meter_config_entry.entry_id in hass.config_entries.async_entry_ids() @@ -900,3 +1000,108 @@ async def test_async_handle_source_entity_new_entity_id( # Check we got the expected events for entity_events in events.values(): assert entity_events == [] + + +@pytest.mark.parametrize( + ("tariffs", "expected_entities"), + [ + ([], {"sensor.my_utility_meter"}), + ( + ["peak", "offpeak"], + { + "select.my_utility_meter", + "sensor.my_utility_meter_offpeak", + "sensor.my_utility_meter_peak", + }, + ), + ], +) +async def test_migration_2_1( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + sensor_entity_entry: er.RegistryEntry, + sensor_device: dr.DeviceEntry, + tariffs: list[str], + expected_entities: set[str], +) -> None: + """Test migration from v2.1 removes utility_meter config entry from device.""" + + utility_meter_config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "cycle": "monthly", + "delta_values": False, + "name": "My utility meter", + "net_consumption": False, + "offset": 0, + "periodically_resetting": True, + "source": sensor_entity_entry.entity_id, + "tariffs": tariffs, + }, + title="My utility meter", + version=2, + minor_version=1, + ) + utility_meter_config_entry.add_to_hass(hass) + + # Add the helper config entry to the device + device_registry.async_update_device( + sensor_device.id, add_config_entry_id=utility_meter_config_entry.entry_id + ) + + # Check preconditions + sensor_device = device_registry.async_get(sensor_device.id) + assert utility_meter_config_entry.entry_id in sensor_device.config_entries + + await hass.config_entries.async_setup(utility_meter_config_entry.entry_id) + await hass.async_block_till_done() + + assert utility_meter_config_entry.state is ConfigEntryState.LOADED + + # Check that the helper config entry is removed from the device and the helper + # entities are linked to the source device + sensor_device = device_registry.async_get(sensor_device.id) + assert utility_meter_config_entry.entry_id not in sensor_device.config_entries + # Check that the entities are linked to the other device + entities = set() + for ( + utility_meter_entity + ) in entity_registry.entities.get_entries_for_config_entry_id( + utility_meter_config_entry.entry_id + ): + entities.add(utility_meter_entity.entity_id) + assert utility_meter_entity.device_id == sensor_entity_entry.device_id + assert entities == expected_entities + + assert utility_meter_config_entry.version == 2 + assert utility_meter_config_entry.minor_version == 2 + + +async def test_migration_from_future_version( + hass: HomeAssistant, +) -> None: + """Test migration from future version.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "cycle": "monthly", + "delta_values": False, + "name": "My utility meter", + "net_consumption": False, + "offset": 0, + "periodically_resetting": True, + "source": "sensor.test", + "tariffs": [], + }, + title="My utility meter", + version=3, + minor_version=1, + ) + 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.MIGRATION_ERROR diff --git a/tests/components/utility_meter/test_sensor.py b/tests/components/utility_meter/test_sensor.py index 2de2ee553b3..f684cdb16a0 100644 --- a/tests/components/utility_meter/test_sensor.py +++ b/tests/components/utility_meter/test_sensor.py @@ -1888,10 +1888,12 @@ async def test_bad_offset(hass: HomeAssistant) -> None: def test_calculate_adjustment_invalid_new_state( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture, ) -> None: """Test that calculate_adjustment method returns None if the new state is invalid.""" mock_sensor = UtilityMeterSensor( + hass, cron_pattern=None, delta_values=False, meter_offset=DEFAULT_OFFSET, diff --git a/tests/components/vacuum/test_init.py b/tests/components/vacuum/test_init.py index 488852521ed..60ff0a1ebde 100644 --- a/tests/components/vacuum/test_init.py +++ b/tests/components/vacuum/test_init.py @@ -562,16 +562,10 @@ async def test_vacuum_log_deprecated_battery_properties_using_attr( # Test we only log once assert ( "Detected that custom integration 'test' is setting the battery_level which has been deprecated." - " Integration test should implement a sensor instead with a correct device class and link it to" - " the same device. This will stop working in Home Assistant 2026.8," - " please report it to the author of the 'test' custom integration" not in caplog.text ) assert ( "Detected that custom integration 'test' is setting the battery_icon which has been deprecated." - " Integration test should implement a sensor instead with a correct device class and link it to" - " the same device. This will stop working in Home Assistant 2026.8," - " please report it to the author of the 'test' custom integration" not in caplog.text ) @@ -613,3 +607,34 @@ async def test_vacuum_log_deprecated_battery_supported_feature( ", please report it to the author of the 'test' custom integration" in caplog.text ) + + +async def test_vacuum_not_log_deprecated_battery_properties_during_init( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test not logging deprecation until after added to hass.""" + + class MockLegacyVacuum(MockVacuum): + """Mocked vacuum entity.""" + + def __init__(self, **kwargs: Any) -> None: + """Initialize a mock vacuum entity.""" + super().__init__(**kwargs) + self._attr_battery_level = 50 + + @property + def activity(self) -> str: + """Return the state of the entity.""" + return VacuumActivity.CLEANING + + entity = MockLegacyVacuum( + name="Testing", + entity_id="vacuum.test", + ) + assert entity.battery_level == 50 + + assert ( + "Detected that custom integration 'test' is setting the battery_level which has been deprecated." + not in caplog.text + ) diff --git a/tests/components/wallbox/test_lock.py b/tests/components/wallbox/test_lock.py index e3c6048e928..3f856ed5dc2 100644 --- a/tests/components/wallbox/test_lock.py +++ b/tests/components/wallbox/test_lock.py @@ -5,7 +5,7 @@ from unittest.mock import patch import pytest from homeassistant.components.lock import SERVICE_LOCK, SERVICE_UNLOCK -from homeassistant.components.wallbox.coordinator import InvalidAuth +from homeassistant.components.wallbox.coordinator import InsufficientRights from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -96,7 +96,7 @@ async def test_wallbox_lock_class_error_handling( with ( patch.object(mock_wallbox, "lockCharger", side_effect=http_403_error), patch.object(mock_wallbox, "unlockCharger", side_effect=http_403_error), - pytest.raises(InvalidAuth), + pytest.raises(InsufficientRights), ): await hass.services.async_call( "lock", diff --git a/tests/components/wallbox/test_number.py b/tests/components/wallbox/test_number.py index cb332d1cb1e..5c77189f264 100644 --- a/tests/components/wallbox/test_number.py +++ b/tests/components/wallbox/test_number.py @@ -6,7 +6,7 @@ import pytest from homeassistant.components.input_number import ATTR_VALUE, SERVICE_SET_VALUE from homeassistant.components.number import DOMAIN as NUMBER_DOMAIN -from homeassistant.components.wallbox.coordinator import InvalidAuth +from homeassistant.components.wallbox.coordinator import InsufficientRights from homeassistant.const import ATTR_ENTITY_ID from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -130,7 +130,7 @@ async def test_wallbox_number_power_class_error_handling( with ( patch.object(mock_wallbox, "setMaxChargingCurrent", side_effect=http_403_error), - pytest.raises(InvalidAuth), + pytest.raises(InsufficientRights), ): await hass.services.async_call( NUMBER_DOMAIN, @@ -202,7 +202,7 @@ async def test_wallbox_number_icp_power_class_error_handling( with ( patch.object(mock_wallbox, "setIcpMaxCurrent", side_effect=http_403_error), - pytest.raises(InvalidAuth), + pytest.raises(InsufficientRights), ): await hass.services.async_call( NUMBER_DOMAIN, diff --git a/tests/components/workday/test_config_flow.py b/tests/components/workday/test_config_flow.py index 2c0e9aa1123..c618c5fd830 100644 --- a/tests/components/workday/test_config_flow.py +++ b/tests/components/workday/test_config_flow.py @@ -108,6 +108,7 @@ async def test_form_province_no_alias(hass: HomeAssistant) -> None: "name": "Workday Sensor", "country": "US", "excludes": ["sat", "sun", "holiday"], + "language": "en_US", "days_offset": 0, "workdays": ["mon", "tue", "wed", "thu", "fri"], "add_holidays": [], diff --git a/tests/components/workday/test_init.py b/tests/components/workday/test_init.py index 2735175b49b..f288c340d9f 100644 --- a/tests/components/workday/test_init.py +++ b/tests/components/workday/test_init.py @@ -61,8 +61,4 @@ async def test_workday_subdiv_aliases() -> None: years=2025, ) subdiv_aliases = country.get_subdivision_aliases() - assert subdiv_aliases["GES"] == [ # codespell:ignore - "Alsace", - "Champagne-Ardenne", - "Lorraine", - ] + assert subdiv_aliases["6AE"] == ["Alsace"] diff --git a/tests/components/wyoming/snapshots/test_tts.ambr b/tests/components/wyoming/snapshots/test_tts.ambr index 53cc02eaacf..67c9b24160c 100644 --- a/tests/components/wyoming/snapshots/test_tts.ambr +++ b/tests/components/wyoming/snapshots/test_tts.ambr @@ -1,6 +1,19 @@ # serializer version: 1 # name: test_get_tts_audio list([ + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-start', + }), + dict({ + 'data': dict({ + 'text': 'Hello world', + }), + 'payload': None, + 'type': 'synthesize-chunk', + }), dict({ 'data': dict({ 'text': 'Hello world', @@ -8,10 +21,29 @@ 'payload': None, 'type': 'synthesize', }), + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-stop', + }), ]) # --- # name: test_get_tts_audio_different_formats list([ + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-start', + }), + dict({ + 'data': dict({ + 'text': 'Hello world', + }), + 'payload': None, + 'type': 'synthesize-chunk', + }), dict({ 'data': dict({ 'text': 'Hello world', @@ -19,10 +51,29 @@ 'payload': None, 'type': 'synthesize', }), + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-stop', + }), ]) # --- # name: test_get_tts_audio_different_formats.1 list([ + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-start', + }), + dict({ + 'data': dict({ + 'text': 'Hello world', + }), + 'payload': None, + 'type': 'synthesize-chunk', + }), dict({ 'data': dict({ 'text': 'Hello world', @@ -30,6 +81,12 @@ 'payload': None, 'type': 'synthesize', }), + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-stop', + }), ]) # --- # name: test_get_tts_audio_streaming @@ -71,6 +128,23 @@ # --- # name: test_voice_speaker list([ + dict({ + 'data': dict({ + 'voice': dict({ + 'name': 'voice1', + 'speaker': 'speaker1', + }), + }), + 'payload': None, + 'type': 'synthesize-start', + }), + dict({ + 'data': dict({ + 'text': 'Hello world', + }), + 'payload': None, + 'type': 'synthesize-chunk', + }), dict({ 'data': dict({ 'text': 'Hello world', @@ -82,5 +156,11 @@ 'payload': None, 'type': 'synthesize', }), + dict({ + 'data': dict({ + }), + 'payload': None, + 'type': 'synthesize-stop', + }), ]) # --- diff --git a/tests/components/wyoming/test_tts.py b/tests/components/wyoming/test_tts.py index 3374328f411..efcf464eebb 100644 --- a/tests/components/wyoming/test_tts.py +++ b/tests/components/wyoming/test_tts.py @@ -52,6 +52,7 @@ async def test_get_tts_audio( # Verify audio audio_events = [ + AudioStart(rate=16000, width=2, channels=1).event(), AudioChunk(audio=audio, rate=16000, width=2, channels=1).event(), AudioStop().event(), ] @@ -77,7 +78,10 @@ async def test_get_tts_audio( assert wav_file.getframerate() == 16000 assert wav_file.getsampwidth() == 2 assert wav_file.getnchannels() == 1 - assert wav_file.readframes(wav_file.getnframes()) == audio + + # nframes = 0 due to streaming + assert len(data) == len(audio) + 44 # WAVE header is 44 bytes + assert data[44:] == audio assert mock_client.written == snapshot @@ -88,6 +92,7 @@ async def test_get_tts_audio_different_formats( """Test changing preferred audio format.""" audio = bytes(16000 * 2 * 1) # one second audio_events = [ + AudioStart(rate=16000, width=2, channels=1).event(), AudioChunk(audio=audio, rate=16000, width=2, channels=1).event(), AudioStop().event(), ] @@ -123,6 +128,7 @@ async def test_get_tts_audio_different_formats( # MP3 is the default audio_events = [ + AudioStart(rate=16000, width=2, channels=1).event(), AudioChunk(audio=audio, rate=16000, width=2, channels=1).event(), AudioStop().event(), ] @@ -167,6 +173,7 @@ async def test_get_tts_audio_audio_oserror( """Test get audio and error raising.""" audio = bytes(100) audio_events = [ + AudioStart(rate=16000, width=2, channels=1).event(), AudioChunk(audio=audio, rate=16000, width=2, channels=1).event(), AudioStop().event(), ] @@ -197,6 +204,7 @@ async def test_voice_speaker( """Test using a different voice and speaker.""" audio = bytes(100) audio_events = [ + AudioStart(rate=16000, width=2, channels=1).event(), AudioChunk(audio=audio, rate=16000, width=2, channels=1).event(), AudioStop().event(), ] diff --git a/tests/components/xiaomi_ble/test_sensor.py b/tests/components/xiaomi_ble/test_sensor.py index f5625d4e74d..3540c92682b 100644 --- a/tests/components/xiaomi_ble/test_sensor.py +++ b/tests/components/xiaomi_ble/test_sensor.py @@ -700,7 +700,7 @@ async def test_miscale_v1_uuid(hass: HomeAssistant) -> None: assert mass_non_stabilized_sensor.state == "86.55" assert ( mass_non_stabilized_sensor_attr[ATTR_FRIENDLY_NAME] - == "Mi Smart Scale (B5DC) Weight non stabilized" + == "Mi Smart Scale (B5DC) Weight non-stabilized" ) assert mass_non_stabilized_sensor_attr[ATTR_UNIT_OF_MEASUREMENT] == "kg" assert mass_non_stabilized_sensor_attr[ATTR_STATE_CLASS] == "measurement" @@ -742,7 +742,7 @@ async def test_miscale_v2_uuid(hass: HomeAssistant) -> None: assert mass_non_stabilized_sensor.state == "85.15" assert ( mass_non_stabilized_sensor_attr[ATTR_FRIENDLY_NAME] - == "Mi Body Composition Scale (B5DC) Weight non stabilized" + == "Mi Body Composition Scale (B5DC) Weight non-stabilized" ) assert mass_non_stabilized_sensor_attr[ATTR_UNIT_OF_MEASUREMENT] == "kg" assert mass_non_stabilized_sensor_attr[ATTR_STATE_CLASS] == "measurement" diff --git a/tests/components/zone/test_condition.py b/tests/components/zone/test_condition.py new file mode 100644 index 00000000000..ab78fc90bae --- /dev/null +++ b/tests/components/zone/test_condition.py @@ -0,0 +1,203 @@ +"""The tests for the location condition.""" + +import pytest + +from homeassistant.components.zone import condition as zone_condition +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConditionError +from homeassistant.helpers import condition, config_validation as cv + + +async def test_zone_raises(hass: HomeAssistant) -> None: + """Test that zone raises ConditionError on errors.""" + config = { + "condition": "zone", + "entity_id": "device_tracker.cat", + "zone": "zone.home", + } + config = cv.CONDITION_SCHEMA(config) + config = await condition.async_validate_condition_config(hass, config) + test = await condition.async_from_config(hass, config) + + with pytest.raises(ConditionError, match="no zone"): + zone_condition.zone(hass, zone_ent=None, entity="sensor.any") + + with pytest.raises(ConditionError, match="unknown zone"): + test(hass) + + hass.states.async_set( + "zone.home", + "zoning", + {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, + ) + + with pytest.raises(ConditionError, match="no entity"): + zone_condition.zone(hass, zone_ent="zone.home", entity=None) + + with pytest.raises(ConditionError, match="unknown entity"): + test(hass) + + hass.states.async_set( + "device_tracker.cat", + "home", + {"friendly_name": "cat"}, + ) + + with pytest.raises(ConditionError, match="latitude"): + test(hass) + + hass.states.async_set( + "device_tracker.cat", + "home", + {"friendly_name": "cat", "latitude": 2.1}, + ) + + with pytest.raises(ConditionError, match="longitude"): + test(hass) + + hass.states.async_set( + "device_tracker.cat", + "home", + {"friendly_name": "cat", "latitude": 2.1, "longitude": 1.1}, + ) + + # All okay, now test multiple failed conditions + assert test(hass) + + config = { + "condition": "zone", + "entity_id": ["device_tracker.cat", "device_tracker.dog"], + "zone": ["zone.home", "zone.work"], + } + config = cv.CONDITION_SCHEMA(config) + config = await condition.async_validate_condition_config(hass, config) + test = await condition.async_from_config(hass, config) + + with pytest.raises(ConditionError, match="dog"): + test(hass) + + with pytest.raises(ConditionError, match="work"): + test(hass) + + hass.states.async_set( + "zone.work", + "zoning", + {"name": "work", "latitude": 20, "longitude": 10, "radius": 25000}, + ) + + hass.states.async_set( + "device_tracker.dog", + "work", + {"friendly_name": "dog", "latitude": 20.1, "longitude": 10.1}, + ) + + assert test(hass) + + +async def test_zone_multiple_entities(hass: HomeAssistant) -> None: + """Test with multiple entities in condition.""" + config = { + "condition": "and", + "conditions": [ + { + "alias": "Zone Condition", + "condition": "zone", + "entity_id": ["device_tracker.person_1", "device_tracker.person_2"], + "zone": "zone.home", + }, + ], + } + config = cv.CONDITION_SCHEMA(config) + config = await condition.async_validate_condition_config(hass, config) + test = await condition.async_from_config(hass, config) + + hass.states.async_set( + "zone.home", + "zoning", + {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, + ) + + hass.states.async_set( + "device_tracker.person_1", + "home", + {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, + ) + hass.states.async_set( + "device_tracker.person_2", + "home", + {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, + ) + assert test(hass) + + hass.states.async_set( + "device_tracker.person_1", + "home", + {"friendly_name": "person_1", "latitude": 20.1, "longitude": 10.1}, + ) + hass.states.async_set( + "device_tracker.person_2", + "home", + {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, + ) + assert not test(hass) + + hass.states.async_set( + "device_tracker.person_1", + "home", + {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, + ) + hass.states.async_set( + "device_tracker.person_2", + "home", + {"friendly_name": "person_2", "latitude": 20.1, "longitude": 10.1}, + ) + assert not test(hass) + + +async def test_multiple_zones(hass: HomeAssistant) -> None: + """Test with multiple entities in condition.""" + config = { + "condition": "and", + "conditions": [ + { + "condition": "zone", + "entity_id": "device_tracker.person", + "zone": ["zone.home", "zone.work"], + }, + ], + } + config = cv.CONDITION_SCHEMA(config) + config = await condition.async_validate_condition_config(hass, config) + test = await condition.async_from_config(hass, config) + + hass.states.async_set( + "zone.home", + "zoning", + {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, + ) + hass.states.async_set( + "zone.work", + "zoning", + {"name": "work", "latitude": 20.1, "longitude": 10.1, "radius": 10}, + ) + + hass.states.async_set( + "device_tracker.person", + "home", + {"friendly_name": "person", "latitude": 2.1, "longitude": 1.1}, + ) + assert test(hass) + + hass.states.async_set( + "device_tracker.person", + "home", + {"friendly_name": "person", "latitude": 20.1, "longitude": 10.1}, + ) + assert test(hass) + + hass.states.async_set( + "device_tracker.person", + "home", + {"friendly_name": "person", "latitude": 50.1, "longitude": 20.1}, + ) + assert not test(hass) diff --git a/tests/components/zwave_js/conftest.py b/tests/components/zwave_js/conftest.py index 138bcd63ede..1163da4971c 100644 --- a/tests/components/zwave_js/conftest.py +++ b/tests/components/zwave_js/conftest.py @@ -325,6 +325,12 @@ def ge_12730_state_fixture() -> dict[str, Any]: return load_json_object_fixture("fan_ge_12730_state.json", DOMAIN) +@pytest.fixture(name="enbrighten_58446_zwa4013_state", scope="package") +def enbrighten_58446_zwa4013_state_fixture() -> dict[str, Any]: + """Load the Enbrighten/GE 58446/zwa401 node state fixture data.""" + return load_json_object_fixture("enbrighten_58446_zwa4013_state.json", DOMAIN) + + @pytest.fixture(name="aeotec_radiator_thermostat_state", scope="package") def aeotec_radiator_thermostat_state_fixture() -> dict[str, Any]: """Load the Aeotec Radiator Thermostat node state fixture data.""" @@ -1078,6 +1084,14 @@ def ge_12730_fixture(client, ge_12730_state) -> Node: return node +@pytest.fixture(name="enbrighten_58446_zwa4013") +def enbrighten_58446_zwa4013_fixture(client, enbrighten_58446_zwa4013_state) -> Node: + """Mock a Enbrighten_58446/zwa4013 fan controller node.""" + node = Node(client, copy.deepcopy(enbrighten_58446_zwa4013_state)) + client.driver.controller.nodes[node.node_id] = node + return node + + @pytest.fixture(name="inovelli_lzw36") def inovelli_lzw36_fixture(client, inovelli_lzw36_state) -> Node: """Mock a Inovelli LZW36 fan controller node.""" diff --git a/tests/components/zwave_js/fixtures/enbrighten_58446_zwa4013_state.json b/tests/components/zwave_js/fixtures/enbrighten_58446_zwa4013_state.json new file mode 100644 index 00000000000..dd580a9b43b --- /dev/null +++ b/tests/components/zwave_js/fixtures/enbrighten_58446_zwa4013_state.json @@ -0,0 +1,1116 @@ +{ + "nodeId": 19, + "index": 0, + "installerIcon": 1024, + "userIcon": 1024, + "status": 4, + "ready": true, + "isListening": true, + "isRouting": true, + "isSecure": true, + "manufacturerId": 99, + "productId": 13619, + "productType": 18756, + "firmwareVersion": "1.26.1", + "zwavePlusVersion": 2, + "name": "zwa4013_fan", + "deviceConfig": { + "manufacturer": "Enbrighten", + "manufacturerId": 99, + "label": "58446 / ZWA4013", + "description": "In-Wall Fan Speed Control, QFSW, 700S", + "devices": [ + { + "productType": 18756, + "productId": 13619 + } + ], + "firmwareVersion": { + "min": "0.0", + "max": "255.255" + }, + "preferred": false, + "associations": {}, + "paramInformation": { + "_map": {} + }, + "compat": { + "mapBasicSet": "event" + }, + "metadata": { + "inclusion": "1. Follow the instructions for your Z-Wave certified Controller to add a device to the Z-Wave network.\n2. Once the controller is ready to add your device, press the top of bottom of the wireless smart Fan controller", + "exclusion": "1. Follow the instructions for your Z-Wave certified controller to remove a device from the Z-wave network\n2. Once the controller is ready to remove your device, press the top or bottom of the wireless smart Fan controller", + "reset": "Pull the airgap switch. Press and hold the bottom button, push the airgap switch in and continue holding the bottom button for 10 seconds. The LED will flash once each of the 8 colors then stop" + } + }, + "label": "58446 / ZWA4013", + "interviewAttempts": 1, + "isFrequentListening": false, + "maxDataRate": 100000, + "supportedDataRates": [40000, 100000], + "protocolVersion": 3, + "supportsBeaming": true, + "supportsSecurity": false, + "nodeType": 1, + "zwavePlusNodeType": 0, + "zwavePlusRoleType": 5, + "deviceClass": { + "basic": { + "key": 4, + "label": "Routing End Node" + }, + "generic": { + "key": 17, + "label": "Multilevel Switch" + }, + "specific": { + "key": 1, + "label": "Multilevel Power Switch" + } + }, + "interviewStage": "Complete", + "deviceDatabaseUrl": "https://devices.zwave-js.io/?jumpTo=0x0063:0x4944:0x3533:1.26.1", + "statistics": { + "commandsTX": 158, + "commandsRX": 154, + "commandsDroppedRX": 2, + "commandsDroppedTX": 0, + "timeoutResponse": 0, + "rtt": 30.1, + "lastSeen": "2025-07-05T19:10:23.100Z", + "lwr": { + "repeaters": [], + "protocolDataRate": 3 + } + }, + "highestSecurityClass": 1, + "isControllerNode": false, + "keepAwake": false, + "lastSeen": "2025-07-05T19:10:23.100Z", + "protocol": 0, + "sdkVersion": "7.18.1", + "values": [ + { + "endpoint": 0, + "commandClass": 32, + "commandClassName": "Basic", + "property": "event", + "propertyName": "event", + "ccVersion": 2, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Event value", + "min": 0, + "max": 255, + "stateful": false, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "currentValue", + "propertyName": "currentValue", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Current value", + "min": 0, + "max": 99, + "stateful": true, + "secret": false + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "duration", + "propertyName": "duration", + "ccVersion": 4, + "metadata": { + "type": "duration", + "readable": true, + "writeable": false, + "label": "Remaining duration", + "stateful": true, + "secret": false + }, + "value": { + "value": 0, + "unit": "seconds" + } + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "targetValue", + "propertyName": "targetValue", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Target value", + "valueChangeOptions": ["transitionDuration"], + "min": 0, + "max": 99, + "stateful": true, + "secret": false + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "Up", + "propertyName": "Up", + "ccVersion": 4, + "metadata": { + "type": "boolean", + "readable": false, + "writeable": true, + "label": "Perform a level change (Up)", + "ccSpecific": { + "switchType": 2 + }, + "valueChangeOptions": ["transitionDuration"], + "states": { + "true": "Start", + "false": "Stop" + }, + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "Down", + "propertyName": "Down", + "ccVersion": 4, + "metadata": { + "type": "boolean", + "readable": false, + "writeable": true, + "label": "Perform a level change (Down)", + "ccSpecific": { + "switchType": 2 + }, + "valueChangeOptions": ["transitionDuration"], + "states": { + "true": "Start", + "false": "Stop" + }, + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 38, + "commandClassName": "Multilevel Switch", + "property": "restorePrevious", + "propertyName": "restorePrevious", + "ccVersion": 4, + "metadata": { + "type": "boolean", + "readable": false, + "writeable": true, + "label": "Restore previous value", + "states": { + "true": "Restore" + }, + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 91, + "commandClassName": "Central Scene", + "property": "scene", + "propertyKey": "001", + "propertyName": "scene", + "propertyKeyName": "001", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Scene 001", + "min": 0, + "max": 255, + "states": { + "0": "KeyPressed", + "1": "KeyReleased", + "2": "KeyHeldDown", + "3": "KeyPressed2x", + "4": "KeyPressed3x" + }, + "stateful": false, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 91, + "commandClassName": "Central Scene", + "property": "scene", + "propertyKey": "002", + "propertyName": "scene", + "propertyKeyName": "002", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Scene 002", + "min": 0, + "max": 255, + "states": { + "0": "KeyPressed", + "1": "KeyReleased", + "2": "KeyHeldDown", + "3": "KeyPressed2x", + "4": "KeyPressed3x" + }, + "stateful": false, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 91, + "commandClassName": "Central Scene", + "property": "slowRefresh", + "propertyName": "slowRefresh", + "ccVersion": 3, + "metadata": { + "type": "boolean", + "readable": true, + "writeable": true, + "description": "When this is true, KeyHeldDown notifications are sent every 55s. When this is false, the notifications are sent every 200ms.", + "label": "Send held down notifications at a slow rate", + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 3, + "propertyName": "LED Indicator", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "LED Indicator", + "default": 0, + "min": 0, + "max": 3, + "states": { + "0": "On when load is off", + "1": "On when load is on", + "2": "Always off", + "3": "Always on" + }, + "valueSize": 1, + "format": 0, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 4, + "propertyName": "Inverted Orientation", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Inverted Orientation", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Disable", + "1": "Enable" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 5, + "propertyName": "3-Way Setup", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "3-Way Setup", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Add-on", + "1": "Standard" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 19, + "propertyName": "Alternate Exclusion", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "description": "Press MENU button once", + "label": "Alternate Exclusion", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Disable", + "1": "Enable" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 34, + "propertyName": "LED Indicator Color", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "LED Indicator Color", + "default": 5, + "min": 1, + "max": 8, + "states": { + "1": "Red", + "2": "Orange", + "3": "Yellow", + "4": "Green", + "5": "Blue", + "6": "Pink", + "7": "Purple", + "8": "White" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 5 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 35, + "propertyName": "LED Indicator Intensity", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "LED Indicator Intensity", + "default": 4, + "min": 0, + "max": 7, + "states": { + "0": "Off" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": true, + "isFromConfig": true + }, + "value": 4 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 36, + "propertyName": "Guidelight Mode Intensity", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Guidelight Mode Intensity", + "default": 4, + "min": 0, + "max": 7, + "states": { + "0": "Off" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": true, + "isFromConfig": true + }, + "value": 4 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 39, + "propertyName": "State After Power Failure", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "State After Power Failure", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Always off", + "1": "Previous state" + }, + "valueSize": 1, + "format": 0, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 40, + "propertyName": "Fan Speed Control", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Fan Speed Control", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Press and hold", + "1": "Single button presses" + }, + "valueSize": 1, + "format": 0, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 112, + "commandClassName": "Configuration", + "property": 84, + "propertyName": "Reset to Factory Default", + "ccVersion": 4, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Reset to Factory Default", + "default": 0, + "min": 0, + "max": 1, + "states": { + "0": "Disable", + "1": "Enable" + }, + "valueSize": 1, + "format": 1, + "allowManualEntry": false, + "isFromConfig": true + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 114, + "commandClassName": "Manufacturer Specific", + "property": "productId", + "propertyName": "productId", + "ccVersion": 2, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Product ID", + "min": 0, + "max": 65535, + "stateful": true, + "secret": false + }, + "value": 13619 + }, + { + "endpoint": 0, + "commandClass": 114, + "commandClassName": "Manufacturer Specific", + "property": "productType", + "propertyName": "productType", + "ccVersion": 2, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Product type", + "min": 0, + "max": 65535, + "stateful": true, + "secret": false + }, + "value": 18756 + }, + { + "endpoint": 0, + "commandClass": 114, + "commandClassName": "Manufacturer Specific", + "property": "manufacturerId", + "propertyName": "manufacturerId", + "ccVersion": 2, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Manufacturer ID", + "min": 0, + "max": 65535, + "stateful": true, + "secret": false + }, + "value": 99 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "hardwareVersion", + "propertyName": "hardwareVersion", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Z-Wave chip hardware version", + "stateful": true, + "secret": false + }, + "value": 1 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "firmwareVersions", + "propertyName": "firmwareVersions", + "ccVersion": 3, + "metadata": { + "type": "string[]", + "readable": true, + "writeable": false, + "label": "Z-Wave chip firmware versions", + "stateful": true, + "secret": false + }, + "value": ["1.26"] + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "protocolVersion", + "propertyName": "protocolVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Z-Wave protocol version", + "stateful": true, + "secret": false + }, + "value": "7.18" + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "libraryType", + "propertyName": "libraryType", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": false, + "label": "Library type", + "states": { + "0": "Unknown", + "1": "Static Controller", + "2": "Controller", + "3": "Enhanced Slave", + "4": "Slave", + "5": "Installer", + "6": "Routing Slave", + "7": "Bridge Controller", + "8": "Device under Test", + "9": "N/A", + "10": "AV Remote", + "11": "AV Device" + }, + "stateful": true, + "secret": false + }, + "value": 3 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "applicationBuildNumber", + "propertyName": "applicationBuildNumber", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Application build number", + "stateful": true, + "secret": false + }, + "value": 273 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "applicationVersion", + "propertyName": "applicationVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Application version", + "stateful": true, + "secret": false + }, + "value": "1.26.1" + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "zWaveProtocolBuildNumber", + "propertyName": "zWaveProtocolBuildNumber", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Z-Wave protocol build number", + "stateful": true, + "secret": false + }, + "value": 273 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "zWaveProtocolVersion", + "propertyName": "zWaveProtocolVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Z-Wave protocol version", + "stateful": true, + "secret": false + }, + "value": "7.18.1" + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "hostInterfaceBuildNumber", + "propertyName": "hostInterfaceBuildNumber", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Serial API build number", + "stateful": true, + "secret": false + }, + "value": 0 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "hostInterfaceVersion", + "propertyName": "hostInterfaceVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Serial API version", + "stateful": true, + "secret": false + }, + "value": "unused" + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "applicationFrameworkBuildNumber", + "propertyName": "applicationFrameworkBuildNumber", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Z-Wave application framework API build number", + "stateful": true, + "secret": false + }, + "value": 273 + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "applicationFrameworkAPIVersion", + "propertyName": "applicationFrameworkAPIVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "Z-Wave application framework API version", + "stateful": true, + "secret": false + }, + "value": "10.18.1" + }, + { + "endpoint": 0, + "commandClass": 134, + "commandClassName": "Version", + "property": "sdkVersion", + "propertyName": "sdkVersion", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": false, + "label": "SDK version", + "stateful": true, + "secret": false + }, + "value": "7.18.1" + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": 80, + "propertyKey": 3, + "propertyName": "Node Identify", + "propertyKeyName": "On/Off Period: Duration", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "description": "Sets the duration of an on/off period in 1/10th seconds. Must be set together with \"On/Off Cycle Count\"", + "label": "0x50 (Node Identify) - On/Off Period: Duration", + "ccSpecific": { + "indicatorId": 80, + "propertyId": 3 + }, + "stateful": true, + "secret": false + }, + "value": 8 + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": 80, + "propertyKey": 4, + "propertyName": "Node Identify", + "propertyKeyName": "On/Off Cycle Count", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "description": "Sets the number of on/off periods. 0xff means infinite. Must be set together with \"On/Off Period duration\"", + "label": "0x50 (Node Identify) - On/Off Cycle Count", + "ccSpecific": { + "indicatorId": 80, + "propertyId": 4 + }, + "stateful": true, + "secret": false + }, + "value": 3 + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": 80, + "propertyKey": 5, + "propertyName": "Node Identify", + "propertyKeyName": "On/Off Period: On time", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "description": "This property is used to set the length of the On time during an On/Off period. It allows asymmetric On/Off periods. The value 0x00 MUST represent symmetric On/Off period (On time equal to Off time)", + "label": "0x50 (Node Identify) - On/Off Period: On time", + "ccSpecific": { + "indicatorId": 80, + "propertyId": 5 + }, + "stateful": true, + "secret": false + }, + "value": 6 + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": "value", + "propertyName": "value", + "ccVersion": 3, + "metadata": { + "type": "number", + "readable": true, + "writeable": true, + "label": "Indicator value", + "ccSpecific": { + "indicatorId": 0 + }, + "min": 0, + "max": 255, + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": "identify", + "propertyName": "identify", + "ccVersion": 3, + "metadata": { + "type": "boolean", + "readable": false, + "writeable": true, + "label": "Identify", + "states": { + "true": "Identify" + }, + "stateful": true, + "secret": false + } + }, + { + "endpoint": 0, + "commandClass": 135, + "commandClassName": "Indicator", + "property": "timeout", + "propertyName": "timeout", + "ccVersion": 3, + "metadata": { + "type": "string", + "readable": true, + "writeable": true, + "label": "Timeout", + "stateful": true, + "secret": false + } + } + ], + "endpoints": [ + { + "nodeId": 19, + "index": 0, + "installerIcon": 1024, + "userIcon": 1024, + "deviceClass": { + "basic": { + "key": 4, + "label": "Routing End Node" + }, + "generic": { + "key": 17, + "label": "Multilevel Switch" + }, + "specific": { + "key": 0, + "label": "Unused" + } + }, + "commandClasses": [ + { + "id": 94, + "name": "Z-Wave Plus Info", + "version": 2, + "isSecure": false + }, + { + "id": 85, + "name": "Transport Service", + "version": 2, + "isSecure": false + }, + { + "id": 159, + "name": "Security 2", + "version": 1, + "isSecure": true + }, + { + "id": 108, + "name": "Supervision", + "version": 1, + "isSecure": false + }, + { + "id": 134, + "name": "Version", + "version": 3, + "isSecure": true + }, + { + "id": 133, + "name": "Association", + "version": 2, + "isSecure": true + }, + { + "id": 142, + "name": "Multi Channel Association", + "version": 3, + "isSecure": true + }, + { + "id": 89, + "name": "Association Group Information", + "version": 3, + "isSecure": true + }, + { + "id": 38, + "name": "Multilevel Switch", + "version": 4, + "isSecure": true + }, + { + "id": 135, + "name": "Indicator", + "version": 3, + "isSecure": true + }, + { + "id": 114, + "name": "Manufacturer Specific", + "version": 2, + "isSecure": true + }, + { + "id": 90, + "name": "Device Reset Locally", + "version": 1, + "isSecure": true + }, + { + "id": 115, + "name": "Powerlevel", + "version": 1, + "isSecure": true + }, + { + "id": 112, + "name": "Configuration", + "version": 4, + "isSecure": true + }, + { + "id": 91, + "name": "Central Scene", + "version": 3, + "isSecure": true + }, + { + "id": 122, + "name": "Firmware Update Meta Data", + "version": 5, + "isSecure": true + } + ] + } + ] +} diff --git a/tests/components/zwave_js/test_discovery.py b/tests/components/zwave_js/test_discovery.py index c8bfca2b35f..44133db03ac 100644 --- a/tests/components/zwave_js/test_discovery.py +++ b/tests/components/zwave_js/test_discovery.py @@ -98,6 +98,20 @@ async def test_ge_12730(hass: HomeAssistant, client, ge_12730, integration) -> N assert state +async def test_enbrighten_58446_zwa4013( + hass: HomeAssistant, client, enbrighten_58446_zwa4013, integration +) -> None: + """Test GE 12730 Fan Controller v2.0 multilevel switch is discovered as a fan.""" + node = enbrighten_58446_zwa4013 + assert node.device_class.specific.label == "Multilevel Power Switch" + + state = hass.states.get("light.zwa4013_fan") + assert not state + + state = hass.states.get("fan.zwa4013_fan") + assert state + + async def test_inovelli_lzw36( hass: HomeAssistant, client, inovelli_lzw36, integration ) -> None: diff --git a/tests/components/zwave_js/test_init.py b/tests/components/zwave_js/test_init.py index 4350d7f7649..324a0f14941 100644 --- a/tests/components/zwave_js/test_init.py +++ b/tests/components/zwave_js/test_init.py @@ -37,7 +37,11 @@ from homeassistant.helpers import ( ) from homeassistant.setup import async_setup_component -from .common import AIR_TEMPERATURE_SENSOR, EATON_RF9640_ENTITY +from .common import ( + AIR_TEMPERATURE_SENSOR, + BULB_6_MULTI_COLOR_LIGHT_ENTITY, + EATON_RF9640_ENTITY, +) from tests.common import ( MockConfigEntry, @@ -2168,3 +2172,39 @@ async def test_factory_reset_node( assert len(notifications) == 1 assert list(notifications)[0] == msg_id assert "network with the home ID `3245146787`" in notifications[msg_id]["message"] + + +async def test_entity_available_when_node_dead( + hass: HomeAssistant, client, bulb_6_multi_color, integration +) -> None: + """Test that entities remain available even when the node is dead.""" + + node = bulb_6_multi_color + state = hass.states.get(BULB_6_MULTI_COLOR_LIGHT_ENTITY) + + assert state + assert state.state != STATE_UNAVAILABLE + + # Send dead event to the node + event = Event( + "dead", data={"source": "node", "event": "dead", "nodeId": node.node_id} + ) + node.receive_event(event) + await hass.async_block_till_done() + + # Entity should remain available even though the node is dead + state = hass.states.get(BULB_6_MULTI_COLOR_LIGHT_ENTITY) + assert state + assert state.state != STATE_UNAVAILABLE + + # Send alive event to bring the node back + event = Event( + "alive", data={"source": "node", "event": "alive", "nodeId": node.node_id} + ) + node.receive_event(event) + await hass.async_block_till_done() + + # Entity should still be available + state = hass.states.get(BULB_6_MULTI_COLOR_LIGHT_ENTITY) + assert state + assert state.state != STATE_UNAVAILABLE diff --git a/tests/components/zwave_js/test_lock.py b/tests/components/zwave_js/test_lock.py index 1011026ac68..9e36810872f 100644 --- a/tests/components/zwave_js/test_lock.py +++ b/tests/components/zwave_js/test_lock.py @@ -28,7 +28,7 @@ from homeassistant.components.zwave_js.lock import ( SERVICE_SET_LOCK_CONFIGURATION, SERVICE_SET_LOCK_USERCODE, ) -from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN +from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -295,7 +295,8 @@ async def test_door_lock( assert node.status == NodeStatus.DEAD state = hass.states.get(SCHLAGE_BE469_LOCK_ENTITY) assert state - assert state.state == STATE_UNAVAILABLE + # The state should still be locked, even if the node is dead + assert state.state == LockState.LOCKED async def test_only_one_lock( diff --git a/tests/components/zwave_js/test_update.py b/tests/components/zwave_js/test_update.py index fc225d529a6..17f154f4f78 100644 --- a/tests/components/zwave_js/test_update.py +++ b/tests/components/zwave_js/test_update.py @@ -277,7 +277,7 @@ async def test_update_entity_dead( zen_31, integration, ) -> None: - """Test update occurs when device is dead after it becomes alive.""" + """Test update occurs even when device is dead.""" event = Event( "dead", data={"source": "node", "event": "dead", "nodeId": zen_31.node_id}, @@ -290,17 +290,7 @@ async def test_update_entity_dead( async_fire_time_changed(hass, dt_util.utcnow() + timedelta(minutes=5, days=1)) await hass.async_block_till_done() - # Because node is asleep we shouldn't attempt to check for firmware updates - assert len(client.async_send_command.call_args_list) == 0 - - event = Event( - "alive", - data={"source": "node", "event": "alive", "nodeId": zen_31.node_id}, - ) - zen_31.receive_event(event) - await hass.async_block_till_done() - - # Now that the node is up we can check for updates + # Checking for firmware updates should proceed even for dead nodes assert len(client.async_send_command.call_args_list) > 0 args = client.async_send_command.call_args_list[0][0][0] diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index 1c10048fee9..86aab3cb681 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -1892,201 +1892,6 @@ async def test_numeric_state_using_input_number(hass: HomeAssistant) -> None: ) -async def test_zone_raises(hass: HomeAssistant) -> None: - """Test that zone raises ConditionError on errors.""" - config = { - "condition": "zone", - "entity_id": "device_tracker.cat", - "zone": "zone.home", - } - config = cv.CONDITION_SCHEMA(config) - config = await condition.async_validate_condition_config(hass, config) - test = await condition.async_from_config(hass, config) - - with pytest.raises(ConditionError, match="no zone"): - condition.zone(hass, zone_ent=None, entity="sensor.any") - - with pytest.raises(ConditionError, match="unknown zone"): - test(hass) - - hass.states.async_set( - "zone.home", - "zoning", - {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, - ) - - with pytest.raises(ConditionError, match="no entity"): - condition.zone(hass, zone_ent="zone.home", entity=None) - - with pytest.raises(ConditionError, match="unknown entity"): - test(hass) - - hass.states.async_set( - "device_tracker.cat", - "home", - {"friendly_name": "cat"}, - ) - - with pytest.raises(ConditionError, match="latitude"): - test(hass) - - hass.states.async_set( - "device_tracker.cat", - "home", - {"friendly_name": "cat", "latitude": 2.1}, - ) - - with pytest.raises(ConditionError, match="longitude"): - test(hass) - - hass.states.async_set( - "device_tracker.cat", - "home", - {"friendly_name": "cat", "latitude": 2.1, "longitude": 1.1}, - ) - - # All okay, now test multiple failed conditions - assert test(hass) - - config = { - "condition": "zone", - "entity_id": ["device_tracker.cat", "device_tracker.dog"], - "zone": ["zone.home", "zone.work"], - } - config = cv.CONDITION_SCHEMA(config) - config = await condition.async_validate_condition_config(hass, config) - test = await condition.async_from_config(hass, config) - - with pytest.raises(ConditionError, match="dog"): - test(hass) - - with pytest.raises(ConditionError, match="work"): - test(hass) - - hass.states.async_set( - "zone.work", - "zoning", - {"name": "work", "latitude": 20, "longitude": 10, "radius": 25000}, - ) - - hass.states.async_set( - "device_tracker.dog", - "work", - {"friendly_name": "dog", "latitude": 20.1, "longitude": 10.1}, - ) - - assert test(hass) - - -async def test_zone_multiple_entities(hass: HomeAssistant) -> None: - """Test with multiple entities in condition.""" - config = { - "condition": "and", - "conditions": [ - { - "alias": "Zone Condition", - "condition": "zone", - "entity_id": ["device_tracker.person_1", "device_tracker.person_2"], - "zone": "zone.home", - }, - ], - } - config = cv.CONDITION_SCHEMA(config) - config = await condition.async_validate_condition_config(hass, config) - test = await condition.async_from_config(hass, config) - - hass.states.async_set( - "zone.home", - "zoning", - {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, - ) - - hass.states.async_set( - "device_tracker.person_1", - "home", - {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, - ) - hass.states.async_set( - "device_tracker.person_2", - "home", - {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, - ) - assert test(hass) - - hass.states.async_set( - "device_tracker.person_1", - "home", - {"friendly_name": "person_1", "latitude": 20.1, "longitude": 10.1}, - ) - hass.states.async_set( - "device_tracker.person_2", - "home", - {"friendly_name": "person_2", "latitude": 2.1, "longitude": 1.1}, - ) - assert not test(hass) - - hass.states.async_set( - "device_tracker.person_1", - "home", - {"friendly_name": "person_1", "latitude": 2.1, "longitude": 1.1}, - ) - hass.states.async_set( - "device_tracker.person_2", - "home", - {"friendly_name": "person_2", "latitude": 20.1, "longitude": 10.1}, - ) - assert not test(hass) - - -async def test_multiple_zones(hass: HomeAssistant) -> None: - """Test with multiple entities in condition.""" - config = { - "condition": "and", - "conditions": [ - { - "condition": "zone", - "entity_id": "device_tracker.person", - "zone": ["zone.home", "zone.work"], - }, - ], - } - config = cv.CONDITION_SCHEMA(config) - config = await condition.async_validate_condition_config(hass, config) - test = await condition.async_from_config(hass, config) - - hass.states.async_set( - "zone.home", - "zoning", - {"name": "home", "latitude": 2.1, "longitude": 1.1, "radius": 10}, - ) - hass.states.async_set( - "zone.work", - "zoning", - {"name": "work", "latitude": 20.1, "longitude": 10.1, "radius": 10}, - ) - - hass.states.async_set( - "device_tracker.person", - "home", - {"friendly_name": "person", "latitude": 2.1, "longitude": 1.1}, - ) - assert test(hass) - - hass.states.async_set( - "device_tracker.person", - "home", - {"friendly_name": "person", "latitude": 20.1, "longitude": 10.1}, - ) - assert test(hass) - - hass.states.async_set( - "device_tracker.person", - "home", - {"friendly_name": "person", "latitude": 50.1, "longitude": 20.1}, - ) - assert not test(hass) - - @pytest.mark.usefixtures("hass") async def test_extract_entities() -> None: """Test extracting entities.""" diff --git a/tests/helpers/test_device.py b/tests/helpers/test_device.py index 266435ef05d..262e700c29e 100644 --- a/tests/helpers/test_device.py +++ b/tests/helpers/test_device.py @@ -8,6 +8,7 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.device import ( async_device_info_to_link_from_device_id, async_device_info_to_link_from_entity, + async_entity_id_to_device, async_entity_id_to_device_id, async_remove_stale_devices_links_keep_current_device, async_remove_stale_devices_links_keep_entity_device, @@ -16,12 +17,12 @@ from homeassistant.helpers.device import ( from tests.common import MockConfigEntry -async def test_entity_id_to_device_id( +async def test_entity_id_to_device_device_id( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, ) -> None: - """Test returning an entity's device ID.""" + """Test returning an entity's device / device ID.""" config_entry = MockConfigEntry(domain="my") config_entry.add_to_hass(hass) @@ -48,6 +49,41 @@ async def test_entity_id_to_device_id( entity_id_or_uuid=entity.entity_id, ) assert device_id == device.id + assert ( + async_entity_id_to_device( + hass, + entity_id_or_uuid=entity.entity_id, + ) + == device + ) + + assert ( + async_entity_id_to_device_id( + hass, + entity_id_or_uuid="unknown.entity_id", + ) + is None + ) + assert ( + async_entity_id_to_device( + hass, + entity_id_or_uuid="unknown.entity_id", + ) + is None + ) + + device_id = async_entity_id_to_device_id( + hass, + entity_id_or_uuid=entity.id, + ) + assert device_id == device.id + assert ( + async_entity_id_to_device( + hass, + entity_id_or_uuid=entity.id, + ) + == device + ) with pytest.raises(vol.Invalid): async_entity_id_to_device_id( @@ -55,6 +91,12 @@ async def test_entity_id_to_device_id( entity_id_or_uuid="unknown_uuid", ) + with pytest.raises(vol.Invalid): + async_entity_id_to_device( + hass, + entity_id_or_uuid="unknown_uuid", + ) + async def test_device_info_to_link( hass: HomeAssistant, diff --git a/tests/helpers/test_device_registry.py b/tests/helpers/test_device_registry.py index 58933ca4314..23a451dd06c 100644 --- a/tests/helpers/test_device_registry.py +++ b/tests/helpers/test_device_registry.py @@ -1652,6 +1652,7 @@ async def test_removing_config_entries( assert update_events[4].data == { "action": "remove", "device_id": entry3.id, + "device": entry3, } @@ -1724,10 +1725,12 @@ async def test_deleted_device_removing_config_entries( assert update_events[3].data == { "action": "remove", "device_id": entry.id, + "device": entry2, } assert update_events[4].data == { "action": "remove", "device_id": entry3.id, + "device": entry3, } device_registry.async_clear_config_entry(config_entry_1.entry_id) @@ -1973,6 +1976,7 @@ async def test_removing_config_subentries( assert update_events[7].data == { "action": "remove", "device_id": entry.id, + "device": entry, } @@ -2102,6 +2106,7 @@ async def test_deleted_device_removing_config_subentries( assert update_events[4].data == { "action": "remove", "device_id": entry.id, + "device": entry4, } device_registry.async_clear_config_subentry(config_entry_1.entry_id, None) @@ -2925,6 +2930,7 @@ async def test_update_remove_config_entries( assert update_events[6].data == { "action": "remove", "device_id": entry3.id, + "device": entry3, } @@ -3104,6 +3110,7 @@ async def test_update_remove_config_subentries( config_entry_3.entry_id: {None}, } + entry_before_remove = entry entry = device_registry.async_update_device( entry_id, remove_config_entry_id=config_entry_3.entry_id, @@ -3201,6 +3208,7 @@ async def test_update_remove_config_subentries( assert update_events[7].data == { "action": "remove", "device_id": entry_id, + "device": entry_before_remove, } @@ -3422,7 +3430,7 @@ async def test_restore_device( ) # Apply user customizations - device_registry.async_update_device( + entry = device_registry.async_update_device( entry.id, area_id="12345A", disabled_by=dr.DeviceEntryDisabler.USER, @@ -3543,6 +3551,7 @@ async def test_restore_device( assert update_events[2].data == { "action": "remove", "device_id": entry.id, + "device": entry, } assert update_events[3].data == { "action": "create", @@ -3865,6 +3874,7 @@ async def test_restore_shared_device( assert update_events[3].data == { "action": "remove", "device_id": entry.id, + "device": updated_device, } assert update_events[4].data == { "action": "create", @@ -3873,6 +3883,7 @@ async def test_restore_shared_device( assert update_events[5].data == { "action": "remove", "device_id": entry.id, + "device": entry2, } assert update_events[6].data == { "action": "create", diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py index 714dfed32e9..e403333d8df 100644 --- a/tests/helpers/test_entity_registry.py +++ b/tests/helpers/test_entity_registry.py @@ -16,9 +16,10 @@ from homeassistant.const import ( STATE_UNAVAILABLE, EntityCategory, ) -from homeassistant.core import CoreState, HomeAssistant, callback +from homeassistant.core import CoreState, Event, HomeAssistant, callback from homeassistant.exceptions import MaxLengthExceeded from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers.event import async_track_entity_registry_updated_event from homeassistant.util.dt import utc_from_timestamp, utcnow from tests.common import ( @@ -1640,6 +1641,8 @@ async def test_remove_config_entry_from_device_removes_entities_2( config_entry_1.add_to_hass(hass) config_entry_2 = MockConfigEntry(domain="device_tracker") config_entry_2.add_to_hass(hass) + config_entry_3 = MockConfigEntry(domain="some_helper") + config_entry_3.add_to_hass(hass) # Create device with two config entries device_registry.async_get_or_create( @@ -1662,8 +1665,18 @@ async def test_remove_config_entry_from_device_removes_entities_2( "5678", device_id=device_entry.id, ) + # Create an entity with a config entry not in the device + entry_2 = entity_registry.async_get_or_create( + "light", + "some_helper", + "5678", + config_entry=config_entry_3, + device_id=device_entry.id, + ) + assert entry_1.entity_id != entry_2.entity_id assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) # Remove the first config entry from the device device_registry.async_update_device( @@ -1672,7 +1685,23 @@ async def test_remove_config_entry_from_device_removes_entities_2( await hass.async_block_till_done() assert device_registry.async_get(device_entry.id) + # Entities which are not tied to the removed config entry should not be removed assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) + + # Remove the second config entry from the device (this removes the device) + device_registry.async_update_device( + device_entry.id, remove_config_entry_id=config_entry_2.entry_id + ) + await hass.async_block_till_done() + + assert not device_registry.async_get(device_entry.id) + # Entities which are not tied to a config entry in the device should not be removed + assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) + # Check the device link is set to None + assert entity_registry.async_get(entry_1.entity_id).device_id is None + assert entity_registry.async_get(entry_2.entity_id).device_id is None async def test_remove_config_subentry_from_device_removes_entities( @@ -1797,10 +1826,19 @@ async def test_remove_config_subentry_from_device_removes_entities( assert not entity_registry.async_is_registered(entry_3.entity_id) +@pytest.mark.parametrize( + ("subentries_in_device", "subentry_in_entity"), + [ + (["mock-subentry-id-1", "mock-subentry-id-2"], None), + ([None, "mock-subentry-id-2"], "mock-subentry-id-1"), + ], +) async def test_remove_config_subentry_from_device_removes_entities_2( hass: HomeAssistant, device_registry: dr.DeviceRegistry, entity_registry: er.EntityRegistry, + subentries_in_device: list[str | None], + subentry_in_entity: str | None, ) -> None: """Test that we don't remove entities with no config entry when device is modified.""" config_entry_1 = MockConfigEntry( @@ -1820,28 +1858,31 @@ async def test_remove_config_subentry_from_device_removes_entities_2( title="Mock title", unique_id="test", ), + config_entries.ConfigSubentryData( + data={}, + subentry_id="mock-subentry-id-3", + subentry_type="test", + title="Mock title", + unique_id="test", + ), ], ) config_entry_1.add_to_hass(hass) - # Create device with three config subentries + # Create device with two config subentries device_registry.async_get_or_create( config_entry_id=config_entry_1.entry_id, - config_subentry_id="mock-subentry-id-1", - connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, - ) - device_registry.async_get_or_create( - config_entry_id=config_entry_1.entry_id, - config_subentry_id="mock-subentry-id-2", + config_subentry_id=subentries_in_device[0], connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) device_entry = device_registry.async_get_or_create( config_entry_id=config_entry_1.entry_id, + config_subentry_id=subentries_in_device[1], connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, ) assert device_entry.config_entries == {config_entry_1.entry_id} assert device_entry.config_entries_subentries == { - config_entry_1.entry_id: {None, "mock-subentry-id-1", "mock-subentry-id-2"}, + config_entry_1.entry_id: set(subentries_in_device), } # Create an entity without config entry or subentry @@ -1851,30 +1892,61 @@ async def test_remove_config_subentry_from_device_removes_entities_2( "5678", device_id=device_entry.id, ) + # Create an entity for same config entry but subentry not in device + entry_2 = entity_registry.async_get_or_create( + "light", + "some_helper", + "5678", + config_entry=config_entry_1, + config_subentry_id=subentry_in_entity, + device_id=device_entry.id, + ) + # Create an entity for same config entry but subentry not in device + entry_3 = entity_registry.async_get_or_create( + "light", + "some_helper", + "abcd", + config_entry=config_entry_1, + config_subentry_id="mock-subentry-id-3", + device_id=device_entry.id, + ) + assert len({entry_1.entity_id, entry_2.entity_id, entry_3.entity_id}) == 3 assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) + assert entity_registry.async_is_registered(entry_3.entity_id) # Remove the first config subentry from the device device_registry.async_update_device( device_entry.id, remove_config_entry_id=config_entry_1.entry_id, - remove_config_subentry_id=None, + remove_config_subentry_id=subentries_in_device[0], ) await hass.async_block_till_done() assert device_registry.async_get(device_entry.id) + # Entities with a config subentry not in the device are not removed assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) + assert entity_registry.async_is_registered(entry_3.entity_id) - # Remove the second config subentry from the device + # Remove the second config subentry from the device, this removes the device device_registry.async_update_device( device_entry.id, remove_config_entry_id=config_entry_1.entry_id, - remove_config_subentry_id="mock-subentry-id-1", + remove_config_subentry_id=subentries_in_device[1], ) await hass.async_block_till_done() - assert device_registry.async_get(device_entry.id) + assert not device_registry.async_get(device_entry.id) + # Entities with a config subentry not in the device are not removed assert entity_registry.async_is_registered(entry_1.entity_id) + assert entity_registry.async_is_registered(entry_2.entity_id) + assert entity_registry.async_is_registered(entry_3.entity_id) + # Check the device link is set to None + assert entity_registry.async_get(entry_1.entity_id).device_id is None + assert entity_registry.async_get(entry_2.entity_id).device_id is None + assert entity_registry.async_get(entry_3.entity_id).device_id is None async def test_update_device_race( @@ -1914,6 +1986,67 @@ async def test_update_device_race( assert not entity_registry.async_is_registered(entry.entity_id) +async def test_update_device_race_2( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test race when a device is removed. + + This test simulates the behavior of helpers which are removed when the + source entity is removed. + """ + config_entry = MockConfigEntry(domain="light") + config_entry.add_to_hass(hass) + + # Create device + device_entry = device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, + ) + # Add entity to the device, from the same config entry + entry_same_config_entry = entity_registry.async_get_or_create( + "light", + "hue", + "5678", + config_entry=config_entry, + device_id=device_entry.id, + ) + # Add entity to the device, not from the same config entry + entry_no_config_entry = entity_registry.async_get_or_create( + "light", + "helper", + "abcd", + device_id=device_entry.id, + ) + # Add a third entity to the device, from the same config entry + entry_same_config_entry_2 = entity_registry.async_get_or_create( + "sensor", + "hue", + "5678", + config_entry=config_entry, + device_id=device_entry.id, + ) + + # Add a listener to remove the 2nd entity it when 1st entity is removed + @callback + def on_entity_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: + """Add entity registry updated event to the list.""" + if event.data["action"] == "remove": + entity_registry.async_remove(entry_no_config_entry.entity_id) + + async_track_entity_registry_updated_event( + hass, entry_same_config_entry.entity_id, on_entity_event + ) + + device_registry.async_remove_device(device_entry.id) + await hass.async_block_till_done() + + assert not entity_registry.async_is_registered(entry_same_config_entry.entity_id) + assert not entity_registry.async_is_registered(entry_no_config_entry.entity_id) + assert not entity_registry.async_is_registered(entry_same_config_entry_2.entity_id) + + async def test_disable_device_disables_entities( hass: HomeAssistant, device_registry: dr.DeviceRegistry, diff --git a/tests/helpers/test_event.py b/tests/helpers/test_event.py index 465d1b1778b..c875522b943 100644 --- a/tests/helpers/test_event.py +++ b/tests/helpers/test_event.py @@ -4946,6 +4946,37 @@ async def test_async_track_state_report_event(hass: HomeAssistant) -> None: unsub() +async def test_async_track_state_report_change_event(hass: HomeAssistant) -> None: + """Test listen for both state change and state report events.""" + tracker_called: dict[str, list[str]] = {"light.bowl": [], "light.top": []} + + @ha.callback + def on_state_change(event: Event[EventStateChangedData]) -> None: + new_state = event.data["new_state"].state + tracker_called[event.data["entity_id"]].append(new_state) + + @ha.callback + def on_state_report(event: Event[EventStateReportedData]) -> None: + new_state = event.data["new_state"].state + tracker_called[event.data["entity_id"]].append(new_state) + + async_track_state_change_event(hass, ["light.bowl", "light.top"], on_state_change) + async_track_state_report_event(hass, ["light.bowl", "light.top"], on_state_report) + entity_ids = ["light.bowl", "light.top"] + state_sequence = ["on", "on", "off", "off"] + for state in state_sequence: + for entity_id in entity_ids: + hass.states.async_set(entity_id, state) + await hass.async_block_till_done() + + # The out-of-order is a result of state change listeners scheduled with + # loop.call_soon, whereas state report listeners are called immediately. + assert tracker_called == { + "light.bowl": ["on", "off", "on", "off"], + "light.top": ["on", "off", "on", "off"], + } + + async def test_async_track_template_no_hass_deprecated( hass: HomeAssistant, caplog: pytest.LogCaptureFixture ) -> None: diff --git a/tests/helpers/test_helper_integration.py b/tests/helpers/test_helper_integration.py index 47f1b62feb7..640b2ff011a 100644 --- a/tests/helpers/test_helper_integration.py +++ b/tests/helpers/test_helper_integration.py @@ -6,10 +6,13 @@ from unittest.mock import AsyncMock, Mock import pytest from homeassistant.config_entries import ConfigEntry -from homeassistant.core import Event, HomeAssistant +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.event import async_track_entity_registry_updated_event -from homeassistant.helpers.helper_integration import async_handle_source_entity_changes +from homeassistant.helpers.helper_integration import ( + async_handle_source_entity_changes, + async_remove_helper_config_entry_from_source_device, +) from tests.common import ( MockConfigEntry, @@ -152,7 +155,7 @@ def mock_helper_integration( async_remove_entry: AsyncMock, async_unload_entry: AsyncMock, set_source_entity_id_or_uuid: Mock, - source_entity_removed: AsyncMock, + source_entity_removed: AsyncMock | None, ) -> None: """Mock the helper integration.""" @@ -184,6 +187,7 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s """Track entity registry actions for an entity.""" events = [] + @callback def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: """Add entity registry updated event to the list.""" events.append(event.data["action"]) @@ -193,6 +197,23 @@ def track_entity_registry_actions(hass: HomeAssistant, entity_id: str) -> list[s return events +def listen_entity_registry_events( + hass: HomeAssistant, +) -> list[er.EventEntityRegistryUpdatedData]: + """Track entity registry actions for an entity.""" + events: list[er.EventEntityRegistryUpdatedData] = [] + + @callback + def add_event(event: Event[er.EventEntityRegistryUpdatedData]) -> None: + """Add entity registry updated event to the list.""" + events.append(event.data) + + hass.bus.async_listen(er.EVENT_ENTITY_REGISTRY_UPDATED, add_event) + + return events + + +@pytest.mark.parametrize("source_entity_removed", [None]) @pytest.mark.parametrize("use_entity_registry_id", [True, False]) @pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration") async def test_async_handle_source_entity_changes_source_entity_removed( @@ -207,6 +228,70 @@ async def test_async_handle_source_entity_changes_source_entity_removed( async_remove_entry: AsyncMock, async_unload_entry: AsyncMock, set_source_entity_id_or_uuid: Mock, +) -> None: + """Test the helper config entry is removed when the source entity is removed.""" + # Add the helper config entry to the source device + device_registry.async_update_device( + source_device.id, add_config_entry_id=helper_config_entry.entry_id + ) + # Add another config entry to the source device + other_config_entry = MockConfigEntry() + other_config_entry.add_to_hass(hass) + device_registry.async_update_device( + source_device.id, add_config_entry_id=other_config_entry.entry_id + ) + + assert await hass.config_entries.async_setup(helper_config_entry.entry_id) + await hass.async_block_till_done() + + # Check preconditions + helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id) + assert helper_entity_entry.device_id == source_entity_entry.device_id + source_device = device_registry.async_get(source_device.id) + assert helper_config_entry.entry_id in source_device.config_entries + + events = track_entity_registry_actions(hass, helper_entity_entry.entity_id) + + # Remove the source entitys's config entry from the device, this removes the + # source entity + device_registry.async_update_device( + source_device.id, remove_config_entry_id=source_config_entry.entry_id + ) + await hass.async_block_till_done() + await hass.async_block_till_done() + + # Check that the helper entity is not linked to the source device anymore + helper_entity_entry = entity_registry.async_get(helper_entity_entry.entity_id) + assert helper_entity_entry.device_id is None + async_unload_entry.assert_not_called() + async_remove_entry.assert_not_called() + set_source_entity_id_or_uuid.assert_not_called() + + # Check that the helper config entry is not removed from the device + source_device = device_registry.async_get(source_device.id) + assert helper_config_entry.entry_id in source_device.config_entries + + # Check that the helper config entry is not removed + assert helper_config_entry.entry_id in hass.config_entries.async_entry_ids() + + # Check we got the expected events + assert events == ["update"] + + +@pytest.mark.parametrize("use_entity_registry_id", [True, False]) +@pytest.mark.usefixtures("mock_helper_flow", "mock_helper_integration") +async def test_async_handle_source_entity_changes_source_entity_removed_custom_handler( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + helper_config_entry: MockConfigEntry, + helper_entity_entry: er.RegistryEntry, + source_config_entry: ConfigEntry, + source_device: dr.DeviceEntry, + source_entity_entry: er.RegistryEntry, + async_remove_entry: AsyncMock, + async_unload_entry: AsyncMock, + set_source_entity_id_or_uuid: Mock, source_entity_removed: AsyncMock, ) -> None: """Test the helper config entry is removed when the source entity is removed.""" @@ -425,3 +510,85 @@ async def test_async_handle_source_entity_new_entity_id( # Check we got the expected events assert events == [] + + +@pytest.mark.parametrize("use_entity_registry_id", [True, False]) +@pytest.mark.usefixtures("source_entity_entry") +async def test_async_remove_helper_config_entry_from_source_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + helper_config_entry: MockConfigEntry, + helper_entity_entry: er.RegistryEntry, + source_device: dr.DeviceEntry, +) -> None: + """Test removing the helper config entry from the source device.""" + # Add the helper config entry to the source device + device_registry.async_update_device( + source_device.id, add_config_entry_id=helper_config_entry.entry_id + ) + + # Create a helper entity entry, not connected to the source device + extra_helper_entity_entry = entity_registry.async_get_or_create( + "sensor", + HELPER_DOMAIN, + f"{helper_config_entry.entry_id}_2", + config_entry=helper_config_entry, + original_name="ABC", + ) + assert extra_helper_entity_entry.entity_id != helper_entity_entry.entity_id + + events = listen_entity_registry_events(hass) + + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=helper_config_entry.entry_id, + source_device_id=source_device.id, + ) + + # Check we got the expected events + assert events == [ + { + "action": "update", + "changes": {"device_id": source_device.id}, + "entity_id": helper_entity_entry.entity_id, + }, + { + "action": "update", + "changes": {"device_id": None}, + "entity_id": helper_entity_entry.entity_id, + }, + ] + + +@pytest.mark.parametrize("use_entity_registry_id", [True, False]) +@pytest.mark.usefixtures("source_entity_entry") +async def test_async_remove_helper_config_entry_from_source_device_helper_not_in_device( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + helper_config_entry: MockConfigEntry, + helper_entity_entry: er.RegistryEntry, + source_device: dr.DeviceEntry, +) -> None: + """Test removing the helper config entry from the source device.""" + # Create a helper entity entry, not connected to the source device + extra_helper_entity_entry = entity_registry.async_get_or_create( + "sensor", + HELPER_DOMAIN, + f"{helper_config_entry.entry_id}_2", + config_entry=helper_config_entry, + original_name="ABC", + ) + assert extra_helper_entity_entry.entity_id != helper_entity_entry.entity_id + + events = listen_entity_registry_events(hass) + + async_remove_helper_config_entry_from_source_device( + hass, + helper_config_entry_id=helper_config_entry.entry_id, + source_device_id=source_device.id, + ) + + # Check we got the expected events + assert events == [] diff --git a/tests/helpers/test_llm.py b/tests/helpers/test_llm.py index 78ff675f0b6..9ba93cef4ca 100644 --- a/tests/helpers/test_llm.py +++ b/tests/helpers/test_llm.py @@ -1161,6 +1161,7 @@ async def test_selector_serializer( "name": {"type": "string"}, "percentage": {"type": "number", "minimum": 30, "maximum": 100}, }, + "required": ["name"], } assert selector_serializer( selector.ObjectSelector( @@ -1190,6 +1191,7 @@ async def test_selector_serializer( "maximum": 100, }, }, + "required": ["name"], }, } assert selector_serializer( diff --git a/tests/helpers/test_target.py b/tests/helpers/test_target.py index 69f022bc9cd..c87a320e378 100644 --- a/tests/helpers/test_target.py +++ b/tests/helpers/test_target.py @@ -2,9 +2,6 @@ import pytest -# TODO(abmantis): is this import needed? -# To prevent circular import when running just this file -import homeassistant.components # noqa: F401 from homeassistant.components.group import Group from homeassistant.const import ( ATTR_AREA_ID, @@ -17,7 +14,8 @@ from homeassistant.const import ( STATE_ON, EntityCategory, ) -from homeassistant.core import HomeAssistant, callback +from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import ( area_registry as ar, device_registry as dr, @@ -466,61 +464,50 @@ async def test_async_track_target_selector_state_change_event_empty_selector( hass: HomeAssistant, caplog: pytest.LogCaptureFixture ) -> None: """Test async_track_target_selector_state_change_event with empty selector.""" - calls = [] @callback def state_change_callback(event): """Handle state change events.""" - calls.append(event) - unsub = target.async_track_target_selector_state_change_event( - hass, {}, state_change_callback + with pytest.raises(HomeAssistantError) as excinfo: + target.async_track_target_selector_state_change_event( + hass, {}, state_change_callback + ) + assert str(excinfo.value) == ( + "Target selector {} does not have any selectors defined" ) - assert "Target selector {} does not have any selectors defined" in caplog.text - - # Test that no state changes are tracked - hass.states.async_set("light.test", "on") - await hass.async_block_till_done() - - assert len(calls) == 0 - - unsub() - async def test_async_track_target_selector_state_change_event( hass: HomeAssistant, ) -> None: """Test async_track_target_selector_state_change_event with multiple targets.""" - calls = [] + events: list[Event[EventStateChangedData]] = [] @callback - def state_change_callback(event): + def state_change_callback(event: Event[EventStateChangedData]): """Handle state change events.""" - calls.append(event) + events.append(event) - # List of entities to toggle state during the test. This list should be insert-only - # so that all entities are changed every time. - entities_to_set_state = [] - # List of entities that should assert a state change when toggled. Contrary to - # entities_to_set_state, entities should be added and removed. - entities_to_assert_change = [] last_state = STATE_OFF - async def toggle_states(): - """Toggle the state of all the entities in test.""" + async def set_states_and_check_events( + entities_to_set_state: list[str], entities_to_assert_change: list[str] + ) -> None: + """Toggle the state entities and check for events.""" nonlocal last_state last_state = STATE_ON if last_state == STATE_OFF else STATE_OFF for entity_id in entities_to_set_state: hass.states.async_set(entity_id, last_state) await hass.async_block_till_done() - def assert_entity_calls_and_reset() -> None: - assert len(calls) == len(entities_to_assert_change) - for change_call in calls: - assert change_call.data["entity_id"] in entities_to_assert_change - assert change_call.data["new_state"].state == last_state - calls.clear() + assert len(events) == len(entities_to_assert_change) + entities_seen = set() + for event in events: + entities_seen.add(event.data["entity_id"]) + assert event.data["new_state"].state == last_state + assert entities_seen == set(entities_to_assert_change) + events.clear() config_entry = MockConfigEntry(domain="test") config_entry.add_to_hass(hass) @@ -559,8 +546,8 @@ async def test_async_track_target_selector_state_change_event( targeted_entity = "light.test_light" - entities_to_set_state.extend([targeted_entity, device_entity, untargeted_entity]) - await toggle_states() + targeted_entities = [targeted_entity, device_entity] + await set_states_and_check_events(targeted_entities, []) label = lr.async_get(hass).async_create("Test Label").name area = ar.async_get(hass).async_create("Test Area").id @@ -578,9 +565,7 @@ async def test_async_track_target_selector_state_change_event( ) # Test directly targeted entity and device - entities_to_assert_change.extend([targeted_entity, device_entity]) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events(targeted_entities, targeted_entities) # Add new entity to the targeted device -> should trigger on state change device_entity_2 = entity_reg.async_get_or_create( @@ -589,83 +574,72 @@ async def test_async_track_target_selector_state_change_event( unique_id="device_light_2", device_id=device_entry.id, ).entity_id - await hass.async_block_till_done() - entities_to_set_state.append(device_entity_2) - entities_to_assert_change.append(device_entity_2) - await toggle_states() - assert_entity_calls_and_reset() + targeted_entities = [targeted_entity, device_entity, device_entity_2] + await set_states_and_check_events(targeted_entities, targeted_entities) # Test untargeted entity -> should not trigger - entities_to_set_state.append(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], targeted_entities + ) # Add label to untargeted entity -> should trigger now entity_reg.async_update_entity(untargeted_entity, labels={label}) - await hass.async_block_till_done() - entities_to_assert_change.append(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], [*targeted_entities, untargeted_entity] + ) # Remove label from untargeted entity -> should not trigger anymore entity_reg.async_update_entity(untargeted_entity, labels={}) - await hass.async_block_till_done() - entities_to_assert_change.remove(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], targeted_entities + ) # Add area to untargeted entity -> should trigger now entity_reg.async_update_entity(untargeted_entity, area_id=area) - await hass.async_block_till_done() - entities_to_assert_change.append(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], [*targeted_entities, untargeted_entity] + ) # Remove area from untargeted entity -> should not trigger anymore entity_reg.async_update_entity(untargeted_entity, area_id=None) - await hass.async_block_till_done() - entities_to_assert_change.remove(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], targeted_entities + ) # Add area to untargeted device -> should trigger on state change device_reg.async_update_device(untargeted_device_entry.id, area_id=area) - await hass.async_block_till_done() - entities_to_set_state.append(untargeted_device_entity) - entities_to_assert_change.append(untargeted_device_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_device_entity], + [*targeted_entities, untargeted_device_entity], + ) # Remove area from untargeted device -> should not trigger anymore device_reg.async_update_device(untargeted_device_entry.id, area_id=None) - await hass.async_block_till_done() - entities_to_assert_change.remove(untargeted_device_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_device_entity], targeted_entities + ) # Set the untargeted area on the untargeted entity -> should not trigger untracked_area = ar.async_get(hass).async_create("Untargeted Area").id entity_reg.async_update_entity(untargeted_entity, area_id=untracked_area) - await hass.async_block_till_done() - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], targeted_entities + ) # Set targeted floor on the untargeted area -> should trigger now ar.async_get(hass).async_update(untracked_area, floor_id=floor) - await hass.async_block_till_done() - entities_to_assert_change.append(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], + [*targeted_entities, untargeted_entity], + ) # Remove untargeted area from targeted floor -> should not trigger anymore ar.async_get(hass).async_update(untracked_area, floor_id=None) - await hass.async_block_till_done() - entities_to_assert_change.remove(untargeted_entity) - await toggle_states() - assert_entity_calls_and_reset() + await set_states_and_check_events( + [*targeted_entities, untargeted_entity], targeted_entities + ) # After unsubscribing, changes should not trigger unsub() - await toggle_states() - assert len(calls) == 0 + await set_states_and_check_events(targeted_entities, []) diff --git a/tests/test_core.py b/tests/test_core.py index d4b5933aebe..0daaafe74cf 100644 --- a/tests/test_core.py +++ b/tests/test_core.py @@ -1847,7 +1847,7 @@ async def test_services_call_return_response_requires_blocking( return_response=True, ) assert str(exc.value) == ( - "A non blocking action call with argument blocking=False " + "A non-blocking action call with argument blocking=False " "can't be used together with argument return_response=True" ) diff --git a/tests/test_util/aiohttp.py b/tests/test_util/aiohttp.py index fe0de66f44c..c3a8be77b77 100644 --- a/tests/test_util/aiohttp.py +++ b/tests/test_util/aiohttp.py @@ -194,7 +194,6 @@ class AiohttpClientMockResponse: if response is None: response = b"" - self.charset = "utf-8" self.method = method self._url = url self.status = status @@ -264,16 +263,32 @@ class AiohttpClientMockResponse: """Return content.""" return mock_stream(self.response) + @property + def charset(self): + """Return charset from Content-Type header.""" + if (content_type := self._headers.get("content-type")) is None: + return None + content_type = content_type.lower() + if "charset=" in content_type: + return content_type.split("charset=")[1].split(";")[0].strip() + return None + async def read(self): """Return mock response.""" return self.response - async def text(self, encoding="utf-8", errors="strict"): + async def text(self, encoding=None, errors="strict") -> str: """Return mock response as a string.""" + # Match real aiohttp behavior: encoding=None means auto-detect + if encoding is None: + encoding = self.charset or "utf-8" return self.response.decode(encoding, errors=errors) - async def json(self, encoding="utf-8", content_type=None, loads=json_loads): + async def json(self, encoding=None, content_type=None, loads=json_loads) -> Any: """Return mock response as a json.""" + # Match real aiohttp behavior: encoding=None means auto-detect + if encoding is None: + encoding = self.charset or "utf-8" return loads(self.response.decode(encoding)) def release(self): diff --git a/tests/util/test_unit_conversion.py b/tests/util/test_unit_conversion.py index 7d0eb7226a0..537cfb33c31 100644 --- a/tests/util/test_unit_conversion.py +++ b/tests/util/test_unit_conversion.py @@ -8,6 +8,7 @@ from itertools import chain import pytest from homeassistant.const import ( + CONCENTRATION_GRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, CONCENTRATION_PARTS_PER_BILLION, @@ -762,6 +763,13 @@ _CONVERTED_VALUE: dict[ 2000, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, ), + # 3 g/m³ = 3000 mg/m³ + ( + 3, + CONCENTRATION_GRAMS_PER_CUBIC_METER, + 3000, + CONCENTRATION_MILLIGRAMS_PER_CUBIC_METER, + ), ], VolumeConverter: [ (5, UnitOfVolume.LITERS, 1.32086, UnitOfVolume.GALLONS),