From 64ed916d9c22640b8d41b403fda0f7ed4d4c0bd5 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 30 Sep 2026 17:04:09 +0000 Subject: [PATCH 001/356] Bump version to 2026.10.0b0 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 17eae8bcb397..ff23dffcd0e0 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0.dev0" +PATCH_VERSION: Final = "0b0" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index f1c94a0ccec1..08b4af9237c0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0.dev0" +version = "2026.10.0b0" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 6df690d60178a313db74f9f73ca04f3c42c820ca Mon Sep 17 00:00:00 2001 From: Niko Savola Date: Mon, 5 Oct 2026 04:22:37 +0300 Subject: [PATCH 002/356] Log when Google Generative AI STT returns no text (#180389) --- .../google_generative_ai_conversation/stt.py | 17 ++++++++ .../test_stt.py | 43 ++++++++++++++++--- 2 files changed, 55 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/google_generative_ai_conversation/stt.py b/homeassistant/components/google_generative_ai_conversation/stt.py index 0a71d7e97540..9a0c5f43cba3 100644 --- a/homeassistant/components/google_generative_ai_conversation/stt.py +++ b/homeassistant/components/google_generative_ai_conversation/stt.py @@ -266,5 +266,22 @@ class GoogleGenerativeAISttEntity( response.text, stt.SpeechResultState.SUCCESS, ) + if response.prompt_feedback: + # block_reason_message is not supported by the Gemini API + # (only Vertex AI), so it is always None for this + # API-key-based client; block_reason is always populated. + LOGGER.error( + "STT response contained no text (block_reason=%s)", + response.prompt_feedback.block_reason, + ) + else: + finish_reason = ( + response.candidates[0].finish_reason + if response.candidates + else None + ) + LOGGER.error( + "STT response contained no text (finish_reason=%s)", finish_reason + ) return stt.SpeechResult(None, stt.SpeechResultState.ERROR) diff --git a/tests/components/google_generative_ai_conversation/test_stt.py b/tests/components/google_generative_ai_conversation/test_stt.py index aa5ae95eeb06..62b382d0a7f8 100644 --- a/tests/components/google_generative_ai_conversation/test_stt.py +++ b/tests/components/google_generative_ai_conversation/test_stt.py @@ -191,16 +191,48 @@ async def test_stt_process_audio_stream_api_error( assert result.text is None +@pytest.mark.parametrize( + ("response", "expected_log"), + [ + pytest.param( + types.GenerateContentResponse(candidates=[]), + "STT response contained no text (finish_reason=None)", + id="empty_response", + ), + pytest.param( + types.GenerateContentResponse( + candidates=[{"finish_reason": "STOP", "content": {"role": "model"}}] + ), + "STT response contained no text (finish_reason=FinishReason.STOP)", + id="blank_text_response", + ), + pytest.param( + types.GenerateContentResponse( + candidates=[], + prompt_feedback={ + "block_reason": "SAFETY", + # Not populated by the Gemini API in practice (only + # Vertex AI); included to prove it is not what gets + # logged. + "block_reason_message": "Blocked for safety reasons", + }, + ), + "STT response contained no text (block_reason=BlockedReason.SAFETY)", + id="blocked_prompt", + ), + ], +) @pytest.mark.usefixtures("setup_integration") -async def test_stt_process_audio_stream_empty_response( +async def test_stt_process_audio_stream_no_text_response( hass: HomeAssistant, mock_genai_client: AsyncMock, + caplog: pytest.LogCaptureFixture, + response: types.GenerateContentResponse, + expected_log: str, ) -> None: - """Test STT processing with an empty response from the API.""" + """Test STT logs when the API response contains no text.""" entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") - mock_genai_client.aio.models.generate_content.return_value = ( - types.GenerateContentResponse(candidates=[]) - ) + mock_genai_client.aio.models.generate_content.return_value = response metadata = stt.SpeechMetadata( language="en-US", @@ -216,6 +248,7 @@ async def test_stt_process_audio_stream_empty_response( assert result.result == stt.SpeechResultState.ERROR assert result.text is None + assert expected_log in caplog.text @pytest.mark.usefixtures("mock_genai_client") From 7978ff6e6cfde8cfa940cb7ed4117caac66d3f7c Mon Sep 17 00:00:00 2001 From: Christian Lackas Date: Thu, 1 Oct 2026 12:57:52 +0200 Subject: [PATCH 003/356] Read ViCare entity values in the executor (#181379) --- .../components/vicare/coordinator.py | 24 +++++- homeassistant/components/vicare/entity.py | 19 ++++- homeassistant/components/vicare/fan.py | 23 +++-- homeassistant/components/vicare/sensor.py | 14 +-- tests/components/vicare/test_fan.py | 85 ++++++++++++++++++- tests/components/vicare/test_sensor.py | 82 +++++++++++++++++- 6 files changed, 230 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/vicare/coordinator.py b/homeassistant/components/vicare/coordinator.py index 534c8ff8054c..93109846ec4c 100644 --- a/homeassistant/components/vicare/coordinator.py +++ b/homeassistant/components/vicare/coordinator.py @@ -1,5 +1,6 @@ """DataUpdateCoordinator for the ViCare integration.""" +from collections.abc import Callable from datetime import timedelta import logging from typing import override @@ -16,7 +17,7 @@ from PyViCare.PyViCareUtils import ( ) import requests -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryAuthFailed from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed @@ -56,6 +57,17 @@ class ViCareCoordinator(DataUpdateCoordinator[None]): ) self._device = device self._accessor = accessor + self._value_readers: list[Callable[[], None]] = [] + + @callback + def async_add_value_reader(self, reader: Callable[[], None]) -> Callable[[], None]: + """Register a reader to run in the executor after each fetch.""" + self._value_readers.append(reader) + + def remove_value_reader() -> None: + self._value_readers.remove(reader) + + return remove_value_reader @override async def _async_update_data(self) -> None: @@ -89,3 +101,13 @@ class ViCareCoordinator(DataUpdateCoordinator[None]): requests.RequestException, ) as err: raise UpdateFailed(str(err)) from err + else: + # Only after a successful fetch: the cache was emptied above, and a + # reader must not be the one to refill it from the event loop. + # Iterate a copy, entities deregister from the event loop thread. + for reader in list(self._value_readers): + try: + reader() + except Exception: + # One unreadable value must not take the whole device down. + _LOGGER.exception("Error reading a ViCare entity value") diff --git a/homeassistant/components/vicare/entity.py b/homeassistant/components/vicare/entity.py index ddcb2658b081..01fbbbbd2eff 100644 --- a/homeassistant/components/vicare/entity.py +++ b/homeassistant/components/vicare/entity.py @@ -123,7 +123,13 @@ class ViCareEntity(Entity): class ViCareCoordinatorEntity(CoordinatorEntity[ViCareCoordinator], ViCareEntity): - """Base class for ViCare entities backed by the update coordinator.""" + """Base class for ViCare entities backed by the update coordinator. + + Values are read in ``_read_value``, which the coordinator calls from its + executor job. Properties must only return what was read there: a PyViCare + getter takes the library cache lock and does blocking I/O when that cache + is cold. + """ def __init__( self, @@ -139,3 +145,14 @@ class ViCareCoordinatorEntity(CoordinatorEntity[ViCareCoordinator], ViCareEntity ViCareEntity.__init__( self, unique_id_suffix, device_serial, device_config, device, component ) + + @override + async def async_added_to_hass(self) -> None: + """Register the value reader and prime the first value.""" + await super().async_added_to_hass() + self.async_on_remove(self.coordinator.async_add_value_reader(self._read_value)) + # The coordinator's first refresh ran before this entity existed. + await self.hass.async_add_executor_job(self._read_value) + + def _read_value(self) -> None: + """Read this entity's value from the API. Runs in the executor.""" diff --git a/homeassistant/components/vicare/fan.py b/homeassistant/components/vicare/fan.py index 966e0df738f5..ec568827dfcb 100644 --- a/homeassistant/components/vicare/fan.py +++ b/homeassistant/components/vicare/fan.py @@ -120,6 +120,7 @@ class ViCareFan(ViCareEntity, FanEntity): _attr_speed_count = len(ORDERED_NAMED_FAN_SPEEDS) _attr_translation_key = "ventilation" + _standby: bool = False def __init__( self, @@ -160,6 +161,11 @@ class ViCareFan(ViCareEntity, FanEntity): ) if VentilationQuickmode.STANDBY in quickmodes: self._attr_supported_features |= FanEntityFeature.TURN_OFF + # The first state is published before the first poll. + with suppress(PyViCareNotSupportedFeatureError): + self._standby = device.getVentilationQuickmode( + VentilationQuickmode.STANDBY + ) def update(self) -> None: """Update state of fan.""" @@ -170,6 +176,15 @@ class ViCareFan(ViCareEntity, FanEntity): self._api.getActiveVentilationMode() ) + if FanEntityFeature.TURN_OFF in self._attr_supported_features: + # Clear before the guarded read, a suppressed error would + # otherwise keep reporting the fan as off. + self._standby = False + with suppress(PyViCareNotSupportedFeatureError): + self._standby = self._api.getVentilationQuickmode( + VentilationQuickmode.STANDBY + ) + with suppress(PyViCareNotSupportedFeatureError): level = filter_state(self._api.getVentilationLevel()) if level is not None and level in ORDERED_NAMED_FAN_SPEEDS: @@ -183,9 +198,7 @@ class ViCareFan(ViCareEntity, FanEntity): @override def is_on(self) -> bool | None: """Return true if the entity is on.""" - if VentilationQuickmode.STANDBY in self._attributes[ - "vicare_quickmodes" - ] and self._api.getVentilationQuickmode(VentilationQuickmode.STANDBY): + if self._standby: return False return self.percentage is not None and self.percentage > 0 @@ -199,9 +212,7 @@ class ViCareFan(ViCareEntity, FanEntity): @override def icon(self) -> str | None: """Return the icon to use in the frontend.""" - if VentilationQuickmode.STANDBY in self._attributes[ - "vicare_quickmodes" - ] and self._api.getVentilationQuickmode(VentilationQuickmode.STANDBY): + if self._standby: return "mdi:fan-off" if hasattr(self, "_attr_preset_mode"): if self._attr_preset_mode == VentilationMode.VENTILATION: diff --git a/homeassistant/components/vicare/sensor.py b/homeassistant/components/vicare/sensor.py index 5b23d3e7179f..edf1e0481092 100644 --- a/homeassistant/components/vicare/sensor.py +++ b/homeassistant/components/vicare/sensor.py @@ -38,7 +38,6 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback -from homeassistant.helpers.typing import StateType from .const import ( VICARE_BAR, @@ -1643,10 +1642,11 @@ class ViCareSensor(ViCareCoordinatorEntity, SensorEntity): vicare_unit ] - @property @override - def native_value(self) -> StateType: - """Return the state of the sensor.""" - with suppress(PyViCareNotSupportedFeatureError): - return self.entity_description.value_getter(self._api) - return None + def _read_value(self) -> None: + """Read the sensor value from the API.""" + # Both context managers swallow read failures, so clear first rather + # than republish the previous value. + self._attr_native_value = None + with self.vicare_api_handler(), suppress(PyViCareNotSupportedFeatureError): + self._attr_native_value = self.entity_description.value_getter(self._api) diff --git a/tests/components/vicare/test_fan.py b/tests/components/vicare/test_fan.py index 0200c3d61303..2d89c454927c 100644 --- a/tests/components/vicare/test_fan.py +++ b/tests/components/vicare/test_fan.py @@ -3,11 +3,14 @@ from unittest.mock import patch import pytest +from PyViCare.PyViCareUtils import PyViCareNotSupportedFeatureError from syrupy.assertion import SnapshotAssertion -from homeassistant.const import Platform +from homeassistant.components.fan import DOMAIN as FAN_DOMAIN +from homeassistant.const import ATTR_ICON, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.entity_component import async_update_entity from . import MODULE, setup_integration from .conftest import Fixture, MockPyViCare @@ -41,3 +44,83 @@ async def test_all_entities( await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_standby_quickmode( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test that the fan follows the standby quickmode. + + The value is now read in the executor and cached, so it has to be primed + before the first state is published, and a read that stops being supported + must not leave the fan reported as in standby. The recorded level of this + device is unknown, which is why the icon and not the state carries the + difference here. + """ + fixtures: list[Fixture] = [Fixture({"type:ventilation"}, "vicare/VitoPure.json")] + vicare_data = MockPyViCare(fixtures).as_vicare_data() + api = vicare_data.devices[0].api + + with ( + patch( + "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", + ), + patch(f"{MODULE}._setup_vicare_api", return_value=vicare_data), + patch(f"{MODULE}.PLATFORMS", [Platform.FAN]), + patch.object(api, "getVentilationQuickmode", return_value=True), + ): + await setup_integration(hass, mock_config_entry) + + entity_id = hass.states.async_entity_ids(FAN_DOMAIN)[0] + assert "standby" in hass.states.get(entity_id).attributes["vicare_quickmodes"] + # The first state is published before the first poll. + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-off" + + # The fixture runs sensor driven and reports the quickmode as inactive. + await async_update_entity(hass, entity_id) + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-auto" + + with patch.object(api, "getVentilationQuickmode", return_value=True): + await async_update_entity(hass, entity_id) + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-off" + + with patch.object( + api, + "getVentilationQuickmode", + side_effect=PyViCareNotSupportedFeatureError("standby"), + ): + await async_update_entity(hass, entity_id) + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-auto" + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_standby_quickmode_with_a_second_fan( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test that a second fan without the quickmode does not stop the refresh.""" + fixtures: list[Fixture] = [ + Fixture({"type:ventilation"}, "vicare/VitoPure.json"), + Fixture({"type:ventilation"}, "vicare/ViAir300F.json"), + ] + vicare_data = MockPyViCare(fixtures).as_vicare_data() + api = vicare_data.devices[0].api + + with ( + patch( + "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", + ), + patch(f"{MODULE}._setup_vicare_api", return_value=vicare_data), + patch(f"{MODULE}.PLATFORMS", [Platform.FAN]), + patch.object(api, "getVentilationQuickmode", return_value=True), + ): + await setup_integration(hass, mock_config_entry) + + entity_id = hass.states.async_entity_ids(FAN_DOMAIN)[0] + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-off" + + # The fixture itself reports the quickmode as inactive. + await async_update_entity(hass, entity_id) + assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-auto" diff --git a/tests/components/vicare/test_sensor.py b/tests/components/vicare/test_sensor.py index 0d35c1f5660f..99bab0689f8a 100644 --- a/tests/components/vicare/test_sensor.py +++ b/tests/components/vicare/test_sensor.py @@ -1,18 +1,28 @@ """Test ViCare sensor entity.""" +from contextlib import ExitStack +from datetime import timedelta +import threading +from typing import Any from unittest.mock import patch +from freezegun.api import FrozenDateTimeFactory import pytest +from PyViCare.PyViCareService import ViCareDeviceAccessor from syrupy.assertion import SnapshotAssertion +from homeassistant.components.fan import DOMAIN as FAN_DOMAIN +from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN +from homeassistant.components.vicare.const import DEFAULT_CACHE_DURATION from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.entity_component import async_update_entity from . import MODULE, setup_integration from .conftest import Fixture, MockPyViCare -from tests.common import MockConfigEntry, snapshot_platform +from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform @pytest.mark.usefixtures("entity_registry_enabled_by_default") @@ -55,3 +65,73 @@ async def test_all_entities( await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_no_api_read_on_event_loop( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Entity values must be read in the executor, never on the event loop. + + A PyViCare getter takes the library's cache lock and does blocking I/O when + that cache is cold, so reading a value from a property freezes the loop for + the length of an HTTP request. + """ + fixtures: list[Fixture] = [ + Fixture({"type:heatpump"}, "vicare/Vitocal250A.json"), + Fixture({"type:ventilation"}, "vicare/VitoPure.json"), + ] + mock_vicare = MockPyViCare(fixtures) + services = {id(d.service): d.service for d in mock_vicare.devices} + + loop_thread_id = threading.get_ident() + reads_on_loop: list[str] = [] + reads_in_executor: list[str] = [] + + def guard(service): + read_property = service.getProperty + + def guarded_get_property( + accessor: ViCareDeviceAccessor, property_name: str + ) -> Any: + if threading.get_ident() == loop_thread_id: + reads_on_loop.append(property_name) + else: + reads_in_executor.append(property_name) + return read_property(accessor, property_name) + + return patch.object(service, "getProperty", guarded_get_property) + + with ( + patch( + "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", + ), + patch( + f"{MODULE}._setup_vicare_api", + return_value=mock_vicare.as_vicare_data(), + ), + patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR, Platform.FAN]), + ): + await setup_integration(hass, mock_config_entry) + + entity_ids = hass.states.async_entity_ids(SENSOR_DOMAIN) + fan_ids = hass.states.async_entity_ids(FAN_DOMAIN) + assert entity_ids + assert fan_ids + + with ExitStack() as stack: + for service in services.values(): + stack.enter_context(guard(service)) + + freezer.tick(timedelta(seconds=DEFAULT_CACHE_DURATION * 2)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + for entity_id in (entity_ids[0], fan_ids[0]): + await async_update_entity(hass, entity_id) + + assert not reads_on_loop + # Without this the test would also pass if nothing read a value at all. + assert reads_in_executor From 7d94bddcb971bee77788a873f7a2cfa0765bbc4f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 3 Oct 2026 22:01:37 +0200 Subject: [PATCH 004/356] Fix NUT sensors failing on variables reported as (null) (#182598) --- homeassistant/components/nut/__init__.py | 6 +++- tests/components/nut/test_sensor.py | 46 +++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nut/__init__.py b/homeassistant/components/nut/__init__.py index 04d85a10aeea..756ad87d4af4 100644 --- a/homeassistant/components/nut/__init__.py +++ b/homeassistant/components/nut/__init__.py @@ -336,7 +336,11 @@ class PyNUTData: self._alias = await self._async_get_alias() if TYPE_CHECKING: assert self._alias is not None - return await self._client.list_vars(self._alias) + status = await self._client.list_vars(self._alias) + if not status: + return status + # a driver formatting a missing C string reports the literal (null) + return {key: value for key, value in status.items() if value != "(null)"} async def async_update(self) -> dict[str, str]: """Fetch the latest status from NUT.""" diff --git a/tests/components/nut/test_sensor.py b/tests/components/nut/test_sensor.py index 9dc7d6d123d6..202072289263 100644 --- a/tests/components/nut/test_sensor.py +++ b/tests/components/nut/test_sensor.py @@ -1,5 +1,6 @@ """The sensor tests for the nut platform.""" +from datetime import timedelta from unittest.mock import patch import pytest @@ -21,6 +22,7 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er, translation +from homeassistant.util import dt as dt_util from .util import ( _get_mock_nutclient, @@ -28,7 +30,7 @@ from .util import ( async_init_integration, ) -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_fire_time_changed @pytest.mark.parametrize( @@ -211,6 +213,48 @@ async def test_unknown_state_sensors(hass: HomeAssistant) -> None: assert state2.state == "OQ" +async def test_null_variable_values( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Test variables a NUT driver reports as a literal (null) count as absent.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_HOST: "mock", CONF_PORT: "mock"}, + ) + entry.add_to_hass(hass) + + mock_pynut = _get_mock_nutclient( + list_ups={"ups1": "UPS 1"}, + list_vars={"battery.charger.status": "(null)", "battery.charge": "10"}, + ) + + with patch( + "homeassistant.components.nut.AIONUTClient", + return_value=mock_pynut, + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + # no sensor for a variable the driver has no value for + assert ( + entity_registry.async_get_entity_id( + Platform.SENSOR, DOMAIN, f"{entry.entry_id}_battery.charger.status" + ) + is None + ) + assert hass.states.get("sensor.ups1_battery_charge").state == "10" + + # a value that goes missing later leaves its sensor unknown + mock_pynut.list_vars.return_value = { + "battery.charger.status": "charging", + "battery.charge": "(null)", + } + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=61)) + await hass.async_block_till_done() + + assert hass.states.get("sensor.ups1_battery_charge").state == STATE_UNKNOWN + + async def test_stale_options( hass: HomeAssistant, entity_registry: er.EntityRegistry ) -> None: From d41a2e7c5465cacafa97bb44f20876c83e1cc082 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Sat, 3 Oct 2026 22:22:57 +0200 Subject: [PATCH 005/356] Update PyJWT to 2.15.1 (#182659) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: edenhaus <26537646+edenhaus@users.noreply.github.com> Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com> --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- tests/components/august/conftest.py | 9 ++++++++- 4 files changed, 11 insertions(+), 4 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index d52d8c75247e..c2b0b7f27f49 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -55,7 +55,7 @@ Pillow==12.3.0 probatio==0.12.4 propcache==0.5.4 psutil-home-assistant==0.0.1 -PyJWT==2.13.0 +PyJWT==2.15.1 pymicro-vad==1.0.1 PyNaCl==1.6.2 pyopenssl==26.4.0 diff --git a/pyproject.toml b/pyproject.toml index 08b4af9237c0..a7080a5e52c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -55,7 +55,7 @@ dependencies = [ "ifaddr==0.2.0", "Jinja2==3.1.6", "lru-dict==1.4.1", - "PyJWT==2.13.0", + "PyJWT==2.15.1", # PyJWT has loose dependency. We want the latest one. "cryptography==50.0.1", "Pillow==12.3.0", diff --git a/requirements.txt b/requirements.txt index c06b77278973..a2112534e6b6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -41,7 +41,7 @@ Pillow==12.3.0 probatio==0.12.4 propcache==0.5.4 psutil-home-assistant==0.0.1 -PyJWT==2.13.0 +PyJWT==2.15.1 pymicro-vad==1.0.1 pyopenssl==26.4.0 pyspeex-noise==1.0.2 diff --git a/tests/components/august/conftest.py b/tests/components/august/conftest.py index ed76a1883226..a18302e88ddd 100644 --- a/tests/components/august/conftest.py +++ b/tests/components/august/conftest.py @@ -1,5 +1,6 @@ """August tests conftest.""" +import base64 from unittest.mock import patch import pytest @@ -94,7 +95,13 @@ def load_reauth_jwt_fixture() -> str: @pytest.fixture(name="migration_jwt") def load_migration_jwt_fixture() -> str: """Load migration JWT fixture data (has email for legacy migration).""" - return load_fixture("migration_jwt", DOMAIN).strip("\n") + token = load_fixture("migration_jwt", DOMAIN).strip() + header, payload, signature = token.split(".") + signature_bytes = base64.urlsafe_b64decode(signature + "=" * (-len(signature) % 4)) + canonical_signature = ( + base64.urlsafe_b64encode(signature_bytes).rstrip(b"=").decode() + ) + return f"{header}.{payload}.{canonical_signature}" @pytest.fixture(name="reauth_jwt_wrong_account") From 095bdd40b670d999fc708c29c82f6b8fb48e9463 Mon Sep 17 00:00:00 2001 From: Andrew Jackson Date: Fri, 2 Oct 2026 19:37:18 +0100 Subject: [PATCH 006/356] Reload Transmission on config options changing (#182847) --- .../components/transmission/config_flow.py | 9 ++- .../transmission/test_config_flow.py | 66 +++++++++++++++---- 2 files changed, 60 insertions(+), 15 deletions(-) diff --git a/homeassistant/components/transmission/config_flow.py b/homeassistant/components/transmission/config_flow.py index f995f8c7d16f..6770e740e118 100644 --- a/homeassistant/components/transmission/config_flow.py +++ b/homeassistant/components/transmission/config_flow.py @@ -14,7 +14,7 @@ from homeassistant.config_entries import ( ConfigEntry, ConfigFlow, ConfigFlowResult, - OptionsFlow, + OptionsFlowWithReload, ) from homeassistant.const import ( CONF_HOST, @@ -79,7 +79,10 @@ class TransmissionFlowHandler(ConfigFlow, domain=DOMAIN): if user_input is not None: self._async_abort_entries_match( - {CONF_HOST: user_input[CONF_HOST], CONF_PORT: user_input[CONF_PORT]} + { + CONF_HOST: user_input[CONF_HOST], + CONF_PORT: user_input[CONF_PORT], + } ) try: api = await get_api(self.hass, user_input) @@ -151,7 +154,7 @@ class TransmissionFlowHandler(ConfigFlow, domain=DOMAIN): ) -class TransmissionOptionsFlowHandler(OptionsFlow): +class TransmissionOptionsFlowHandler(OptionsFlowWithReload): """Handle Transmission client options.""" async def async_step_init( diff --git a/tests/components/transmission/test_config_flow.py b/tests/components/transmission/test_config_flow.py index 346c99e6c992..471239bcdc61 100644 --- a/tests/components/transmission/test_config_flow.py +++ b/tests/components/transmission/test_config_flow.py @@ -12,6 +12,7 @@ from transmission_rpc.error import ( from homeassistant import config_entries from homeassistant.components import transmission from homeassistant.components.transmission.const import DOMAIN +from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @@ -64,9 +65,9 @@ async def test_device_already_configured( assert result["type"] is FlowResultType.ABORT +@pytest.mark.usefixtures("mock_transmission_client") async def test_options( hass: HomeAssistant, - mock_config_entry: MockConfigEntry, ) -> None: """Test updating options.""" entry = MockConfigEntry( @@ -74,23 +75,20 @@ async def test_options( data=MOCK_CONFIG_DATA, options={"limit": 10, "order": "oldest_first"}, ) - entry.add_to_hass(hass) - - with patch( - "homeassistant.components.transmission.async_setup_entry", - return_value=True, - ): - assert await hass.config_entries.async_setup(entry.entry_id) - await hass.async_block_till_done() + await setup_integration(hass, entry) result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" - result = await hass.config_entries.options.async_configure( - result["flow_id"], user_input={"limit": 20} - ) + with patch.object(hass.config_entries, "async_reload") as mock_reload: + result = await hass.config_entries.options.async_configure( + result["flow_id"], user_input={"limit": 20} + ) + await hass.async_block_till_done() + + mock_reload.assert_awaited_once_with(entry.entry_id) assert result["data"]["limit"] == 20 assert result["data"]["order"] == "oldest_first" @@ -232,6 +230,50 @@ async def test_reauth_success( assert result["type"] is FlowResultType.ABORT +async def test_reauth_success_after_setup_error( + hass: HomeAssistant, + mock_transmission_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauth retries an entry that failed during setup.""" + mock_config_entry.add_to_hass(hass) + mock_transmission_client.side_effect = TransmissionAuthError() + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + + mock_transmission_client.side_effect = None + result = await mock_config_entry.start_reauth_flow(hass) + + with patch.object(hass.config_entries, "async_schedule_reload") as mock_reload: + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "test-password"} + ) + + mock_reload.assert_called_once_with(mock_config_entry.entry_id) + assert result["reason"] == "reauth_successful" + assert result["type"] is FlowResultType.ABORT + + +async def test_reauth_success_when_credentials_are_unchanged( + hass: HomeAssistant, + mock_transmission_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauth reloads when the credentials are unchanged.""" + await setup_integration(hass, mock_config_entry) + result = await mock_config_entry.start_reauth_flow(hass) + + with patch.object(hass.config_entries, "async_schedule_reload") as mock_reload: + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"password": "pass"} + ) + + mock_reload.assert_called_once_with(mock_config_entry.entry_id) + assert result["reason"] == "reauth_successful" + assert result["type"] is FlowResultType.ABORT + + @pytest.mark.parametrize( ("exception", "field", "error"), [ From 67e2e4900b7fd7645ca786064579f2916eaecb2e Mon Sep 17 00:00:00 2001 From: Guillaume BAILLEUL Date: Fri, 2 Oct 2026 11:33:23 +0200 Subject: [PATCH 007/356] Fix 500 instead of 401 when reverse DNS lookup fails to decode (#182919) Co-authored-by: Claude Sonnet 5 Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- homeassistant/components/http/ban.py | 2 +- tests/components/http/test_ban.py | 28 ++++++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/http/ban.py b/homeassistant/components/http/ban.py index c9f6cab2c888..f05911ba8952 100644 --- a/homeassistant/components/http/ban.py +++ b/homeassistant/components/http/ban.py @@ -119,7 +119,7 @@ async def process_wrong_login(request: Request) -> None: assert request.remote remote_addr = ip_address(request.remote) remote_host = request.remote - with suppress(herror): + with suppress(herror, UnicodeDecodeError): remote_host, _, _ = await hass.async_add_executor_job( gethostbyaddr, request.remote ) diff --git a/tests/components/http/test_ban.py b/tests/components/http/test_ban.py index 58498d99f521..df11d862818c 100644 --- a/tests/components/http/test_ban.py +++ b/tests/components/http/test_ban.py @@ -4,6 +4,7 @@ from http import HTTPStatus from ipaddress import ip_address import logging import os +from typing import NoReturn from unittest.mock import AsyncMock, Mock, mock_open, patch from aiohttp import web @@ -462,6 +463,33 @@ async def test_failed_login_attempts_counter( assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 2 +async def test_failed_login_attempts_counter_reverse_dns_unicode_decode_error( + hass: HomeAssistant, aiohttp_client: ClientSessionGenerator +) -> None: + """Test a wrong login still gets a 401 if the reverse DNS lookup fails to decode.""" + app = web.Application() + app[KEY_HASS] = hass + + async def unauth_handler(request: web.Request) -> NoReturn: + """Return a mock web response.""" + raise HTTPUnauthorized + + app.router.add_get("/example", unauth_handler) + setup_bans(hass, app, 5) + remote_ip = ip_address("200.201.202.204") + mock_real_ip(app)("200.201.202.204") + + with patch( + "homeassistant.components.http.ban.gethostbyaddr", + side_effect=UnicodeDecodeError("utf-8", b"\x8a", 0, 1, "invalid start byte"), + ): + client = await aiohttp_client(app) + resp = await client.get("/example") + + assert resp.status == HTTPStatus.UNAUTHORIZED + assert app[KEY_FAILED_LOGIN_ATTEMPTS][remote_ip] == 1 + + async def test_single_ban_file_entry( hass: HomeAssistant, ) -> None: From 48849c7332ff67a0dea861a8d8f83d8476d7232f Mon Sep 17 00:00:00 2001 From: Chris <53621277+smitec11@users.noreply.github.com> Date: Fri, 2 Oct 2026 10:22:44 +0200 Subject: [PATCH 008/356] Fall back to the MAC address when a Bravia television reports no CID (#182949) Co-authored-by: Claude Opus 5 Co-authored-by: Maciej Bieniek --- homeassistant/components/braviatv/__init__.py | 43 ++++++- .../components/braviatv/config_flow.py | 19 ++- .../components/braviatv/diagnostics.py | 2 +- .../braviatv/snapshots/test_diagnostics.ambr | 4 +- tests/components/braviatv/test_config_flow.py | 83 ++++++++++++- tests/components/braviatv/test_init.py | 117 ++++++++++++++++++ 6 files changed, 259 insertions(+), 9 deletions(-) create mode 100644 tests/components/braviatv/test_init.py diff --git a/homeassistant/components/braviatv/__init__.py b/homeassistant/components/braviatv/__init__.py index 477af6e3f495..1418070c672a 100644 --- a/homeassistant/components/braviatv/__init__.py +++ b/homeassistant/components/braviatv/__init__.py @@ -7,11 +7,12 @@ from pybravia import BraviaClient from homeassistant.components import ssdp from homeassistant.const import CONF_HOST, CONF_MAC, Platform -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo -from .const import CONF_USE_SSL +from .const import CONF_USE_SSL, DOMAIN from .coordinator import BraviaTVConfigEntry, BraviaTVCoordinator PLATFORMS: Final[list[Platform]] = [ @@ -69,6 +70,44 @@ async def async_unload_entry( return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS) +async def async_migrate_entry( + hass: HomeAssistant, config_entry: BraviaTVConfigEntry +) -> bool: + """Migrate an old config entry.""" + if config_entry.version == 1 and config_entry.minor_version == 1: + # Old entries from a TV without CID have an empty unique ID + new_unique_id = config_entry.unique_id or dr.format_mac( + config_entry.data[CONF_MAC] + ) + + if new_unique_id != config_entry.unique_id: + device_registry = dr.async_get(hass) + if device_entry := device_registry.async_get_device_by_identifier( + (DOMAIN, ""), config_entry.entry_id + ): + new_identifiers = device_entry.identifiers.copy() + new_identifiers.discard((DOMAIN, "")) + new_identifiers.add((DOMAIN, new_unique_id)) + device_registry.async_update_device( + device_entry.id, new_identifiers=new_identifiers + ) + + @callback + def update_unique_id(entity_entry: er.RegistryEntry) -> dict[str, str]: + """Prefix the entity unique ID, which was the suffix alone.""" + return {"new_unique_id": f"{new_unique_id}{entity_entry.unique_id}"} + + await er.async_migrate_entries( + hass, config_entry.entry_id, update_unique_id + ) + + hass.config_entries.async_update_entry( + config_entry, unique_id=new_unique_id, minor_version=2 + ) + + return True + + async def update_listener( hass: HomeAssistant, config_entry: BraviaTVConfigEntry ) -> None: diff --git a/homeassistant/components/braviatv/config_flow.py b/homeassistant/components/braviatv/config_flow.py index b5bf211fad44..2f1a336240a7 100644 --- a/homeassistant/components/braviatv/config_flow.py +++ b/homeassistant/components/braviatv/config_flow.py @@ -19,6 +19,7 @@ from homeassistant.const import ( ) from homeassistant.helpers import instance_id from homeassistant.helpers.aiohttp_client import async_create_clientsession +from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.service_info.ssdp import ( ATTR_UPNP_FRIENDLY_NAME, ATTR_UPNP_MODEL_NAME, @@ -42,6 +43,7 @@ class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a config flow for Bravia TV integration.""" VERSION = 1 + MINOR_VERSION = 2 def __init__(self) -> None: """Initialize config flow.""" @@ -84,13 +86,24 @@ class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN): await self.async_connect_device() system_info = await self.client.get_system_info() - cid = system_info[ATTR_CID].lower() + mac = system_info[ATTR_MAC] + formatted_mac = format_mac(mac) - self.device_config[CONF_MAC] = system_info[ATTR_MAC] + # Some TVs return an empty CID + unique_id = system_info[ATTR_CID].lower() or formatted_mac - await self.async_set_unique_id(cid) + self.device_config[CONF_MAC] = mac + + await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured() + # Disabled entries are not migrated, so they still have an empty unique ID + if any( + not entry.unique_id and format_mac(entry.data[CONF_MAC]) == formatted_mac + for entry in self._async_current_entries(include_ignore=False) + ): + return self.async_abort(reason="already_configured") + return self.async_create_entry( title=f"{system_info['name']} {system_info[ATTR_MODEL]}", data=self.device_config, diff --git a/homeassistant/components/braviatv/diagnostics.py b/homeassistant/components/braviatv/diagnostics.py index 13019dacd963..a69d32d1c710 100644 --- a/homeassistant/components/braviatv/diagnostics.py +++ b/homeassistant/components/braviatv/diagnostics.py @@ -8,7 +8,7 @@ from homeassistant.core import HomeAssistant from .coordinator import BraviaTVConfigEntry -TO_REDACT = {CONF_MAC, CONF_PIN, "macAddr"} +TO_REDACT = {CONF_MAC, CONF_PIN, "macAddr", "unique_id"} async def async_get_config_entry_diagnostics( diff --git a/tests/components/braviatv/snapshots/test_diagnostics.ambr b/tests/components/braviatv/snapshots/test_diagnostics.ambr index c46a998913ce..56ab37a00b8d 100644 --- a/tests/components/braviatv/snapshots/test_diagnostics.ambr +++ b/tests/components/braviatv/snapshots/test_diagnostics.ambr @@ -13,7 +13,7 @@ }), 'domain': 'braviatv', 'entry_id': '3bd2acb0e4f0476d40865546d0d91921', - 'minor_version': 1, + 'minor_version': 2, 'options': dict({ }), 'pref_disable_new_entities': False, @@ -22,7 +22,7 @@ 'subentries': list([ ]), 'title': 'BRAVIA TV-Model', - 'unique_id': 'very_unique_string', + 'unique_id': '**REDACTED**', 'version': 1, }), 'device_info': dict({ diff --git a/tests/components/braviatv/test_config_flow.py b/tests/components/braviatv/test_config_flow.py index 8ef581e86816..27f557254e56 100644 --- a/tests/components/braviatv/test_config_flow.py +++ b/tests/components/braviatv/test_config_flow.py @@ -17,7 +17,7 @@ from homeassistant.components.braviatv.const import ( DOMAIN, NICKNAME_PREFIX, ) -from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER +from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER, ConfigEntryDisabler from homeassistant.const import CONF_CLIENT_ID, CONF_HOST, CONF_MAC, CONF_PIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @@ -455,3 +455,84 @@ async def test_reauth_successful(hass: HomeAssistant, use_psk, new_pin) -> None: assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" assert config_entry.data[CONF_PIN] == new_pin + + +@pytest.mark.parametrize( + ( + "existing_unique_id", + "existing_mac", + "disabled_by", + "expected_type", + "expected_unique_ids", + ), + [ + pytest.param( + "", + "11:22:33:44:55:66", + None, + FlowResultType.CREATE_ENTRY, + ["11:22:33:44:55:66", "aa:bb:cc:dd:ee:ff"], + id="other_tv_without_cid", + ), + pytest.param( + "aa:bb:cc:dd:ee:ff", + "AA:BB:CC:DD:EE:FF", + None, + FlowResultType.ABORT, + ["aa:bb:cc:dd:ee:ff"], + id="same_tv_migrated", + ), + pytest.param( + "", + "AA:BB:CC:DD:EE:FF", + ConfigEntryDisabler.USER, + FlowResultType.ABORT, + [""], + id="same_tv_disabled", + ), + ], +) +async def test_user_flow_with_empty_cid( + hass: HomeAssistant, + existing_unique_id: str, + existing_mac: str, + disabled_by: ConfigEntryDisabler | None, + expected_type: FlowResultType, + expected_unique_ids: list[str], +) -> None: + """Test a television that reports an empty CID is identified by its MAC.""" + MockConfigEntry( + domain=DOMAIN, + unique_id=existing_unique_id, + data={CONF_HOST: "other-host", CONF_MAC: existing_mac}, + disabled_by=disabled_by, + ).add_to_hass(hass) + + with ( + patch("pybravia.BraviaClient.connect"), + patch("pybravia.BraviaClient.pair"), + patch("pybravia.BraviaClient.set_wol_mode"), + patch( + "pybravia.BraviaClient.get_system_info", + return_value=BRAVIA_SYSTEM_INFO + | {"cid": "", "macAddr": "AA:BB:CC:DD:EE:FF"}, + ), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "bravia-host"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_USE_PSK: True, CONF_USE_SSL: False} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_PIN: "secret"} + ) + + assert result["type"] is expected_type + assert ( + sorted(entry.unique_id for entry in hass.config_entries.async_entries(DOMAIN)) + == expected_unique_ids + ) diff --git a/tests/components/braviatv/test_init.py b/tests/components/braviatv/test_init.py new file mode 100644 index 000000000000..92da87951621 --- /dev/null +++ b/tests/components/braviatv/test_init.py @@ -0,0 +1,117 @@ +"""Test the Bravia TV integration setup.""" + +from unittest.mock import patch + +import pytest + +from homeassistant.components.braviatv.const import CONF_USE_PSK, DOMAIN +from homeassistant.const import CONF_HOST, CONF_MAC, CONF_PIN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr, entity_registry as er + +from tests.common import MockConfigEntry + +ENTRY_DATA = { + CONF_HOST: "bravia-host", + CONF_MAC: "AA:BB:CC:DD:EE:FF", + CONF_PIN: "secret", + CONF_USE_PSK: True, +} + + +@pytest.mark.parametrize( + ("unique_id", "mac", "expected_unique_id"), + [ + pytest.param("", "AA:BB:CC:DD:EE:FF", "aa:bb:cc:dd:ee:ff", id="empty_cid"), + pytest.param( + "very_unique_string", + "AA:BB:CC:DD:EE:FF", + "very_unique_string", + id="existing_cid", + ), + pytest.param("", "", "", id="empty_cid_and_mac"), + ], +) +async def test_migrate_unique_id( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + unique_id: str, + mac: str, + expected_unique_id: str, +) -> None: + """Test only an entry stored without a CID gets a new unique ID.""" + config_entry = MockConfigEntry( + domain=DOMAIN, + unique_id=unique_id, + data=ENTRY_DATA | {CONF_MAC: mac}, + version=1, + minor_version=1, + ) + config_entry.add_to_hass(hass) + entity = entity_registry.async_get_or_create( + "media_player", DOMAIN, unique_id, config_entry=config_entry + ) + + with ( + patch("homeassistant.components.braviatv.BraviaClient", autospec=True), + patch( + "homeassistant.components.braviatv.coordinator.BraviaTVCoordinator._async_update_data", + return_value=None, + ), + ): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.unique_id == expected_unique_id + assert config_entry.minor_version == 2 + + migrated_entity = entity_registry.async_get(entity.entity_id) + assert migrated_entity is not None + assert migrated_entity.unique_id == expected_unique_id + + +async def test_migration_keeps_entities_and_device( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + device_registry: dr.DeviceRegistry, +) -> None: + """Test entities and the device move along and keep their entity IDs.""" + config_entry = MockConfigEntry( + domain=DOMAIN, unique_id="", data=ENTRY_DATA, version=1, minor_version=1 + ) + config_entry.add_to_hass(hass) + + device = device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, "")} + ) + media_player = entity_registry.async_get_or_create( + "media_player", DOMAIN, "", config_entry=config_entry, device_id=device.id + ) + button = entity_registry.async_get_or_create( + "button", DOMAIN, "_reboot", config_entry=config_entry, device_id=device.id + ) + + with ( + patch("homeassistant.components.braviatv.BraviaClient", autospec=True), + patch( + "homeassistant.components.braviatv.coordinator.BraviaTVCoordinator._async_update_data", + return_value=None, + ), + ): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.unique_id == "aa:bb:cc:dd:ee:ff" + assert config_entry.minor_version == 2 + + migrated_media_player = entity_registry.async_get(media_player.entity_id) + assert migrated_media_player is not None + assert migrated_media_player.unique_id == "aa:bb:cc:dd:ee:ff" + + migrated_button = entity_registry.async_get(button.entity_id) + assert migrated_button is not None + assert migrated_button.unique_id == "aa:bb:cc:dd:ee:ff_reboot" + + assert device_registry.async_get(device.id).identifiers == { + (DOMAIN, "aa:bb:cc:dd:ee:ff") + } From 42a371b5d8bcca971636c94af56e0b0425af5e7d Mon Sep 17 00:00:00 2001 From: Sylvain Date: Fri, 2 Oct 2026 22:41:20 +0200 Subject: [PATCH 009/356] Add plate count for KM7999 (#182993) --- homeassistant/components/miele/sensor.py | 1 + tests/components/miele/test_sensor.py | 19 ++++++++++++++++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/miele/sensor.py b/homeassistant/components/miele/sensor.py index bf507a218426..21c5e26ceca1 100644 --- a/homeassistant/components/miele/sensor.py +++ b/homeassistant/components/miele/sensor.py @@ -65,6 +65,7 @@ PLATE_COUNT = { "KM7878": 6, "KM7897": 6, "KM7899": 5, + "KM7999": 5, "KMDA7633": 5, "KMDA7634": 5, "KMDA7774": 5, diff --git a/tests/components/miele/test_sensor.py b/tests/components/miele/test_sensor.py index af633ff1918e..05146a800ac1 100644 --- a/tests/components/miele/test_sensor.py +++ b/tests/components/miele/test_sensor.py @@ -9,7 +9,7 @@ import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.miele.const import DOMAIN -from homeassistant.components.miele.sensor import _convert_temperature +from homeassistant.components.miele.sensor import _convert_temperature, _get_plate_count from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant, State @@ -902,3 +902,20 @@ def test_convert_temperature_invalid_raw_types() -> None: """int() must not raise: bad API payloads become unknown.""" assert _convert_temperature([_core_temperature_entry("n/a")], 0) is None assert _convert_temperature([_core_temperature_entry([1])], 0) is None + + +@pytest.mark.parametrize( + ("tech_type", "expected"), + [ + ("KM7575", 6), + ("KM7699", 5), + ("KM7899", 5), + ("KM7999 FR/R01", 5), + ("KMX 123", 6), + ("KMDA7774-1 R01", 5), + ("Unknown model", 4), + ], +) +def test_get_plate_count(tech_type: str, expected: int) -> None: + """Cover _get_plate_count prefix matching, including the KM7999 entry.""" + assert _get_plate_count(tech_type) == expected From 75cc467a6adb1fe0a74a577aeac4eb17e11d59a7 Mon Sep 17 00:00:00 2001 From: Samuel Date: Fri, 2 Oct 2026 11:44:53 +0200 Subject: [PATCH 010/356] Fix Philips TV state on TVs where screenstate is always off (#183207) Co-authored-by: Claude Opus 5.5 --- .../components/philips_js/media_player.py | 15 ++++++++- .../philips_js/test_media_player.py | 33 +++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/philips_js/media_player.py b/homeassistant/components/philips_js/media_player.py index a8336a287b2c..43eac33fcdbb 100644 --- a/homeassistant/components/philips_js/media_player.py +++ b/homeassistant/components/philips_js/media_player.py @@ -456,11 +456,24 @@ class PhilipsTVMediaPlayer(PhilipsJsEntity, MediaPlayerEntity): self.media_content_type, self.media_content_id, None ) + @property + def _ambilight_idle(self) -> bool: + """Return True if ambilight reports no active configuration. + + Some TVs without a powerstate endpoint always report the screen as off, + but only return an ambilight configuration while the TV is on. + """ + if not self._tv.json_feature_supported("ambilight", "Ambilight"): + return True + return self._tv.ambilight_current_configuration is None + @callback def _update_from_coordinator(self): if self._tv.on: if self._tv.powerstate in ("Standby", "StandbyKeep") or ( - self._tv.powerstate is None and self._tv.screenstate == TV_STATE_OFF + self._tv.powerstate is None + and self._tv.screenstate == TV_STATE_OFF + and self._ambilight_idle ): self._attr_state = MediaPlayerState.OFF else: diff --git a/tests/components/philips_js/test_media_player.py b/tests/components/philips_js/test_media_player.py index 3a4425736347..a616a9f6a8b6 100644 --- a/tests/components/philips_js/test_media_player.py +++ b/tests/components/philips_js/test_media_player.py @@ -39,3 +39,36 @@ async def test_state( assert (state := hass.states.get(MOCK_ENTITY_ID)) assert state.state == expected_state + + +@pytest.mark.parametrize( + ("ambilight_configuration", "expected_state"), + [ + pytest.param(None, STATE_OFF, id="ambilight-idle"), + pytest.param( + {"styleName": "FOLLOW_VIDEO", "isExpert": False}, + STATE_ON, + id="ambilight-active", + ), + ], +) +async def test_state_screenstate_always_off( + hass: HomeAssistant, + mock_tv: PhilipsTV, + mock_config_entry: MockConfigEntry, + ambilight_configuration: dict[str, str | bool] | None, + expected_state: str, +) -> None: + """Test ambilight decides the state when screenstate is always off.""" + mock_tv.json_feature_supported.side_effect = lambda feature, value: ( + (feature, value) == ("ambilight", "Ambilight") + ) + mock_tv.powerstate = None + mock_tv.screenstate = TV_STATE_OFF + mock_tv.ambilight_current_configuration = ambilight_configuration + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get(MOCK_ENTITY_ID)) + assert state.state == expected_state From 460d0e7f5008b7387aefd10649fb6400d852cf1d Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Fri, 2 Oct 2026 06:16:46 -0400 Subject: [PATCH 011/356] Match track titles in a Squeezebox search inside a genre (#183423) Co-authored-by: Claude --- .../components/squeezebox/browse_media.py | 4 ++ .../components/squeezebox/media_player.py | 13 ++++-- .../squeezebox/test_media_browser.py | 44 ++++++++++++++----- 3 files changed, 47 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/squeezebox/browse_media.py b/homeassistant/components/squeezebox/browse_media.py index b42a176f2280..3da966f2b1dd 100644 --- a/homeassistant/components/squeezebox/browse_media.py +++ b/homeassistant/components/squeezebox/browse_media.py @@ -47,6 +47,7 @@ MEDIA_TYPE_TO_SQUEEZEBOX: dict[str | MediaType, str] = { "new music": "new music", "album artists": "album artists", "artist tracks": "titles", + "genre tracks": "titles", MediaType.ALBUM: "album", MediaType.ARTIST: "artist", MediaType.TRACK: "title", @@ -63,6 +64,7 @@ SQUEEZEBOX_ID_BY_TYPE: dict[str | MediaType, str] = { MediaType.ARTIST: "artist_id", "artists": "artist_id", "artist tracks": "artist_id", + "genre tracks": "genre_id", MediaType.TRACK: "track_id", "tracks": "track_id", MediaType.PLAYLIST: "playlist_id", @@ -90,6 +92,7 @@ CONTENT_TYPE_MEDIA_CLASS: dict[str | MediaType, dict[str, MediaClass | str]] = { "new music": {"item": MediaClass.DIRECTORY, "children": MediaClass.ALBUM}, "album artists": {"item": MediaClass.DIRECTORY, "children": MediaClass.ARTIST}, "artist tracks": {"item": MediaClass.DIRECTORY, "children": MediaClass.TRACK}, + "genre tracks": {"item": MediaClass.DIRECTORY, "children": MediaClass.TRACK}, MediaType.ALBUM: {"item": MediaClass.ALBUM, "children": MediaClass.TRACK}, MediaType.ARTIST: {"item": MediaClass.ARTIST, "children": MediaClass.ALBUM}, MediaType.TRACK: {"item": MediaClass.TRACK, "children": ""}, @@ -117,6 +120,7 @@ CONTENT_TYPE_TO_CHILD_TYPE: dict[ "new music": MediaType.ALBUM, "album artists": MediaType.ARTIST, "artist tracks": MediaType.TRACK, + "genre tracks": MediaType.TRACK, MediaType.APPS: MediaType.APP, MediaType.APP: MediaType.TRACK, "favorite": None, diff --git a/homeassistant/components/squeezebox/media_player.py b/homeassistant/components/squeezebox/media_player.py index 0e7250d4678b..69ea433bd6a5 100644 --- a/homeassistant/components/squeezebox/media_player.py +++ b/homeassistant/components/squeezebox/media_player.py @@ -665,7 +665,8 @@ class SqueezeBoxMediaPlayerEntity(SqueezeboxEntity, MediaPlayerEntity): _valid_type_list = [ key for key in self._browse_data.content_type_media_class - if key not in ["apps", "app", "radios", "radio", "artist tracks"] + if key + not in ["apps", "app", "radios", "radio", "artist tracks", "genre tracks"] ] _media_content_type_list = ( @@ -687,9 +688,13 @@ class SqueezeBoxMediaPlayerEntity(SqueezeboxEntity, MediaPlayerEntity): }, ) - if query.media_content_id and MediaType.ARTIST in _media_content_type_list: - # LMS matches the albums of an artist by album title only - _media_content_type_list.append("artist tracks") + if query.media_content_id: + # Without full text search, LMS matches only album titles inside an + # artist and only artist names inside a genre + if MediaType.ARTIST in _media_content_type_list: + _media_content_type_list.append("artist tracks") + if MediaType.GENRE in _media_content_type_list: + _media_content_type_list.append("genre tracks") search_response_list: list[BrowseMedia] = [] diff --git a/tests/components/squeezebox/test_media_browser.py b/tests/components/squeezebox/test_media_browser.py index cdca9c77594c..891206eef7c0 100644 --- a/tests/components/squeezebox/test_media_browser.py +++ b/tests/components/squeezebox/test_media_browser.py @@ -260,12 +260,35 @@ async def test_async_search_media( assert category_level[0]["title"] == "Fake Item 1" -async def test_async_search_media_in_artist( +@pytest.mark.parametrize( + ("media_content_type", "category", "id_key", "first_item"), + [ + pytest.param( + MediaType.ARTIST, + "artist", + "artist_id", + ("Love Album", MediaClass.ALBUM, MediaType.ALBUM, "1", True), + id="artist", + ), + pytest.param( + MediaType.GENRE, + "genre", + "genre_id", + ("Love Band", MediaClass.ARTIST, MediaType.ARTIST, "1", True), + id="genre", + ), + ], +) +async def test_async_search_media_in_container( hass: HomeAssistant, lms: MagicMock, hass_ws_client: WebSocketGenerator, + media_content_type: MediaType, + category: str, + id_key: str, + first_item: tuple[str, MediaClass, MediaType, str, bool], ) -> None: - """Test a search inside an artist returns matching albums and tracks.""" + """Test a search inside an artist or genre also matches track titles.""" async def mock_browse( category: str, @@ -274,10 +297,9 @@ async def test_async_search_media_in_artist( search_query: str | None = None, ) -> dict[str, Any]: items = { - "artist": [{"id": "1", "title": "Love Album"}], "titles": [{"id": "2", "title": "Love Song"}], - } - return {"title": category, "items": items[category]} + }.get(category, [{"id": "1", "title": first_item[0]}]) + return {"title": category, "items": items} player = (await lms.async_get_players())[0] player.async_browse.side_effect = mock_browse @@ -289,7 +311,7 @@ async def test_async_search_media_in_artist( "type": "media_player/search_media", "entity_id": "media_player.test_player", "media_content_id": "42", - "media_content_type": MediaType.ARTIST, + "media_content_type": media_content_type, "search_query": "love", } ) @@ -305,12 +327,12 @@ async def test_async_search_media_in_artist( ) for item in response["result"]["result"] ] == [ - ("Love Album", MediaClass.ALBUM, MediaType.ALBUM, "1", True), + first_item, ("Love Song", MediaClass.TRACK, MediaType.TRACK, "2", False), ] assert player.async_browse.call_args_list == [ - call("artist", limit=ANY, browse_id=("artist_id", "42"), search_query="love"), - call("titles", limit=ANY, browse_id=("artist_id", "42"), search_query="love"), + call(category, limit=ANY, browse_id=(id_key, "42"), search_query="love"), + call("titles", limit=ANY, browse_id=(id_key, "42"), search_query="love"), ] @@ -345,7 +367,8 @@ async def test_async_search_media_invalid_filter( "media_content_type", [ pytest.param("Fake Type", id="unknown"), - pytest.param("artist tracks", id="internal"), + pytest.param("artist tracks", id="internal_artist"), + pytest.param("genre tracks", id="internal_genre"), ], ) async def test_async_search_media_invalid_type( @@ -375,6 +398,7 @@ async def test_async_search_media_invalid_type( err_message = "If specified, Media content type must be one of" assert err_message in response["error"]["message"] assert "artist tracks" not in response["error"]["message"] + assert "genre tracks" not in response["error"]["message"] async def test_async_search_media_not_found( From 079f457af77a7fc14b67917e20c0c147d917dbc3 Mon Sep 17 00:00:00 2001 From: Philipp Waller <1090452+philippwaller@users.noreply.github.com> Date: Fri, 2 Oct 2026 06:21:42 +0200 Subject: [PATCH 012/356] Add KNX panel translation keys for future frontend adoption (#183479) --- homeassistant/components/knx/strings.json | 222 +++++++++++++++++++++- 1 file changed, 218 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/knx/strings.json b/homeassistant/components/knx/strings.json index 16d6025915c3..3f6bb5919edb 100644 --- a/homeassistant/components/knx/strings.json +++ b/homeassistant/components/knx/strings.json @@ -152,10 +152,49 @@ }, "config_panel": { "common": { + "attention": "Attention", + "create_binary_sensor": "Create binary sensor", + "create_sensor": "Create sensor", + "description": "Description", + "dpt": "DPT", "exposes_count": "Exposes: {count}", + "filter": { + "dpt": { + "sort": { + "options": { + "number": "Number" + } + }, + "title": "[%key:component::knx::config_panel::common::dpt%]" + }, + "no_results": "No results found", + "pin_selected": "Pin selected items", + "remove_tooltip": "Remove filter for {value}", + "scroll_to_selection": "Scroll to selection", + "set_tooltip": "Filter by {value}", + "title": "Filter" + }, "group_address": "Group address", "group_addresses": "Group addresses", - "monitor_x_group_addresses": "Monitor {count} group addresses" + "monitor_x_group_addresses": "Monitor {count} group addresses", + "sort": { + "ascending": "Ascending", + "ascending_tooltip": "Sorted ascending", + "descending": "Descending", + "descending_tooltip": "Sorted descending", + "options": { + "badge": "Badge", + "count": "Count", + "description": "[%key:component::knx::config_panel::common::description%]", + "filtered_count": "Filtered count", + "total_count": "Total count", + "value": "[%key:component::knx::config_panel::common::value%]" + }, + "sort_by": "Sort by:", + "title": "Sort" + }, + "title": "KNX", + "value": "Value" }, "dashboard": { "connection_flow": { @@ -186,6 +225,20 @@ }, "dialogs": { "project_upload": { + "current_project": { + "ets_version": { + "label": "ETS version" + }, + "imported_with": { + "label": "Imported with" + }, + "last_modified": { + "label": "[%key:component::knx::config_panel::info::project_data::last_modified::label%]" + }, + "modified": "Modified {relative_time}", + "short_ets_version": "ETS {version}", + "title": "Currently loaded" + }, "description": "Details such as group address names, datapoint types, devices and group objects are extracted from your project file. The ETS project file itself and its optional password are not stored.\n\n`.knxproj` files exported by ETS 4, 5 or 6 are supported.", "file_upload_label": "ETS project file", "title": "Import ETS project" @@ -204,6 +257,14 @@ "title": "Send KNX telegram", "write_button": "Write" }, + "telegram_info": { + "destination": "[%key:component::knx::config_panel::group_monitor::columns::destination%]", + "payload": "[%key:component::knx::config_panel::group_monitor::columns::payload%]", + "source": "[%key:component::knx::config_panel::group_monitor::columns::source%]", + "title": "KNX telegram", + "type": "[%key:component::knx::config_panel::group_monitor::columns::type%]", + "value": "[%key:component::knx::config_panel::common::value%]" + }, "time_server": { "date": { "label": "Date" @@ -458,6 +519,8 @@ }, "dpt_reference": { "description": "Browse supported KNX datapoint types", + "search_label": "Search {count} items", + "search_label_singular": "Search {count} item", "title": "DPT reference" }, "entities": { @@ -1169,6 +1232,9 @@ } }, "description": "Add and manage KNX entities", + "edit": { + "title": "Edit entity" + }, "title": "Entities" }, "expose": { @@ -1193,6 +1259,8 @@ "ga": { "label": "[%key:component::knx::config_panel::common::group_address%]" }, + "load_error": "Error loading expose configuration.", + "loading": "Loading expose configuration.", "notes": { "label": "Notes", "placeholder": "Add your notes here..." @@ -1214,6 +1282,7 @@ }, "show_raw_values": "Show raw values", "title": "Add exposure", + "validation_error": "Validation error", "value_template": { "description": "Optionally transform the entity state or attribute value before sending it to KNX using a template. The template receives the entity state or attribute value as `value` variable.", "label": "Value template" @@ -1227,11 +1296,141 @@ "title": "Expose" }, "group_monitor": { + "clear_cache": "Clear cache", + "columns": { + "destination": "Destination", + "destination_name": "Destination name", + "direction": "Direction", + "payload": "Payload", + "source": "Source", + "source_name": "Source name", + "time": "Time", + "time_delta": "Time Δ", + "type": "Type", + "value": "[%key:component::knx::config_panel::common::value%]" + }, + "connection_error": { + "retry": "Retry", + "title": "Connection error" + }, "description": "Monitor KNX group communication", - "title": "Group monitor" + "direction": { + "options": { + "incoming": "Incoming", + "outgoing": "Outgoing" + } + }, + "filters": { + "destination": { + "sort": { + "options": { + "address": "Destination address", + "name": "[%key:component::knx::config_panel::group_monitor::columns::destination_name%]" + } + } + }, + "source": { + "sort": { + "options": { + "address": "Source address", + "name": "[%key:component::knx::config_panel::group_monitor::columns::source_name%]" + } + } + } + }, + "pause": "Pause", + "paused": { + "description": "New telegrams will not be displayed until you resume monitoring.", + "title": "Monitoring paused" + }, + "project_not_loaded": { + "description": "Device names and telegram values can only be displayed after an ETS project has been loaded.", + "title": "ETS project not loaded" + }, + "reload": "Sync", + "resume": "Resume", + "search_label": "Search {count} telegrams", + "search_label_singular": "Search {count} telegram", + "time_delta": { + "after": { + "label": "+ After (ms)" + }, + "before": { + "label": "- Before (ms)" + }, + "description": "Also shows all telegrams within the defined time span before/after a filtered telegram – regardless of the applied filters. (0 = off)", + "disabled": "Set a filter to use the context time span.", + "summary": "Within -{before} ms / +{after} ms", + "title": "Context time span" + }, + "time_range": { + "description": "Selecting a range may load additional data from the recorder.", + "now": "now", + "options": { + "5_minutes": "Last 5 minutes", + "6_hours": "Last 6 hours", + "30_minutes": "Last 30 minutes" + }, + "partial": "The range is large; only part of it could be loaded.", + "retention_clamped": "Adjusted to the oldest available data.", + "select": "Select a time range", + "title": "Time range" + }, + "title": "Group monitor", + "waiting_message": "Waiting for telegrams" }, "info": { + "connected_to_bus": { + "label": "Connected to bus" + }, "description": "Version information, manage KNX project file", + "individual_address": { + "label": "Individual address" + }, + "issue_tracker": { + "description": "If you'd like to report a bug or suggest a new feature, create an issue in our GitHub repository" + }, + "my_knx": { + "description": "If you'd like to learn more about the KNX system or ETS, visit" + }, + "project_data": { + "delete": "Delete project data", + "last_modified": { + "label": "Last modified" + }, + "name": { + "label": "Project name" + }, + "title": "ETS project data", + "tool_version": { + "label": "Tool version" + }, + "xknxproject_version": { + "label": "XKNXProject version" + } + }, + "project_file": { + "description": "We extract details such as names, group addresses, devices, group objects, topology, and building structure from your project file. Home Assistant does not store the ETS project file itself nor its optional password for security reasons.", + "title": "[%key:component::knx::config_panel::dialogs::project_upload::file_upload_label%]" + }, + "telegram_storage": { + "backend": { + "options": { + "memory": "Memory", + "postgres": "PostgreSQL", + "sqlite": "SQLite" + } + }, + "label": "Telegram storage", + "limit": { + "label": "Limit" + }, + "retention": { + "day": "1 day", + "days": "{retention} days", + "label": "Retention" + } + }, "title": "Information" }, "project": { @@ -1245,9 +1444,24 @@ "title": "Devices" }, "group_addresses": { - "title": "[%key:component::knx::config_panel::common::group_addresses%]" + "add_switch": "Add switch", + "columns": { + "address": "Address", + "description": "[%key:component::knx::config_panel::common::description%]", + "dpt": "[%key:component::knx::config_panel::common::dpt%]", + "last_value": "Last value", + "updated": "Updated" + }, + "title": "[%key:component::knx::config_panel::common::group_addresses%]", + "view_telegrams": "View telegrams" }, - "title": "Project" + "title": "Project", + "upload_description": "To use the project viewer, please upload a KNX project first!", + "version": { + "description": "The `XKNXProject` version used for parsing the ETS project was:", + "minimum_required": "minimum version required", + "reimport": "Please resubmit your ETS project file." + } }, "selectors": { "knx-payload-selector": { From f12df14332c172f1dfe62e60ffba543178050207 Mon Sep 17 00:00:00 2001 From: Davide Caputo Date: Fri, 2 Oct 2026 11:00:57 +0100 Subject: [PATCH 013/356] Reload retrying Music Assistant entry when the server is rediscovered (#183579) --- .../components/music_assistant/config_flow.py | 10 +++ .../music_assistant/test_config_flow.py | 85 +++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/homeassistant/components/music_assistant/config_flow.py b/homeassistant/components/music_assistant/config_flow.py index a98b16db7198..d99a3c5882fe 100644 --- a/homeassistant/components/music_assistant/config_flow.py +++ b/homeassistant/components/music_assistant/config_flow.py @@ -178,6 +178,10 @@ class MusicAssistantConfigFlow(ConfigFlow, domain=DOMAIN): ConfigEntryState.SETUP_IN_PROGRESS, ): self.hass.config_entries.async_schedule_reload(entry.entry_id) + elif entry.state is ConfigEntryState.SETUP_RETRY: + # The server answered, so it is back online: retry setup now + # instead of waiting for the next backoff interval + self.hass.config_entries.async_schedule_reload(entry.entry_id) # Abort since entry already exists return self.async_abort(reason="already_configured") @@ -218,6 +222,12 @@ class MusicAssistantConfigFlow(ConfigFlow, domain=DOMAIN): # Ignore servers running as Home Assistant app # (they should be discovered through hassio discovery instead) if server_info.homeassistant_addon: + # The app server announcing itself means it is online, so an + # existing entry waiting to retry setup is reloaded now + await self.async_set_unique_id( + server_info.server_id, raise_on_progress=False + ) + self._abort_if_unique_id_configured() LOGGER.debug("Ignoring HA app server in zeroconf discovery") return self.async_abort(reason="already_discovered_addon") diff --git a/tests/components/music_assistant/test_config_flow.py b/tests/components/music_assistant/test_config_flow.py index f716eabe7b22..6c8926d94cc3 100644 --- a/tests/components/music_assistant/test_config_flow.py +++ b/tests/components/music_assistant/test_config_flow.py @@ -516,6 +516,48 @@ async def test_hassio_flow_updates_failed_entry_and_reloads( mock_schedule_reload.assert_called_once_with(failed_entry.entry_id) +@pytest.mark.parametrize( + ("entry_state", "reload_expected"), + [ + (ConfigEntryState.SETUP_RETRY, True), + (ConfigEntryState.LOADED, False), + (ConfigEntryState.NOT_LOADED, False), + ], +) +async def test_hassio_flow_unchanged_entry_reloads_only_when_retrying( + hass: HomeAssistant, + mock_get_server_info: AsyncMock, + entry_state: ConfigEntryState, + reload_expected: bool, +) -> None: + """Test hassio discovery with unchanged data reloads only a retrying entry.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="Music Assistant", + data={CONF_URL: "http://addon-music-assistant:8094", CONF_TOKEN: "test_token"}, + unique_id="1234", + ) + entry.add_to_hass(hass) + entry.mock_state(hass, entry_state) + + with patch.object( + hass.config_entries, "async_schedule_reload" + ) as mock_schedule_reload: + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_HASSIO}, + data=HASSIO_DATA, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + if reload_expected: + mock_schedule_reload.assert_called_once_with(entry.entry_id) + else: + mock_schedule_reload.assert_not_called() + + @pytest.mark.parametrize( ("exception", "error_reason"), [ @@ -565,6 +607,49 @@ async def test_zeroconf_addon_server_ignored( assert result["reason"] == "already_discovered_addon" +@pytest.mark.parametrize( + ("entry_state", "reload_expected"), + [ + (ConfigEntryState.SETUP_RETRY, True), + (ConfigEntryState.LOADED, False), + ], +) +async def test_zeroconf_addon_server_reloads_retrying_entry( + hass: HomeAssistant, + mock_get_server_info: AsyncMock, + mock_config_entry: MockConfigEntry, + entry_state: ConfigEntryState, + reload_expected: bool, +) -> None: + """Test zeroconf discovery of an add-on server reloads a retrying entry.""" + mock_config_entry.add_to_hass(hass) + mock_config_entry.mock_state(hass, entry_state) + addon_zeroconf_data = deepcopy(ZEROCONF_DATA) + addon_zeroconf_data.properties["homeassistant_addon"] = ( + "True" # Zeroconf properties are strings + ) + + with patch.object( + hass.config_entries, "async_schedule_reload" + ) as mock_schedule_reload: + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=addon_zeroconf_data, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + # The add-on entry keeps its own URL, not the zeroconf base_url + assert mock_config_entry.data == {CONF_URL: "http://localhost:8095"} + mock_get_server_info.assert_not_called() + if reload_expected: + mock_schedule_reload.assert_called_once_with(mock_config_entry.entry_id) + else: + mock_schedule_reload.assert_not_called() + + async def test_zeroconf_old_schema_addon_not_ignored( hass: HomeAssistant, mock_get_server_info: AsyncMock, From 0ab41b97f5f88966dfaf69537bedd9ff436c949b Mon Sep 17 00:00:00 2001 From: Jeffrey Larson Date: Thu, 1 Oct 2026 09:27:45 -0700 Subject: [PATCH 014/356] Fix Supervisor connection leak when leaving an app's log page (#183772) --- homeassistant/components/hassio/http.py | 31 ++++++++++++------------ tests/components/hassio/test_http.py | 32 +++++++++++++++++++++++-- tests/test_util/aiohttp.py | 1 + 3 files changed, 46 insertions(+), 18 deletions(-) diff --git a/homeassistant/components/hassio/http.py b/homeassistant/components/hassio/http.py index f057744128c6..d4ff391267c1 100644 --- a/homeassistant/components/hassio/http.py +++ b/homeassistant/components/hassio/http.py @@ -178,29 +178,28 @@ class HassIOView(HomeAssistantView): headers[RANGE] = request.headers[RANGE] try: - client = await self._websession.request( + async with self._websession.request( method=request.method, url=f"http://{self._host}/{quote(path)}", params=request.query, data=request.content if request.method != "GET" else None, headers=headers, timeout=_get_timeout(path), - ) + ) as client: + # Stream response + response = web.StreamResponse( + status=client.status, headers=_response_header(client) + ) + response.content_type = client.content_type - # Stream response - response = web.StreamResponse( - status=client.status, headers=_response_header(client) - ) - response.content_type = client.content_type - - if should_compress(response.content_type, path): - response.enable_compression() - await response.prepare(request) - # In testing iter_chunked, iter_any, and iter_chunks: - # iter_chunks was the best performing option since - # it does not have to do as much re-assembly - async for data, _ in client.content.iter_chunks(): - await response.write(data) + if should_compress(response.content_type, path): + response.enable_compression() + await response.prepare(request) + # In testing iter_chunked, iter_any, and iter_chunks: + # iter_chunks was the best performing option since + # it does not have to do as much re-assembly + async for data, _ in client.content.iter_chunks(): + await response.write(data) except aiohttp.ClientError as err: _LOGGER.error("Client error on api %s request %s", path, err) diff --git a/tests/components/hassio/test_http.py b/tests/components/hassio/test_http.py index 4126ae326dea..2cb87d7258cd 100644 --- a/tests/components/hassio/test_http.py +++ b/tests/components/hassio/test_http.py @@ -1,13 +1,16 @@ """The tests for the hassio component.""" +import asyncio +from contextlib import suppress from http import HTTPStatus +from unittest.mock import Mock, PropertyMock, patch -from aiohttp import StreamReader +from aiohttp import ClientError, StreamReader from aiohttp.test_utils import TestClient import pytest from tests.common import MockUser -from tests.test_util.aiohttp import AiohttpClientMocker +from tests.test_util.aiohttp import AiohttpClientMocker, AiohttpClientMockResponse @pytest.fixture @@ -478,3 +481,28 @@ async def test_forward_range_header_for_logs( assert aioclient_mock.mock_calls[3][-1].get("Range") == test_range assert aioclient_mock.mock_calls[4][-1].get("Range") == test_range assert aioclient_mock.mock_calls[5][-1].get("Range") is None + + +async def test_supervisor_response_released_when_stream_cancelled( + hassio_client: TestClient, aioclient_mock: AiohttpClientMocker +) -> None: + """Test the response from the Supervisor is released when the stream is cancelled.""" + # A frontend disconnect cancels the handler, simulated here from the stream. + stream = StreamReader(Mock(), limit=2**16) + stream.feed_data(b"line 1\n") + stream.set_exception(asyncio.CancelledError()) + + aioclient_mock.get("http://127.0.0.1/addons/bl_b392/logs/follow") + + with ( + patch.object( + AiohttpClientMockResponse, "content", new_callable=PropertyMock + ) as mock_content, + patch.object(AiohttpClientMockResponse, "release") as mock_release, + ): + mock_content.return_value = stream + resp = await hassio_client.get("/api/hassio/addons/bl_b392/logs/follow") + with suppress(ClientError): + await resp.read() + + mock_release.assert_called_once() diff --git a/tests/test_util/aiohttp.py b/tests/test_util/aiohttp.py index 5a62ae1672e7..b426c905e26e 100644 --- a/tests/test_util/aiohttp.py +++ b/tests/test_util/aiohttp.py @@ -336,6 +336,7 @@ class AiohttpClientMockResponse: exc_tb: TracebackType | None, ) -> None: """Exit the context manager.""" + self.release() @contextmanager From 0bc55bc32a6a32d389045a1b672e131692b8ff44 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Fri, 2 Oct 2026 19:31:27 +1000 Subject: [PATCH 015/356] Do not fail Teslemetry energy coordinators when Home Assistant stops (#183828) --- .../components/teslemetry/__init__.py | 6 ++-- tests/components/teslemetry/test_init.py | 32 +++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/teslemetry/__init__.py b/homeassistant/components/teslemetry/__init__.py index 7657e5a9c28b..9dc0d4d0f9d4 100644 --- a/homeassistant/components/teslemetry/__init__.py +++ b/homeassistant/components/teslemetry/__init__.py @@ -871,7 +871,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: TeslemetryConfigEntry) - if energysites: entry.async_on_unload( stream.async_add_connection_listener( - create_handle_energy_stream_connection(energysites) + create_handle_energy_stream_connection(hass, energysites) ) ) @@ -907,6 +907,7 @@ def _setup_subentry_change_reload( def create_handle_energy_stream_connection( + hass: HomeAssistant, energysites: list[TeslemetryEnergyData], ) -> Callable[[bool], None]: """Create a stream connection listener for the energy coordinators.""" @@ -918,7 +919,8 @@ def create_handle_energy_stream_connection( Each subsequent streamed document restores its coordinator via async_set_updated_data, so no reload is required on reconnect. """ - if connected: + # Stopping cancels the listen task, which reports a disconnect. + if connected or hass.is_stopping: return error = UpdateFailed( translation_domain=DOMAIN, diff --git a/tests/components/teslemetry/test_init.py b/tests/components/teslemetry/test_init.py index 655c75a0e146..417e5c99ad98 100644 --- a/tests/components/teslemetry/test_init.py +++ b/tests/components/teslemetry/test_init.py @@ -2131,6 +2131,38 @@ async def test_energy_stream_unload_unsubscribes_and_closes_stream( mock_close.assert_called_once() +async def test_energy_stream_stop_does_not_fail_coordinators( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_stream_listen: MagicMock, + mock_add_connection_listener: MagicMock, + mock_energy_totals_stream: MagicMock, +) -> None: + """Stopping Home Assistant does not fail the energy coordinators.""" + + async def listen() -> None: + # Like the library, report a disconnect when the listen task ends. + try: + await asyncio.Event().wait() + finally: + mock_add_connection_listener.send(False) + + mock_stream_listen.side_effect = listen + await setup_platform(hass, [Platform.SENSOR, Platform.CALENDAR]) + mock_energy_totals_stream.send() + await hass.async_block_till_done() + assert hass.states.get("sensor.energy_site_solar_power").state == "1.185" + assert hass.states.get("calendar.energy_site_buy_tariff").state != STATE_UNAVAILABLE + assert hass.states.get("sensor.energy_site_battery_discharged").state == "0.036" + + await hass.async_stop() + + assert hass.states.get("sensor.energy_site_solar_power").state == "1.185" + assert hass.states.get("calendar.energy_site_buy_tariff").state != STATE_UNAVAILABLE + assert hass.states.get("sensor.energy_site_battery_discharged").state == "0.036" + assert "Disconnected from the Teslemetry stream" not in caplog.text + + async def test_energy_stream_disconnect_marks_unavailable_and_recovers( hass: HomeAssistant, mock_add_connection_listener: MagicMock, From df32e6bf68984a834bff3b8a9868163968d39f22 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Thu, 1 Oct 2026 09:44:57 +0200 Subject: [PATCH 016/356] Match SMA DHCP MAC updates on serial (#183845) --- homeassistant/components/sma/config_flow.py | 19 +++---------- tests/components/sma/test_config_flow.py | 30 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/sma/config_flow.py b/homeassistant/components/sma/config_flow.py index 8ed6e6938c54..7d610768bf47 100644 --- a/homeassistant/components/sma/config_flow.py +++ b/homeassistant/components/sma/config_flow.py @@ -280,25 +280,12 @@ class SmaConfigFlow(ConfigFlow, domain=DOMAIN): self._discovery_data[CONF_MAC], ) - existing_entries_with_host = [ - entry - for entry in self._async_current_entries(include_ignore=False) - if entry.data.get(CONF_HOST) == self._data[CONF_HOST] - and not entry.data.get(CONF_MAC) - ] - - # If we have an existing entry with the same host but no MAC address, - # we update the entry with the MAC address and reload it. - if existing_entries_with_host: - entry = existing_entries_with_host[0] - self.async_update_reload_and_abort( - entry, data_updates={CONF_MAC: self._data[CONF_MAC]} - ) - if not (match := HOSTNAME_SERIAL.match(discovery_info.hostname)): return self.async_abort(reason="not_supported") await self.async_set_unique_id(match.group(1)) - self._abort_if_unique_id_configured(updates={CONF_HOST: self._data[CONF_HOST]}) + self._abort_if_unique_id_configured( + updates={CONF_HOST: self._data[CONF_HOST], CONF_MAC: self._data[CONF_MAC]} + ) return await self.async_step_discovery_confirm() diff --git a/tests/components/sma/test_config_flow.py b/tests/components/sma/test_config_flow.py index 725e53705c9e..32e2a9a97ed8 100644 --- a/tests/components/sma/test_config_flow.py +++ b/tests/components/sma/test_config_flow.py @@ -242,6 +242,36 @@ async def test_dhcp_already_configured_duplicate( ) +@pytest.mark.parametrize( + ("hostname", "result_type"), + [ + pytest.param("SMA987654321", FlowResultType.FORM, id="other_serial"), + pytest.param("evcharger", FlowResultType.ABORT, id="not_sma"), + ], +) +async def test_dhcp_other_device_on_same_host( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + hostname: str, + result_type: FlowResultType, +) -> None: + """Test another device on the host of an entry doesn't change that entry.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_DHCP}, + data=DhcpServiceInfo( + ip=mock_config_entry.data[CONF_HOST], + hostname=hostname, + macaddress="0015bb00ffff", + ), + ) + + assert result["type"] is result_type + assert CONF_MAC not in mock_config_entry.data + + @pytest.mark.parametrize( ("hostname", "unique_id"), [ From 5764ec0fa882a64fb15b5d41cde1bfebf4a4e33a Mon Sep 17 00:00:00 2001 From: Maciej Bieniek Date: Thu, 1 Oct 2026 09:50:05 +0200 Subject: [PATCH 017/356] Bump imgw-pib to 2.5.3 (#183847) --- homeassistant/components/imgw_pib/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/imgw_pib/manifest.json b/homeassistant/components/imgw_pib/manifest.json index b6cb5e6fc945..5a990302a4dd 100644 --- a/homeassistant/components/imgw_pib/manifest.json +++ b/homeassistant/components/imgw_pib/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "quality_scale": "platinum", - "requirements": ["imgw_pib==2.5.2"] + "requirements": ["imgw_pib==2.5.3"] } diff --git a/requirements_all.txt b/requirements_all.txt index 79d10b86c726..4cd3d901aa79 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1387,7 +1387,7 @@ ihcsdk==2.8.12 imeon_inverter_api==0.4.0 # homeassistant.components.imgw_pib -imgw_pib==2.5.2 +imgw_pib==2.5.3 # homeassistant.components.incomfort incomfort-client==0.7.1 From 67076bf0cea01b88e6d949294091a9716f6dd76a Mon Sep 17 00:00:00 2001 From: Simone Chemelli Date: Thu, 1 Oct 2026 11:25:40 +0200 Subject: [PATCH 018/356] Bump aioshelly to 13.34.1 (#183855) --- homeassistant/components/shelly/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/shelly/manifest.json b/homeassistant/components/shelly/manifest.json index 924a14f34da2..fd877e0a5e30 100644 --- a/homeassistant/components/shelly/manifest.json +++ b/homeassistant/components/shelly/manifest.json @@ -17,7 +17,7 @@ "iot_class": "local_push", "loggers": ["aioshelly"], "quality_scale": "platinum", - "requirements": ["aioshelly==13.34.0"], + "requirements": ["aioshelly==13.34.1"], "zeroconf": [ { "name": "shelly*", diff --git a/requirements_all.txt b/requirements_all.txt index 4cd3d901aa79..9e47da8c08dd 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -426,7 +426,7 @@ aiorussound==5.0.2 aioruuvigateway==0.1.0 # homeassistant.components.shelly -aioshelly==13.34.0 +aioshelly==13.34.1 # homeassistant.components.skybell aioskybell==23.12.0 From e1231aadca0ecdd7a08df44ad9623ac1c0b84ce5 Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Thu, 1 Oct 2026 11:25:06 +0200 Subject: [PATCH 019/356] Bump aioacaia to 0.2.2 (#183858) --- homeassistant/components/acaia/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/acaia/manifest.json b/homeassistant/components/acaia/manifest.json index 4189e093b13a..d1d2360d2116 100644 --- a/homeassistant/components/acaia/manifest.json +++ b/homeassistant/components/acaia/manifest.json @@ -26,5 +26,5 @@ "iot_class": "local_push", "loggers": ["aioacaia"], "quality_scale": "platinum", - "requirements": ["aioacaia==0.2.1"] + "requirements": ["aioacaia==0.2.2"] } diff --git a/requirements_all.txt b/requirements_all.txt index 9e47da8c08dd..6ecedcdf221b 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -178,7 +178,7 @@ aio-ownet==0.0.5 aio-wattwaechter==1.0.0 # homeassistant.components.acaia -aioacaia==0.2.1 +aioacaia==0.2.2 # homeassistant.components.airq aioairq==0.4.8 From ea72f864c0e237a0c8c6ac375186712c0c0914a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=85ke=20Strandberg?= Date: Thu, 1 Oct 2026 21:34:54 +0200 Subject: [PATCH 020/356] Dont expose irrelevant myuplink entities (#183869) --- homeassistant/components/myuplink/helpers.py | 6 ++ .../fixtures/device_points_nibe_f730.json | 34 ++++++++++ .../myuplink/snapshots/test_diagnostics.ambr | 68 +++++++++++++++++++ 3 files changed, 108 insertions(+) diff --git a/homeassistant/components/myuplink/helpers.py b/homeassistant/components/myuplink/helpers.py index 0c29c32ecb9c..64687382fe5f 100644 --- a/homeassistant/components/myuplink/helpers.py +++ b/homeassistant/components/myuplink/helpers.py @@ -68,6 +68,7 @@ PARAMETER_ID_TO_EXCLUDE_F730 = ( "47272", "47273", "47274", + "47374", "47375", "47376", "47538", @@ -87,7 +88,12 @@ PARAMETER_ID_TO_EXCLUDE_F730 = ( "47975", "48009", "48072", + "48181", + "48185", "48442", + "48740", + "48741", + "48742", "49909", "50113", ) diff --git a/tests/components/myuplink/fixtures/device_points_nibe_f730.json b/tests/components/myuplink/fixtures/device_points_nibe_f730.json index ffc79d45b392..19c1115cbbf6 100644 --- a/tests/components/myuplink/fixtures/device_points_nibe_f730.json +++ b/tests/components/myuplink/fixtures/device_points_nibe_f730.json @@ -1125,5 +1125,39 @@ "enumValues": [], "scaleValue": "1", "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48740", + "parameterName": "flow line temp. at 30 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48741", + "parameterName": "flow line temp. at 10 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null } ] diff --git a/tests/components/myuplink/snapshots/test_diagnostics.ambr b/tests/components/myuplink/snapshots/test_diagnostics.ambr index bb499f14daf2..172516d95e8f 100644 --- a/tests/components/myuplink/snapshots/test_diagnostics.ambr +++ b/tests/components/myuplink/snapshots/test_diagnostics.ambr @@ -1186,6 +1186,40 @@ "enumValues": [], "scaleValue": "1", "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48740", + "parameterName": "flow line temp. at 30 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48741", + "parameterName": "flow line temp. at 10 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null } ] @@ -2365,6 +2399,40 @@ "enumValues": [], "scaleValue": "1", "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48740", + "parameterName": "flow line temp. at 30 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null + }, + { + "category": "F1253-4 R PC EM", + "parameterId": "48741", + "parameterName": "flow line temp. at 10 \u00b0C", + "parameterUnit": "\u00b0C", + "writable": true, + "timestamp": "2026-09-22T09:58:47+00:00", + "value": 19.0, + "strVal": "19\u00b0C", + "smartHomeCategories": [], + "minValue": -5.0, + "maxValue": 40.0, + "stepValue": 1.0, + "enumValues": [], + "scaleValue": "1", + "zoneId": null } ] From 34dd7ba9d2f255930b89f1c93f096e5867493dca Mon Sep 17 00:00:00 2001 From: Wendelin <12148533+wendevlin@users.noreply.github.com> Date: Fri, 2 Oct 2026 09:51:54 +0200 Subject: [PATCH 021/356] issue_schema: Add optional short_title translations (#183883) --- homeassistant/components/automation/strings.json | 6 ++++++ script/hassfest/translations.py | 1 + tests/hassfest/test_translations.py | 1 + 3 files changed, 8 insertions(+) diff --git a/homeassistant/components/automation/strings.json b/homeassistant/components/automation/strings.json index b841d44e00ab..ea18ca3c105a 100644 --- a/homeassistant/components/automation/strings.json +++ b/homeassistant/components/automation/strings.json @@ -1,5 +1,6 @@ { "common": { + "validation_failed_short_title": "Automation failed to set up", "validation_failed_title": "Automation {name} failed to set up" }, "entity_component": { @@ -48,22 +49,27 @@ }, "validation_failed_actions": { "description": "The automation \"{name}\" (`{entity_id}`) is not active because its actions could not be set up.\n\nError:`{error}`.\n\nTo fix this error, [edit the automation]({edit}) to correct it, then save and reload the automation configuration.", + "short_title": "[%key:component::automation::common::validation_failed_short_title%]", "title": "[%key:component::automation::common::validation_failed_title%]" }, "validation_failed_blueprint": { "description": "The blueprinted automation \"{name}\" (`{entity_id}`) failed to set up.\n\nError:`{error}`.\n\nTo fix this error, [edit the automation]({edit}) to correct it, then save and reload the automation configuration.", + "short_title": "[%key:component::automation::common::validation_failed_short_title%]", "title": "[%key:component::automation::common::validation_failed_title%]" }, "validation_failed_conditions": { "description": "The automation \"{name}\" (`{entity_id}`) is not active because its conditions could not be set up.\n\nError:`{error}`.\n\nTo fix this error, [edit the automation]({edit}) to correct it, then save and reload the automation configuration.", + "short_title": "[%key:component::automation::common::validation_failed_short_title%]", "title": "[%key:component::automation::common::validation_failed_title%]" }, "validation_failed_schema": { "description": "The automation \"{name}\" (`{entity_id}`) is not active because the configuration has errors.\n\nError:`{error}`.\n\nTo fix this error, [edit the automation]({edit}) to correct it, then save and reload the automation configuration.", + "short_title": "[%key:component::automation::common::validation_failed_short_title%]", "title": "[%key:component::automation::common::validation_failed_title%]" }, "validation_failed_triggers": { "description": "The automation \"{name}\" (`{entity_id}`) is not active because its triggers could not be set up.\n\nError:`{error}`.\n\nTo fix this error, [edit the automation]({edit}) to correct it, then save and reload the automation configuration.", + "short_title": "[%key:component::automation::common::validation_failed_short_title%]", "title": "[%key:component::automation::common::validation_failed_title%]" } }, diff --git a/script/hassfest/translations.py b/script/hassfest/translations.py index 19ae1cec5db1..c1a62460114f 100644 --- a/script/hassfest/translations.py +++ b/script/hassfest/translations.py @@ -325,6 +325,7 @@ def gen_issues_schema(frontend_issues: frozenset[str]) -> dict[str, Any]: probatio.Schema( { probatio.Required("title"): translation_value_validator, + probatio.Optional("short_title"): translation_value_validator, probatio.Exclusive( "description", "fixable" ): translation_value_validator, diff --git a/tests/hassfest/test_translations.py b/tests/hassfest/test_translations.py index 83b1d4fad065..846560d696dd 100644 --- a/tests/hassfest/test_translations.py +++ b/tests/hassfest/test_translations.py @@ -251,6 +251,7 @@ SAMPLE_STRINGS = { }, "deprecated_yaml": { "title": "Deprecated YAML configuration", + "short_title": "Deprecated YAML", "description": "YAML configuration is deprecated, please use the UI", }, }, From 14d5dcb7f241e758ac9d6ac23d27a83a76712306 Mon Sep 17 00:00:00 2001 From: Petar Petrov Date: Thu, 1 Oct 2026 17:40:17 +0300 Subject: [PATCH 022/356] Keep the ESPHome Z-Wave home ID current after a home ID change (#183886) --- .../components/esphome/entry_data.py | 3 +- homeassistant/components/esphome/manager.py | 12 +++-- tests/components/esphome/test_manager.py | 49 +++++++++++++++++++ 3 files changed, 60 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/esphome/entry_data.py b/homeassistant/components/esphome/entry_data.py index 2bd034318059..8be654a651ef 100644 --- a/homeassistant/components/esphome/entry_data.py +++ b/homeassistant/components/esphome/entry_data.py @@ -572,7 +572,8 @@ class RuntimeEntryData: for state_type, states in self.state.items() if states and state_type in STATE_TYPE_TO_COMPONENT_TYPE } - if store_data == self._storage_contents: + # A pending save may still overwrite the store with stale data. + if self._pending_storage is None and store_data == self._storage_contents: return def _memorized_storage() -> StoreData: diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 8926d35b7016..a0a8fdea1ac1 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -802,9 +802,15 @@ class ESPHomeManager: # if it's a broken connection or Z-Wave controller or a not # yet provisioned controller. zwave_home_id: int = UNPACK_UINT32_BE(request.data[0:4])[0] - assert self.entry_data.device_info is not None - self.entry_data.async_create_zwave_js_flow( - self.hass, self.entry_data.device_info, zwave_home_id + entry_data = self.entry_data + assert entry_data.device_info is not None + # DeviceInfo is a snapshot from connect time; keep its home ID current. + entry_data.device_info = EsphomeDeviceInfo.from_dict( + {**entry_data.device_info.to_dict(), "zwave_home_id": zwave_home_id} + ) + entry_data.async_save_to_store() + entry_data.async_create_zwave_js_flow( + self.hass, entry_data.device_info, zwave_home_id ) async def on_disconnect(self, expected_disconnect: bool) -> None: diff --git a/tests/components/esphome/test_manager.py b/tests/components/esphome/test_manager.py index 00ec37186c78..5ec39aa80fb4 100644 --- a/tests/components/esphome/test_manager.py +++ b/tests/components/esphome/test_manager.py @@ -3991,6 +3991,7 @@ def test_zero_noise_psk_is_not_the_probe_key() -> None: async def test_zwave_proxy_request_home_id_change( hass: HomeAssistant, mock_client: APIClient, + hass_storage: dict[str, Any], mock_esphome_device: MockESPHomeDeviceType, ) -> None: """Test Z-Wave proxy request handler with HOME_ID_CHANGE request.""" @@ -4077,6 +4078,54 @@ async def test_zwave_proxy_request_home_id_change( # The noise PSK is taken from the config entry, not the live client assert call_args[0][3].noise_psk == noise_psk + assert entry.runtime_data.device_info.zwave_home_id == zwave_home_id + + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + data = hass_storage[f"{DOMAIN}.{entry.entry_id}"]["data"] + assert data["device_info"]["zwave_home_id"] == zwave_home_id + + +async def test_zwave_home_id_change_saved_after_reconnect( + hass: HomeAssistant, + mock_client: APIClient, + hass_storage: dict[str, Any], + mock_esphome_device: MockESPHomeDeviceType, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a home ID change replaces the pending connect-time save.""" + device = await mock_esphome_device( + mock_client=mock_client, + device_info={"zwave_proxy_feature_flags": 1}, + ) + storage_key = f"{DOMAIN}.{device.entry.entry_id}" + zwave_home_id = 3551671779 + + async def report_home_id() -> None: + callback = mock_client.subscribe_zwave_proxy_request.call_args[0][0] + callback( + ZWaveProxyRequest( + type=ZWaveProxyRequestType.HOME_ID_CHANGE, + data=zwave_home_id.to_bytes(4, byteorder="big"), + ) + ) + freezer.tick(SAVE_DELAY + 1) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + with patch("homeassistant.helpers.discovery_flow.async_create_flow"): + await report_home_id() + stored = hass_storage[storage_key]["data"] + assert stored["device_info"]["zwave_home_id"] == zwave_home_id + + # The device reconnects with home ID 0, so the connect-time save holds 0 + await device.mock_disconnect(expected_disconnect=False) + await device.mock_connect() + await report_home_id() + + # Equal to the store, so only replacing the pending save can write it + assert hass_storage[storage_key]["data"] == stored + async def test_no_zwave_proxy_subscribe_without_feature_flags( hass: HomeAssistant, From 0f8e4d87515a16d4b5728169a3910884fac54a98 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 1 Oct 2026 19:14:51 +0200 Subject: [PATCH 023/356] Update probatio to 0.12.5 (#183887) --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index c2b0b7f27f49..22c3d7a57154 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -52,7 +52,7 @@ orjson==3.11.9 packaging>=23.1 paho-mqtt==2.1.0 Pillow==12.3.0 -probatio==0.12.4 +probatio==0.12.5 propcache==0.5.4 psutil-home-assistant==0.0.1 PyJWT==2.15.1 diff --git a/pyproject.toml b/pyproject.toml index a7080a5e52c2..b093ab3f21f4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -78,7 +78,7 @@ dependencies = [ "ulid-transform==2.2.9", "urllib3>=2.0", "uv==0.12.20", - "probatio==0.12.4", + "probatio==0.12.5", "yarl==1.25.1", "webrtc-models==0.3.0", "zeroconf==0.151.5", diff --git a/requirements.txt b/requirements.txt index a2112534e6b6..9f8a0e941ed6 100644 --- a/requirements.txt +++ b/requirements.txt @@ -38,7 +38,7 @@ mutagen==1.48.1 orjson==3.11.9 packaging>=23.1 Pillow==12.3.0 -probatio==0.12.4 +probatio==0.12.5 propcache==0.5.4 psutil-home-assistant==0.0.1 PyJWT==2.15.1 From 0c659d790da6368e6d728a8467b95b0595a41ef1 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Thu, 1 Oct 2026 21:17:41 +0200 Subject: [PATCH 024/356] Sentence-cased strings for my-PV integration (#183894) --- homeassistant/components/my_pv/strings.json | 8 +++---- .../my_pv/snapshots/test_number.ambr | 24 +++++++++---------- .../my_pv/snapshots/test_switch.ambr | 6 ++--- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/homeassistant/components/my_pv/strings.json b/homeassistant/components/my_pv/strings.json index 34ad525949bc..9e9ba5c1549b 100644 --- a/homeassistant/components/my_pv/strings.json +++ b/homeassistant/components/my_pv/strings.json @@ -60,13 +60,13 @@ "entity": { "number": { "ww1boost": { - "name": "Boost Target Temperature" + "name": "Boost target temperature" }, "ww_boost_h": { - "name": "Minimum Hysteresis" + "name": "Minimum hysteresis" }, "ww_targ_h": { - "name": "Maximum Hysteresis" + "name": "Maximum hysteresis" } }, "select": { @@ -163,7 +163,7 @@ }, "switch": { "bstmode": { - "name": "Boost Mode" + "name": "Boost mode" } } }, diff --git a/tests/components/my_pv/snapshots/test_number.ambr b/tests/components/my_pv/snapshots/test_number.ambr index 6a2fbaa184eb..03e198d80e3c 100644 --- a/tests/components/my_pv/snapshots/test_number.ambr +++ b/tests/components/my_pv/snapshots/test_number.ambr @@ -26,12 +26,12 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Boost Target Temperature', + 'object_id_base': 'Boost target temperature', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Boost Target Temperature', + 'original_name': 'Boost target temperature', 'platform': 'my_pv', 'previous_unique_id': None, 'suggested_object_id': None, @@ -45,7 +45,7 @@ StateSnapshot({ 'attributes': ReadOnlyDict({ : 'temperature', - : 'my-PV AC ELWA 2 Boost Target Temperature', + : 'my-PV AC ELWA 2 Boost target temperature', : 95.0, : 5.0, : , @@ -87,12 +87,12 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Boost Target Temperature', + 'object_id_base': 'Boost target temperature', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Boost Target Temperature', + 'original_name': 'Boost target temperature', 'platform': 'my_pv', 'previous_unique_id': None, 'suggested_object_id': None, @@ -106,7 +106,7 @@ StateSnapshot({ 'attributes': ReadOnlyDict({ : 'temperature', - : 'my-PV AC ELWA 2 Boost Target Temperature', + : 'my-PV AC ELWA 2 Boost target temperature', : 95.0, : 5.0, : , @@ -148,12 +148,12 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Maximum Hysteresis', + 'object_id_base': 'Maximum hysteresis', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Maximum Hysteresis', + 'original_name': 'Maximum hysteresis', 'platform': 'my_pv', 'previous_unique_id': None, 'suggested_object_id': None, @@ -167,7 +167,7 @@ StateSnapshot({ 'attributes': ReadOnlyDict({ : 'temperature_delta', - : 'my-PV AC ELWA 2 Maximum Hysteresis', + : 'my-PV AC ELWA 2 Maximum hysteresis', : 9.9, : 0.1, : , @@ -209,12 +209,12 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Minimum Hysteresis', + 'object_id_base': 'Minimum hysteresis', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Minimum Hysteresis', + 'original_name': 'Minimum hysteresis', 'platform': 'my_pv', 'previous_unique_id': None, 'suggested_object_id': None, @@ -228,7 +228,7 @@ StateSnapshot({ 'attributes': ReadOnlyDict({ : 'temperature_delta', - : 'my-PV AC ELWA 2 Minimum Hysteresis', + : 'my-PV AC ELWA 2 Minimum hysteresis', : 9.9, : 0.1, : , diff --git a/tests/components/my_pv/snapshots/test_switch.ambr b/tests/components/my_pv/snapshots/test_switch.ambr index 21c336fe3c33..53bdd89ca241 100644 --- a/tests/components/my_pv/snapshots/test_switch.ambr +++ b/tests/components/my_pv/snapshots/test_switch.ambr @@ -21,12 +21,12 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Boost Mode', + 'object_id_base': 'Boost mode', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Boost Mode', + 'original_name': 'Boost mode', 'platform': 'my_pv', 'previous_unique_id': None, 'suggested_object_id': None, @@ -40,7 +40,7 @@ StateSnapshot({ 'attributes': ReadOnlyDict({ : 'switch', - : 'my-PV AC ELWA 2 Boost Mode', + : 'my-PV AC ELWA 2 Boost mode', }), 'context': , 'entity_id': 'switch.my_pv_ac_elwa_2_boost_mode', From 21bc1cf111a9eaf9c2b506436260646978058988 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 1 Oct 2026 17:07:25 +0200 Subject: [PATCH 025/356] Bump renault-api to 0.5.14 (#183902) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/renault/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/renault/manifest.json b/homeassistant/components/renault/manifest.json index 45c8cd7c706c..cb4c3420de54 100644 --- a/homeassistant/components/renault/manifest.json +++ b/homeassistant/components/renault/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["renault_api"], "quality_scale": "silver", - "requirements": ["renault-api==0.5.13"] + "requirements": ["renault-api==0.5.14"] } diff --git a/requirements_all.txt b/requirements_all.txt index 6ecedcdf221b..673c34b575a1 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2965,7 +2965,7 @@ refoss-ha==1.2.5 regenmaschine==2024.03.0 # homeassistant.components.renault -renault-api==0.5.13 +renault-api==0.5.14 # homeassistant.components.renson renson-endura-delta==1.7.2 From 38ec2c4dae62ec7ae0e91843bf5cebe37c9b8064 Mon Sep 17 00:00:00 2001 From: Filippo Scatigna Date: Mon, 5 Oct 2026 13:51:36 +0200 Subject: [PATCH 026/356] Fix proxy camera crop breaking after a small frame (#183798) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/proxy/camera.py | 33 ++++++---- tests/components/proxy/__init__.py | 1 + tests/components/proxy/test_camera.py | 84 ++++++++++++++++++++++++ 3 files changed, 105 insertions(+), 13 deletions(-) create mode 100644 tests/components/proxy/__init__.py create mode 100644 tests/components/proxy/test_camera.py diff --git a/homeassistant/components/proxy/camera.py b/homeassistant/components/proxy/camera.py index 0318506b97d3..0150445958b7 100644 --- a/homeassistant/components/proxy/camera.py +++ b/homeassistant/components/proxy/camera.py @@ -160,18 +160,25 @@ def _crop_image(image, opts): quality = opts.quality or DEFAULT_QUALITY (old_width, old_height) = img.size old_size = len(image) - if opts.top is None: - opts.top = 0 - if opts.left is None: - opts.left = 0 - if opts.max_width is None or opts.max_width > old_width - opts.left: - opts.max_width = old_width - opts.left - if opts.max_height is None or opts.max_height > old_height - opts.top: - opts.max_height = old_height - opts.top + top = opts.top or 0 + left = opts.left or 0 + width = old_width - left + if opts.max_width is not None: + width = min(opts.max_width, width) + height = old_height - top + if opts.max_height is not None: + height = min(opts.max_height, height) + if width <= 0 or height <= 0: + _LOGGER.debug( + "Image (%dx%d) is too small to crop at (%d, %d)", + old_width, + old_height, + left, + top, + ) + return image - img = img.crop( - (opts.left, opts.top, opts.left + opts.max_width, opts.top + opts.max_height) - ) + img = img.crop((left, top, left + width, top + height)) imgbuf = io.BytesIO() img.save(imgbuf, "JPEG", optimize=True, quality=quality) newimage = imgbuf.getvalue() @@ -181,8 +188,8 @@ def _crop_image(image, opts): old_width, old_height, old_size, - opts.max_width, - opts.max_height, + width, + height, len(newimage), ) return newimage diff --git a/tests/components/proxy/__init__.py b/tests/components/proxy/__init__.py new file mode 100644 index 000000000000..274f88f6ea9b --- /dev/null +++ b/tests/components/proxy/__init__.py @@ -0,0 +1 @@ +"""Tests for the Camera Proxy integration.""" diff --git a/tests/components/proxy/test_camera.py b/tests/components/proxy/test_camera.py new file mode 100644 index 000000000000..5fec0cdab8c9 --- /dev/null +++ b/tests/components/proxy/test_camera.py @@ -0,0 +1,84 @@ +"""Tests for the Camera Proxy camera platform.""" + +from collections.abc import AsyncGenerator +import io +from unittest.mock import AsyncMock, patch + +from PIL import Image as PilImage +import pytest + +from homeassistant.components.camera import Image, async_get_image +from homeassistant.components.proxy.camera import ProxyCamera +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + +from tests.typing import ClientSessionGenerator + +CROP_CONFIG = { + "platform": "proxy", + "entity_id": "camera.source", + "name": "Cropped", + "mode": "crop", + "max_image_width": 400, + "max_image_height": 225, + "max_stream_width": 400, + "max_stream_height": 225, + "image_left": 550, + "image_top": 90, +} + + +def _jpeg(width: int, height: int) -> Image: + buffer = io.BytesIO() + PilImage.new("RGB", (width, height)).save(buffer, "JPEG") + return Image("image/jpeg", buffer.getvalue()) + + +def _size(content: bytes) -> tuple[int, int]: + return PilImage.open(io.BytesIO(content)).size + + +@pytest.fixture +async def setup_proxy(hass: HomeAssistant) -> AsyncGenerator[None]: + """Set up a cropping proxy camera with no delay between stream frames.""" + with patch.object(ProxyCamera, "_attr_frame_interval", 0): + assert await async_setup_component(hass, "camera", {"camera": CROP_CONFIG}) + await hass.async_block_till_done() + yield + + +@pytest.mark.usefixtures("setup_proxy") +async def test_crop_image_after_small_frame(hass: HomeAssistant) -> None: + """Test a frame smaller than the crop area does not break later crops.""" + small = _jpeg(320, 180) + with patch( + "homeassistant.components.proxy.camera.async_get_image", + AsyncMock(side_effect=[small, _jpeg(1536, 576)]), + ): + first = await async_get_image(hass, "camera.cropped") + second = await async_get_image(hass, "camera.cropped") + + assert first.content == small.content + assert _size(second.content) == (400, 225) + + +@pytest.mark.usefixtures("setup_proxy") +async def test_crop_stream_after_small_frame( + hass: HomeAssistant, hass_client: ClientSessionGenerator +) -> None: + """Test a small frame does not break the cropped MJPEG stream.""" + client = await hass_client() + with patch( + "homeassistant.components.proxy.camera.async_get_image", + AsyncMock(side_effect=[_jpeg(320, 180), _jpeg(1536, 576), None]), + ): + response = await client.get("/api/camera_proxy_stream/camera.cropped") + body = await response.read() + + assert response.status == 200 + frames = [ + part.split(b"\r\n\r\n", 1)[1].rstrip(b"\r\n") + for part in body.split(b"--frameboundary\r\n") + if b"\r\n\r\n" in part + ] + assert _size(frames[-1]) == (400, 225) From 7635c81fa3ad293607dd725fb7c29d6fee5af01a Mon Sep 17 00:00:00 2001 From: Simone Chemelli Date: Thu, 1 Oct 2026 20:50:49 +0200 Subject: [PATCH 027/356] Don't trigger reauth on connection errors for Mikrotik (#183904) --- .../components/mikrotik/coordinator.py | 10 +++---- tests/components/mikrotik/test_init.py | 29 ++++++++++++++++++- 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/mikrotik/coordinator.py b/homeassistant/components/mikrotik/coordinator.py index 0f7a97cc1633..5bcc36f847b4 100644 --- a/homeassistant/components/mikrotik/coordinator.py +++ b/homeassistant/components/mikrotik/coordinator.py @@ -445,11 +445,11 @@ def get_api(entry: dict[str, Any]) -> librouteros.Api: ) _error = None break - except ( - librouteros.exceptions.LibRouterosError, - OSError, - TimeoutError, - ) as api_error: + except CONNECTION_ERRORS as api_error: + LOGGER.debug("Mikrotik %s error: %s", entry[CONF_HOST], api_error) + # Falling back to token login would mask this with a bogus auth error + raise CannotConnect from api_error + except librouteros.exceptions.LibRouterosError as api_error: _error = api_error if _error is not None: diff --git a/tests/components/mikrotik/test_init.py b/tests/components/mikrotik/test_init.py index 1e833aebc9a4..566acde7d13a 100644 --- a/tests/components/mikrotik/test_init.py +++ b/tests/components/mikrotik/test_init.py @@ -6,7 +6,7 @@ from typing import Any from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory -from librouteros.exceptions import ConnectionClosed, LibRouterosError +from librouteros.exceptions import ConnectionClosed, LibRouterosError, TrapError import pytest from homeassistant.components import mikrotik @@ -156,6 +156,33 @@ async def test_hub_login_error_starts_reauth( assert any(entry.async_get_active_flows(hass, {SOURCE_REAUTH})) +@pytest.mark.parametrize( + "error", + [ConnectionClosed(), OSError(), TimeoutError()], + ids=["connection_closed", "os_error", "timeout_error"], +) +async def test_hub_connect_error_skips_token_login_fallback( + hass: HomeAssistant, + mock_config_entry: MockConfigEntryFactory, + error: Exception, +) -> None: + """Test a connection error on plain login doesn't fall back to token login.""" + entry = mock_config_entry() + entry.add_to_hass(hass) + + # Modern RouterOS rejects the legacy token login as invalid credentials + with patch( + "librouteros.connect", + side_effect=[error, TrapError("invalid user name or password (6)")], + ) as mock_connect: + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert mock_connect.call_count == 1 + assert entry.state is ConfigEntryState.SETUP_RETRY + assert not any(entry.async_get_active_flows(hass, {SOURCE_REAUTH})) + + async def test_optional_command_error_is_suppressed( hass: HomeAssistant, mock_api: MagicMock, mock_config_entry: MockConfigEntryFactory ) -> None: From 3213b6e09ec2bed89fdff322908a54fd2336f20f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 1 Oct 2026 20:57:19 +0200 Subject: [PATCH 028/356] Resolve the probatio codec import before the event loop (#183909) --- homeassistant/__init__.py | 9 +++++++++ tests/test_init.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 tests/test_init.py diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index 1da1060af55e..525aa3f8ef24 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -1,5 +1,6 @@ """Init file for Home Assistant.""" +import probatio from probatio import BuildPolicy, set_build_policy from probatio.compat import install_as_voluptuous @@ -13,3 +14,11 @@ install_as_voluptuous() # a large number of schemas, many of which are never validated in a given run, so # lazy building avoids that upfront cost. Only the application may set this policy. set_build_policy(BuildPolicy.LAZY) + +# Probatio resolves its codec re-exports through a lazy import on first attribute +# access. Both of these are reached from the event loop, where that import is a +# blocking call: to_field_list renders every config flow form, to_openapi builds +# the tool schemas for a conversation turn. Resolve them here instead. It costs +# about 4 ms and pulls in no voluptuous of its own. +_ = probatio.to_field_list +_ = probatio.to_openapi diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 000000000000..a197ec8378dd --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,32 @@ +"""Test the Home Assistant package init.""" + +import subprocess +import sys + +IMPORT_TIMEOUT = 60 + + +def test_probatio_codecs_is_imported_before_the_event_loop() -> None: + """Importing Home Assistant must leave no lazy codec import for the loop. + + Probatio resolves to_field_list and to_openapi through a lazy import of + probatio.codecs on first attribute access, and both are reached from the + event loop: the first renders every config flow form, the second builds the + tool schemas for a conversation turn. + + A clean interpreter is the only way to see this: anything the test suite + imported first would hide it. + """ + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys, homeassistant; print('probatio.codecs' in sys.modules)", + ], + capture_output=True, + check=True, + text=True, + timeout=IMPORT_TIMEOUT, + ) + + assert result.stdout.strip() == "True" From 692bd453cf016b7d6c54a0446daccae3a7e135b0 Mon Sep 17 00:00:00 2001 From: Claire Novotny <1427284+clairernovotny@users.noreply.github.com> Date: Sun, 4 Oct 2026 02:39:24 -0400 Subject: [PATCH 029/356] Bump av to 19.0.0 (#183912) --- homeassistant/components/generic/manifest.json | 2 +- homeassistant/components/stream/manifest.json | 2 +- homeassistant/components/stream/recorder.py | 6 +++--- homeassistant/components/stream/worker.py | 6 +++--- homeassistant/package_constraints.txt | 2 +- requirements_all.txt | 2 +- 6 files changed, 10 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/generic/manifest.json b/homeassistant/components/generic/manifest.json index ec69e74bc215..e59a2e4217cd 100644 --- a/homeassistant/components/generic/manifest.json +++ b/homeassistant/components/generic/manifest.json @@ -7,5 +7,5 @@ "documentation": "https://www.home-assistant.io/integrations/generic", "integration_type": "device", "iot_class": "local_push", - "requirements": ["av==17.0.1", "Pillow==12.3.0"] + "requirements": ["av==19.0.0", "Pillow==12.3.0"] } diff --git a/homeassistant/components/stream/manifest.json b/homeassistant/components/stream/manifest.json index b9cc560699d4..c634850be8c0 100644 --- a/homeassistant/components/stream/manifest.json +++ b/homeassistant/components/stream/manifest.json @@ -7,5 +7,5 @@ "integration_type": "system", "iot_class": "local_push", "quality_scale": "internal", - "requirements": ["PyTurboJPEG==1.8.3", "av==17.0.1", "numpy==2.3.2"] + "requirements": ["PyTurboJPEG==1.8.3", "av==19.0.0", "numpy==2.3.2"] } diff --git a/homeassistant/components/stream/recorder.py b/homeassistant/components/stream/recorder.py index b88f0cab5932..e47c031d9839 100644 --- a/homeassistant/components/stream/recorder.py +++ b/homeassistant/components/stream/recorder.py @@ -110,7 +110,7 @@ class RecorderOutput(StreamOutput): # Create output on first segment if not output: container_options: dict[str, str] = { - "video_track_timescale": str(int(1 / source_v.time_base)), # type: ignore[operator] + "video_track_timescale": str(int(1 / source_v.time_base)), "movflags": "frag_keyframe+empty_moov", "min_frag_duration": str(self.stream_settings.min_segment_duration), } @@ -133,12 +133,12 @@ class RecorderOutput(StreamOutput): last_stream_id = segment.stream_id pts_adjuster["video"] = int( (running_duration - source.start_time) - / (av.time_base * source_v.time_base) # type: ignore[operator] + / (av.time_base * source_v.time_base) ) if source_a: pts_adjuster["audio"] = int( (running_duration - source.start_time) - / (av.time_base * source_a.time_base) # type: ignore[operator] + / (av.time_base * source_a.time_base) ) # Remux video diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index 2236756d6f86..6b555fa2a958 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -197,7 +197,7 @@ class StreamMuxer: # in test_durations "avoid_negative_ts": "make_non_negative", "fragment_index": str(sequence + 1), - "video_track_timescale": str(int(1 / input_vstream.time_base)), # type: ignore[operator] + "video_track_timescale": str(int(1 / input_vstream.time_base)), # Only do extra fragmenting if we are using ll_hls # Let ffmpeg do the work using frag_duration # Fragment durations may exceed the 15% allowed variance but it seems ok @@ -669,8 +669,8 @@ def stream_worker( stream_state.diagnostics.set_value("audio_codec", audio_stream.name) dts_validator = TimestampValidator( - int(1 / video_stream.time_base), # type: ignore[operator] - int(1 / audio_stream.time_base) if audio_stream else 1, # type: ignore[operator] + int(1 / video_stream.time_base), + int(1 / audio_stream.time_base) if audio_stream else 1, ) unvalidated_packets = PeekIterator(container.demux((video_stream, audio_stream))) container_packets = PeekIterator( diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 22c3d7a57154..c00474ccda97 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -17,7 +17,7 @@ async-upnp-client==0.48.2 atomicwrites-homeassistant==1.4.1 attrs==26.1.0 audioop-lts==0.2.2 -av==17.0.1 +av==19.0.0 awesomeversion==25.8.0 bcrypt==5.0.0 bleak-retry-connector==4.7.1 diff --git a/requirements_all.txt b/requirements_all.txt index 673c34b575a1..c5a3de0d6492 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -625,7 +625,7 @@ autoskope_client==1.4.1 # homeassistant.components.generic # homeassistant.components.stream -av==17.0.1 +av==19.0.0 # homeassistant.components.avea avea==1.8.0 From bd77abd265c4abc01565d12b8837b88a0b69dfa9 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Sun, 4 Oct 2026 15:27:57 +0200 Subject: [PATCH 030/356] Handle unsupported devices for the my-PV integration (#183920) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- homeassistant/components/my_pv/__init__.py | 13 +++- homeassistant/components/my_pv/config_flow.py | 6 +- homeassistant/components/my_pv/strings.json | 6 +- tests/components/my_pv/test_config_flow.py | 63 ++++++++++++++++++- tests/components/my_pv/test_init.py | 23 ++++++- 5 files changed, 105 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/my_pv/__init__.py b/homeassistant/components/my_pv/__init__.py index 56826d0310e1..60172aa0581b 100644 --- a/homeassistant/components/my_pv/__init__.py +++ b/homeassistant/components/my_pv/__init__.py @@ -1,11 +1,15 @@ """The my-PV integration for Home Assistant.""" from my_pv import MyPVLocalDevice -from my_pv.exceptions import MyPVAuthenticationError +from my_pv.exceptions import MyPVAuthenticationError, MyPVDeviceNotSupportedError from homeassistant.const import CONF_HOST, CONF_PASSWORD, Platform from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady +from homeassistant.exceptions import ( + ConfigEntryAuthFailed, + ConfigEntryError, + ConfigEntryNotReady, +) from .const import DOMAIN from .coordinator import MyPVConfigEntry, MyPVCoordinator @@ -36,6 +40,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: MyPVConfigEntry) -> bool translation_domain=DOMAIN, translation_key="auth_error", ) from exc + except MyPVDeviceNotSupportedError as exc: + raise ConfigEntryError( + translation_domain=DOMAIN, + translation_key="unsupported_device", + ) from exc coordinator = MyPVCoordinator(hass, entry, device) diff --git a/homeassistant/components/my_pv/config_flow.py b/homeassistant/components/my_pv/config_flow.py index 966bfdff2ff1..d7642dc57f09 100644 --- a/homeassistant/components/my_pv/config_flow.py +++ b/homeassistant/components/my_pv/config_flow.py @@ -5,7 +5,7 @@ import logging from typing import Any, Final, override from my_pv import MyPVLocalDevice -from my_pv.exceptions import MyPVAuthenticationError +from my_pv.exceptions import MyPVAuthenticationError, MyPVDeviceNotSupportedError import probatio from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -93,6 +93,8 @@ class MyPVConfigFlow(ConfigFlow, domain=DOMAIN): return self.async_abort(reason="cannot_connect") except MyPVAuthenticationError: password_needed = True + except MyPVDeviceNotSupportedError: + return self.async_abort(reason="unsupported_device") finally: await device.disconnect() @@ -142,6 +144,8 @@ class MyPVConfigFlow(ConfigFlow, domain=DOMAIN): errors[CONF_BASE] = "cannot_connect" except MyPVAuthenticationError: password_needed = True + except MyPVDeviceNotSupportedError: + return self.async_abort(reason="unsupported_device") finally: await device.disconnect() diff --git a/homeassistant/components/my_pv/strings.json b/homeassistant/components/my_pv/strings.json index 9e9ba5c1549b..5797e1a02bc3 100644 --- a/homeassistant/components/my_pv/strings.json +++ b/homeassistant/components/my_pv/strings.json @@ -7,7 +7,8 @@ "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", - "unique_id_mismatch": "The device serial number does not match the original device." + "unique_id_mismatch": "The device serial number does not match the original device.", + "unsupported_device": "This my-PV device is not supported." }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", @@ -182,6 +183,9 @@ }, "unknown_error": { "message": "The device could not complete the requested action." + }, + "unsupported_device": { + "message": "This my-PV device is not supported." } } } diff --git a/tests/components/my_pv/test_config_flow.py b/tests/components/my_pv/test_config_flow.py index c5531c3474d0..873e43f2a8bb 100644 --- a/tests/components/my_pv/test_config_flow.py +++ b/tests/components/my_pv/test_config_flow.py @@ -3,7 +3,7 @@ from ipaddress import ip_address from unittest.mock import AsyncMock -from my_pv.exceptions import MyPVAuthenticationError +from my_pv.exceptions import MyPVAuthenticationError, MyPVDeviceNotSupportedError import pytest from homeassistant import config_entries @@ -90,6 +90,32 @@ async def test_step_user_already_configured( assert result["reason"] == "already_configured" +async def test_step_user_unsupported_device( + hass: HomeAssistant, + mock_my_pv_client: AsyncMock, +) -> None: + """Test if we get the local setup form with error if the device is not supported.""" + 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" + assert not result["errors"] + + mock_my_pv_client.connect.side_effect = MyPVDeviceNotSupportedError + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + { + CONF_HOST: "127.0.0.1", + }, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + + async def test_step_user_cannot_connect( hass: HomeAssistant, mock_my_pv_client: AsyncMock, @@ -299,6 +325,41 @@ async def test_step_discovery_already_configured( assert result["reason"] == "already_configured" +@pytest.mark.parametrize( + ("source", "data"), + [ + ( + config_entries.SOURCE_DHCP, + DHCP_DISCOVERY, + ), + ( + config_entries.SOURCE_ZEROCONF, + ZEROCONF_DISCOVERY, + ), + ], +) +@pytest.mark.usefixtures("mock_my_pv_client") +async def test_step_discovery_unsupported_device( + hass: HomeAssistant, + mock_my_pv_client: AsyncMock, + source: str, + data: BaseServiceInfo, +) -> None: + """Test discovery of an unsupported device.""" + mock_my_pv_client.connect.side_effect = MyPVDeviceNotSupportedError + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={ + "source": source, + }, + data=data, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + + @pytest.mark.parametrize( ("source", "data"), [ diff --git a/tests/components/my_pv/test_init.py b/tests/components/my_pv/test_init.py index 0ef74efc0411..541abef9181c 100644 --- a/tests/components/my_pv/test_init.py +++ b/tests/components/my_pv/test_init.py @@ -2,7 +2,11 @@ from unittest.mock import AsyncMock -from my_pv.exceptions import MyPVAuthenticationError, MyPVConnectionError +from my_pv.exceptions import ( + MyPVAuthenticationError, + MyPVConnectionError, + MyPVDeviceNotSupportedError, +) import pytest from homeassistant.config_entries import ConfigEntryState @@ -41,6 +45,23 @@ async def test_setup_entry_cannot_connect( assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY +async def test_setup_entry_unsupported_device( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_my_pv_client: AsyncMock, +) -> None: + """Test setup of a config entry when device is not supported.""" + mock_config_entry.add_to_hass(hass) + + mock_my_pv_client.connect.side_effect = MyPVDeviceNotSupportedError() + + assert not await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + assert mock_config_entry.error_reason_translation_key == "unsupported_device" + + async def test_setup_entry_auth_error( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 46866445f3afba2a4e0607a1d53e9b6fd8be6734 Mon Sep 17 00:00:00 2001 From: Matos Date: Thu, 1 Oct 2026 18:40:51 +0000 Subject: [PATCH 031/356] Allow the none reasoning effort for GPT-6 Luna (#183922) --- .../openai_conversation/config_flow.py | 1 + .../snapshots/test_conversation.ambr | 40 +++++++++++++++++++ .../openai_conversation/test_config_flow.py | 37 +++++++++++++++++ .../openai_conversation/test_conversation.py | 7 ++++ 4 files changed, 85 insertions(+) diff --git a/homeassistant/components/openai_conversation/config_flow.py b/homeassistant/components/openai_conversation/config_flow.py index fcef2c2a8f2b..a851c4e2522d 100644 --- a/homeassistant/components/openai_conversation/config_flow.py +++ b/homeassistant/components/openai_conversation/config_flow.py @@ -629,6 +629,7 @@ class OpenAISubentryFlowHandler(ConfigSubentryFlow): return [] models_reasoning_map: dict[str | tuple[str, ...], list[str]] = { + "gpt-6-luna": ["none", "low", "medium", "high", "xhigh", "max"], "gpt-6": ["low", "medium", "high", "xhigh", "max"], "gpt-5.6": ["none", "low", "medium", "high", "xhigh", "max"], ("gpt-5.2-pro", "gpt-5.4-pro", "gpt-5.5-pro"): ["medium", "high", "xhigh"], diff --git a/tests/components/openai_conversation/snapshots/test_conversation.ambr b/tests/components/openai_conversation/snapshots/test_conversation.ambr index b6c08393fa67..c9a9b56a560a 100644 --- a/tests/components/openai_conversation/snapshots/test_conversation.ambr +++ b/tests/components/openai_conversation/snapshots/test_conversation.ambr @@ -529,6 +529,46 @@ }), }) # --- +# name: test_model_args[subentry_options7] + dict({ + 'max_output_tokens': 3000, + 'model': 'gpt-6-luna', + 'prompt_cache_options': dict({ + 'ttl': '30m', + }), + 'reasoning': dict({ + 'effort': 'low', + 'summary': 'auto', + }), + 'service_tier': 'auto', + 'store': False, + 'stream': True, + 'text': dict({ + 'verbosity': 'medium', + }), + }) +# --- +# name: test_model_args[subentry_options8] + dict({ + 'max_output_tokens': 3000, + 'model': 'gpt-6-luna', + 'prompt_cache_options': dict({ + 'ttl': '30m', + }), + 'reasoning': dict({ + 'effort': 'none', + 'summary': 'auto', + }), + 'service_tier': 'auto', + 'store': False, + 'stream': True, + 'temperature': 0.5, + 'text': dict({ + 'verbosity': 'medium', + }), + 'top_p': 0.9, + }) +# --- # name: test_web_search[False] list([ dict({ diff --git a/tests/components/openai_conversation/test_config_flow.py b/tests/components/openai_conversation/test_config_flow.py index e47a93fada71..82d55d32df39 100644 --- a/tests/components/openai_conversation/test_config_flow.py +++ b/tests/components/openai_conversation/test_config_flow.py @@ -275,6 +275,7 @@ async def test_subentry_unsupported_model( ("gpt-5.5", ["none", "low", "medium", "high", "xhigh"]), ("gpt-5.5-pro", ["medium", "high", "xhigh"]), ("gpt-5.6", ["none", "low", "medium", "high", "xhigh", "max"]), + ("gpt-6-luna", ["none", "low", "medium", "high", "xhigh", "max"]), ("gpt-6-astra", ["low", "medium", "high", "xhigh", "max"]), ], ) @@ -320,6 +321,42 @@ async def test_subentry_reasoning_effort_list( ) +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize("subentry_type", ["conversation", "ai_task_data"]) +@pytest.mark.parametrize("reasoning_effort", ["none", "low"]) +async def test_subentry_luna_reasoning_effort( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + subentry_type: str, + reasoning_effort: str, +) -> None: + """Test that Luna reasoning effort can be selected and saved.""" + subentry = next( + entry + for entry in mock_config_entry.subentries.values() + if entry.subentry_type == subentry_type + ) + result = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry.subentry_id + ) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_RECOMMENDED: False} + ) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_CHAT_MODEL: "gpt-6-luna"} + ) + assert result["step_id"] == "model" + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {CONF_REASONING_EFFORT: reasoning_effort} + ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + saved = mock_config_entry.subentries[subentry.subentry_id].data + assert saved[CONF_CHAT_MODEL] == "gpt-6-luna" + assert saved[CONF_REASONING_EFFORT] == reasoning_effort + + @pytest.mark.parametrize( ("model", "has_reasoning_summary"), [ diff --git a/tests/components/openai_conversation/test_conversation.py b/tests/components/openai_conversation/test_conversation.py index 723d3d03e8f1..0fccf58b3853 100644 --- a/tests/components/openai_conversation/test_conversation.py +++ b/tests/components/openai_conversation/test_conversation.py @@ -879,6 +879,13 @@ async def test_flex_tier_retry( CONF_REASONING_SUMMARY: "off", CONF_VERBOSITY: "high", }, + {CONF_CHAT_MODEL: "gpt-6-luna"}, + { + CONF_CHAT_MODEL: "gpt-6-luna", + CONF_REASONING_EFFORT: "none", + CONF_TEMPERATURE: 0.5, + CONF_TOP_P: 0.9, + }, ], ) @pytest.mark.usefixtures("mock_init_component") From 31bf909d36431e605310969990a65f45f334df08 Mon Sep 17 00:00:00 2001 From: Kevin Stillhammer Date: Thu, 1 Oct 2026 19:43:36 +0200 Subject: [PATCH 032/356] Bump pywaze to 1.2.3 and close Waze clients on unload (#183923) --- .../components/waze_travel_time/__init__.py | 1 + .../components/waze_travel_time/helpers.py | 12 +++---- .../components/waze_travel_time/manifest.json | 2 +- .../components/waze_travel_time/services.py | 36 +++++++++---------- requirements_all.txt | 2 +- 5 files changed, 27 insertions(+), 26 deletions(-) diff --git a/homeassistant/components/waze_travel_time/__init__.py b/homeassistant/components/waze_travel_time/__init__.py index 5af3dfface6a..a67c03fc4e76 100644 --- a/homeassistant/components/waze_travel_time/__init__.py +++ b/homeassistant/components/waze_travel_time/__init__.py @@ -49,6 +49,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry) -> b client = WazeRouteCalculator( region=config_entry.data[CONF_REGION].upper(), client=httpx_client ) + config_entry.async_on_unload(client.close) coordinator = WazeTravelTimeCoordinator(hass, config_entry, client) config_entry.runtime_data = coordinator diff --git a/homeassistant/components/waze_travel_time/helpers.py b/homeassistant/components/waze_travel_time/helpers.py index 7bee77e8e4fd..c2d3d5d37122 100644 --- a/homeassistant/components/waze_travel_time/helpers.py +++ b/homeassistant/components/waze_travel_time/helpers.py @@ -38,10 +38,10 @@ async def is_valid_config_entry( resolved_origin = find_coordinates(hass, origin) resolved_destination = find_coordinates(hass, destination) httpx_client = get_async_client(hass) - client = WazeRouteCalculator(region=region, client=httpx_client) - try: - await client.calc_routes(resolved_origin, resolved_destination) - except WRCError as error: - _LOGGER.error("Error trying to validate entry: %s", error) - return False + async with WazeRouteCalculator(region=region, client=httpx_client) as client: + try: + await client.calc_routes(resolved_origin, resolved_destination) + except WRCError as error: + _LOGGER.error("Error trying to validate entry: %s", error) + return False return True diff --git a/homeassistant/components/waze_travel_time/manifest.json b/homeassistant/components/waze_travel_time/manifest.json index 312db2587cd8..d677c06512a9 100644 --- a/homeassistant/components/waze_travel_time/manifest.json +++ b/homeassistant/components/waze_travel_time/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["pywaze", "homeassistant.helpers.location"], - "requirements": ["pywaze==1.2.1"] + "requirements": ["pywaze==1.2.3"] } diff --git a/homeassistant/components/waze_travel_time/services.py b/homeassistant/components/waze_travel_time/services.py index 4193f123a2ac..4671921f65db 100644 --- a/homeassistant/components/waze_travel_time/services.py +++ b/homeassistant/components/waze_travel_time/services.py @@ -113,9 +113,6 @@ SERVICE_GET_TRAVEL_TIMES_SCHEMA = probatio.Schema( async def async_get_travel_times_service(service: ServiceCall) -> ServiceResponse: """Get travel times.""" httpx_client = get_async_client(service.hass) - client = WazeRouteCalculator( - region=service.data[CONF_REGION].upper(), client=httpx_client - ) origin_coordinates = find_coordinates(service.hass, service.data[CONF_ORIGIN]) destination_coordinates = find_coordinates( @@ -135,21 +132,24 @@ async def async_get_travel_times_service(service: ServiceCall) -> ServiceRespons / 60 ) - response = await async_get_travel_times( - client=client, - origin=origin, - destination=destination, - vehicle_type=service.data[CONF_VEHICLE_TYPE], - avoid_toll_roads=service.data[CONF_AVOID_TOLL_ROADS], - avoid_subscription_roads=service.data[CONF_AVOID_SUBSCRIPTION_ROADS], - avoid_ferries=service.data[CONF_AVOID_FERRIES], - realtime=service.data[CONF_REALTIME], - units=service.data[CONF_UNITS], - incl_filters=service.data.get(CONF_INCL_FILTER, DEFAULT_FILTER), - excl_filters=service.data.get(CONF_EXCL_FILTER, DEFAULT_FILTER), - time_delta=time_delta, - base_coordinates=base_coordinates, - ) + async with WazeRouteCalculator( + region=service.data[CONF_REGION].upper(), client=httpx_client + ) as client: + response = await async_get_travel_times( + client=client, + origin=origin, + destination=destination, + vehicle_type=service.data[CONF_VEHICLE_TYPE], + avoid_toll_roads=service.data[CONF_AVOID_TOLL_ROADS], + avoid_subscription_roads=service.data[CONF_AVOID_SUBSCRIPTION_ROADS], + avoid_ferries=service.data[CONF_AVOID_FERRIES], + realtime=service.data[CONF_REALTIME], + units=service.data[CONF_UNITS], + incl_filters=service.data.get(CONF_INCL_FILTER, DEFAULT_FILTER), + excl_filters=service.data.get(CONF_EXCL_FILTER, DEFAULT_FILTER), + time_delta=time_delta, + base_coordinates=base_coordinates, + ) return {"routes": [vars(route) for route in response]} diff --git a/requirements_all.txt b/requirements_all.txt index c5a3de0d6492..1dc04f99860a 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2887,7 +2887,7 @@ pyvlx==0.2.36 pyvolumio==0.1.5 # homeassistant.components.waze_travel_time -pywaze==1.2.1 +pywaze==1.2.3 # homeassistant.components.weatherflow pyweatherflowudp==1.6.3 From 7178f6b0006b7e5f3cfa6e0a44de9ad4adc03b7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=85ke=20Strandberg?= Date: Thu, 1 Oct 2026 20:46:20 +0200 Subject: [PATCH 033/356] Bump pymiele to 0.6.3 (#183936) --- homeassistant/components/miele/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/miele/manifest.json b/homeassistant/components/miele/manifest.json index c9f1a3df39a1..7f3285623932 100644 --- a/homeassistant/components/miele/manifest.json +++ b/homeassistant/components/miele/manifest.json @@ -9,7 +9,7 @@ "iot_class": "cloud_push", "loggers": ["pymiele"], "quality_scale": "platinum", - "requirements": ["pymiele==0.6.2"], + "requirements": ["pymiele==0.6.3"], "single_config_entry": true, "zeroconf": ["_mieleathome._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 1dc04f99860a..1cfff307501f 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2415,7 +2415,7 @@ pymeteoclimatic==0.1.1 pymicro-vad==1.0.1 # homeassistant.components.miele -pymiele==0.6.2 +pymiele==0.6.3 # homeassistant.components.xiaomi_tv pymitv==1.4.3 From 66a0c866108703cf0e21e83bbb7f8dba727f380e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=85ke=20Strandberg?= Date: Thu, 1 Oct 2026 21:34:21 +0200 Subject: [PATCH 034/356] Fix race condition in miele switches (#183942) --- homeassistant/components/miele/switch.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/miele/switch.py b/homeassistant/components/miele/switch.py index 05290ea0d63e..d038094918e7 100644 --- a/homeassistant/components/miele/switch.py +++ b/homeassistant/components/miele/switch.py @@ -1,4 +1,4 @@ -"""Switch platform for Miele switch integration.""" +"""Switch platform for Miele integration.""" from collections.abc import Callable from dataclasses import dataclass @@ -56,7 +56,8 @@ SWITCH_TYPES: Final[tuple[MieleSwitchDefinition, ...]] = ( description=MieleSwitchDescription( key="supercooling", value_fn=lambda value: value.state_status, - on_value=StateStatus.supercooling, + on_value=StateStatus.supercooling.value, + off_value=StateStatus.in_use.value, translation_key="supercooling", on_cmd_data={PROCESS_ACTION: MieleActions.START_SUPERCOOL}, off_cmd_data={PROCESS_ACTION: MieleActions.STOP_SUPERCOOL}, @@ -71,7 +72,8 @@ SWITCH_TYPES: Final[tuple[MieleSwitchDefinition, ...]] = ( description=MieleSwitchDescription( key="superfreezing", value_fn=lambda value: value.state_status, - on_value=StateStatus.superfreezing, + on_value=StateStatus.superfreezing.value, + off_value=StateStatus.in_use.value, translation_key="superfreezing", on_cmd_data={PROCESS_ACTION: MieleActions.START_SUPERFREEZE}, off_cmd_data={PROCESS_ACTION: MieleActions.STOP_SUPERFREEZE}, @@ -228,3 +230,19 @@ class MieleSuperSwitch(MieleSwitch): self.entity_description.value_fn(self.device) == self.entity_description.on_value ) + + @override + async def async_turn_on(self, **kwargs: Any) -> None: + """Turn on the device.""" + await self.async_turn_switch(self.entity_description.on_cmd_data) + _LOGGER.debug("Turned on super switch for %s", self.entity_id) + self.device.state_status = self.entity_description.on_value + self.async_write_ha_state() + + @override + async def async_turn_off(self, **kwargs: Any) -> None: + """Turn off the device.""" + await self.async_turn_switch(self.entity_description.off_cmd_data) + _LOGGER.debug("Turned off super switch for %s", self.entity_id) + self.device.state_status = self.entity_description.off_value + self.async_write_ha_state() From 265c7d953044c33fd6d97c8bdde71007fbc7fdef Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=2E=20Diego=20Rodr=C3=ADguez=20Royo?= Date: Fri, 2 Oct 2026 09:22:00 +0200 Subject: [PATCH 035/356] Add missing values and fix milk ratio option entity values_translation_key (#183969) --- homeassistant/components/home_connect/const.py | 1 + homeassistant/components/home_connect/select.py | 2 +- homeassistant/components/home_connect/services.yaml | 1 + homeassistant/components/home_connect/strings.json | 6 ++++-- 4 files changed, 7 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/home_connect/const.py b/homeassistant/components/home_connect/const.py index 94c8c7216af6..65d4a0d0daa3 100644 --- a/homeassistant/components/home_connect/const.py +++ b/homeassistant/components/home_connect/const.py @@ -180,6 +180,7 @@ COFFEE_TEMPERATURE_OPTIONS = { "ConsumerProducts.CoffeeMaker.EnumType.CoffeeTemperature.94C", "ConsumerProducts.CoffeeMaker.EnumType.CoffeeTemperature.95C", "ConsumerProducts.CoffeeMaker.EnumType.CoffeeTemperature.96C", + "ConsumerProducts.CoffeeMaker.EnumType.CoffeeTemperature.98C", ) } diff --git a/homeassistant/components/home_connect/select.py b/homeassistant/components/home_connect/select.py index 1bc36501aa58..5b9f62ceb2c6 100644 --- a/homeassistant/components/home_connect/select.py +++ b/homeassistant/components/home_connect/select.py @@ -229,7 +229,7 @@ PROGRAM_SELECT_OPTION_ENTITY_DESCRIPTIONS = ( translation_key_values=COFFEE_MILK_RATIO_OPTIONS, values_translation_key={ value: translation_key - for translation_key, value in FLOW_RATE_OPTIONS.items() + for translation_key, value in COFFEE_MILK_RATIO_OPTIONS.items() }, ), HomeConnectSelectEntityDescription( diff --git a/homeassistant/components/home_connect/services.yaml b/homeassistant/components/home_connect/services.yaml index a81a873ded2a..e1f8f4718413 100644 --- a/homeassistant/components/home_connect/services.yaml +++ b/homeassistant/components/home_connect/services.yaml @@ -404,6 +404,7 @@ set_program_and_options: - consumer_products_coffee_maker_enum_type_coffee_temperature_94_c - consumer_products_coffee_maker_enum_type_coffee_temperature_95_c - consumer_products_coffee_maker_enum_type_coffee_temperature_96_c + - consumer_products_coffee_maker_enum_type_coffee_temperature_98_c consumer_products_coffee_maker_option_bean_container_selection: example: consumer_products_coffee_maker_enum_type_bean_container_selection_right required: false diff --git a/homeassistant/components/home_connect/strings.json b/homeassistant/components/home_connect/strings.json index d252cc1119b8..9398e92ae941 100644 --- a/homeassistant/components/home_connect/strings.json +++ b/homeassistant/components/home_connect/strings.json @@ -557,7 +557,8 @@ "consumer_products_coffee_maker_enum_type_coffee_temperature_92_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_92_c%]", "consumer_products_coffee_maker_enum_type_coffee_temperature_94_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_94_c%]", "consumer_products_coffee_maker_enum_type_coffee_temperature_95_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_95_c%]", - "consumer_products_coffee_maker_enum_type_coffee_temperature_96_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_96_c%]" + "consumer_products_coffee_maker_enum_type_coffee_temperature_96_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_96_c%]", + "consumer_products_coffee_maker_enum_type_coffee_temperature_98_c": "[%key:component::home_connect::selector::coffee_temperature::options::consumer_products_coffee_maker_enum_type_coffee_temperature_98_c%]" } }, "current_map": { @@ -1758,7 +1759,8 @@ "consumer_products_coffee_maker_enum_type_coffee_temperature_92_c": "92ºC", "consumer_products_coffee_maker_enum_type_coffee_temperature_94_c": "94ºC", "consumer_products_coffee_maker_enum_type_coffee_temperature_95_c": "95ºC", - "consumer_products_coffee_maker_enum_type_coffee_temperature_96_c": "96ºC" + "consumer_products_coffee_maker_enum_type_coffee_temperature_96_c": "96ºC", + "consumer_products_coffee_maker_enum_type_coffee_temperature_98_c": "98ºC" } }, "drying_target": { From cbf7ca6601a452e26eb06064b7c2d2223c72ebdf Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Fri, 2 Oct 2026 10:02:08 +0200 Subject: [PATCH 036/356] Fix OpenDisplay upload_image timeout with image and camera entities (#183974) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../components/opendisplay/services.py | 37 ++++++++--- tests/components/opendisplay/test_services.py | 62 +++++++++++++++++++ 2 files changed, 89 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/opendisplay/services.py b/homeassistant/components/opendisplay/services.py index 971d0076860d..984abce80e96 100644 --- a/homeassistant/components/opendisplay/services.py +++ b/homeassistant/components/opendisplay/services.py @@ -21,6 +21,7 @@ from opendisplay import ( from PIL import Image as PILImage, ImageOps import probatio +from homeassistant.components import camera, image as image_component from homeassistant.components.bluetooth import ( BluetoothReachabilityIntent, async_address_reachability_diagnostics, @@ -128,6 +129,31 @@ async def _async_download_image(hass: HomeAssistant, url: str) -> PILImage.Image return await hass.async_add_executor_job(_load_image_from_bytes, data) +async def _async_get_pil_image( + hass: HomeAssistant, image_data: dict[str, Any] +) -> PILImage.Image: + """Return a PIL Image for the selected media.""" + media_content_id: str = image_data["media_content_id"] + + # Camera and image entities resolve to never-ending MJPEG streams, + # so fetch a single snapshot from the entity instead. + for integration in camera, image_component: + media_source_prefix = f"media-source://{integration.DOMAIN}/" + if not media_content_id.startswith(media_source_prefix): + continue + + entity_id = media_content_id.removeprefix(media_source_prefix) + snapshot = await integration.async_get_image(hass, entity_id) + return await hass.async_add_executor_job( + _load_image_from_bytes, snapshot.content + ) + + media = await async_resolve_media(hass, media_content_id, None) + if media.path is not None: + return await hass.async_add_executor_job(_load_image, str(media.path)) + return await _async_download_image(hass, media.url) + + async def _async_upload_image(call: ServiceCall) -> None: """Handle the upload_image service call.""" entry = _get_entry_for_device(call) @@ -166,16 +192,7 @@ async def _async_upload_image(call: ServiceCall) -> None: entry.runtime_data.upload_task = current try: - media = await async_resolve_media( - call.hass, image_data["media_content_id"], None - ) - - if media.path is not None: - pil_image = await call.hass.async_add_executor_job( - _load_image, str(media.path) - ) - else: - pil_image = await _async_download_image(call.hass, media.url) + pil_image = await _async_get_pil_image(call.hass, image_data) raw_key = entry.data.get(CONF_ENCRYPTION_KEY) if raw_key is not None and len(raw_key) != 32: diff --git a/tests/components/opendisplay/test_services.py b/tests/components/opendisplay/test_services.py index 903533a91d1d..e3b8a3fdac7f 100644 --- a/tests/components/opendisplay/test_services.py +++ b/tests/components/opendisplay/test_services.py @@ -17,6 +17,8 @@ import probatio import pytest from homeassistant import config_entries +from homeassistant.components.camera import Image as CameraImage +from homeassistant.components.image import Image as ImageEntityImage from homeassistant.components.opendisplay.const import CONF_ENCRYPTION_KEY, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError, ServiceValidationError @@ -128,6 +130,66 @@ async def test_upload_image_remote_url( mock_upload_device.upload_image.assert_called_once() +@pytest.mark.parametrize( + ("media_content_id", "patch_target", "entity_id", "image_cls"), + [ + pytest.param( + "media-source://image/image.collection", + "homeassistant.components.image.async_get_image", + "image.collection", + ImageEntityImage, + id="image_entity", + ), + pytest.param( + "media-source://camera/camera.front_door", + "homeassistant.components.camera.async_get_image", + "camera.front_door", + CameraImage, + id="camera_entity", + ), + ], +) +async def test_upload_image_from_entity( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_upload_device: MagicMock, + media_content_id: str, + patch_target: str, + entity_id: str, + image_cls: type[ImageEntityImage | CameraImage], +) -> None: + """Test uploading a snapshot from an image or camera entity.""" + device_id = _device_id(hass, mock_config_entry) + + buf = io.BytesIO() + PILImage.new("RGB", (10, 10)).save(buf, format="PNG") + + with ( + patch( + patch_target, return_value=image_cls("image/png", buf.getvalue()) + ) as mock_get_image, + patch( + "homeassistant.components.opendisplay.services.async_resolve_media" + ) as mock_resolve, + ): + await hass.services.async_call( + DOMAIN, + "upload_image", + { + "device_id": device_id, + "image": { + "media_content_id": media_content_id, + "media_content_type": "image/png", + }, + }, + blocking=True, + ) + + mock_get_image.assert_awaited_once_with(hass, entity_id) + mock_resolve.assert_not_called() + mock_upload_device.upload_image.assert_called_once() + + async def test_upload_image_invalid_device_id( hass: HomeAssistant, ) -> None: From ed1a70fe0375c50ba0a6a9b0f774cf98c9184e01 Mon Sep 17 00:00:00 2001 From: Hamish Date: Fri, 2 Oct 2026 17:50:36 +0930 Subject: [PATCH 037/356] indi_allsky: Simplify and fix keogram and startrail fetching (#183987) --- homeassistant/components/indi_allsky/image.py | 21 +++++++++---------- tests/components/indi_allsky/test_image.py | 8 +++---- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/homeassistant/components/indi_allsky/image.py b/homeassistant/components/indi_allsky/image.py index a713bcd42d46..3b22a84c2ad3 100644 --- a/homeassistant/components/indi_allsky/image.py +++ b/homeassistant/components/indi_allsky/image.py @@ -31,7 +31,7 @@ class IndiAllSkyImageEntityDescription(ImageEntityDescription): """Class describing INDI Allsky image entities.""" media_fn: Callable[[IndiAllSkyData], MediaData | None] - fallback_filename: str + image_filename: str IMAGE_DESCRIPTIONS: tuple[IndiAllSkyImageEntityDescription, ...] = ( @@ -39,13 +39,13 @@ IMAGE_DESCRIPTIONS: tuple[IndiAllSkyImageEntityDescription, ...] = ( key="latest_keogram", translation_key="latest_keogram", media_fn=lambda data: data.latest_keogram, - fallback_filename="latestkeogram", + image_filename="latestkeogram", ), IndiAllSkyImageEntityDescription( key="latest_startrail", translation_key="latest_startrail", media_fn=lambda data: data.latest_startrail, - fallback_filename="lateststartrail", + image_filename="lateststartrail", ), ) @@ -97,20 +97,19 @@ class IndiAllSkyImageEntity(IndiAllSkyEntity, ImageEntity): @override async def async_image(self) -> bytes | None: """Return bytes of the image.""" - media = self.entity_description.media_fn(self.coordinator.data) - filename = ( - media.filename - if (media and media.filename) - else self.entity_description.fallback_filename - ) try: - image_bytes = await self.coordinator.client.fetch_image(filename) + image_bytes = await self.coordinator.client.fetch_image( + self.entity_description.image_filename + ) except IndiAllSkyError: return None else: if content_type := infer_image_type(image_bytes): self._attr_content_type = content_type - if media is None and self._last_fetched is None: + if ( + self.entity_description.media_fn(self.coordinator.data) is None + and self._last_fetched is None + ): self._last_fetched = dt_util.utcnow() self.async_write_ha_state() return image_bytes diff --git a/tests/components/indi_allsky/test_image.py b/tests/components/indi_allsky/test_image.py index ca0b549db16e..803df5c35d5c 100644 --- a/tests/components/indi_allsky/test_image.py +++ b/tests/components/indi_allsky/test_image.py @@ -86,7 +86,7 @@ async def test_image_events_and_fetching( mock_indi_allsky_client.fetch_image.return_value = b"\xff\xd8\xff\xe0keogram_bytes" img = await image.async_get_image(hass, "image.indi_allsky_latest_keogram") assert img.content == b"\xff\xd8\xff\xe0keogram_bytes" - mock_indi_allsky_client.fetch_image.assert_called_with("keogram_20260813.jpg") + mock_indi_allsky_client.fetch_image.assert_called_with("latestkeogram") state = hass.states.get("image.indi_allsky_latest_star_trail") assert state is not None @@ -97,7 +97,7 @@ async def test_image_events_and_fetching( ) img = await image.async_get_image(hass, "image.indi_allsky_latest_star_trail") assert img.content == b"\xff\xd8\xff\xe0startrail_bytes" - mock_indi_allsky_client.fetch_image.assert_called_with("startrail_20260813.jpg") + mock_indi_allsky_client.fetch_image.assert_called_with("lateststartrail") async def test_image_fetch_error( @@ -120,12 +120,12 @@ async def test_image_fetch_error( await image.async_get_image(hass, "image.indi_allsky_latest_keogram") -async def test_image_fallback_fetching_before_events( +async def test_image_fetching_before_events( hass: HomeAssistant, mock_indi_allsky_client: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: - """Test fetching fallback alias images before any media event arrives.""" + """Test fetching images before any media event arrives.""" with patch("homeassistant.components.indi_allsky._PLATFORMS", [Platform.IMAGE]): await setup_integration(hass, mock_config_entry) From 1bdb0cc62e1cc21c1072bafd2e79bd4041b144bb Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 2 Oct 2026 12:38:44 +0200 Subject: [PATCH 038/356] Update probatio to 0.13.0 (#184006) --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index c00474ccda97..c8a461c8bd42 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -52,7 +52,7 @@ orjson==3.11.9 packaging>=23.1 paho-mqtt==2.1.0 Pillow==12.3.0 -probatio==0.12.5 +probatio==0.13.0 propcache==0.5.4 psutil-home-assistant==0.0.1 PyJWT==2.15.1 diff --git a/pyproject.toml b/pyproject.toml index b093ab3f21f4..93158e55854c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -78,7 +78,7 @@ dependencies = [ "ulid-transform==2.2.9", "urllib3>=2.0", "uv==0.12.20", - "probatio==0.12.5", + "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", "zeroconf==0.151.5", diff --git a/requirements.txt b/requirements.txt index 9f8a0e941ed6..f4ce0886261e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -38,7 +38,7 @@ mutagen==1.48.1 orjson==3.11.9 packaging>=23.1 Pillow==12.3.0 -probatio==0.12.5 +probatio==0.13.0 propcache==0.5.4 psutil-home-assistant==0.0.1 PyJWT==2.15.1 From 5b79f0bb99f8fcf895c8c7700048501fe9bc3be3 Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Fri, 2 Oct 2026 16:39:09 +0100 Subject: [PATCH 039/356] Check only_supervisor against the Supervisor user provided by hassio (#184041) Co-authored-by: Claude Fable 5.1 --- .../components/websocket_api/decorators.py | 7 ++- .../websocket_api/test_decorators.py | 45 ++++++++++++++++++- tests/conftest.py | 11 ++++- 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/websocket_api/decorators.py b/homeassistant/components/websocket_api/decorators.py index 557f2b287604..d5df7f88646d 100644 --- a/homeassistant/components/websocket_api/decorators.py +++ b/homeassistant/components/websocket_api/decorators.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING, Any import probatio -from homeassistant.const import HASSIO_USER_NAME +from homeassistant.components.http.const import DATA_SUPERVISOR_USER from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import Unauthorized from homeassistant.helpers.typing import VolDictType @@ -117,7 +117,10 @@ def ws_require_user( output_error("only_inactive_user", "Not allowed as active user") return None - if only_supervisor and connection.user.name != HASSIO_USER_NAME: + if only_supervisor and ( + (supervisor_user := hass.data.get(DATA_SUPERVISOR_USER)) is None + or connection.user.id != supervisor_user.id + ): output_error("only_supervisor", "Only allowed as Supervisor") return None diff --git a/tests/components/websocket_api/test_decorators.py b/tests/components/websocket_api/test_decorators.py index f343543735e5..75908cf518fd 100644 --- a/tests/components/websocket_api/test_decorators.py +++ b/tests/components/websocket_api/test_decorators.py @@ -3,10 +3,15 @@ from typing import Any import probatio +import pytest from homeassistant.components import http, websocket_api +from homeassistant.const import HASSIO_USER_NAME from homeassistant.core import HomeAssistant +from tests.common import MockUser +from tests.typing import MockHAClientWebSocket, WebSocketGenerator + async def test_async_response_request_context( hass: HomeAssistant, websocket_client @@ -156,8 +161,18 @@ async def test_async_response_request_context( ) -async def test_supervisor_only(hass: HomeAssistant, websocket_client) -> None: - """Test that only the Supervisor can make requests.""" +@pytest.mark.usefixtures("hass_supervisor_user") +async def test_supervisor_only( + hass: HomeAssistant, + websocket_client: MockHAClientWebSocket, + hass_admin_user: MockUser, +) -> None: + """Test that only the Supervisor can make requests. + + With the Supervisor user registered, an admin that is merely named like + the Supervisor user must still be rejected. + """ + await hass.auth.async_update_user(hass_admin_user, name=HASSIO_USER_NAME) @websocket_api.ws_require_user(only_supervisor=True) @websocket_api.websocket_command({"type": "test-require-supervisor-user"}) @@ -181,3 +196,29 @@ async def test_supervisor_only(hass: HomeAssistant, websocket_client) -> None: assert msg["id"] == 5 assert not msg["success"] assert msg["error"]["code"] == "only_supervisor" + + +async def test_supervisor_only_allows_supervisor( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + hass_supervisor_access_token: str, +) -> None: + """Test that the Supervisor user can make Supervisor-only requests.""" + + @websocket_api.ws_require_user(only_supervisor=True) + @websocket_api.websocket_command({"type": "test-require-supervisor-user"}) + def require_supervisor_request( + hass: HomeAssistant, + connection: websocket_api.ActiveConnection, + msg: dict[str, Any], + ) -> None: + connection.send_result(msg["id"]) + + websocket_api.async_register_command(hass, require_supervisor_request) + + client = await hass_ws_client(hass, hass_supervisor_access_token) + await client.send_json({"id": 5, "type": "test-require-supervisor-user"}) + + msg = await client.receive_json() + assert msg["id"] == 5 + assert msg["success"] diff --git a/tests/conftest.py b/tests/conftest.py index bdf1af45e3e7..02bfd3ff6a4e 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -60,6 +60,7 @@ from homeassistant.auth.const import GROUP_ID_ADMIN, GROUP_ID_READ_ONLY from homeassistant.auth.models import Credentials from homeassistant.auth.providers import homeassistant from homeassistant.components.device_tracker.legacy import Device +from homeassistant.components.http.const import DATA_SUPERVISOR_USER # pylint: disable-next=home-assistant-component-root-import from homeassistant.components.websocket_api.auth import ( @@ -902,11 +903,17 @@ async def hass_read_only_access_token( async def hass_supervisor_user( hass: HomeAssistant, local_auth: homeassistant.HassAuthProvider ) -> MockUser: - """Return the Home Assistant Supervisor user.""" + """Return the Home Assistant Supervisor user. + + The user is published the same way the hassio integration does, so + commands restricted to the Supervisor accept it. + """ admin_group = await hass.auth.async_get_group(GROUP_ID_ADMIN) - return MockUser( + user = MockUser( name=HASSIO_USER_NAME, groups=[admin_group], system_generated=True ).add_to_hass(hass) + hass.data[DATA_SUPERVISOR_USER] = user + return user @pytest.fixture From e337b225f7384c966ebeef77948c5df86b8cd9e2 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Fri, 2 Oct 2026 17:37:33 +0200 Subject: [PATCH 040/356] Don't create water heater entity when no temp sensor for my-PV integration (#184042) --- .../components/my_pv/water_heater.py | 10 +++-- tests/components/my_pv/test_water_heater.py | 37 +++++++++---------- 2 files changed, 24 insertions(+), 23 deletions(-) diff --git a/homeassistant/components/my_pv/water_heater.py b/homeassistant/components/my_pv/water_heater.py index f9010c286176..233335ecee48 100644 --- a/homeassistant/components/my_pv/water_heater.py +++ b/homeassistant/components/my_pv/water_heater.py @@ -17,7 +17,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from .const import DOMAIN from .coordinator import MyPVConfigEntry, MyPVCoordinator -from .entity import MyPVDataEntity +from .entity import MyPVBaseEntity async def async_setup_entry( @@ -29,8 +29,10 @@ async def async_setup_entry( coordinator = config_entry.runtime_data entities = [] - if coordinator.device.supports_main_mode(MyPVDeviceMainMode.HOT_WATER) and ( - configuration := coordinator.device.get_setup_configuration("ww1target") + if ( + coordinator.device.supports_main_mode(MyPVDeviceMainMode.HOT_WATER) + and coordinator.device.current_temperature is not None + and (configuration := coordinator.device.get_setup_configuration("ww1target")) ): entity_description = WaterHeaterEntityDescription( key="temp1", @@ -47,7 +49,7 @@ async def async_setup_entry( async_add_entities(entities) -class MyPVWaterHeater(MyPVDataEntity, WaterHeaterEntity): +class MyPVWaterHeater(MyPVBaseEntity, WaterHeaterEntity): """my-PV water heater.""" _attr_name = None diff --git a/tests/components/my_pv/test_water_heater.py b/tests/components/my_pv/test_water_heater.py index c33f1477966e..428ea78e68f2 100644 --- a/tests/components/my_pv/test_water_heater.py +++ b/tests/components/my_pv/test_water_heater.py @@ -1,6 +1,6 @@ """Test the my-PV water heater.""" -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, patch from my_pv.exceptions import MyPVAuthenticationError, MyPVConnectionError import pytest @@ -47,6 +47,23 @@ async def test_water_heater( await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) +async def test_water_heater_no_temp_sensor( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_my_pv_client: AsyncMock, +) -> None: + """Test if a water_heater is not created when there is no temperature sensor connected.""" + mock_config_entry.add_to_hass(hass) + + mock_my_pv_client.current_temperature = None + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get("water_heater.my_pv_ac_elwa_2") + assert state is None + + async def test_water_heater_unavailable_not_connected( hass: HomeAssistant, mock_config_entry: MockConfigEntry, @@ -65,24 +82,6 @@ async def test_water_heater_unavailable_not_connected( assert state.state == STATE_UNAVAILABLE -async def test_water_heater_unavailable_data_value_none( - hass: HomeAssistant, - mock_config_entry: MockConfigEntry, - mock_my_pv_client: AsyncMock, -) -> None: - """Test if a water_heater is unavailable when data value is None.""" - - mock_config_entry.add_to_hass(hass) - - mock_my_pv_client.get_data_value = Mock(return_value=None) - - assert await hass.config_entries.async_setup(mock_config_entry.entry_id) - await hass.async_block_till_done() - - state = hass.states.get("water_heater.my_pv_ac_elwa_2") - assert state.state == STATE_UNAVAILABLE - - async def test_water_heater_turn_off( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From a75d3ee61e3707e70844478601e59d7ce8c5a260 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 2 Oct 2026 16:54:16 +0200 Subject: [PATCH 041/356] Bump radios to 1.0.0 (#184059) --- homeassistant/components/radio_browser/manifest.json | 2 +- requirements_all.txt | 2 +- script/hassfest/requirements.py | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/radio_browser/manifest.json b/homeassistant/components/radio_browser/manifest.json index 943187596d75..34d82a5ae080 100644 --- a/homeassistant/components/radio_browser/manifest.json +++ b/homeassistant/components/radio_browser/manifest.json @@ -6,6 +6,6 @@ "documentation": "https://www.home-assistant.io/integrations/radio_browser", "integration_type": "service", "iot_class": "cloud_polling", - "requirements": ["radios==0.3.2", "pycountry==24.6.1"], + "requirements": ["radios==1.0.0", "pycountry==24.6.1"], "single_config_entry": true } diff --git a/requirements_all.txt b/requirements_all.txt index 1cfff307501f..471fc2f877b9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2944,7 +2944,7 @@ qnapstats==0.4.0 quantum-gateway==0.0.8 # homeassistant.components.radio_browser -radios==0.3.2 +radios==1.0.0 # homeassistant.components.radiotherm radiotherm==2.1.0 diff --git a/script/hassfest/requirements.py b/script/hassfest/requirements.py index 0a85f5736380..9f098d346d2b 100644 --- a/script/hassfest/requirements.py +++ b/script/hassfest/requirements.py @@ -220,7 +220,6 @@ FORBIDDEN_PACKAGE_EXCEPTIONS: dict[str, dict[str, set[str]]] = { "opengarage": {"open-garage": {"async-timeout"}}, "overkiz": {"pyoverkiz": {"backoff"}}, "prosegur": {"pyprosegur": {"backoff"}}, - "radio_browser": {"radios": {"backoff"}}, "remote_rpi_gpio": { # https://github.com/waveform80/colorzero/issues/9 # gpiozero > colorzero > setuptools From ff68fea56c51de5cb6d600912a958ac7ec9a9acb Mon Sep 17 00:00:00 2001 From: Samuel Siburian Date: Mon, 5 Oct 2026 21:50:09 +0800 Subject: [PATCH 042/356] Fix AirGradient VOC and NOx learning offset units (#180305) --- .../components/airgradient/sensor.py | 4 ++-- .../airgradient/snapshots/test_sensor.ambr | 24 +++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/airgradient/sensor.py b/homeassistant/components/airgradient/sensor.py index 3f5ee2a20515..9b967914cd3c 100644 --- a/homeassistant/components/airgradient/sensor.py +++ b/homeassistant/components/airgradient/sensor.py @@ -236,7 +236,7 @@ CONFIG_SENSOR_TYPES: tuple[AirGradientConfigSensorEntityDescription, ...] = ( key="nox_learning_offset", translation_key="nox_learning_offset", device_class=SensorDeviceClass.DURATION, - native_unit_of_measurement=UnitOfTime.DAYS, + native_unit_of_measurement=UnitOfTime.HOURS, entity_category=EntityCategory.DIAGNOSTIC, config_key="nox_learning_offset", value_fn=lambda config: config.nox_learning_offset, @@ -245,7 +245,7 @@ CONFIG_SENSOR_TYPES: tuple[AirGradientConfigSensorEntityDescription, ...] = ( key="tvoc_learning_offset", translation_key="tvoc_learning_offset", device_class=SensorDeviceClass.DURATION, - native_unit_of_measurement=UnitOfTime.DAYS, + native_unit_of_measurement=UnitOfTime.HOURS, entity_category=EntityCategory.DIAGNOSTIC, config_key="tvoc_learning_offset", value_fn=lambda config: config.tvoc_learning_offset, diff --git a/tests/components/airgradient/snapshots/test_sensor.ambr b/tests/components/airgradient/snapshots/test_sensor.ambr index 91e074a9bb8c..96f31c05e49e 100644 --- a/tests/components/airgradient/snapshots/test_sensor.ambr +++ b/tests/components/airgradient/snapshots/test_sensor.ambr @@ -538,7 +538,7 @@ 'supported_features': 0, 'translation_key': 'nox_learning_offset', 'unique_id': '84fce612f5b8-nox_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_all_entities[indoor][sensor.airgradient_nox_index_learning_offset-state] @@ -546,7 +546,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient NOx index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_nox_index_learning_offset', @@ -1141,7 +1141,7 @@ 'supported_features': 0, 'translation_key': 'tvoc_learning_offset', 'unique_id': '84fce612f5b8-tvoc_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_all_entities[indoor][sensor.airgradient_voc_index_learning_offset-state] @@ -1149,7 +1149,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient VOC index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_voc_index_learning_offset', @@ -1304,7 +1304,7 @@ 'supported_features': 0, 'translation_key': 'nox_learning_offset', 'unique_id': '84fce612f5b8-nox_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_all_entities[outdoor][sensor.airgradient_nox_index_learning_offset-state] @@ -1312,7 +1312,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient NOx index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_nox_index_learning_offset', @@ -1575,7 +1575,7 @@ 'supported_features': 0, 'translation_key': 'tvoc_learning_offset', 'unique_id': '84fce612f5b8-tvoc_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_all_entities[outdoor][sensor.airgradient_voc_index_learning_offset-state] @@ -1583,7 +1583,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient VOC index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_voc_index_learning_offset', @@ -2139,7 +2139,7 @@ 'supported_features': 0, 'translation_key': 'nox_learning_offset', 'unique_id': '84fce612f5b8-nox_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_v1_entities[sensor.airgradient_nox_index_learning_offset-state] @@ -2147,7 +2147,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient NOx index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_nox_index_learning_offset', @@ -2957,7 +2957,7 @@ 'supported_features': 0, 'translation_key': 'tvoc_learning_offset', 'unique_id': '84fce612f5b8-tvoc_learning_offset', - 'unit_of_measurement': , + 'unit_of_measurement': , }) # --- # name: test_v1_entities[sensor.airgradient_voc_index_learning_offset-state] @@ -2965,7 +2965,7 @@ 'attributes': ReadOnlyDict({ : 'duration', : 'Airgradient VOC index learning offset', - : , + : , }), 'context': , 'entity_id': 'sensor.airgradient_voc_index_learning_offset', From 93ad971397567581c78deb43789f3e35e1506092 Mon Sep 17 00:00:00 2001 From: Avi Miller Date: Thu, 1 Oct 2026 05:59:40 +1000 Subject: [PATCH 043/356] Bump lifx-async to 7.6.4 (#183788) Signed-off-by: Avi Miller Co-authored-by: Claude Opus 5.5 --- homeassistant/components/lifx/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/lifx/manifest.json b/homeassistant/components/lifx/manifest.json index c1b71bbb4f25..f1529f2b9d1b 100644 --- a/homeassistant/components/lifx/manifest.json +++ b/homeassistant/components/lifx/manifest.json @@ -52,6 +52,6 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["lifx"], - "requirements": ["lifx-async==7.4.0"], + "requirements": ["lifx-async==7.6.4"], "zeroconf": ["_lifx._udp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 471fc2f877b9..cf943fb6f769 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1526,7 +1526,7 @@ librouteros==4.2.2 libsoundtouch==0.8 # homeassistant.components.lifx -lifx-async==7.4.0 +lifx-async==7.6.4 # homeassistant.components.osramlightify lightify==1.0.7.3 From 62f753e79f199750e8bc766682a1707c67cbcb22 Mon Sep 17 00:00:00 2001 From: Avi Miller Date: Sat, 3 Oct 2026 00:22:52 +1000 Subject: [PATCH 044/356] Bump lifx-async to 7.6.5 (#184063) Signed-off-by: Avi Miller --- homeassistant/components/lifx/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/lifx/manifest.json b/homeassistant/components/lifx/manifest.json index f1529f2b9d1b..8153db222331 100644 --- a/homeassistant/components/lifx/manifest.json +++ b/homeassistant/components/lifx/manifest.json @@ -52,6 +52,6 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["lifx"], - "requirements": ["lifx-async==7.6.4"], + "requirements": ["lifx-async==7.6.5"], "zeroconf": ["_lifx._udp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index cf943fb6f769..8d3e505a0214 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1526,7 +1526,7 @@ librouteros==4.2.2 libsoundtouch==0.8 # homeassistant.components.lifx -lifx-async==7.6.4 +lifx-async==7.6.5 # homeassistant.components.osramlightify lightify==1.0.7.3 From a40f504d4198996f8da787d2871cd0b5568fee0c Mon Sep 17 00:00:00 2001 From: Maximilian <43999966+DeerMaximum@users.noreply.github.com> Date: Fri, 2 Oct 2026 17:28:47 +0200 Subject: [PATCH 045/356] Bump pynina to 1.0.3 (#184067) --- homeassistant/components/nina/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nina/manifest.json b/homeassistant/components/nina/manifest.json index 882371d1d96e..8792570c62b9 100644 --- a/homeassistant/components/nina/manifest.json +++ b/homeassistant/components/nina/manifest.json @@ -8,6 +8,6 @@ "iot_class": "cloud_polling", "loggers": ["pynina"], "quality_scale": "silver", - "requirements": ["pynina==1.0.2"], + "requirements": ["pynina==1.0.3"], "single_config_entry": true } diff --git a/requirements_all.txt b/requirements_all.txt index 8d3e505a0214..aa356184eea9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2442,7 +2442,7 @@ pynetgear==0.10.10 pynetio==0.1.9.1 # homeassistant.components.nina -pynina==1.0.2 +pynina==1.0.3 # homeassistant.components.nintendo_parental_controls pynintendoauth==1.0.3 From 21dec15cd3e7aed1d2affaed816c822fa367ff24 Mon Sep 17 00:00:00 2001 From: Sarah Seidman Date: Fri, 2 Oct 2026 16:35:01 -0400 Subject: [PATCH 046/356] Upgrade pydroplet to v2.5.0 (#184087) --- homeassistant/components/droplet/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/droplet/manifest.json b/homeassistant/components/droplet/manifest.json index 17d4bf8def63..916ab68094a2 100644 --- a/homeassistant/components/droplet/manifest.json +++ b/homeassistant/components/droplet/manifest.json @@ -7,6 +7,6 @@ "integration_type": "device", "iot_class": "local_push", "quality_scale": "bronze", - "requirements": ["pydroplet==2.4.0"], + "requirements": ["pydroplet==2.5.0"], "zeroconf": ["_droplet._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index aa356184eea9..ee2bdf97f344 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2186,7 +2186,7 @@ pydrawise==2026.9.0 pydroid-ipcam==3.0.0 # homeassistant.components.droplet -pydroplet==2.4.0 +pydroplet==2.5.0 # homeassistant.components.ebox pyebox==1.1.4 From b795ede58cdea4980d1a9b05d36555d169cb7067 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Fri, 2 Oct 2026 22:35:28 +0200 Subject: [PATCH 047/356] Bump my-pv to 0.0.10 (#184088) --- homeassistant/components/my_pv/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/my_pv/manifest.json b/homeassistant/components/my_pv/manifest.json index 30213320a9af..fa75649d8f7d 100644 --- a/homeassistant/components/my_pv/manifest.json +++ b/homeassistant/components/my_pv/manifest.json @@ -16,6 +16,6 @@ "iot_class": "local_polling", "loggers": ["my_pv"], "quality_scale": "bronze", - "requirements": ["my-pv==0.0.8"], + "requirements": ["my-pv==0.0.10"], "zeroconf": ["_mypv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index ee2bdf97f344..8b222273cdbb 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1686,7 +1686,7 @@ mutesync==0.0.1 mvg==1.6.0 # homeassistant.components.my_pv -my-pv==0.0.8 +my-pv==0.0.10 # homeassistant.components.myuplink myuplink==0.7.0 From ec8b79d1d49719df0c2ec414ed000f1e34930fdc Mon Sep 17 00:00:00 2001 From: Sarah Seidman Date: Mon, 5 Oct 2026 07:58:18 -0400 Subject: [PATCH 048/356] Improve Droplet connection handling (#184092) --- homeassistant/components/droplet/config_flow.py | 16 ++++++++++++---- homeassistant/components/droplet/const.py | 3 ++- homeassistant/components/droplet/coordinator.py | 12 +++++------- tests/components/droplet/conftest.py | 4 ++-- tests/components/droplet/test_config_flow.py | 3 +++ 5 files changed, 24 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/droplet/config_flow.py b/homeassistant/components/droplet/config_flow.py index 1f971e522656..46c4f46d2ec2 100644 --- a/homeassistant/components/droplet/config_flow.py +++ b/homeassistant/components/droplet/config_flow.py @@ -57,7 +57,11 @@ class DropletConfigFlow(ConfigFlow, domain=DOMAIN): # Test if we can connect before returning session = async_get_clientsession(self.hass) code = normalize_pairing_code(user_input[CONF_CODE]) - if await self._droplet_discovery.try_connect(session, code): + try: + connected = await self._droplet_discovery.try_connect(session, code) + finally: + await self._droplet_discovery.close() + if connected: device_data = { CONF_IP_ADDRESS: self._droplet_discovery.host, CONF_PORT: self._droplet_discovery.port, @@ -95,9 +99,13 @@ class DropletConfigFlow(ConfigFlow, domain=DOMAIN): ) session = async_get_clientsession(self.hass) code = normalize_pairing_code(user_input[CONF_CODE]) - if await self._droplet_discovery.try_connect(session, code) and ( - device_id := await self._droplet_discovery.get_device_id() - ): + device_id = "" + try: + if await self._droplet_discovery.try_connect(session, code): + device_id = await self._droplet_discovery.get_device_id() + finally: + await self._droplet_discovery.close() + if device_id: device_data = { CONF_IP_ADDRESS: self._droplet_discovery.host, CONF_PORT: self._droplet_discovery.port, diff --git a/homeassistant/components/droplet/const.py b/homeassistant/components/droplet/const.py index fa9df48a02d1..1f55507ce8eb 100644 --- a/homeassistant/components/droplet/const.py +++ b/homeassistant/components/droplet/const.py @@ -1,6 +1,7 @@ """Constants for the droplet integration.""" -CONNECT_DELAY = 5 +CONNECT_TIMEOUT = 15 +RECONNECT_DELAY = 5 DOMAIN = "droplet" DEVICE_NAME = "Droplet" diff --git a/homeassistant/components/droplet/coordinator.py b/homeassistant/components/droplet/coordinator.py index 1ee324536453..31a0d41e8ab3 100644 --- a/homeassistant/components/droplet/coordinator.py +++ b/homeassistant/components/droplet/coordinator.py @@ -14,9 +14,7 @@ from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -from .const import CONNECT_DELAY, DOMAIN - -VERSION_TIMEOUT = 5 +from .const import CONNECT_TIMEOUT, DOMAIN, RECONNECT_DELAY _LOGGER = logging.getLogger(__name__) @@ -50,8 +48,8 @@ class DropletDataCoordinator(DataUpdateCoordinator[None]): if not await self.setup(): raise ConfigEntryNotReady("Device is offline") - # Droplet should send its metadata within 5 seconds - end = time.time() + VERSION_TIMEOUT + # Droplet should send its metadata shortly after connecting + end = time.time() + CONNECT_TIMEOUT while not self.droplet.version_info_available(): await asyncio.sleep(TIMEOUT) if time.time() > end: @@ -70,10 +68,10 @@ class DropletDataCoordinator(DataUpdateCoordinator[None]): self.config_entry.async_on_unload(self.droplet.stop_listening) self.config_entry.async_create_background_task( self.hass, - self.droplet.listen_forever(CONNECT_DELAY, self.async_set_updated_data), + self.droplet.listen_forever(RECONNECT_DELAY, self.async_set_updated_data), "droplet-listen", ) - end = time.time() + CONNECT_DELAY + end = time.time() + CONNECT_TIMEOUT while time.time() < end: if self.droplet.connected: return True diff --git a/tests/components/droplet/conftest.py b/tests/components/droplet/conftest.py index f3c2a1aac52a..a3631fe464db 100644 --- a/tests/components/droplet/conftest.py +++ b/tests/components/droplet/conftest.py @@ -65,11 +65,11 @@ def mock_timeout() -> Generator[None]: 0.05, ), patch( - "homeassistant.components.droplet.coordinator.VERSION_TIMEOUT", + "homeassistant.components.droplet.coordinator.CONNECT_TIMEOUT", 0.1, ), patch( - "homeassistant.components.droplet.coordinator.CONNECT_DELAY", + "homeassistant.components.droplet.coordinator.RECONNECT_DELAY", 0.1, ), ): diff --git a/tests/components/droplet/test_config_flow.py b/tests/components/droplet/test_config_flow.py index f706a94eb748..9f979767e5c4 100644 --- a/tests/components/droplet/test_config_flow.py +++ b/tests/components/droplet/test_config_flow.py @@ -65,6 +65,7 @@ async def test_user_setup( } assert result.get("context") is not None assert result.get("context", {}).get("unique_id") == MOCK_DEVICE_ID + mock_droplet_discovery.close.assert_awaited_once() @pytest.mark.parametrize( @@ -107,6 +108,7 @@ async def test_user_setup_fail( assert result is not None assert result.get("type") is FlowResultType.FORM assert result.get("errors") == {"base": "cannot_connect"} + mock_droplet_discovery.close.assert_awaited_once() # The user should be able to try again. Maybe the droplet # was disconnected from the network or something @@ -200,6 +202,7 @@ async def test_zeroconf_setup( } assert result.get("context") is not None assert result.get("context", {}).get("unique_id") == MOCK_DEVICE_ID + mock_droplet_discovery.close.assert_awaited_once() @pytest.mark.parametrize("mock_droplet_discovery", ["192.168.1.5"], indirect=True) From 3082b3ca09809a73b14a95c8196aaf418aafdf3c Mon Sep 17 00:00:00 2001 From: tronikos Date: Sat, 3 Oct 2026 01:53:05 -0700 Subject: [PATCH 049/356] Bump opower to 0.22.2 (#184115) --- homeassistant/components/opower/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/opower/manifest.json b/homeassistant/components/opower/manifest.json index 4d933b995437..8657337df337 100644 --- a/homeassistant/components/opower/manifest.json +++ b/homeassistant/components/opower/manifest.json @@ -9,5 +9,5 @@ "iot_class": "cloud_polling", "loggers": ["opower"], "quality_scale": "platinum", - "requirements": ["opower==0.22.1"] + "requirements": ["opower==0.22.2"] } diff --git a/requirements_all.txt b/requirements_all.txt index 8b222273cdbb..81dee599a4b3 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1848,7 +1848,7 @@ openwrt-luci-rpc==1.1.17 openwrt-ubus-rpc==0.0.3 # homeassistant.components.opower -opower==0.22.1 +opower==0.22.2 # homeassistant.components.oralb oralb-ble==1.1.3 From 2c0cf541180e02a13a80398c9e878e107d68cef0 Mon Sep 17 00:00:00 2001 From: Joakim Plate Date: Sat, 3 Oct 2026 13:03:18 +0200 Subject: [PATCH 050/356] Non numeric sensors in nibe broken (#184116) --- .../components/nibe_heatpump/sensor.py | 3 +- .../nibe_heatpump/snapshots/test_sensor.ambr | 50 +++++++++++++++++++ tests/components/nibe_heatpump/test_sensor.py | 2 +- 3 files changed, 53 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nibe_heatpump/sensor.py b/homeassistant/components/nibe_heatpump/sensor.py index 4d3ed237549c..675dfbf220bd 100644 --- a/homeassistant/components/nibe_heatpump/sensor.py +++ b/homeassistant/components/nibe_heatpump/sensor.py @@ -249,7 +249,8 @@ class Sensor(CoilEntity, SensorEntity): if state_class := NATURE_TO_STATE_CLASS.get(coil.nature): self._attr_state_class = state_class - self._attr_suggested_display_precision = ceil(log10(abs(coil.factor))) + if not coil.mappings: + self._attr_suggested_display_precision = ceil(log10(abs(coil.factor))) @override def _async_read_coil(self, data: CoilData): diff --git a/tests/components/nibe_heatpump/snapshots/test_sensor.ambr b/tests/components/nibe_heatpump/snapshots/test_sensor.ambr index ef8aeb40415e..7fe6a5c5d545 100644 --- a/tests/components/nibe_heatpump/snapshots/test_sensor.ambr +++ b/tests/components/nibe_heatpump/snapshots/test_sensor.ambr @@ -226,6 +226,56 @@ 'state': '0', }) # --- +# name: test_entities[Model.F1155-data0][sensor.supply_pump_state_ep14_43431-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + '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.supply_pump_state_ep14_43431', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': None, + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Supply Pump State EP14', + 'platform': 'nibe_heatpump', + 'previous_unique_id': None, + 'suggested_object_id': 'supply_pump_state_ep14_43431', + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mock_entry_unique_id-43431', + 'unit_of_measurement': None, + }) +# --- +# name: test_entities[Model.F1155-data0][sensor.supply_pump_state_ep14_43431-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'F1155 Supply Pump State EP14', + }), + 'context': , + 'entity_id': 'sensor.supply_pump_state_ep14_43431', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'OFF', + }) +# --- # name: test_entities[Model.SMOS40-data1][sensor.current_outdoor_temperature_bt1_30002-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/nibe_heatpump/test_sensor.py b/tests/components/nibe_heatpump/test_sensor.py index b126c3357e32..bc16d4059cb4 100644 --- a/tests/components/nibe_heatpump/test_sensor.py +++ b/tests/components/nibe_heatpump/test_sensor.py @@ -26,7 +26,7 @@ async def fixture_single_platform(): @pytest.mark.parametrize( ("model", "data"), [ - (Model.F1155, {43005: 1234, 40004: 20.0, 40321: 50, 40317: 0}), + (Model.F1155, {43005: 1234, 40004: 20.0, 40321: 50, 40317: 0, 43431: "OFF"}), (Model.SMOS40, {40019: 1234, 30002: 20.0, 31855: 50}), ], ) From ec61dda08d63613ff973ec1425f0aa7007a9a42c Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Sat, 3 Oct 2026 13:02:08 +0200 Subject: [PATCH 051/356] Swap optimistic MQTT climate setpoints on HVAC mode change (#184122) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/mqtt/climate.py | 75 ++++++++++--- tests/components/mqtt/test_climate.py | 132 +++++++++++++++++++++++ 2 files changed, 193 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/mqtt/climate.py b/homeassistant/components/mqtt/climate.py index 2b0d84912b7f..f469bb6a533b 100644 --- a/homeassistant/components/mqtt/climate.py +++ b/homeassistant/components/mqtt/climate.py @@ -471,6 +471,8 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): _attr_target_temperature_low: float | None = None _attr_target_temperature_high: float | None = None _single_and_range_setpoints: bool + _parked_target_temperature: float | None = None + _parked_target_temperature_range: tuple[float | None, float | None] = (None, None) @staticmethod @override @@ -677,9 +679,8 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): ) is UNDEFINED: return self._attr_target_temperature = value - if value is not None and self._single_and_range_setpoints: - self._attr_target_temperature_low = None - self._attr_target_temperature_high = None + if value is not None: + self._park_range_setpoints() @callback def _handle_target_temperature_low_received(self, msg: ReceiveMessage) -> None: @@ -691,8 +692,8 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): ) is UNDEFINED: return self._attr_target_temperature_low = value - if value is not None and self._single_and_range_setpoints: - self._attr_target_temperature = None + if value is not None: + self._park_single_setpoint() @callback def _handle_target_temperature_high_received(self, msg: ReceiveMessage) -> None: @@ -704,8 +705,8 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): ) is UNDEFINED: return self._attr_target_temperature_high = value - if value is not None and self._single_and_range_setpoints: - self._attr_target_temperature = None + if value is not None: + self._park_single_setpoint() @callback def _handle_current_humidity_received(self, msg: ReceiveMessage) -> None: @@ -831,9 +832,7 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): optimistic_update = True self._attr_target_temperature = temperature # We reset low and high setpoints when a single setpoint is set - if self._single_and_range_setpoints: - self._attr_target_temperature_low = None - self._attr_target_temperature_high = None + self._park_range_setpoints() mqtt_payload = self._command_templates[CONF_TEMP_COMMAND_TEMPLATE]( temperature ) @@ -845,8 +844,7 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): optimistic_update = True self._attr_target_temperature_low = target_temp_low # We reset the single setpoint when a setpoint range is set - if self._single_and_range_setpoints: - self._attr_target_temperature = None + self._park_single_setpoint() mqtt_payload = self._command_templates[CONF_TEMP_LOW_COMMAND_TEMPLATE]( target_temp_low ) @@ -857,8 +855,7 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): if self._optimistic or self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is None: optimistic_update = True self._attr_target_temperature_high = target_temp_high - if self._single_and_range_setpoints: - self._attr_target_temperature = None + self._park_single_setpoint() mqtt_payload = self._command_templates[CONF_TEMP_HIGH_COMMAND_TEMPLATE]( target_temp_high ) @@ -920,8 +917,58 @@ class MqttClimate(MqttTemperatureControlEntity, ClimateEntity): if self._optimistic or self._topic[CONF_MODE_STATE_TOPIC] is None: self._attr_hvac_mode = hvac_mode + self._swap_setpoints(hvac_mode) self.async_write_ha_state() + def _park_single_setpoint(self) -> None: + """Park and reset the single setpoint when a setpoint range is active.""" + if not self._single_and_range_setpoints or self.target_temperature is None: + return + self._parked_target_temperature = self.target_temperature + self._attr_target_temperature = None + + def _park_range_setpoints(self) -> None: + """Park and reset the setpoint range when a single setpoint is active.""" + temp_range = (self.target_temperature_low, self.target_temperature_high) + if not self._single_and_range_setpoints or temp_range == (None, None): + return + self._parked_target_temperature_range = temp_range + self._attr_target_temperature_low = None + self._attr_target_temperature_high = None + + def _swap_setpoints(self, hvac_mode: HVACMode) -> None: + """Swap optimistic single and range setpoints on an HVAC mode change. + + The inactive setpoints are parked, so they can be restored + when switching back, as the device is expected to remember them. + """ + if not self._single_and_range_setpoints or hvac_mode not in ( + HVACMode.COOL, + HVACMode.HEAT, + HVACMode.HEAT_COOL, + ): + return + uses_range = hvac_mode is HVACMode.HEAT_COOL + if self._optimistic or self._topic[CONF_TEMP_STATE_TOPIC] is None: + if uses_range: + self._park_single_setpoint() + elif self.target_temperature is None: + self._attr_target_temperature = self._parked_target_temperature + if self._optimistic or ( + self._topic[CONF_TEMP_LOW_STATE_TOPIC] is None + and self._topic[CONF_TEMP_HIGH_STATE_TOPIC] is None + ): + if not uses_range: + self._park_range_setpoints() + elif ( + self.target_temperature_low is None + and self.target_temperature_high is None + ): + ( + self._attr_target_temperature_low, + self._attr_target_temperature_high, + ) = self._parked_target_temperature_range + @override async def async_set_preset_mode(self, preset_mode: str) -> None: """Set a preset mode.""" diff --git a/tests/components/mqtt/test_climate.py b/tests/components/mqtt/test_climate.py index 4c84de16282d..891defba8513 100644 --- a/tests/components/mqtt/test_climate.py +++ b/tests/components/mqtt/test_climate.py @@ -1127,6 +1127,138 @@ async def test_received_setpoint_resets_other_setpoints( ) == expected +SWAP_MODES = {"modes": ["off", "auto", "heat_cool", "heat", "cool"]} + + +def _setpoints(hass: HomeAssistant) -> tuple[float | None, float | None, float | None]: + """Return the single and range setpoints of the climate entity.""" + state = hass.states.get(ENTITY_CLIMATE) + return ( + state.attributes.get("temperature"), + state.attributes.get("target_temp_low"), + state.attributes.get("target_temp_high"), + ) + + +@pytest.mark.parametrize( + "hass_config", + [help_custom_config(climate.DOMAIN, DEFAULT_CONFIG, (SWAP_MODES,))], +) +async def test_set_hvac_mode_swaps_setpoints_optimistic( + hass: HomeAssistant, mqtt_mock_entry: MqttMockHAClientGenerator +) -> None: + """Test inactive optimistic setpoints are parked and restored on mode changes.""" + await mqtt_mock_entry() + assert _setpoints(hass) == (21, 21, 21) + + await common.async_set_hvac_mode(hass, HVACMode.HEAT, ENTITY_CLIMATE) + assert _setpoints(hass) == (21, None, None) + + await common.async_set_temperature(hass, temperature=19, entity_id=ENTITY_CLIMATE) + await common.async_set_hvac_mode(hass, HVACMode.HEAT_COOL, ENTITY_CLIMATE) + assert _setpoints(hass) == (None, 21, 21) + + await common.async_set_temperature( + hass, target_temp_low=20, target_temp_high=23, entity_id=ENTITY_CLIMATE + ) + await common.async_set_hvac_mode(hass, HVACMode.COOL, ENTITY_CLIMATE) + assert _setpoints(hass) == (19, None, None) + + # Modes without specific setpoint logic leave the setpoints untouched + await common.async_set_hvac_mode(hass, HVACMode.OFF, ENTITY_CLIMATE) + assert _setpoints(hass) == (19, None, None) + + await common.async_set_hvac_mode(hass, HVACMode.HEAT_COOL, ENTITY_CLIMATE) + assert _setpoints(hass) == (None, 20, 23) + + await common.async_set_hvac_mode(hass, HVACMode.HEAT, ENTITY_CLIMATE) + assert _setpoints(hass) == (19, None, None) + + await common.async_set_hvac_mode(hass, HVACMode.AUTO, ENTITY_CLIMATE) + assert _setpoints(hass) == (19, None, None) + + # Setpoints reset by a temperature command are parked as well + await common.async_set_hvac_mode(hass, HVACMode.HEAT_COOL, ENTITY_CLIMATE) + await common.async_set_temperature( + hass, target_temp_low=21, target_temp_high=24, entity_id=ENTITY_CLIMATE + ) + await common.async_set_hvac_mode(hass, HVACMode.AUTO, ENTITY_CLIMATE) + await common.async_set_temperature(hass, temperature=18, entity_id=ENTITY_CLIMATE) + assert _setpoints(hass) == (18, None, None) + + await common.async_set_hvac_mode(hass, HVACMode.HEAT_COOL, ENTITY_CLIMATE) + assert _setpoints(hass) == (None, 21, 24) + + +@pytest.mark.parametrize( + ("hass_config", "messages", "expected"), + [ + pytest.param( + help_custom_config( + climate.DOMAIN, + DEFAULT_CONFIG, + ({**SETPOINT_STATE_TOPICS, **SWAP_MODES, "optimistic": True},), + ), + [], + [(21, None, None), (None, 21, 21)], + id="optimistic_with_state_topics", + ), + pytest.param( + help_custom_config( + climate.DOMAIN, + DEFAULT_CONFIG, + ( + { + "temperature_low_state_topic": "temperature-low-state", + "temperature_high_state_topic": "temperature-high-state", + **SWAP_MODES, + }, + ), + ), + [("temperature-low-state", "18"), ("temperature-high-state", "25")], + [(21, 18, 25), (None, 18, 25)], + id="range_from_device", + ), + pytest.param( + help_custom_config( + climate.DOMAIN, + DEFAULT_CONFIG, + ({"temperature_state_topic": "temperature-state", **SWAP_MODES},), + ), + [("temperature-state", "19")], + [(19, None, None), (19, 21, 21)], + id="single_from_device", + ), + pytest.param( + help_custom_config( + climate.DOMAIN, + DEFAULT_CONFIG, + ({"mode_state_topic": "mode-state", **SWAP_MODES},), + ), + [], + [(21, 21, 21), (21, 21, 21)], + id="mode_from_device", + ), + ], +) +async def test_set_hvac_mode_keeps_setpoints( + hass: HomeAssistant, + mqtt_mock_entry: MqttMockHAClientGenerator, + messages: list[tuple[str, str]], + expected: list[tuple[float | None, float | None, float | None]], +) -> None: + """Test mode changes only swap setpoints that are optimistic and apply.""" + await mqtt_mock_entry() + for topic, payload in messages: + async_fire_mqtt_message(hass, topic, payload) + + await common.async_set_hvac_mode(hass, HVACMode.HEAT, ENTITY_CLIMATE) + assert _setpoints(hass) == expected[0] + + await common.async_set_hvac_mode(hass, HVACMode.HEAT_COOL, ENTITY_CLIMATE) + assert _setpoints(hass) == expected[1] + + @pytest.mark.parametrize( "hass_config", [ From 2d44b667a432b7e9d172bf87ea92c14e7a9ca555 Mon Sep 17 00:00:00 2001 From: Petro31 <35082313+Petro31@users.noreply.github.com> Date: Sat, 3 Oct 2026 07:00:01 -0400 Subject: [PATCH 052/356] Ensure template results are converted to string before validating against a list of strings. (#184123) --- homeassistant/components/template/climate.py | 16 ++++- homeassistant/components/template/light.py | 6 +- .../components/template/validators.py | 4 ++ tests/components/template/test_validators.py | 63 +++++++++++++++++++ 4 files changed, 86 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/template/climate.py b/homeassistant/components/template/climate.py index 082555df37d6..bbe982eb93af 100644 --- a/homeassistant/components/template/climate.py +++ b/homeassistant/components/template/climate.py @@ -508,7 +508,13 @@ class AbstractTemplateClimate(AbstractTemplateEntity, ClimateEntity, RestoreEnti self.setup_template( CONF_FAN_MODE, "_attr_fan_mode", - tcv.item_in_list(self, CONF_FAN_MODE, "_attr_fan_modes", CONF_FAN_MODES), + tcv.item_in_list( + self, + CONF_FAN_MODE, + "_attr_fan_modes", + CONF_FAN_MODES, + stringify_result=True, + ), ) self.add_assumed_attribute("_attr_fan_mode", CONF_FAN_MODE, SET_FAN_MODE_ACTION) @@ -521,7 +527,11 @@ class AbstractTemplateClimate(AbstractTemplateEntity, ClimateEntity, RestoreEnti CONF_SWING_MODE, "_attr_swing_mode", tcv.item_in_list( - self, CONF_SWING_MODE, "_attr_swing_modes", CONF_SWING_MODES + self, + CONF_SWING_MODE, + "_attr_swing_modes", + CONF_SWING_MODES, + stringify_result=True, ), ) self.add_assumed_attribute( @@ -541,6 +551,7 @@ class AbstractTemplateClimate(AbstractTemplateEntity, ClimateEntity, RestoreEnti CONF_SWING_HORIZONTAL_MODE, "_attr_swing_horizontal_modes", CONF_SWING_HORIZONTAL_MODES, + stringify_result=True, ), ) self.add_assumed_attribute( @@ -562,6 +573,7 @@ class AbstractTemplateClimate(AbstractTemplateEntity, ClimateEntity, RestoreEnti CONF_PRESET_MODE, "_attr_preset_modes", CONF_PRESET_MODES, + stringify_result=True, ), ) self.add_assumed_attribute( diff --git a/homeassistant/components/template/light.py b/homeassistant/components/template/light.py index f20bf37d8233..a5fc0b26a413 100644 --- a/homeassistant/components/template/light.py +++ b/homeassistant/components/template/light.py @@ -450,7 +450,11 @@ class AbstractTemplateLight(AbstractTemplateEntity, LightEntity, RestoreEntity): CONF_EFFECT, "_attr_effect", tcv.item_in_list( - self, "_attr_effect", "_attr_effect_list", CONF_EFFECT_LIST + self, + "_attr_effect", + "_attr_effect_list", + CONF_EFFECT_LIST, + stringify_result=True, ), ) diff --git a/homeassistant/components/template/validators.py b/homeassistant/components/template/validators.py index 7f946e54abb3..7f94ef603f5b 100644 --- a/homeassistant/components/template/validators.py +++ b/homeassistant/components/template/validators.py @@ -350,6 +350,7 @@ def item_in_list[T]( attribute: str, items: list[Any] | str | None, items_attribute: str | None = None, + stringify_result: bool = False, **kwargs: Any, ) -> Callable[[Any], Any | None]: """Assert the result of the template is an item inside a list. @@ -381,6 +382,9 @@ def item_in_list[T]( return None + if stringify_result: + result = str(result) + if result not in _items: log_validation_result_error( entity, diff --git a/tests/components/template/test_validators.py b/tests/components/template/test_validators.py index 018ebdcdc3a9..03b1ba61820e 100644 --- a/tests/components/template/test_validators.py +++ b/tests/components/template/test_validators.py @@ -893,6 +893,69 @@ async def test_item_in_list( check_for_error(value, expected, caplog.text, error.format(value)) +@pytest.mark.parametrize( + ("config", "error"), + [ + ( + {"default_entity_id": "test.test"}, + "Received invalid test state: {} for entity test.test, expected 1, 2, 3, 4", + ), + ( + {}, + "Received invalid state: {} for entity Test, expected 1, 2, 3, 4", + ), + ], +) +@pytest.mark.parametrize( + ("value", "expected"), + [ + ("1", "1"), + ("2", "2"), + ("3", "3"), + ("4", "4"), + (1, "1"), + (2, "2"), + (3, "3"), + (4, "4"), + *expect_none( + None, + "1.0", + "2.0", + "3.0", + "4.0", + "BEER", + "IS", + "good", + "al;dfj", + "unknown", + "unavailable", + "tru", # codespell:ignore tru + 83242.2342, + True, + False, + {}, + {"junk": "stuff"}, + {"junk"}, + ), + ], +) +async def test_string_item_in_list( + hass: HomeAssistant, + config: dict, + error: str, + value: Any, + expected: bool | None, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test result is in a list.""" + entity = create_test_entity(hass, config) + value = cv.item_in_list( + entity, "state", ["1", "2", "3", "4"], stringify_result=True + )(value) + assert value == expected + check_for_error(value, expected, caplog.text, error.format(value)) + + @pytest.mark.parametrize( ("config", "error"), [ From c9f1e5d3efb501d11223c4ee3c1a15335bdd6896 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Sat, 3 Oct 2026 15:58:30 +0200 Subject: [PATCH 053/356] Handle error while getting wan status in FRITZ!Box Tools (#184133) --- homeassistant/components/fritz/coordinator.py | 6 ++- tests/components/fritz/test_coordinator.py | 38 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/fritz/coordinator.py b/homeassistant/components/fritz/coordinator.py index 9ca71298ddab..fba6f9d254d0 100644 --- a/homeassistant/components/fritz/coordinator.py +++ b/homeassistant/components/fritz/coordinator.py @@ -269,7 +269,11 @@ class FritzBoxTools(DataUpdateCoordinator[UpdateCoordinatorDataType]): if self.fritz_status.has_wan_support: self.device_conn_type = self.fritz_status.connection_service - self.device_is_router = self.fritz_status.has_wan_enabled + try: + self.device_is_router = self.fritz_status.has_wan_enabled + except FritzActionError: + LOGGER.debug("assume that device has no wan enabled", exc_info=True) + self.device_is_router = False self.has_call_deflections = "X_AVM-DE_OnTel1" in self.connection.services diff --git a/tests/components/fritz/test_coordinator.py b/tests/components/fritz/test_coordinator.py index d5f99b2f42c0..1e16a1e41c72 100644 --- a/tests/components/fritz/test_coordinator.py +++ b/tests/components/fritz/test_coordinator.py @@ -11,6 +11,7 @@ from fritzconnection.core.exceptions import ( FritzConnectionException, FritzSecurityError, ) +from fritzconnection.lib.fritzstatus import FritzStatus from fritzconnection.lib.fritztools import ArgumentNamespace import pytest @@ -257,6 +258,43 @@ async def test_async_get_wan_access_success( assert await fritz_tools._async_get_wan_access("192.168.1.2") is True +async def test_setup_ignores_wan_enabled_action_error( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + caplog: pytest.LogCaptureFixture, + patch_fritzconnectioncached_globally: FritzConnectionMock, +) -> None: + """Test WAN capability check falls back when the router reports a call error.""" + + mock_config_entry.add_to_hass(hass) + coordinator = FritzBoxTools( + hass=hass, + config_entry=mock_config_entry, + password=mock_config_entry.data["password"], + port=mock_config_entry.data["port"], + ) + hass.data.setdefault(FRITZ_DATA_KEY, FritzData()) + + with ( + patch.object( + FritzStatus, + "has_wan_enabled", + new_callable=PropertyMock, + side_effect=FritzActionError("401 Invalid Action."), + ), + patch.object( + FritzStatus, + "has_wan_support", + new_callable=PropertyMock, + return_value=True, + ), + ): + await coordinator.async_setup() + + assert coordinator.device_is_router is False + assert "assume that device has no wan enabled" in caplog.text + + async def test_async_update_hosts_info_attributes_branches( fritz_tools, ) -> None: From 4c2f1dfed81a5f44f3cef3489bf6ce26bf07025d Mon Sep 17 00:00:00 2001 From: Robert Gering Date: Sat, 3 Oct 2026 13:09:37 -0700 Subject: [PATCH 054/356] Fix Hue temperature sensor crash on None value (#184148) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/hue/v2/sensor.py | 4 +++- tests/components/hue/test_sensor_v2.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/hue/v2/sensor.py b/homeassistant/components/hue/v2/sensor.py index 6f408c2959b2..41bce23e81a7 100644 --- a/homeassistant/components/hue/v2/sensor.py +++ b/homeassistant/components/hue/v2/sensor.py @@ -149,8 +149,10 @@ class HueTemperatureSensor(HueSensorBase): @property @override - def native_value(self) -> float: + def native_value(self) -> float | None: """Return the value reported by the sensor.""" + if self.resource.temperature.value is None: + return None return round(self.resource.temperature.value, 1) diff --git a/tests/components/hue/test_sensor_v2.py b/tests/components/hue/test_sensor_v2.py index ed86444933cc..028b4b2682ab 100644 --- a/tests/components/hue/test_sensor_v2.py +++ b/tests/components/hue/test_sensor_v2.py @@ -187,6 +187,24 @@ async def test_grouped_light_level_sensor( ) # Light level 30000 translates to 10^((30000-1)/10000) ≈ 999 lux +async def test_temperature_sensor_none_value( + hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType +) -> None: + """Test that temperature sensor handles None value without crashing.""" + for resource in v2_resources_test_data: + if resource.get("id") == "66466e14-d2fa-4b96-b2a0-e10de9cd8b8b": + resource["temperature"]["temperature"] = None + resource["temperature"]["temperature_valid"] = False + break + + await mock_bridge_v2.api.load_test_data(v2_resources_test_data) + await setup_platform(hass, mock_bridge_v2, Platform.SENSOR) + + sensor = hass.states.get("sensor.hue_motion_sensor_temperature") + assert sensor is not None + assert sensor.state == STATE_UNKNOWN + + async def test_light_level_sensor_none_value( hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType ) -> None: From dbf6356565b2bd23f89766e8e1a06d3735927a83 Mon Sep 17 00:00:00 2001 From: Simone Chemelli Date: Sun, 4 Oct 2026 14:48:28 +0200 Subject: [PATCH 055/356] Bump aiovodafone to 3.3.5 (#184207) --- homeassistant/components/vodafone_station/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/vodafone_station/manifest.json b/homeassistant/components/vodafone_station/manifest.json index abbc71958f20..1a59635bb8e6 100644 --- a/homeassistant/components/vodafone_station/manifest.json +++ b/homeassistant/components/vodafone_station/manifest.json @@ -8,5 +8,5 @@ "iot_class": "local_polling", "loggers": ["aiovodafone"], "quality_scale": "platinum", - "requirements": ["aiovodafone==3.3.2"] + "requirements": ["aiovodafone==3.3.5"] } diff --git a/requirements_all.txt b/requirements_all.txt index 81dee599a4b3..6b76c0661bf9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -477,7 +477,7 @@ aiovitesy==1.3.0 aiovlc==0.5.1 # homeassistant.components.vodafone_station -aiovodafone==3.3.2 +aiovodafone==3.3.5 # homeassistant.components.waqi aiowaqi==3.1.0 From 0a17b58ce852544486cdd196c9a336d37dba5daa Mon Sep 17 00:00:00 2001 From: Thomas <10558666+mosandlt@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:23:27 +0200 Subject: [PATCH 056/356] bosch_shc: bump boschshcpy to 0.6.15 (#184220) --- homeassistant/components/bosch_shc/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/bosch_shc/manifest.json b/homeassistant/components/bosch_shc/manifest.json index f0233bc4a95a..b39a199bb3c4 100644 --- a/homeassistant/components/bosch_shc/manifest.json +++ b/homeassistant/components/bosch_shc/manifest.json @@ -8,7 +8,7 @@ "integration_type": "hub", "iot_class": "local_push", "loggers": ["boschshcpy"], - "requirements": ["boschshcpy==0.6.13"], + "requirements": ["boschshcpy==0.6.15"], "zeroconf": [ { "name": "bosch shc*", diff --git a/requirements_all.txt b/requirements_all.txt index 6b76c0661bf9..dd7ea144b063 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -724,7 +724,7 @@ bond-async==0.2.1 bosch-alarm-mode2==0.4.11 # homeassistant.components.bosch_shc -boschshcpy==0.6.13 +boschshcpy==0.6.15 # homeassistant.components.amazon_polly # homeassistant.components.route53 From 956b47ae41638df76d75e69ced5bd32681fad58a Mon Sep 17 00:00:00 2001 From: Jan Bouwhuis Date: Sun, 4 Oct 2026 21:05:16 +0200 Subject: [PATCH 057/356] Improve Alexa debug logging (#184241) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/alexa/handlers.py | 251 +++++++++++++----- homeassistant/components/alexa/smart_home.py | 9 +- .../components/alexa/state_report.py | 21 +- .../components/alexa/test_smart_home_http.py | 36 +++ 4 files changed, 251 insertions(+), 66 deletions(-) diff --git a/homeassistant/components/alexa/handlers.py b/homeassistant/components/alexa/handlers.py index abf02137a632..8ae3a8f5ac2f 100644 --- a/homeassistant/components/alexa/handlers.py +++ b/homeassistant/components/alexa/handlers.py @@ -78,6 +78,7 @@ from homeassistant.components.water_heater import ( WaterHeaterCapabilityAttribute, ) from homeassistant.const import ( + ATTR_CODE, ATTR_ENTITY_ID, ATTR_TEMPERATURE, SERVICE_ALARM_ARM_AWAY, @@ -103,6 +104,7 @@ from homeassistant.const import ( UnitOfTemperature, ) from homeassistant.helpers import network +from homeassistant.helpers.redact import async_redact_data from homeassistant.util import color as color_util, dt as dt_util from homeassistant.util.decorator import Registry from homeassistant.util.unit_conversion import ( @@ -135,6 +137,7 @@ from .state_report import AlexaDirective, AlexaResponse, async_enable_proactive_ _LOGGER = logging.getLogger(__name__) DIRECTIVE_NOT_SUPPORTED = "Entity does not support directive" +TO_REDACT_SERVICE_DATA = {ATTR_CODE} MIN_MAX_TEMP = { CLIMATE_DOMAIN: { @@ -161,6 +164,30 @@ HANDLERS: Registry[ ] = Registry() +async def _async_call_service( + hass: ha.HomeAssistant, + directive: AlexaDirective, + domain: str, + service: str, + service_data: dict[str, Any], + *, + blocking: bool, + context: ha.Context, +) -> None: + """Call an action and log it with the Alexa directive that triggered it.""" + _LOGGER.debug( + "Calling action %s.%s for Alexa directive %s.%s with data: %s", + domain, + service, + directive.namespace, + directive.name, + async_redact_data(service_data, TO_REDACT_SERVICE_DATA), + ) + await hass.services.async_call( + domain, service, service_data, blocking=blocking, context=context + ) + + @HANDLERS.register(("Alexa.Discovery", "Discover")) async def async_api_discovery( hass: ha.HomeAssistant, @@ -257,7 +284,9 @@ async def async_api_turn_on( if not supported & power_features: service = media_player.SERVICE_MEDIA_PLAY - await hass.services.async_call( + await _async_call_service( + hass, + directive, domain, service, {ATTR_ENTITY_ID: entity.entity_id}, @@ -310,7 +339,9 @@ async def async_api_turn_off( if not supported & power_features: service = media_player.SERVICE_MEDIA_STOP - await hass.services.async_call( + await _async_call_service( + hass, + directive, domain, service, {ATTR_ENTITY_ID: entity.entity_id}, @@ -332,7 +363,9 @@ async def async_api_set_brightness( entity = directive.entity brightness = int(directive.payload["brightness"]) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id, light.ATTR_BRIGHTNESS_PCT: brightness}, @@ -355,7 +388,9 @@ async def async_api_adjust_brightness( brightness_delta = int(directive.payload["brightnessDelta"]) # set brightness - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, { @@ -384,7 +419,9 @@ async def async_api_set_color( float(directive.payload["color"]["brightness"]), ) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id, light.ATTR_RGB_COLOR: rgb}, @@ -406,7 +443,9 @@ async def async_api_set_color_temperature( entity = directive.entity kelvin = int(directive.payload["colorTemperatureInKelvin"]) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id, light.ATTR_COLOR_TEMP_KELVIN: kelvin}, @@ -432,7 +471,9 @@ async def async_api_decrease_color_temp( ) value = max(min_kelvin, current - 500) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id, light.ATTR_COLOR_TEMP_KELVIN: value}, @@ -458,7 +499,9 @@ async def async_api_increase_color_temp( ) value = min(max_kelvin, current + 500) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_TURN_ON, {ATTR_ENTITY_ID: entity.entity_id, light.ATTR_COLOR_TEMP_KELVIN: value}, @@ -486,7 +529,9 @@ async def async_api_activate( elif domain == INPUT_BUTTON_DOMAIN: service = input_button.SERVICE_PRESS - await hass.services.async_call( + await _async_call_service( + hass, + directive, domain, service, {ATTR_ENTITY_ID: entity.entity_id}, @@ -515,7 +560,9 @@ async def async_api_deactivate( entity = directive.entity domain = entity.domain - await hass.services.async_call( + await _async_call_service( + hass, + directive, domain, SERVICE_TURN_OFF, {ATTR_ENTITY_ID: entity.entity_id}, @@ -542,7 +589,9 @@ async def async_api_lock( ) -> AlexaResponse: """Process a lock request.""" entity = directive.entity - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_LOCK, {ATTR_ENTITY_ID: entity.entity_id}, @@ -591,7 +640,9 @@ async def async_api_unlock( raise AlexaInvalidDirectiveError(msg) entity = directive.entity - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_UNLOCK, {ATTR_ENTITY_ID: entity.entity_id}, @@ -623,8 +674,14 @@ async def async_api_set_volume( media_player.ATTR_MEDIA_VOLUME_LEVEL: volume, } - await hass.services.async_call( - entity.domain, SERVICE_VOLUME_SET, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_VOLUME_SET, + data, + blocking=False, + context=context, ) return directive.response() @@ -671,7 +728,9 @@ async def async_api_select_input( media_player.ATTR_INPUT_SOURCE: media_input, } - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, media_player.SERVICE_SELECT_SOURCE, data, @@ -710,8 +769,14 @@ async def async_api_adjust_volume( media_player.ATTR_MEDIA_VOLUME_LEVEL: volume, } - await hass.services.async_call( - entity.domain, SERVICE_VOLUME_SET, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_VOLUME_SET, + data, + blocking=False, + context=context, ) return directive.response() @@ -748,8 +813,14 @@ async def async_api_adjust_volume_step( data: dict[str, Any] = {ATTR_ENTITY_ID: entity.entity_id} for _ in range(abs(volume_int)): - await hass.services.async_call( - entity.domain, service_volume, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + service_volume, + data, + blocking=False, + context=context, ) return directive.response() @@ -771,8 +842,14 @@ async def async_api_set_mute( media_player.ATTR_MEDIA_VOLUME_MUTED: mute, } - await hass.services.async_call( - entity.domain, SERVICE_VOLUME_MUTE, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_VOLUME_MUTE, + data, + blocking=False, + context=context, ) return directive.response() @@ -789,8 +866,14 @@ async def async_api_play( entity = directive.entity data: dict[str, Any] = {ATTR_ENTITY_ID: entity.entity_id} - await hass.services.async_call( - entity.domain, SERVICE_MEDIA_PLAY, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_MEDIA_PLAY, + data, + blocking=False, + context=context, ) return directive.response() @@ -807,8 +890,14 @@ async def async_api_pause( entity = directive.entity data: dict[str, Any] = {ATTR_ENTITY_ID: entity.entity_id} - await hass.services.async_call( - entity.domain, SERVICE_MEDIA_PAUSE, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_MEDIA_PAUSE, + data, + blocking=False, + context=context, ) return directive.response() @@ -835,16 +924,28 @@ async def async_api_stop( } await asyncio.gather( *( - hass.services.async_call( - entity.domain, service, data, blocking=False, context=context + _async_call_service( + hass, + directive, + entity.domain, + service, + data, + blocking=False, + context=context, ) for feature, service in feature_services.items() if feature & supported ) ) else: - await hass.services.async_call( - entity.domain, SERVICE_MEDIA_STOP, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_MEDIA_STOP, + data, + blocking=False, + context=context, ) return directive.response() @@ -861,8 +962,14 @@ async def async_api_next( entity = directive.entity data: dict[str, Any] = {ATTR_ENTITY_ID: entity.entity_id} - await hass.services.async_call( - entity.domain, SERVICE_MEDIA_NEXT_TRACK, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_MEDIA_NEXT_TRACK, + data, + blocking=False, + context=context, ) return directive.response() @@ -879,7 +986,9 @@ async def async_api_previous( entity = directive.entity data: dict[str, Any] = {ATTR_ENTITY_ID: entity.entity_id} - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, SERVICE_MEDIA_PREVIOUS_TRACK, data, @@ -967,7 +1076,9 @@ async def async_api_set_target_temp( service = SERVICE_SET_TEMPERATURE[domain] - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, service, data, @@ -1059,7 +1170,9 @@ async def async_api_adjust_target_temp( service = SERVICE_SET_TEMPERATURE[domain] - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, service, data, @@ -1136,8 +1249,8 @@ async def async_api_set_thermostat_mode( data[climate.ATTR_HVAC_MODE] = ha_mode response = directive.response() - await hass.services.async_call( - CLIMATE_DOMAIN, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, CLIMATE_DOMAIN, service, data, blocking=False, context=context ) response.add_context_property( { @@ -1193,8 +1306,8 @@ async def async_api_arm( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - entity.domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, entity.domain, service, data, blocking=False, context=context ) # return 0 until alarm integration supports an exit delay @@ -1237,10 +1350,16 @@ async def async_api_disarm( if "authorization" in payload: value = payload["authorization"]["value"] if payload["authorization"]["type"] == "FOUR_DIGIT_PIN": - data["code"] = value + data[ATTR_CODE] = value - await hass.services.async_call( - entity.domain, SERVICE_ALARM_DISARM, data, blocking=True, context=context + await _async_call_service( + hass, + directive, + entity.domain, + SERVICE_ALARM_DISARM, + data, + blocking=True, + context=context, ) response.add_context_property( @@ -1362,8 +1481,8 @@ async def async_api_set_mode( if not service: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, domain, service, data, blocking=False, context=context ) response = directive.response() @@ -1426,8 +1545,8 @@ async def async_api_toggle_on( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, domain, service, data, blocking=False, context=context ) response = directive.response() @@ -1465,8 +1584,8 @@ async def async_api_toggle_off( fan.ATTR_OSCILLATING: False, } - await hass.services.async_call( - domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, domain, service, data, blocking=False, context=context ) response = directive.response() @@ -1581,8 +1700,8 @@ async def async_api_set_range( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, domain, service, data, blocking=False, context=context ) response = directive.response() @@ -1751,8 +1870,8 @@ async def async_api_adjust_range( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, domain, service, data, blocking=False, context=context ) response = directive.response() @@ -1804,7 +1923,9 @@ async def async_api_changechannel( media_player.ATTR_MEDIA_CONTENT_TYPE: (media_player.MediaType.CHANNEL), } - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, media_player.SERVICE_PLAY_MEDIA, data, @@ -1844,8 +1965,14 @@ async def async_api_skipchannel( service_media = SERVICE_MEDIA_NEXT_TRACK for _ in range(abs(channel)): - await hass.services.async_call( - entity.domain, service_media, data, blocking=False, context=context + await _async_call_service( + hass, + directive, + entity.domain, + service_media, + data, + blocking=False, + context=context, ) response = directive.response() @@ -1892,7 +2019,9 @@ async def async_api_seek( media_player.ATTR_MEDIA_SEEK_POSITION: seek_position, } - await hass.services.async_call( + await _async_call_service( + hass, + directive, MEDIA_PLAYER_DOMAIN, media_player.SERVICE_MEDIA_SEEK, data, @@ -1932,7 +2061,9 @@ async def async_api_set_eq_mode( msg = f"failed to map sound mode {mode} to a mode on {entity.entity_id}" raise AlexaInvalidValueError(msg) - await hass.services.async_call( + await _async_call_service( + hass, + directive, entity.domain, media_player.SERVICE_SELECT_SOUND_MODE, data, @@ -1980,8 +2111,8 @@ async def async_api_hold( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - entity.domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, entity.domain, service, data, blocking=False, context=context ) return directive.response() @@ -2007,8 +2138,8 @@ async def async_api_resume( else: raise AlexaInvalidDirectiveError(DIRECTIVE_NOT_SUPPORTED) - await hass.services.async_call( - entity.domain, service, data, blocking=False, context=context + await _async_call_service( + hass, directive, entity.domain, service, data, blocking=False, context=context ) return directive.response() diff --git a/homeassistant/components/alexa/smart_home.py b/homeassistant/components/alexa/smart_home.py index 04f836b7d4aa..ad71680a4701 100644 --- a/homeassistant/components/alexa/smart_home.py +++ b/homeassistant/components/alexa/smart_home.py @@ -22,6 +22,7 @@ from .auth import Auth from .config import AbstractConfig from .const import ( API_DIRECTIVE, + API_ENDPOINT, API_HEADER, CONF_ENDPOINT, CONF_ENTITY_CONFIG, @@ -165,8 +166,14 @@ class SmartHomeView(HomeAssistantView): message: dict[str, Any] = await request.json() if _LOGGER.isEnabledFor(logging.DEBUG): + endpoint_id = ( + message.get(API_DIRECTIVE, {}).get(API_ENDPOINT, {}).get("endpointId") + ) _LOGGER.debug( - "Received Alexa Smart Home request: %s", + "Received Alexa Smart Home request for entity %s: %s", + endpoint_id.replace("#", ".") + if isinstance(endpoint_id, str) + else endpoint_id, async_redact_auth_data(message), ) diff --git a/homeassistant/components/alexa/state_report.py b/homeassistant/components/alexa/state_report.py index 70ebae4fa1ac..cfa6ad2fe2a5 100644 --- a/homeassistant/components/alexa/state_report.py +++ b/homeassistant/components/alexa/state_report.py @@ -109,7 +109,8 @@ class AlexaDirective: Will raise AlexaInvalidEndpointError if the endpoint in the request is malformed or nonexistent. """ - _endpoint_id: str = self._directive[API_ENDPOINT]["endpointId"] + # A malformed request can contain a non-string endpointId + _endpoint_id = str(self._directive[API_ENDPOINT]["endpointId"]) self.entity_id = _endpoint_id.replace("#", ".") entity: State | None = hass.states.get(self.entity_id) @@ -293,6 +294,7 @@ async def async_enable_proactive_mode( return old_extra_arg is not None and old_extra_arg != new_extra_arg checker = await create_checker(hass, DOMAIN, extra_significant_check) + logged_exposure: dict[str, bool] = {} @callback def _async_entity_state_filter(data: EventStateChangedData) -> bool: @@ -306,11 +308,20 @@ async def async_enable_proactive_mode( return False changed_entity = data["entity_id"] - if not smart_home_config.should_expose(changed_entity): - _LOGGER.debug("Not exposing %s because filtered by config", changed_entity) - return False + should_expose = smart_home_config.should_expose(changed_entity) + if ( + _LOGGER.isEnabledFor(logging.DEBUG) + and logged_exposure.get(changed_entity) != should_expose + ): + logged_exposure[changed_entity] = should_expose + if should_expose: + _LOGGER.debug("Exposing %s", changed_entity) + else: + _LOGGER.debug( + "Not exposing %s because filtered by config", changed_entity + ) - return True + return should_expose async def _async_entity_state_listener( event_: Event[EventStateChangedData], diff --git a/tests/components/alexa/test_smart_home_http.py b/tests/components/alexa/test_smart_home_http.py index 20d9b30dda54..9a0e9b05b522 100644 --- a/tests/components/alexa/test_smart_home_http.py +++ b/tests/components/alexa/test_smart_home_http.py @@ -71,3 +71,39 @@ async def test_http_api_disabled( config = {"alexa": {}} response = await do_http_discovery(config, hass, hass_client) assert response.status == HTTPStatus.NOT_FOUND + + +@pytest.mark.parametrize( + ("endpoint_id", "logged_entity_id"), + [ + pytest.param("light#kitchen", "light.kitchen", id="string"), + pytest.param(123, "123", id="non_string"), + ], +) +async def test_http_api_logs_entity_id( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + hass_client: ClientSessionGenerator, + endpoint_id: str | int, + logged_entity_id: str, +) -> None: + """Test the entity ID is logged and an unknown endpoint returns an error.""" + await async_setup_component(hass, DOMAIN, {"alexa": {"smart_home": None}}) + http_client = await hass_client() + request = get_new_request("Alexa.PowerController", "TurnOn", "light#kitchen") + request["directive"]["endpoint"]["endpointId"] = endpoint_id + + with caplog.at_level(logging.DEBUG): + response = await http_client.post( + smart_home.SMART_HOME_HTTP_ENDPOINT, + data=json.dumps(request), + headers={"content-type": CONTENT_TYPE_JSON}, + ) + response_data = await response.json() + + assert ( + f"Received Alexa Smart Home request for entity {logged_entity_id}:" + in caplog.text + ) + assert response_data["event"]["header"]["name"] == "ErrorResponse" + assert response_data["event"]["payload"]["type"] == "NO_SUCH_ENDPOINT" From 72ca4c89f09b5cedb87344441606f03dce73fdac Mon Sep 17 00:00:00 2001 From: Crocmagnon Date: Mon, 5 Oct 2026 13:07:28 +0200 Subject: [PATCH 058/356] Filter removed LLM APIs when reconfiguring OVHcloud AI Endpoints (#184249) --- .../ovhcloud_ai_endpoints/config_flow.py | 13 +++-- .../ovhcloud_ai_endpoints/test_config_flow.py | 55 +++++++++++++++++++ 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/ovhcloud_ai_endpoints/config_flow.py b/homeassistant/components/ovhcloud_ai_endpoints/config_flow.py index 6a8d38f7f3c0..b25757d470fd 100644 --- a/homeassistant/components/ovhcloud_ai_endpoints/config_flow.py +++ b/homeassistant/components/ovhcloud_ai_endpoints/config_flow.py @@ -187,6 +187,14 @@ class ConversationFlowHandler(ConfigSubentryFlow): SelectOptionDict(label=api.name, value=api.id) for api in llm.async_get_apis(self.hass) ] + valid_api_ids = {api["value"] for api in hass_apis} + selected_apis = [ + api + for api in existing.get( + CONF_LLM_HASS_API, RECOMMENDED_CONVERSATION_OPTIONS[CONF_LLM_HASS_API] + ) + if api in valid_api_ids + ] return self.async_show_form( step_id="reconfigure", data_schema=probatio.Schema( @@ -202,10 +210,7 @@ class ConversationFlowHandler(ConfigSubentryFlow): ): TemplateSelector(), probatio.Optional( CONF_LLM_HASS_API, - default=existing.get( - CONF_LLM_HASS_API, - RECOMMENDED_CONVERSATION_OPTIONS[CONF_LLM_HASS_API], - ), + default=selected_apis, ): SelectSelector( SelectSelectorConfig(options=hass_apis, multiple=True) ), diff --git a/tests/components/ovhcloud_ai_endpoints/test_config_flow.py b/tests/components/ovhcloud_ai_endpoints/test_config_flow.py index c342c96378a4..6b8d7bece76d 100644 --- a/tests/components/ovhcloud_ai_endpoints/test_config_flow.py +++ b/tests/components/ovhcloud_ai_endpoints/test_config_flow.py @@ -474,6 +474,61 @@ async def test_reconfigure_conversation_agent( assert subentry.data[CONF_MODEL] == "Meta-Llama-3_3-70B-Instruct" +@pytest.mark.parametrize( + ("stored_apis", "expected_apis"), + [ + pytest.param(["assist"], ["assist"], id="valid-api"), + pytest.param(["mcp-deleted-entry"], [], id="removed-api"), + pytest.param( + ["assist", "mcp-deleted-entry"], ["assist"], id="valid-and-removed-api" + ), + ], +) +async def test_reconfigure_conversation_agent_filters_removed_llm_api( + hass: HomeAssistant, + mock_openai_client: AsyncMock, + mock_config_entry: MockConfigEntry, + stored_apis: list[str], + expected_apis: list[str], +) -> None: + """Test reconfiguration drops unavailable LLM APIs from the form default.""" + await setup_integration(hass, mock_config_entry, mock_openai_client) + + subentry = next(iter(mock_config_entry.subentries.values())) + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={**subentry.data, CONF_LLM_HASS_API: stored_apis}, + ) + await hass.async_block_till_done() + + result = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry.subentry_id + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "reconfigure" + + schema = result["data_schema"].schema + key = next(k for k in schema if k == CONF_LLM_HASS_API) + assert [option["value"] for option in schema[key].config["options"]] == ["assist"] + assert key.default() == expected_apis + + # An unchanged form submission must pass the selector's validation. + user_input = result["data_schema"]( + {CONF_PROMPT: subentry.data[CONF_PROMPT], CONF_LLM_HASS_API: key.default()} + ) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], user_input + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + updated_subentry = mock_config_entry.subentries[subentry.subentry_id] + assert updated_subentry.data[CONF_LLM_HASS_API] == expected_apis + assert updated_subentry.data[CONF_PROMPT] == subentry.data[CONF_PROMPT] + assert updated_subentry.data[CONF_MODEL] == subentry.data[CONF_MODEL] + + async def test_reconfigure_conversation_agent_clears_llm_api( hass: HomeAssistant, mock_openai_client: AsyncMock, From c79b2bf70e13a7cb9fa6f46dac762bb7e5401ba9 Mon Sep 17 00:00:00 2001 From: Jason Hunter Date: Mon, 5 Oct 2026 10:36:20 -0400 Subject: [PATCH 059/356] Correct OAuth discovery metadata for public clients (#184254) --- homeassistant/components/auth/login_flow.py | 5 ++++ tests/components/auth/test_login_flow.py | 27 +++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/homeassistant/components/auth/login_flow.py b/homeassistant/components/auth/login_flow.py index 59a3e3d20bec..b5134ce5205c 100644 --- a/homeassistant/components/auth/login_flow.py +++ b/homeassistant/components/auth/login_flow.py @@ -121,6 +121,7 @@ class WellKnownOAuthInfoView(HomeAssistantView): """View to host the OAuth2 information.""" requires_auth = False + cors_allowed = True url = "/.well-known/oauth-authorization-server" name = "well-known/oauth-authorization-server" @@ -138,6 +139,9 @@ class WellKnownOAuthInfoView(HomeAssistantView): "authorization_endpoint": f"{url_prefix}/auth/authorize", "token_endpoint": f"{url_prefix}/auth/token", "revocation_endpoint": f"{url_prefix}/auth/revoke", + "grant_types_supported": ["authorization_code", "refresh_token"], + "token_endpoint_auth_methods_supported": ["none"], + "revocation_endpoint_auth_methods_supported": ["none"], # Home Assistant accepts URL-based client_ids via IndieAuth without # prior registration, and discovers allowed redirect URIs from link # tags or a Client ID Metadata Document served at the client_id URL. @@ -162,6 +166,7 @@ class WellKnownProtectedResourceView(HomeAssistantView): """View to host the OAuth2 Protected Resource Metadata per RFC9728.""" requires_auth = False + cors_allowed = True url = "/.well-known/oauth-protected-resource" name = "well-known/oauth-protected-resource" diff --git a/tests/components/auth/test_login_flow.py b/tests/components/auth/test_login_flow.py index bf386c212628..96cefdf7910f 100644 --- a/tests/components/auth/test_login_flow.py +++ b/tests/components/auth/test_login_flow.py @@ -425,6 +425,9 @@ async def test_well_known_auth_info( "authorization_endpoint": f"{expected_url_prefix}/auth/authorize", "token_endpoint": f"{expected_url_prefix}/auth/token", "revocation_endpoint": f"{expected_url_prefix}/auth/revoke", + "grant_types_supported": ["authorization_code", "refresh_token"], + "token_endpoint_auth_methods_supported": ["none"], + "revocation_endpoint_auth_methods_supported": ["none"], "client_id_metadata_document_supported": True, "code_challenge_methods_supported": ["S256"], "response_types_supported": ["code"], @@ -564,3 +567,27 @@ async def test_login_flow_pkce_validation( assert resp.status == HTTPStatus.BAD_REQUEST result = await resp.json() assert expected_message in result["message"] + + +@pytest.mark.parametrize( + "path", + [ + pytest.param( + "/.well-known/oauth-authorization-server", id="authorization-server" + ), + pytest.param("/.well-known/oauth-protected-resource", id="protected-resource"), + ], +) +async def test_well_known_auth_info_allows_cors( + hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, path: str +) -> None: + """Test browser clients can discover authorization server capabilities.""" + client = await async_setup_auth(hass, aiohttp_client, setup_api=True) + + resp = await client.get( + path, + headers={"origin": "https://client.example"}, + ) + + assert resp.status == HTTPStatus.OK + assert resp.headers["Access-Control-Allow-Origin"] == "https://client.example" From ec03bdf9a7a8e502e042f6a72b1b78bd9a079a22 Mon Sep 17 00:00:00 2001 From: Sridhar Neti Date: Mon, 5 Oct 2026 07:03:05 -0500 Subject: [PATCH 060/356] Fix Hanna sensors showing readings from another device (#184258) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/hanna/coordinator.py | 2 +- tests/components/hanna/test_sensor.py | 47 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 tests/components/hanna/test_sensor.py diff --git a/homeassistant/components/hanna/coordinator.py b/homeassistant/components/hanna/coordinator.py index 688911b20ee0..2b71e0d9cb16 100644 --- a/homeassistant/components/hanna/coordinator.py +++ b/homeassistant/components/hanna/coordinator.py @@ -50,7 +50,7 @@ class HannaDataCoordinator(DataUpdateCoordinator[dict[str, Any]]): def get_parameters(self) -> list[dict[str, Any]]: """Get all parameters from the sensor data.""" - return self.api_client.parameters + return self.data.get("messages", {}).get("parameters", []) def get_parameter_value(self, key: str) -> Any: """Get the value for a specific parameter.""" diff --git a/tests/components/hanna/test_sensor.py b/tests/components/hanna/test_sensor.py new file mode 100644 index 000000000000..3c882f8a7fbd --- /dev/null +++ b/tests/components/hanna/test_sensor.py @@ -0,0 +1,47 @@ +"""Tests for the Hanna Instruments sensor platform.""" + +from typing import Any +from unittest.mock import MagicMock + +from homeassistant.const import Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from tests.common import MockConfigEntry + +DEVICE_READINGS = { + "pool": {"DID": "pool", "messages": {"parameters": [{"name": "ph", "value": 7.2}]}}, + "spa": {"DID": "spa", "messages": {"parameters": [{"name": "ph", "value": 7.8}]}}, +} + + +async def test_sensors_use_own_device_readings( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_hanna_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test each device's sensors show that device's readings.""" + mock_hanna_client.get_devices.return_value = [ + {"DID": "pool", "name": "Pool"}, + {"DID": "spa", "name": "Spa"}, + ] + + def get_last_device_reading(device_id: str) -> dict[str, Any]: + # The real client keeps only the most recently fetched device's parameters. + readings = DEVICE_READINGS[device_id] + mock_hanna_client.parameters = readings["messages"]["parameters"] + return readings + + mock_hanna_client.get_last_device_reading.side_effect = get_last_device_reading + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + pool_ph = entity_registry.async_get_entity_id(Platform.SENSOR, "hanna", "pool_ph") + spa_ph = entity_registry.async_get_entity_id(Platform.SENSOR, "hanna", "spa_ph") + assert pool_ph is not None + assert spa_ph is not None + assert hass.states.get(pool_ph).state == "7.2" + assert hass.states.get(spa_ph).state == "7.8" From b837e4047789c8a0e8e17a67b4afdf7ce352cd23 Mon Sep 17 00:00:00 2001 From: Christophe Gagnier Date: Mon, 5 Oct 2026 02:48:34 -0400 Subject: [PATCH 061/356] Bump python-hotspring to 3.1.0 (#184271) Co-authored-by: Moustachauve <2206577+Moustachauve@users.noreply.github.com> --- homeassistant/components/hotspring/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/hotspring/manifest.json b/homeassistant/components/hotspring/manifest.json index 300964d8f8cc..df1465e2fdff 100644 --- a/homeassistant/components/hotspring/manifest.json +++ b/homeassistant/components/hotspring/manifest.json @@ -8,7 +8,7 @@ "iot_class": "local_polling", "loggers": ["hotspring"], "quality_scale": "platinum", - "requirements": ["python-hotspring==3.0.1"], + "requirements": ["python-hotspring==3.1.0"], "zeroconf": [ { "name": "watkins_spa*", diff --git a/requirements_all.txt b/requirements_all.txt index dd7ea144b063..220df87d5fde 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2741,7 +2741,7 @@ python-homeassistant-analytics==0.9.0 python-homewizard-energy==10.2.0 # homeassistant.components.hotspring -python-hotspring==3.0.1 +python-hotspring==3.1.0 # homeassistant.components.hp_ilo python-hpilo==4.4.3 From efd4742d87857fe641abd31d709ba219e95bb37c Mon Sep 17 00:00:00 2001 From: tronikos Date: Mon, 5 Oct 2026 03:00:44 -0700 Subject: [PATCH 062/356] Send thinking level for Gemma 4 models in Google Generative AI (#184275) Co-authored-by: Franck Nijhof --- .../entity.py | 21 ++++++++++-- .../test_conversation.py | 33 ++++++++++++++++++- 2 files changed, 51 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/google_generative_ai_conversation/entity.py b/homeassistant/components/google_generative_ai_conversation/entity.py index 08f60d0cb8fd..547b3d41ab3e 100644 --- a/homeassistant/components/google_generative_ai_conversation/entity.py +++ b/homeassistant/components/google_generative_ai_conversation/entity.py @@ -110,6 +110,12 @@ def _is_gemini_3_model(model: str) -> bool: return name.startswith("gemini-3") +def _is_gemma_4_model(model: str) -> bool: + """Check if the model is a Gemma 4 series model.""" + name = model.removeprefix("models/") + return name.startswith("gemma-4") + + def _create_thinking_config( model: str, thinking_budget: int, @@ -123,10 +129,21 @@ def _create_thinking_config( -1 = automatic (default behavior), 0 = disable thinking, >0 = custom token budget (Gemini 2.5 only). - thinking_level: The user-configured thinking level for Gemini 3 models: - "auto" = automatic (default), "minimal", "low", "medium", "high". + thinking_level: The user-configured thinking level for Gemini 3 and + Gemma 4 models: "auto" = automatic (default), "minimal", "low", + "medium", "high". """ + if _is_gemma_4_model(model): + # Gemma 4 only supports the minimal and high thinking levels + gemma_level_map: dict[str, ThinkingLevel] = { + "minimal": ThinkingLevel.MINIMAL, + "high": ThinkingLevel.HIGH, + } + if thinking_level and thinking_level in gemma_level_map: + return ThinkingConfig(thinking_level=gemma_level_map[thinking_level]) + return None + if not _is_thinking_model(model): return None diff --git a/tests/components/google_generative_ai_conversation/test_conversation.py b/tests/components/google_generative_ai_conversation/test_conversation.py index 046387d3772b..e25f1a68fbe2 100644 --- a/tests/components/google_generative_ai_conversation/test_conversation.py +++ b/tests/components/google_generative_ai_conversation/test_conversation.py @@ -4,7 +4,7 @@ import datetime from unittest.mock import AsyncMock, patch from freezegun import freeze_time -from google.genai.types import GenerateContentResponse, ThinkingLevel +from google.genai.types import GenerateContentResponse, ThinkingConfig, ThinkingLevel import pytest from syrupy.assertion import SnapshotAssertion @@ -881,6 +881,37 @@ def test_create_thinking_config_gemini3_auto( assert result.thinking_level is None +@pytest.mark.parametrize( + ("model", "thinking_level", "expected"), + [ + pytest.param( + "models/gemma-4-26b-a4b-it", + "minimal", + ThinkingConfig(thinking_level=ThinkingLevel.MINIMAL), + id="minimal", + ), + pytest.param( + "gemma-4-31b-it", + "high", + ThinkingConfig(thinking_level=ThinkingLevel.HIGH), + id="high", + ), + # The API rejects any other thinking level for Gemma 4 + pytest.param("models/gemma-4-31b-it", "low", None, id="low"), + pytest.param("models/gemma-4-31b-it", "medium", None, id="medium"), + pytest.param("models/gemma-4-31b-it", "auto", None, id="auto"), + pytest.param("models/gemma-4-31b-it", None, None, id="unset"), + ], +) +def test_create_thinking_config_gemma4( + model: str, + thinking_level: str | None, + expected: ThinkingConfig | None, +) -> None: + """Test Gemma 4 models only send the supported thinking levels.""" + assert _create_thinking_config(model, 0, thinking_level) == expected + + @pytest.mark.parametrize( ("model", "thinking_budget", "expected_budget"), [ From b743192e9dd8afbc266078a3636974e67b942677 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Mon, 5 Oct 2026 09:20:33 +0200 Subject: [PATCH 063/356] Exclude the empty backup_restore fixture from check-json (#184289) Co-authored-by: Claude Opus 5 --- .pre-commit-config.yaml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 7870cfbc7270..80f5066ce5c0 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -30,7 +30,12 @@ repos: - id: check-executables-have-shebangs stages: [manual] - id: check-json - exclude: (.vscode|.devcontainer) + exclude: | + (?x)^( + .vscode| + .devcontainer| + tests/fixtures/core/backup_restore/restore1.json + ) - id: no-commit-to-branch args: - --branch=dev From 7daab281790247ae634a752a4d1290d7b6bfeb5c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Mon, 5 Oct 2026 14:44:28 +0200 Subject: [PATCH 064/356] Stop asking a SolarEdge inverter about blocks it never answers (#184290) --- .../components/solaredge_modbus/__init__.py | 14 +- .../components/solaredge_modbus/const.py | 9 ++ .../solaredge_modbus/coordinator.py | 8 ++ .../components/solaredge_modbus/manifest.json | 2 +- requirements_all.txt | 2 +- .../components/solaredge_modbus/test_init.py | 123 +++++++++++++++++- 6 files changed, 153 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/solaredge_modbus/__init__.py b/homeassistant/components/solaredge_modbus/__init__.py index 28f426f35a02..004c9a35e19e 100644 --- a/homeassistant/components/solaredge_modbus/__init__.py +++ b/homeassistant/components/solaredge_modbus/__init__.py @@ -33,6 +33,7 @@ from homeassistant.helpers.event import async_track_time_interval from .const import ( ATTACHMENT_SCAN_INTERVAL, CONF_UNIT_ID, + DISCOVERY_SUBSYSTEMS, DOMAIN, LOGGER, SCAN_INTERVAL, @@ -237,13 +238,24 @@ async def _async_reload_when_attachments_change( return try: - probed = await SolarEdge.async_probe(unit) + probed = await SolarEdge.async_probe( + unit, assume_absent=entry.runtime_data.settled_silent_blocks + ) except SolarEdgeError as err: # Nothing to conclude from a probe that did not finish; the coordinators # report an inverter that stopped answering. LOGGER.debug("%s: could not probe for attached hardware: %s", entry.title, err) return + # Silent while setting up and silent again here. A block that answered at + # setup and merely blipped now is not settled, or one timeout would hide a + # later removal until the entry loads again. Blocks that finding hardware + # depends on are never settled: picking up what was wired in later is what + # asking is for. + entry.runtime_data.settled_silent_blocks = ( + probed.unresponsive_blocks & solaredge.unresponsive_blocks + ) - DISCOVERY_SUBSYSTEMS + known = _probed_blocks(solaredge) for name, found in _probed_blocks(probed).items(): if found == known[name]: diff --git a/homeassistant/components/solaredge_modbus/const.py b/homeassistant/components/solaredge_modbus/const.py index 023026f45645..0a1d45670766 100644 --- a/homeassistant/components/solaredge_modbus/const.py +++ b/homeassistant/components/solaredge_modbus/const.py @@ -29,9 +29,18 @@ SUBSYSTEM_BATTERIES: Final = "batteries" SUBSYSTEM_EXPORT_CONTROL: Final = "export_control" SUBSYSTEM_GRID_STATUS: Final = "grid_status" SUBSYSTEM_METERS: Final = "meters" +SUBSYSTEM_MMPPT: Final = "mmppt" SUBSYSTEM_STORAGE_CAPACITY: Final = "storage_capacity" SUBSYSTEM_STORAGE_CONTROL: Final = "storage_control" +# The blocks that finding hardware depends on, so they are worth a timeout +# however long they stay quiet. Meters and batteries each bring a device, and +# the multiple-MPPT block decides the offset the meters are looked for at: +# taking it for absent would look for them at the wrong addresses for good. +DISCOVERY_SUBSYSTEMS: Final = frozenset( + {SUBSYSTEM_BATTERIES, SUBSYSTEM_METERS, SUBSYSTEM_MMPPT} +) + # The writable control blocks, as an UpdateReport names them. Export control's # read spans storage control, so the library reads and reports the two as one. SUBSYSTEM_ADVANCED_POWER_CONTROL: Final = "advanced_power_control" diff --git a/homeassistant/components/solaredge_modbus/coordinator.py b/homeassistant/components/solaredge_modbus/coordinator.py index aa6964151857..20ac9dcaa87d 100644 --- a/homeassistant/components/solaredge_modbus/coordinator.py +++ b/homeassistant/components/solaredge_modbus/coordinator.py @@ -168,10 +168,18 @@ class SolarEdgeModbusRuntimeData: settings: SolarEdgeModbusDataUpdateCoordinator device_info: DeviceInfo inverter_device_id: str + # What was attached when this entry was built, to notice a swap: a meter # replaced by another one leaves the count alone. attachments: frozenset[str] + # Blocks that answered nothing while setting up and nothing again on the + # first check after it. Asking costs a full timeout each, which on a shared + # link is time every other inverter spends waiting, so they are taken for + # absent until the entry loads again. Empty until that first check, so a + # block that was merely busy at setup still gets picked up. + settled_silent_blocks: frozenset[str] = frozenset() + @property def solaredge(self) -> SolarEdge: """Return the polled device, which both coordinators share.""" diff --git a/homeassistant/components/solaredge_modbus/manifest.json b/homeassistant/components/solaredge_modbus/manifest.json index 0bfb15d167b2..670803f6d5ca 100644 --- a/homeassistant/components/solaredge_modbus/manifest.json +++ b/homeassistant/components/solaredge_modbus/manifest.json @@ -9,6 +9,6 @@ "iot_class": "local_polling", "loggers": ["modbus_connection", "solaredged", "tmodbus"], "quality_scale": "platinum", - "requirements": ["solaredged==0.4.0"], + "requirements": ["solaredged==0.5.0"], "zeroconf": ["_solaredge-modbus._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 220df87d5fde..862560514441 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3123,7 +3123,7 @@ sofar-modbus==0.17.0 solaredge-web==0.4.0 # homeassistant.components.solaredge_modbus -solaredged==0.4.0 +solaredged==0.5.0 # homeassistant.components.solarlog solarlog_cli==0.7.1 diff --git a/tests/components/solaredge_modbus/test_init.py b/tests/components/solaredge_modbus/test_init.py index ebe518f5d96c..7ad80076d77d 100644 --- a/tests/components/solaredge_modbus/test_init.py +++ b/tests/components/solaredge_modbus/test_init.py @@ -57,6 +57,9 @@ INVERTER_REGISTER = 40069 # The register the probe counts meters by. METER_MODEL_REGISTER = 40188 +# The identifier the multiple-MPPT probe reads, which sets the meter offset. +MMPPT_REGISTER = 40121 + # An address inside the pooled storage and export control read. SITE_CONTROL_REGISTER = 57348 @@ -643,10 +646,12 @@ async def _tick_attachment_check( probes = 0 probe = SolarEdge.async_probe - async def counting_probe(unit: ModbusUnit) -> SolarEdge: + async def counting_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: nonlocal probes probes += 1 - return await probe(unit) + return await probe(unit, assume_absent=assume_absent) with patch.object(SolarEdge, "async_probe", counting_probe): freezer.tick(ATTACHMENT_SCAN_INTERVAL) @@ -1042,3 +1047,117 @@ async def test_setup_error_when_link_settings_are_in_use( await _setup(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR + + +async def test_a_block_that_stays_silent_stops_being_asked( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, +) -> None: + """A block silent at setup is looked for once more, then left alone. + + Asking costs a full timeout each time, and the link is shared, so that is + time every other inverter on it spends queued behind the question. + """ + mock_modbus_unit.fail_read(POWER_CONTROL_REGISTER, ModbusTimeoutError("timed out")) + await _setup(hass, mock_config_entry) + + asked: list[frozenset[str]] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + asked.append(assume_absent) + return await probe(unit, assume_absent=assume_absent) + + with patch.object(SolarEdge, "async_probe", recording_probe): + for _ in range(2): + freezer.tick(ATTACHMENT_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert asked[0] == frozenset(), "the first check still looks for it" + assert "power_control" in asked[1], "a block still silent is not asked again" + + +async def test_a_block_that_blips_once_keeps_being_asked( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, +) -> None: + """A block that answered at setup is not settled by one timeout later. + + Settling it would hide the block going away for good, since a block taken + for absent is reported back as though it had been silent again. + """ + await _setup(hass, mock_config_entry) + + asked: list[frozenset[str]] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + asked.append(assume_absent) + return await probe(unit, assume_absent=assume_absent) + + with patch.object(SolarEdge, "async_probe", recording_probe): + mock_modbus_unit.fail_read( + POWER_CONTROL_REGISTER, ModbusTimeoutError("timed out") + ) + freezer.tick(ATTACHMENT_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + mock_modbus_unit.fail_read(POWER_CONTROL_REGISTER, None) + freezer.tick(ATTACHMENT_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert "power_control" not in asked[1], "a blip settled a block that answered" + + +@pytest.mark.parametrize( + ("register", "subsystem"), + [ + pytest.param(BATTERY_RATED_ENERGY, "batteries", id="batteries"), + pytest.param(METER_MODEL_REGISTER, "meters", id="meters"), + pytest.param(MMPPT_REGISTER, "mmppt", id="mmppt"), + ], +) +async def test_a_block_discovery_depends_on_keeps_being_asked( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, + register: int, + subsystem: str, +) -> None: + """A block that finding hardware depends on is asked however quiet it stays. + + Meters and batteries each bring a device. The multiple-MPPT block decides + the offset the meters are looked for at, so taking it for absent would look + for them at the wrong addresses for good. + """ + mock_modbus_unit.fail_read(register, ModbusTimeoutError("timed out")) + await _setup(hass, mock_config_entry) + + asked: list[frozenset[str]] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + asked.append(assume_absent) + return await probe(unit, assume_absent=assume_absent) + + with patch.object(SolarEdge, "async_probe", recording_probe): + for _ in range(2): + freezer.tick(ATTACHMENT_SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert subsystem not in asked[1], "a block discovery depends on was settled" From abca52ec9b8de1aa6607a734818ca701f11bbb29 Mon Sep 17 00:00:00 2001 From: Simone Chemelli Date: Mon, 5 Oct 2026 11:23:08 +0200 Subject: [PATCH 065/356] Bump midea-local to 12.2.0 (#184301) --- homeassistant/components/midea/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/midea/manifest.json b/homeassistant/components/midea/manifest.json index 2a110ee733a1..0c2e4eb22f30 100644 --- a/homeassistant/components/midea/manifest.json +++ b/homeassistant/components/midea/manifest.json @@ -13,5 +13,5 @@ "iot_class": "local_polling", "loggers": ["midealocal"], "quality_scale": "gold", - "requirements": ["midea-local==12.1.0"] + "requirements": ["midea-local==12.2.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 862560514441..0e56c1a293e3 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1623,7 +1623,7 @@ micloud==0.5 microBeesPy==0.3.5 # homeassistant.components.midea -midea-local==12.1.0 +midea-local==12.2.0 # homeassistant.components.mill mill-local==0.5.0 From 45e0e36b7d048cb2bcf18db821139ca0084fb269 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Mon, 5 Oct 2026 11:52:41 +0200 Subject: [PATCH 066/356] Update frontend to 20260930.1 (#184308) --- homeassistant/components/frontend/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- pylint/plugins/pylint_home_assistant/generated/mdi_icons.py | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 7a7a81b84503..53b71f2c8c34 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -22,5 +22,5 @@ "integration_type": "system", "preview_features": { "winter_mode": {} }, "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20260930.0"] + "requirements": ["home-assistant-frontend==20260930.1"] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index c8a461c8bd42..610cfe9d70ae 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -40,7 +40,7 @@ habluetooth==7.1.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-frontend==20260930.0 +home-assistant-frontend==20260930.1 home-assistant-intents==2026.9.30 httpx==0.28.1 ifaddr==0.2.0 diff --git a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py index f9a5ee6378a0..5925990b61f8 100644 --- a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py +++ b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py @@ -5,7 +5,7 @@ To update, run python3 -m script.hassfest from typing import Final -FRONTEND_VERSION: Final[str] = "20260930.0" +FRONTEND_VERSION: Final[str] = "20260930.1" MDI_ICONS: Final[set[str]] = { "ab-testing", diff --git a/requirements_all.txt b/requirements_all.txt index 0e56c1a293e3..ed33365854fa 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1312,7 +1312,7 @@ hole==0.9.2 holidays==0.104 # homeassistant.components.frontend -home-assistant-frontend==20260930.0 +home-assistant-frontend==20260930.1 # homeassistant.components.conversation home-assistant-intents==2026.9.30 From c466d4ba55ea3b2bcd34a20d69db085190a419f0 Mon Sep 17 00:00:00 2001 From: Paul Bottein Date: Mon, 5 Oct 2026 15:43:09 +0200 Subject: [PATCH 067/356] Bump yoto-api to 4.5.1 (#184323) --- homeassistant/components/yoto/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/yoto/manifest.json b/homeassistant/components/yoto/manifest.json index 1960099ee76b..b4eb26b9a14f 100644 --- a/homeassistant/components/yoto/manifest.json +++ b/homeassistant/components/yoto/manifest.json @@ -10,5 +10,5 @@ "iot_class": "cloud_push", "loggers": ["yoto_api"], "quality_scale": "platinum", - "requirements": ["yoto-api==4.5.0"] + "requirements": ["yoto-api==4.5.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index ed33365854fa..36a97f618455 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3508,7 +3508,7 @@ yeelightsunflower==0.0.10 yolink-api==0.6.5 # homeassistant.components.yoto -yoto-api==4.5.0 +yoto-api==4.5.1 # homeassistant.components.youless youless-api==2.2.0 From 28b4f0213ff5e0f1d8667ff684ac3c33641cbafc Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Mon, 5 Oct 2026 15:36:07 +0200 Subject: [PATCH 068/356] Keep Portainer entities known on endpoint timeout (#184325) --- .../components/portainer/coordinator.py | 43 +++++++++++++---- tests/components/portainer/test_sensor.py | 46 ++++++++++++++++++- 2 files changed, 79 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/portainer/coordinator.py b/homeassistant/components/portainer/coordinator.py index 17d839bc3441..ab33e3ac3546 100644 --- a/homeassistant/components/portainer/coordinator.py +++ b/homeassistant/components/portainer/coordinator.py @@ -224,6 +224,8 @@ class PortainerCoordinator( self._event_listeners: dict[int, PortainerEventListener] = {} self._event_listeners_enabled = False self._container_ids_by_endpoint: dict[int, dict[str, str]] = {} + # Last successful fetch per endpoint, kept across timed-out polls + self._last_endpoint_data: dict[int, PortainerCoordinatorData] = {} @override async def update_data(self) -> dict[int, PortainerCoordinatorData]: @@ -246,6 +248,7 @@ class PortainerCoordinator( ) from err mapped_endpoints: dict[int, PortainerCoordinatorData] = {} + timed_out_endpoints: set[int] = set() for endpoint in endpoints: if endpoint.status == EndpointStatus.DOWN: _LOGGER.debug( @@ -293,7 +296,7 @@ class PortainerCoordinator( for stack in result ] - prev_endpoint = self.data.get(endpoint.id) if self.data else None + prev_endpoint = self._last_endpoint_data.get(endpoint.id) container_map: dict[str, PortainerContainerData] = {} stack_map: dict[str, PortainerStackData] = { stack.name: PortainerStackData(stack=stack, container_count=0) @@ -433,9 +436,15 @@ class PortainerCoordinator( endpoint.name, endpoint.id, ) + timed_out_endpoints.add(endpoint.id) continue - self._async_add_remove_endpoints(mapped_endpoints) + self._last_endpoint_data = { + endpoint_id: data + for endpoint_id, data in self._last_endpoint_data.items() + if endpoint_id in timed_out_endpoints + } | mapped_endpoints + self._async_add_remove_endpoints(mapped_endpoints, timed_out_endpoints) self._async_sync_event_listeners(mapped_endpoints) return mapped_endpoints @@ -492,11 +501,17 @@ class PortainerCoordinator( ) def _async_add_remove_endpoints( - self, mapped_endpoints: dict[int, PortainerCoordinatorData] + self, + mapped_endpoints: dict[int, PortainerCoordinatorData], + timed_out_endpoints: set[int], ) -> None: - """Add new endpoints, remove non-existing endpoints.""" + """Add new endpoints, remove non-existing endpoints. + + Timed-out endpoints keep their known entities, so they aren't added + again once the endpoint answers. + """ current_endpoints = {endpoint.id for endpoint in mapped_endpoints.values()} - self.known_endpoints &= current_endpoints + self.known_endpoints &= current_endpoints | timed_out_endpoints new_endpoints = current_endpoints - self.known_endpoints # The stack ID is part of the key because it is part of the stack device @@ -507,7 +522,11 @@ class PortainerCoordinator( for endpoint in mapped_endpoints.values() for stack_name, stack_data in endpoint.stacks.items() } - self.known_stacks &= current_stacks + self.known_stacks = { + stack + for stack in self.known_stacks + if stack in current_stacks or stack[0] in timed_out_endpoints + } new_stacks = current_stacks - self.known_stacks if new_endpoints or new_stacks: @@ -534,7 +553,11 @@ class PortainerCoordinator( } # Prune departed containers so a recreated container is detected as new # and its entity is rebuilt with the fresh (ephemeral) Docker container ID. - self.known_containers &= current_containers + self.known_containers = { + container + for container in self.known_containers + if container in current_containers or container[0] in timed_out_endpoints + } new_containers = current_containers - self.known_containers if new_containers: _LOGGER.debug("New containers found: %s", new_containers) @@ -556,7 +579,11 @@ class PortainerCoordinator( for volume_name in endpoint.volumes } - self.known_volumes &= current_volumes + self.known_volumes = { + volume + for volume in self.known_volumes + if volume in current_volumes or volume[0] in timed_out_endpoints + } new_volumes = current_volumes - self.known_volumes if new_volumes: _LOGGER.debug("New volumes found: %s", new_volumes) diff --git a/tests/components/portainer/test_sensor.py b/tests/components/portainer/test_sensor.py index 4abe68c9ebf8..a61b24ae30b5 100644 --- a/tests/components/portainer/test_sensor.py +++ b/tests/components/portainer/test_sensor.py @@ -5,14 +5,17 @@ from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory from pyportainer.exceptions import PortainerTimeoutError -from pyportainer.models.docker import EndpointStatus +from pyportainer.models.docker import DockerContainerStats, EndpointStatus from pyportainer.models.docker_inspect import DockerInspect from pyportainer.models.portainer import Endpoint import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.portainer.const import DOMAIN -from homeassistant.components.portainer.coordinator import DEFAULT_DF_SCAN_INTERVAL +from homeassistant.components.portainer.coordinator import ( + DEFAULT_DF_SCAN_INTERVAL, + DEFAULT_SCAN_INTERVAL, +) from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -28,6 +31,8 @@ from tests.common import ( snapshot_platform, ) +CPU_USAGE_ENTITY_ID = "sensor.focused_einstein_cpu_usage_total" + @pytest.fixture(autouse=True) def enable_all_entities(entity_registry_enabled_by_default: None) -> None: @@ -105,6 +110,43 @@ async def test_df_endpoint_timeout_only_marks_that_endpoint_unavailable( assert state.state != STATE_UNAVAILABLE +async def test_endpoint_timeout_keeps_known_entities( + hass: HomeAssistant, + mock_portainer_client: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a timed-out poll doesn't re-add entities or reset CPU usage.""" + await setup_integration(hass, mock_config_entry) + + mock_portainer_client.docker_version.side_effect = PortainerTimeoutError("timeout") + freezer.tick(DEFAULT_SCAN_INTERVAL) + async_fire_time_changed(hass, dt_util.utcnow()) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get(CPU_USAGE_ENTITY_ID)) + assert state.state == STATE_UNAVAILABLE + + stats = cast( + dict[str, Any], load_json_value_fixture("container_stats.json", DOMAIN) + ) + stats["cpu_stats"]["system_cpu_usage"] += 1_000_000_000 + stats["cpu_stats"]["cpu_usage"]["total_usage"] += 125_000_000 + mock_portainer_client.container_stats.return_value = DockerContainerStats.from_dict( + stats + ) + mock_portainer_client.docker_version.side_effect = None + freezer.tick(DEFAULT_SCAN_INTERVAL) + async_fire_time_changed(hass, dt_util.utcnow()) + await hass.async_block_till_done(wait_background_tasks=True) + + # Usage is averaged since the last successful poll + assert (state := hass.states.get(CPU_USAGE_ENTITY_ID)) + assert state.state == "50.0" + assert "does not generate unique IDs" not in caplog.text + + async def test_container_never_started( hass: HomeAssistant, mock_portainer_client: AsyncMock, From 6d7c5068ee40366d577dfcfd5de48565185ee0d6 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Mon, 5 Oct 2026 16:33:16 +0000 Subject: [PATCH 069/356] Bump version to 2026.10.0b1 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index ff23dffcd0e0..d8e979a6cf83 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b0" +PATCH_VERSION: Final = "0b1" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 93158e55854c..3ccbd3d808d8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b0" +version = "2026.10.0b1" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From e8000ba1f95610d5ae2fd05e5c4dc211f3e613a0 Mon Sep 17 00:00:00 2001 From: MoonDevLT <107535193+MoonDevLT@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:30:08 +0200 Subject: [PATCH 070/356] Fix certain device variants failing during setup of lunatone (#182396) --- homeassistant/components/lunatone/__init__.py | 15 ++++-- .../components/lunatone/coordinator.py | 6 +-- homeassistant/components/lunatone/sensor.py | 18 ++++--- tests/components/lunatone/test_init.py | 49 +++++++++++++++++-- tests/components/lunatone/test_sensor.py | 10 ++-- 5 files changed, 72 insertions(+), 26 deletions(-) diff --git a/homeassistant/components/lunatone/__init__.py b/homeassistant/components/lunatone/__init__.py index b274df83a8bc..cdb2fab8238a 100644 --- a/homeassistant/components/lunatone/__init__.py +++ b/homeassistant/components/lunatone/__init__.py @@ -11,6 +11,7 @@ from lunatone_rest_api_client import ( Info, Sensors, ) +from lunatone_rest_api_client.models import DeviceCapabilities from homeassistant.const import CONF_URL, Platform from homeassistant.core import HomeAssistant @@ -142,14 +143,18 @@ async def async_setup_entry(hass: HomeAssistant, entry: LunatoneConfigEntry) -> coordinator_devices = LunatoneDevicesDataUpdateCoordinator(hass, entry, devices_api) await coordinator_devices.async_config_entry_first_refresh() - sensors_api = Sensors(auth_api) - coordinator_sensors = LunatoneSensorsDataUpdateCoordinator(hass, entry, sensors_api) - await coordinator_sensors.async_config_entry_first_refresh() - dali_scan_api = DALIScan(auth_api) coordinator_scan = LunatoneScanDataUpdateCoordinator(hass, entry, dali_scan_api) await coordinator_scan.async_config_entry_first_refresh() + coordinator_sensors = None + if DeviceCapabilities.SENSORS in info_api.data.device_capabilities: + sensors_api = Sensors(auth_api) + coordinator_sensors = LunatoneSensorsDataUpdateCoordinator( + hass, entry, sensors_api + ) + await coordinator_sensors.async_config_entry_first_refresh() + dali_line_broadcasts = [ DALIBroadcast(auth_api, int(line)) for line in coordinator_info.data.lines ] @@ -157,8 +162,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: LunatoneConfigEntry) -> entry.runtime_data = LunatoneData( coordinator_info, coordinator_devices, - coordinator_sensors, coordinator_scan, + coordinator_sensors, dali_line_broadcasts, ) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) diff --git a/homeassistant/components/lunatone/coordinator.py b/homeassistant/components/lunatone/coordinator.py index cf321bb95055..4b7d3d5776b5 100644 --- a/homeassistant/components/lunatone/coordinator.py +++ b/homeassistant/components/lunatone/coordinator.py @@ -1,7 +1,7 @@ """Coordinator for handling data fetching and updates.""" from collections import defaultdict -from dataclasses import dataclass +from dataclasses import dataclass, field from datetime import timedelta import logging from typing import override @@ -38,9 +38,9 @@ class LunatoneData: coordinator_info: LunatoneInfoDataUpdateCoordinator coordinator_devices: LunatoneDevicesDataUpdateCoordinator - coordinator_sensors: LunatoneSensorsDataUpdateCoordinator coordinator_scan: LunatoneScanDataUpdateCoordinator - dali_line_broadcasts: list[DALIBroadcast] + coordinator_sensors: LunatoneSensorsDataUpdateCoordinator | None = None + dali_line_broadcasts: list[DALIBroadcast] = field(default_factory=list) type LunatoneConfigEntry = ConfigEntry[LunatoneData] diff --git a/homeassistant/components/lunatone/sensor.py b/homeassistant/components/lunatone/sensor.py index 38e454c445d4..dd5204dc46fa 100644 --- a/homeassistant/components/lunatone/sensor.py +++ b/homeassistant/components/lunatone/sensor.py @@ -95,16 +95,18 @@ async def async_setup_entry( assert config_entry.unique_id is not None entities: list[SensorEntity] = [ - LunatoneSensor( - coordinator_sensors, description, sensor_id, config_entry.unique_id - ) - for sensor_id, sensor_data in coordinator_sensors.data.items() - if (description := SENSOR_TYPES.get(sensor_data.data.type)) - ] - entities.extend( LunatoneDALILineStatusSensor(coordinator_info, line_id, config_entry.unique_id) for line_id in coordinator_info.data.lines - ) + ] + + if coordinator_sensors is not None: + entities.extend( + LunatoneSensor( + coordinator_sensors, description, sensor_id, config_entry.unique_id + ) + for sensor_id, sensor_data in coordinator_sensors.data.items() + if (description := SENSOR_TYPES.get(sensor_data.data.type)) + ) async_add_entities(entities) diff --git a/tests/components/lunatone/test_init.py b/tests/components/lunatone/test_init.py index 93702fe2c2ba..eeb205ca1e72 100644 --- a/tests/components/lunatone/test_init.py +++ b/tests/components/lunatone/test_init.py @@ -3,6 +3,8 @@ from unittest.mock import AsyncMock, PropertyMock import aiohttp +from lunatone_rest_api_client.models.info import Tier +import pytest from homeassistant.components.lunatone.const import DOMAIN, MANUFACTURER from homeassistant.config_entries import ConfigEntryState @@ -61,6 +63,44 @@ async def test_load_unload_config_entry( assert mock_config_entry.state is ConfigEntryState.NOT_LOADED +@pytest.mark.parametrize( + ("tier", "emergency_light", "sensors_supported"), + [ + (Tier.BASIC, False, True), + (Tier.BASIC, True, False), + (Tier.PLUS, False, True), + (Tier.PLUS, True, True), + ], + ids=["basic", "emergency", "plus", "plus+emergency"], +) +async def test_load_config_entry_sensor_capability( + hass: HomeAssistant, + mock_lunatone_info: AsyncMock, + mock_lunatone_devices: AsyncMock, + mock_lunatone_sensors: AsyncMock, + mock_lunatone_scan: AsyncMock, + mock_config_entry: MockConfigEntry, + tier: Tier, + emergency_light: bool, + sensors_supported: bool, +) -> None: + """Test the sensor coordinator follows the device capabilities.""" + mock_lunatone_info.data.tier = tier + mock_lunatone_info.data.emergency_light = emergency_light + + await setup_integration(hass, mock_config_entry) + + assert ( + mock_config_entry.runtime_data.coordinator_sensors is not None + ) == sensors_supported + if sensors_supported: + mock_lunatone_sensors.async_refresh.assert_called() + mock_lunatone_sensors.async_update.assert_called() + else: + mock_lunatone_sensors.async_refresh.assert_not_called() + mock_lunatone_sensors.async_update.assert_not_called() + + async def test_config_entry_not_ready_info_api_fail( hass: HomeAssistant, mock_lunatone_info: AsyncMock, @@ -146,8 +186,8 @@ async def test_config_entry_not_ready_scan_api_fail( hass: HomeAssistant, mock_lunatone_info: AsyncMock, mock_lunatone_devices: AsyncMock, - mock_lunatone_sensors: AsyncMock, mock_lunatone_scan: AsyncMock, + mock_lunatone_sensors: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: """Test config entry not ready due to sensors API failure.""" @@ -157,7 +197,6 @@ async def test_config_entry_not_ready_scan_api_fail( mock_lunatone_info.async_update.assert_called_once() mock_lunatone_devices.async_update.assert_called_once() - mock_lunatone_sensors.async_update.assert_called_once() mock_lunatone_scan.async_update.assert_called_once() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY @@ -168,8 +207,8 @@ async def test_config_entry_not_ready_scan_api_fail( mock_lunatone_info.async_update.assert_called() mock_lunatone_devices.async_update.assert_called() - mock_lunatone_sensors.async_update.assert_called() mock_lunatone_scan.async_update.assert_called() + mock_lunatone_sensors.async_update.assert_called() assert mock_config_entry.state is ConfigEntryState.LOADED @@ -225,6 +264,7 @@ async def test_config_entry_not_ready_no_sensors_data( hass: HomeAssistant, mock_lunatone_info: AsyncMock, mock_lunatone_devices: AsyncMock, + mock_lunatone_scan: AsyncMock, mock_lunatone_sensors: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: @@ -235,6 +275,7 @@ async def test_config_entry_not_ready_no_sensors_data( mock_lunatone_info.async_update.assert_called_once() mock_lunatone_devices.async_update.assert_called_once() + mock_lunatone_scan.async_update.assert_called_once() mock_lunatone_sensors.async_update.assert_called_once() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY @@ -243,7 +284,6 @@ async def test_config_entry_not_ready_no_dali_scan_data( hass: HomeAssistant, mock_lunatone_info: AsyncMock, mock_lunatone_devices: AsyncMock, - mock_lunatone_sensors: AsyncMock, mock_lunatone_scan: AsyncMock, mock_config_entry: MockConfigEntry, ) -> None: @@ -254,7 +294,6 @@ async def test_config_entry_not_ready_no_dali_scan_data( mock_lunatone_info.async_update.assert_called_once() mock_lunatone_devices.async_update.assert_called_once() - mock_lunatone_sensors.async_update.assert_called_once() mock_lunatone_scan.async_update.assert_called_once() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY diff --git a/tests/components/lunatone/test_sensor.py b/tests/components/lunatone/test_sensor.py index 774ecde829f9..92637bac74fb 100644 --- a/tests/components/lunatone/test_sensor.py +++ b/tests/components/lunatone/test_sensor.py @@ -60,18 +60,18 @@ async def test_sensor_value_update( mock_lunatone_sensors.async_update.side_effect = fake_update entities = hass.states.async_all(Platform.SENSOR) - assert entities[0].state == "unknown" - assert entities[1].state == "unknown" assert entities[2].state == "unknown" + assert entities[3].state == "unknown" + assert entities[4].state == "unknown" freezer.tick(timedelta(seconds=40)) async_fire_time_changed(hass) await hass.async_block_till_done() entities = hass.states.async_all(Platform.SENSOR) - assert entities[0].state == "22" - assert entities[1].state == "55" - assert entities[2].state == "20" + assert entities[2].state == "22" + assert entities[3].state == "55" + assert entities[4].state == "20" async def test_dali_line_status_value_update( From e848786a7492b0f288576070d28480ecdcf86c12 Mon Sep 17 00:00:00 2001 From: Christian Bartels Date: Mon, 5 Oct 2026 23:30:02 -0600 Subject: [PATCH 071/356] Fix lutron_caseta warm dim level and transition not sent to bridge (#182995) --- .../components/lutron_caseta/light.py | 4 +- tests/components/lutron_caseta/__init__.py | 8 ++- tests/components/lutron_caseta/test_light.py | 58 +++++++++++++++++++ 3 files changed, 65 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/lutron_caseta/light.py b/homeassistant/components/lutron_caseta/light.py index 8a6451149d71..5bea5017253a 100644 --- a/homeassistant/components/lutron_caseta/light.py +++ b/homeassistant/components/lutron_caseta/light.py @@ -188,7 +188,7 @@ class LutronCasetaLight(LutronCasetaUpdatableEntity, LightEntity): brightness = to_lutron_level(brightness) await self._smartbridge.set_warm_dim( - self.device_id, brightness, **set_warm_dim_kwargs + self.device_id, True, value=brightness, **set_warm_dim_kwargs ) @override @@ -199,7 +199,7 @@ class LutronCasetaLight(LutronCasetaUpdatableEntity, LightEntity): # Only remember non-zero levels (see brightness handling below) if white_color: self._prev_brightness = white_color - await self._async_set_warm_dim(white_color) + await self._async_set_warm_dim(white_color, **kwargs) return # Parse the color first, so a color-only call can leave brightness alone diff --git a/tests/components/lutron_caseta/__init__.py b/tests/components/lutron_caseta/__init__.py index 898dd73996c9..2bc4dec11590 100644 --- a/tests/components/lutron_caseta/__init__.py +++ b/tests/components/lutron_caseta/__init__.py @@ -205,13 +205,15 @@ class MockBridge: async def set_warm_dim( self, device_id: str, + enabled: bool, value: int | None = None, fade_time: timedelta | None = None, ) -> None: """Mock changing the warm dim state and invoke callbacks.""" - if device_id in self.devices and value is not None: - self.devices[device_id]["current_state"] = value - self.devices[device_id]["warm_dim"] = True + if device_id in self.devices: + self.devices[device_id]["warm_dim"] = enabled + if value is not None: + self.devices[device_id]["current_state"] = value self.call_subscribers(device_id) def load_devices(self): diff --git a/tests/components/lutron_caseta/test_light.py b/tests/components/lutron_caseta/test_light.py index 40b52cca55e3..8b694fa5d148 100644 --- a/tests/components/lutron_caseta/test_light.py +++ b/tests/components/lutron_caseta/test_light.py @@ -1,10 +1,12 @@ """Tests for the Lutron Caseta integration.""" +from datetime import timedelta from unittest.mock import patch from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, + ATTR_TRANSITION, ATTR_WHITE, DOMAIN as LIGHT_DOMAIN, SERVICE_TURN_OFF, @@ -218,6 +220,62 @@ async def test_white_mode_turn_on_remembers_brightness( assert state.state == STATE_ON +async def test_white_mode_turn_on_sends_level( + hass: HomeAssistant, +) -> None: + """Test white mode enables warm dim and sends the requested level.""" + mock_entry = await async_setup_integration(hass, MockBridgeWithColorLight) + + entity_id = "light.kitchen_kitchen_spectrum_light" + bridge = mock_entry.runtime_data.bridge + + with patch.object( + bridge, "set_warm_dim", wraps=bridge.set_warm_dim + ) as mock_set_warm_dim: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_WHITE: 100}, + target={ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + await hass.async_block_till_done() + + # to_lutron_level(100) == round(100 * 100 / 255) == 39 + mock_set_warm_dim.assert_called_once_with("904", True, value=39) + + state = hass.states.get(entity_id) + assert state is not None + # to_hass_level(39) == (39 * 255) // 100 == 99 + assert state.attributes.get(ATTR_BRIGHTNESS) == 99 + + +async def test_white_mode_turn_on_with_transition( + hass: HomeAssistant, +) -> None: + """Test white mode passes the transition through as fade time.""" + mock_entry = await async_setup_integration(hass, MockBridgeWithColorLight) + + entity_id = "light.kitchen_kitchen_spectrum_light" + bridge = mock_entry.runtime_data.bridge + + with patch.object( + bridge, "set_warm_dim", wraps=bridge.set_warm_dim + ) as mock_set_warm_dim: + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_WHITE: 255, ATTR_TRANSITION: 2}, + target={ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + await hass.async_block_till_done() + + mock_set_warm_dim.assert_called_once_with( + "904", True, value=100, fade_time=timedelta(seconds=2) + ) + + async def test_async_update_syncs_previous_brightness( hass: HomeAssistant, ) -> None: From 23bb16e628def17cad4e11c513c6fc89172dfb2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=96mer=20G=C3=BCven?= <97512+DragonWork@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:55:49 +0200 Subject: [PATCH 072/356] Fix PostgreSQL prerelease version detection in recorder (#183146) --- homeassistant/components/recorder/util.py | 10 +++++ tests/components/recorder/test_util.py | 49 +++++++++++++++++------ 2 files changed, 47 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/recorder/util.py b/homeassistant/components/recorder/util.py index fed4bda88410..64d7cc24cbec 100644 --- a/homeassistant/components/recorder/util.py +++ b/homeassistant/components/recorder/util.py @@ -695,6 +695,16 @@ def setup_connection_for_dialect( result = query_on_connection(dbapi_connection, "SHOW server_version") version_string = result[0][0] version = _extract_version_from_server_response(version_string) + if version is None: + # PostgreSQL prereleases such as 19beta3 are not SimpleVer. + result = query_on_connection( + dbapi_connection, "SHOW server_version_num" + ) + version_num = int(result[0][0]) + # PostgreSQL < 12 is rejected regardless of the minor version. + version = _simple_version( + f"{version_num // 10000}.{version_num % 10000}" + ) if not version or version < MIN_VERSION_PGSQL: _raise_if_version_unsupported( version or version_string, "PostgreSQL", MIN_VERSION_PGSQL diff --git a/tests/components/recorder/test_util.py b/tests/components/recorder/test_util.py index 1715eda7183c..6a6cf033af1a 100644 --- a/tests/components/recorder/test_util.py +++ b/tests/components/recorder/test_util.py @@ -430,27 +430,39 @@ def test_supported_mysql(caplog: pytest.LogCaptureFixture, mysql_version) -> Non @pytest.mark.parametrize( - ("pgsql_version", "message"), + ("pgsql_version", "pgsql_version_num", "message"), [ ( "11.12 (Debian 11.12-1.pgdg100+1)", + "110012", "Version 11.12 of PostgreSQL is not supported;" " minimum supported version is 12.0.", ), ( "9.2.10", + "90210", "Version 9.2.10 of PostgreSQL is not supported;" " minimum supported version is 12.0.", ), + ( + "11beta3", + "110000", + "Version 11.0 of PostgreSQL is not supported;" + " minimum supported version is 12.0.", + ), ( "unexpected", - "Version unexpected of PostgreSQL is not supported;" + "110012", + "Version 11.12 of PostgreSQL is not supported;" " minimum supported version is 12.0.", ), ], ) def test_fail_outdated_pgsql( - caplog: pytest.LogCaptureFixture, pgsql_version, message + caplog: pytest.LogCaptureFixture, + pgsql_version: str, + pgsql_version_num: str, + message: str, ) -> None: """Test setting up the connection for an outdated PostgreSQL version.""" instance_mock = MagicMock() @@ -463,9 +475,10 @@ def test_fail_outdated_pgsql( def fetchall_mock(): nonlocal execute_args - if execute_args[-1] == "SHOW server_version": - return [[pgsql_version]] - return None + return { + "SHOW server_version": [[pgsql_version]], + "SHOW server_version_num": [[pgsql_version_num]], + }[execute_args[-1]] def _make_cursor_mock(*_): return MagicMock(execute=execute_mock, close=close_mock, fetchall=fetchall_mock) @@ -481,10 +494,20 @@ def test_fail_outdated_pgsql( @pytest.mark.parametrize( - "pgsql_version", - ["14.0 (Debian 14.0-1.pgdg110+1)"], + ("pgsql_version", "pgsql_version_num", "expected_version"), + [ + ("14.0 (Debian 14.0-1.pgdg110+1)", "140000", "14.0"), + ("19beta3", "190000", "19.0"), + ("19beta3 (Debian 19~beta3-1.pgdg14+1)", "190000", "19.0"), + ("19rc1", "190000", "19.0"), + ], ) -def test_supported_pgsql(caplog: pytest.LogCaptureFixture, pgsql_version) -> None: +def test_supported_pgsql( + caplog: pytest.LogCaptureFixture, + pgsql_version: str, + pgsql_version_num: str, + expected_version: str, +) -> None: """Test setting up the connection for a supported PostgreSQL version.""" instance_mock = MagicMock() execute_args = [] @@ -496,9 +519,10 @@ def test_supported_pgsql(caplog: pytest.LogCaptureFixture, pgsql_version) -> Non def fetchall_mock(): nonlocal execute_args - if execute_args[-1] == "SHOW server_version": - return [[pgsql_version]] - return None + return { + "SHOW server_version": [[pgsql_version]], + "SHOW server_version_num": [[pgsql_version_num]], + }[execute_args[-1]] def _make_cursor_mock(*_): return MagicMock(execute=execute_mock, close=close_mock, fetchall=fetchall_mock) @@ -511,6 +535,7 @@ def test_supported_pgsql(caplog: pytest.LogCaptureFixture, pgsql_version) -> Non assert "minimum supported version" not in caplog.text assert database_engine is not None + assert str(database_engine.version) == expected_version assert database_engine.optimizer.slow_range_in_select is True assert database_engine.optimizer.slow_dependent_subquery is False From b839c0a187dc8ae936fa84701a55bce8a6ead547 Mon Sep 17 00:00:00 2001 From: Marco Hillger Date: Mon, 5 Oct 2026 22:37:15 +0200 Subject: [PATCH 073/356] Avoid reserved time fields in InfluxDB writes (#183743) --- homeassistant/components/influxdb/__init__.py | 8 ++++ tests/components/influxdb/test_init.py | 45 +++++++++++++++++-- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/influxdb/__init__.py b/homeassistant/components/influxdb/__init__.py index c28940f7e23c..096c44c1a3c3 100644 --- a/homeassistant/components/influxdb/__init__.py +++ b/homeassistant/components/influxdb/__init__.py @@ -338,6 +338,14 @@ def _generate_event_to_json(conf: dict) -> Callable[[Event], dict[str, Any] | No if not math.isfinite(json[INFLUX_CONF_FIELDS][key]): del json[INFLUX_CONF_FIELDS][key] + # InfluxDB reserves "time"; leave the valid "time_str" field unchanged. + fields = json[INFLUX_CONF_FIELDS] + if INFLUX_CONF_TIME in fields: + key = f"{INFLUX_CONF_TIME}_" + while key in fields: + key = f"{key}_" + fields[key] = fields.pop(INFLUX_CONF_TIME) + json[INFLUX_CONF_TAGS].update(tags) return json diff --git a/tests/components/influxdb/test_init.py b/tests/components/influxdb/test_init.py index 8d9ad5b4a571..1cc656a31cc9 100644 --- a/tests/components/influxdb/test_init.py +++ b/tests/components/influxdb/test_init.py @@ -5,6 +5,7 @@ from dataclasses import dataclass import datetime from http import HTTPStatus import logging +import math from typing import Any from unittest.mock import ANY, MagicMock, Mock, call, patch @@ -1923,20 +1924,56 @@ async def test_event_listener_backlog_full( ], indirect=["mock_client", "get_mock_call"], ) +@pytest.mark.parametrize( + ("attributes", "fields"), + [ + pytest.param( + {"value": "value_str"}, {"value__str": "value_str"}, id="state-value" + ), + pytest.param({"time": 42}, {"time_": 42.0}, id="numeric-time"), + pytest.param({"time": "42.5"}, {"time_": 42.5}, id="numeric-string-time"), + pytest.param( + {"time": "2026-09-28T08:10:53.050Z"}, + { + "time_str": "2026-09-28T08:10:53.050Z", + "time_": 20260928081053.05, + }, + id="timestamp-time", + ), + pytest.param({"time": "unknown"}, {"time_str": "unknown"}, id="string-time"), + pytest.param({"time": math.inf}, {}, id="nonfinite-time"), + pytest.param( + {"time_": 84, "time": 42}, + {"time_": 84.0, "time__": 42.0}, + id="reserved-name-conflict", + ), + pytest.param( + {"time": 42, "time_": 84}, + {"time_": 84.0, "time__": 42.0}, + id="renamed-field-conflict", + ), + ], +) async def test_event_listener_attribute_name_conflict( - hass: HomeAssistant, mock_client, config_ext, get_write_api, get_mock_call + hass: HomeAssistant, + mock_client: MagicMock, + config_ext: dict[str, Any], + get_write_api: Callable[[MagicMock], MagicMock], + get_mock_call: Callable[..., Any], + attributes: dict[str, Any], + fields: dict[str, Any], ) -> None: - """Test the event listener when an attribute conflicts with another field.""" + """Test attributes that conflict with an existing or reserved field name.""" await _setup(hass, mock_client, config_ext, get_write_api) body = [ { "measurement": "fake.something", "tags": {"domain": "fake", "entity_id": "something"}, "time": ANY, - "fields": {"value": 1, "value__str": "value_str"}, + "fields": {"value": 1, **fields}, } ] - hass.states.async_set("fake.something", 1, {"value": "value_str"}) + hass.states.async_set("fake.something", 1, attributes) await hass.async_block_till_done() await async_wait_for_queue_to_process(hass) From 4f52a53a174312405c347e30e1358c59b38f6133 Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Mon, 5 Oct 2026 21:38:38 +0100 Subject: [PATCH 074/356] Report read-only climate entities as such to Google Assistant (#183820) --- .../components/google_assistant/trait.py | 14 +++- .../components/google_assistant/test_trait.py | 84 +++++++++++++++++++ 2 files changed, 97 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/google_assistant/trait.py b/homeassistant/components/google_assistant/trait.py index df79037e350b..cb2622255f81 100644 --- a/homeassistant/components/google_assistant/trait.py +++ b/homeassistant/components/google_assistant/trait.py @@ -1385,11 +1385,23 @@ class TemperatureSettingTrait(_Trait): modes = self.climate_google_modes + features = attrs.get(EntityStateAttribute.SUPPORTED_FEATURES, 0) + has_setpoint = features & ( + ClimateEntityFeature.TARGET_TEMPERATURE + | ClimateEntityFeature.TARGET_TEMPERATURE_RANGE + ) + + # A climate entity that can neither set a target temperature nor switch + # between modes (e.g. a template climate that only mirrors sensors) can + # only be queried; tell Google so it doesn't offer controls that fail. + if not has_setpoint and len(modes) <= 1: + response["queryOnlyTemperatureSetting"] = True + # Some integrations don't support modes (e.g. opentherm), but Google doesn't # support changing the temperature if we don't have any modes. If there's # only one Google doesn't support changing it, so the default mode here is # only cosmetic. - if len(modes) == 0: + if len(modes) == 0 and has_setpoint: modes.append("heat") if "off" in modes and any( diff --git a/tests/components/google_assistant/test_trait.py b/tests/components/google_assistant/test_trait.py index e9de954e30fd..2bf00be6cc7d 100644 --- a/tests/components/google_assistant/test_trait.py +++ b/tests/components/google_assistant/test_trait.py @@ -1348,6 +1348,7 @@ async def test_temperature_setting_climate_no_modes(hass: HomeAssistant) -> None "climate.bla", climate.HVACMode.AUTO, { + ATTR_SUPPORTED_FEATURES: ClimateEntityFeature.TARGET_TEMPERATURE, climate.ATTR_HVAC_MODES: [], climate.ATTR_MIN_TEMP: climate.DEFAULT_MIN_TEMP, climate.ATTR_MAX_TEMP: climate.DEFAULT_MAX_TEMP, @@ -1365,6 +1366,89 @@ async def test_temperature_setting_climate_no_modes(hass: HomeAssistant) -> None } +@pytest.mark.parametrize( + ("hvac_modes", "expected_modes"), + [ + # No made-up "heat" fallback: it only exists to allow setting a temperature. + pytest.param([], [], id="no_modes"), + pytest.param([climate.HVACMode.HEAT], ["heat"], id="single_mode"), + ], +) +async def test_temperature_setting_climate_query_only( + hass: HomeAssistant, + hvac_modes: list[climate.HVACMode], + expected_modes: list[str], +) -> None: + """Test a climate entity that can neither set a target nor switch modes. + + Such an entity (e.g. a template climate that only mirrors sensors) must be + reported as query-only so Google doesn't offer controls that would fail. + """ + trt = trait.TemperatureSettingTrait( + hass, + State( + "climate.bla", + climate.HVACMode.HEAT, + { + ATTR_SUPPORTED_FEATURES: 0, + climate.ATTR_CURRENT_TEMPERATURE: 21.5, + climate.ATTR_CURRENT_HUMIDITY: 48, + climate.ATTR_HVAC_MODES: hvac_modes, + climate.ATTR_MIN_TEMP: climate.DEFAULT_MIN_TEMP, + climate.ATTR_MAX_TEMP: climate.DEFAULT_MAX_TEMP, + }, + ), + BASIC_CONFIG, + ) + assert trt.sync_attributes() == { + "availableThermostatModes": expected_modes, + "thermostatTemperatureRange": { + "minThresholdCelsius": climate.DEFAULT_MIN_TEMP, + "maxThresholdCelsius": climate.DEFAULT_MAX_TEMP, + }, + "thermostatTemperatureUnit": "C", + "queryOnlyTemperatureSetting": True, + } + assert trt.query_attributes() == { + "thermostatMode": "heat", + "thermostatTemperatureAmbient": 21.5, + "thermostatHumidityAmbient": 48, + } + + +@pytest.mark.parametrize( + ("features", "hvac_modes"), + [ + pytest.param(ClimateEntityFeature.TARGET_TEMPERATURE, [], id="target"), + pytest.param(ClimateEntityFeature.TARGET_TEMPERATURE_RANGE, [], id="range"), + pytest.param( + 0, [climate.HVACMode.OFF, climate.HVACMode.HEAT], id="multiple_modes" + ), + ], +) +async def test_temperature_setting_climate_not_query_only( + hass: HomeAssistant, + features: ClimateEntityFeature, + hvac_modes: list[climate.HVACMode], +) -> None: + """Test a climate entity with any control is not reported as query-only.""" + trt = trait.TemperatureSettingTrait( + hass, + State( + "climate.bla", + climate.HVACMode.HEAT, + { + ATTR_SUPPORTED_FEATURES: features, + climate.ATTR_HVAC_MODES: hvac_modes, + climate.ATTR_MIN_TEMP: climate.DEFAULT_MIN_TEMP, + climate.ATTR_MAX_TEMP: climate.DEFAULT_MAX_TEMP, + }, + ), + BASIC_CONFIG, + ) + assert "queryOnlyTemperatureSetting" not in trt.sync_attributes() + + async def test_temperature_setting_climate_range_fahrenheit_precision( hass: HomeAssistant, ) -> None: From b98e990a9549038f623ee52fb64a2a7ccb8c82bb Mon Sep 17 00:00:00 2001 From: John Costa Date: Mon, 5 Oct 2026 13:34:44 -0700 Subject: [PATCH 075/356] Handle removed issue in repairs ignore_issue websocket command (#183934) --- homeassistant/components/repairs/websocket_api.py | 10 +++++++++- tests/components/repairs/test_websocket_api.py | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/repairs/websocket_api.py b/homeassistant/components/repairs/websocket_api.py index 92d476a8f985..4af9337bb7e2 100644 --- a/homeassistant/components/repairs/websocket_api.py +++ b/homeassistant/components/repairs/websocket_api.py @@ -72,7 +72,15 @@ def ws_ignore_issue( hass: HomeAssistant, connection: websocket_api.ActiveConnection, msg: dict[str, Any] ) -> None: """Fix an issue.""" - ir.async_ignore_issue(hass, msg["domain"], msg["issue_id"], msg["ignore"]) + issue_registry = ir.async_get(hass) + if not issue_registry.async_get_issue(msg["domain"], msg["issue_id"]): + connection.send_error( + msg["id"], + "unknown_issue", + f"Issue '{msg['issue_id']}' not found", + ) + return + issue_registry.async_ignore(msg["domain"], msg["issue_id"], msg["ignore"]) connection.send_result(msg["id"]) diff --git a/tests/components/repairs/test_websocket_api.py b/tests/components/repairs/test_websocket_api.py index f4abff415934..03ab29fdf532 100644 --- a/tests/components/repairs/test_websocket_api.py +++ b/tests/components/repairs/test_websocket_api.py @@ -195,6 +195,10 @@ async def test_dismiss_issue( ) msg = await client.receive_json() assert not msg["success"] + assert msg["error"] == { + "code": "unknown_issue", + "message": "Issue 'no_such_issue' not found", + } await client.send_json( { From 1f93c36b88427ec8c2d6e3e889408eed1db7b9f4 Mon Sep 17 00:00:00 2001 From: Christian Lackas Date: Mon, 5 Oct 2026 22:33:39 +0200 Subject: [PATCH 076/356] Retry ViCare setup while no device is online (#184027) --- homeassistant/components/vicare/__init__.py | 3 ++ tests/components/vicare/test_init.py | 37 +++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/homeassistant/components/vicare/__init__.py b/homeassistant/components/vicare/__init__.py index c35445057b31..3f9f74cf730e 100644 --- a/homeassistant/components/vicare/__init__.py +++ b/homeassistant/components/vicare/__init__.py @@ -289,6 +289,9 @@ def _setup_vicare_api( devices.append( ViCareDevice(config=device_config, api=api, serial=get_device_serial(api)) ) + if device_config_list and not devices: + # Offline devices get no entities, and nothing would set them up later. + raise ConfigEntryNotReady("No ViCare device is online") return ViCareData(client=client, devices=devices) diff --git a/tests/components/vicare/test_init.py b/tests/components/vicare/test_init.py index ba59aa7ae1af..c2a4271cc6c0 100644 --- a/tests/components/vicare/test_init.py +++ b/tests/components/vicare/test_init.py @@ -989,6 +989,43 @@ async def test_offline_gateway_does_not_stretch_the_cache( assert client.services["gwC"].fetch_all_features.call_count == 0 +async def test_setup_retries_until_a_device_is_online( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, +) -> None: + """Setup retries while every device is offline and loads once one is back.""" + fixtures: list[Fixture] = [ + Fixture({"type:boiler"}, "vicare/Vitodens300W.json", online=False) + ] + client = MockPyViCare(fixtures) + client.loadViaGateway = Mock() + client.setCacheDuration = Mock() + client.initWithExternalOAuth = Mock() + + with ( + patch( + "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", + ), + patch(f"{MODULE}.PyViCare", return_value=client), + patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), + ): + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert mock_config_entry.reason == "No ViCare device is online" + + client.devices[0].status = "Online" + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert hass.states.get(SENSOR_ID).state != STATE_UNAVAILABLE + + async def test_setup_loads_with_unpaid_package_gateway( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 09dfa9fb8160ae32332d64e527e3396e1c2dd2e6 Mon Sep 17 00:00:00 2001 From: TheEvilCoder42 <35196983+TheEvilCoder42@users.noreply.github.com> Date: Mon, 5 Oct 2026 22:49:53 +0200 Subject: [PATCH 077/356] denonavr: keep Telnet connected when a zone's entity is removed (#184147) Co-authored-by: Claude Opus 5.5 (1M context) --- homeassistant/components/denonavr/__init__.py | 10 +-- .../components/denonavr/media_player.py | 2 - .../components/denonavr/test_media_player.py | 66 +++++++++++++++++-- 3 files changed, 66 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/denonavr/__init__.py b/homeassistant/components/denonavr/__init__.py index 4475bcd86c64..4c9058fcb3e5 100644 --- a/homeassistant/components/denonavr/__init__.py +++ b/homeassistant/components/denonavr/__init__.py @@ -65,7 +65,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: DenonavrConfigEntry) -> entry.runtime_data = receiver - await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) use_telnet = entry.options.get(CONF_USE_TELNET, DEFAULT_USE_TELNET) async def _async_disconnect(event: Event) -> None: @@ -74,10 +73,15 @@ async def async_setup_entry(hass: HomeAssistant, entry: DenonavrConfigEntry) -> await receiver.async_telnet_disconnect() if use_telnet: + # Not keyed on options at unload: an options change reloads the entry, and + # turning Telnet off there must still close the connection opened here. + entry.async_on_unload(entry.runtime_data.async_telnet_disconnect) entry.async_on_unload( hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, _async_disconnect) ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + return True @@ -89,10 +93,6 @@ async def async_unload_entry( config_entry, PLATFORMS ) - if config_entry.options.get(CONF_USE_TELNET, DEFAULT_USE_TELNET): - receiver = config_entry.runtime_data - await receiver.async_telnet_disconnect() - # Remove zone2 and zone3 entities if needed entity_registry = er.async_get(hass) entries = er.async_entries_for_config_entry(entity_registry, config_entry.entry_id) diff --git a/homeassistant/components/denonavr/media_player.py b/homeassistant/components/denonavr/media_player.py index db0afe38a818..e50c347fc12c 100644 --- a/homeassistant/components/denonavr/media_player.py +++ b/homeassistant/components/denonavr/media_player.py @@ -289,8 +289,6 @@ class DenonDevice(MediaPlayerEntity): @override async def async_will_remove_from_hass(self) -> None: """Clean up the entity.""" - if self._receiver.telnet_connected: - await self._receiver.async_telnet_disconnect() self._receiver.unregister_callback(ALL_TELNET_EVENTS, self._telnet_callback) @async_log_errors diff --git a/tests/components/denonavr/test_media_player.py b/tests/components/denonavr/test_media_player.py index 68be058f5838..d34453b2ee1a 100644 --- a/tests/components/denonavr/test_media_player.py +++ b/tests/components/denonavr/test_media_player.py @@ -1,9 +1,11 @@ """The tests for the denonavr media player platform.""" -from collections.abc import Generator +from collections.abc import Generator, Mapping from datetime import timedelta -from unittest.mock import MagicMock, patch +from typing import Any +from unittest.mock import MagicMock, create_autospec, patch +from denonavr import DenonAVR from denonavr.exceptions import AvrIncompleteResponseError, AvrInvalidResponseError from freezegun.api import FrozenDateTimeFactory import pytest @@ -15,7 +17,11 @@ from homeassistant.components.denonavr.config_flow import ( CONF_TYPE, DOMAIN, ) -from homeassistant.components.denonavr.const import ATTR_DYNAMIC_EQ, CONF_USE_TELNET +from homeassistant.components.denonavr.const import ( + ATTR_DYNAMIC_EQ, + CONF_USE_TELNET, + CONF_ZONE2, +) from homeassistant.components.denonavr.services import ( ATTR_COMMAND, SERVICE_GET_COMMAND, @@ -25,7 +31,7 @@ from homeassistant.components.denonavr.services import ( from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_ENTITY_ID, CONF_HOST, CONF_MODEL, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant -from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import device_registry as dr, entity_registry as er from tests.common import MockConfigEntry, async_fire_time_changed @@ -67,7 +73,9 @@ def client_fixture() -> Generator[MagicMock]: async def setup_denonavr( - hass: HomeAssistant, serial_number: str | None = TEST_SERIALNUMBER + hass: HomeAssistant, + serial_number: str | None = TEST_SERIALNUMBER, + options: Mapping[str, Any] | None = None, ) -> MockConfigEntry: """Initialize media_player for tests.""" entry_data = { @@ -82,6 +90,7 @@ async def setup_denonavr( domain=DOMAIN, unique_id=TEST_UNIQUE_ID if serial_number else None, data=entry_data, + options=options or {}, ) mock_entry.add_to_hass(hass) @@ -224,3 +233,50 @@ async def test_malformed_response_marks_unavailable( state = hass.states.get(ENTITY_ID) assert state.state == STATE_UNAVAILABLE + + +@pytest.mark.parametrize( + "unload_options", + [ + pytest.param({CONF_USE_TELNET: True, CONF_ZONE2: True}, id="options_unchanged"), + pytest.param( + {CONF_USE_TELNET: False, CONF_ZONE2: True}, id="telnet_turned_off" + ), + ], +) +async def test_telnet_outlives_zone_entity_removal( + hass: HomeAssistant, + client: MagicMock, + entity_registry: er.EntityRegistry, + unload_options: dict[str, bool], +) -> None: + """Test removing one zone's entity keeps Telnet, and unloading closes it.""" + zone2 = create_autospec(DenonAVR, instance=True) + zone2.name = TEST_NAME + zone2.zone = "Zone2" + zone2.input_func_list = [] + zone2.sound_mode_list = [] + client.zones = {"Main": client, "Zone2": zone2} + entry = await setup_denonavr( + hass, options={CONF_USE_TELNET: True, CONF_ZONE2: True} + ) + zone2_entity_id = entity_registry.async_get_entity_id( + media_player.DOMAIN, DOMAIN, f"{TEST_UNIQUE_ID}-Zone2" + ) + assert zone2_entity_id + + entity_registry.async_update_entity( + zone2_entity_id, disabled_by=er.RegistryEntryDisabler.USER + ) + await hass.async_block_till_done() + + assert hass.states.get(zone2_entity_id) is None + client.async_telnet_disconnect.assert_not_awaited() + zone2.async_telnet_disconnect.assert_not_awaited() + + # The options flow saves the new options before it reloads the entry. + hass.config_entries.async_update_entry(entry, options=unload_options) + assert await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + + client.async_telnet_disconnect.assert_awaited_once() From 4a0e0108a8b1e7dc62982e1bf5e1e6575c90a1b3 Mon Sep 17 00:00:00 2001 From: Tagliax <112966866+Tagliax@users.noreply.github.com> Date: Mon, 5 Oct 2026 23:11:53 +0200 Subject: [PATCH 078/356] Fix Netatmo schedule select depending on room features order (#184179) --- .../components/netatmo/coordinator.py | 7 +- tests/components/netatmo/test_select.py | 80 ++++++++++++++++++- 2 files changed, 83 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/netatmo/coordinator.py b/homeassistant/components/netatmo/coordinator.py index 7ab2370d8412..030a845ee463 100644 --- a/homeassistant/components/netatmo/coordinator.py +++ b/homeassistant/components/netatmo/coordinator.py @@ -537,9 +537,10 @@ class NetatmoDataHandler: self, home: pyatmo.Home, signal_home: str ) -> None: """Set up climate schedule per home.""" - if NetatmoDeviceCategory.climate in [ - next(iter(x)) for x in [room.features for room in home.rooms.values()] if x - ]: + if any( + NetatmoDeviceCategory.climate in room.features + for room in home.rooms.values() + ): self.schedules[home.entity_id] = self.account.homes[ home.entity_id ].schedules diff --git a/tests/components/netatmo/test_select.py b/tests/components/netatmo/test_select.py index c4067775b4b8..16873ac48ac1 100644 --- a/tests/components/netatmo/test_select.py +++ b/tests/components/netatmo/test_select.py @@ -1,7 +1,10 @@ """The tests for the Netatmo climate platform.""" +from collections.abc import Iterator +from typing import Any from unittest.mock import AsyncMock, patch +from pyatmo.room import Room import pytest from syrupy.assertion import SnapshotAssertion @@ -19,7 +22,13 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er -from .common import selected_platforms, simulate_webhook, snapshot_platform_entities +from .common import ( + HOME_ID, + fake_post_request, + selected_platforms, + simulate_webhook, + snapshot_platform_entities, +) from tests.common import MockConfigEntry @@ -126,3 +135,72 @@ async def test_select_schedule_unknown_schedule_id( await hass.async_block_till_done() assert hass.states.get(select_entity).state == original_state + + +class _ClimateLastFeatures(set[str]): + """Room features iterating with the climate feature last.""" + + def __iter__(self) -> Iterator[str]: + """Iterate over the features with climate last.""" + return iter( + sorted(super().__iter__(), key=lambda feature: feature == "climate") + ) + + +class _ClimateLastRoom(Room): + """Netatmo room iterating over its features with climate last. + + pyatmo keeps the room features in a set, so their iteration order + changes with the hash seed of the process. + """ + + def evaluate_device_type(self) -> None: + """Evaluate the device type keeping the features ordered.""" + self.features = _ClimateLastFeatures(self.features) + super().evaluate_device_type() + + +async def test_select_created_when_climate_is_not_first_room_feature( + hass: HomeAssistant, + config_entry: MockConfigEntry, +) -> None: + """Test the schedule select does not depend on the room features order. + + Simulate a home whose only climate room has a Smarther (BNS), which also + reports humidity, with the climate feature iterated last. + """ + + def keep_only_smarther_climate_room(payload: dict[str, Any]) -> None: + body = payload.get("body") + if not isinstance(body, dict): + return + for home in body.get("homes", []): + if home["id"] != HOME_ID: + continue + module_types = {module["id"]: module["type"] for module in home["modules"]} + for room in home["rooms"]: + room["module_ids"] = [ + module_id + for module_id in room.get("module_ids", []) + if module_types[module_id] not in {"NATherm1", "NRV", "OTH", "OTM"} + ] + + async def fake_post(*args: Any, **kwargs: Any): + return await fake_post_request( + hass, *args, msg_callback=keep_only_smarther_climate_room, **kwargs + ) + + with ( + selected_platforms([Platform.SELECT]), + patch( + "homeassistant.components.netatmo.api.AsyncConfigEntryNetatmoAuth" + ) as mock_auth, + patch("pyatmo.home.Room", _ClimateLastRoom), + ): + mock_auth.return_value.async_post_api_request.side_effect = fake_post + mock_auth.return_value.async_addwebhook.side_effect = AsyncMock() + mock_auth.return_value.async_dropwebhook.side_effect = AsyncMock() + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get("select.myhome_schedule").state == "Default" From b86fffc1f46b5ede317bc5cb20cb790352ea90b9 Mon Sep 17 00:00:00 2001 From: Jim Strang Date: Tue, 6 Oct 2026 01:55:46 -0400 Subject: [PATCH 079/356] Preserve UniFi UPS sensors during temporary telemetry gaps (#184231) --- homeassistant/components/unifi/sensor.py | 47 +++++-- tests/components/unifi/test_sensor.py | 164 ++++++++++++++++++++++- 2 files changed, 194 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/unifi/sensor.py b/homeassistant/components/unifi/sensor.py index aa58061f5e34..20750b01a213 100644 --- a/homeassistant/components/unifi/sensor.py +++ b/homeassistant/components/unifi/sensor.py @@ -207,18 +207,21 @@ def async_device_outlet_supported_fn(hub: UnifiHub, obj_id: str) -> bool: @callback def async_device_battery_pool_supported_fn( - field: str, hub: UnifiHub, obj_id: str + field: str, key: str, hub: UnifiHub, obj_id: str ) -> bool: - """Determine if a device provides a battery pool field.""" - return field in (hub.api.devices[obj_id].battery_pool or {}) + """Discover reported battery pool fields and retain discovered sensors.""" + return (key, obj_id) in hub.entity_loader.known_objects or ( + async_device_battery_pool_value_fn(field, hub, hub.api.devices[obj_id]) + is not None + ) @callback def async_device_battery_pool_value_fn( field: str, hub: UnifiHub, device: Device -) -> float | int: +) -> float | int | None: """Retrieve a battery pool field.""" - return cast(dict[str, float | int], device.battery_pool)[field] + return cast(dict[str, float | int | None], device.battery_pool or {}).get(field) @callback @@ -656,7 +659,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( available_fn=async_device_available_fn, device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], - supported_fn=partial(async_device_battery_pool_supported_fn, "batteryLevel"), + supported_fn=partial( + async_device_battery_pool_supported_fn, "batteryLevel", "UPS battery level" + ), unique_id_fn=lambda hub, obj_id: f"ups_battery_level-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "batteryLevel"), ), @@ -670,7 +675,11 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( available_fn=async_device_available_fn, device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], - supported_fn=partial(async_device_battery_pool_supported_fn, "timeToRemain"), + supported_fn=partial( + async_device_battery_pool_supported_fn, + "timeToRemain", + "UPS battery runtime", + ), unique_id_fn=lambda hub, obj_id: f"ups_battery_runtime-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "timeToRemain"), ), @@ -686,7 +695,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_total_power_output" + async_device_battery_pool_supported_fn, + "device_total_power_output", + "UPS output power", ), unique_id_fn=lambda hub, obj_id: f"ups_output_power-{obj_id}", value_fn=partial( @@ -705,7 +716,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_output_current" + async_device_battery_pool_supported_fn, + "device_output_current", + "UPS output current", ), unique_id_fn=lambda hub, obj_id: f"ups_output_current-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "device_output_current"), @@ -722,7 +735,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_output_voltage" + async_device_battery_pool_supported_fn, + "device_output_voltage", + "UPS output voltage", ), unique_id_fn=lambda hub, obj_id: f"ups_output_voltage-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "device_output_voltage"), @@ -739,7 +754,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_input_voltage" + async_device_battery_pool_supported_fn, + "device_input_voltage", + "UPS input voltage", ), unique_id_fn=lambda hub, obj_id: f"ups_input_voltage-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "device_input_voltage"), @@ -756,7 +773,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_bypass_voltage" + async_device_battery_pool_supported_fn, + "device_bypass_voltage", + "UPS bypass voltage", ), unique_id_fn=lambda hub, obj_id: f"ups_bypass_voltage-{obj_id}", value_fn=partial(async_device_battery_pool_value_fn, "device_bypass_voltage"), @@ -772,7 +791,9 @@ ENTITY_DESCRIPTIONS: tuple[UnifiSensorEntityDescription, ...] = ( device_info_fn=async_device_device_info_fn, object_fn=lambda api, obj_id: api.devices[obj_id], supported_fn=partial( - async_device_battery_pool_supported_fn, "device_total_power_factor" + async_device_battery_pool_supported_fn, + "device_total_power_factor", + "UPS output power factor", ), unique_id_fn=lambda hub, obj_id: f"ups_output_power_factor-{obj_id}", value_fn=partial( diff --git a/tests/components/unifi/test_sensor.py b/tests/components/unifi/test_sensor.py index 933ba6bfdd3c..9fbdef4d6a5a 100644 --- a/tests/components/unifi/test_sensor.py +++ b/tests/components/unifi/test_sensor.py @@ -1,5 +1,6 @@ """UniFi Network sensor platform tests.""" +from collections.abc import Callable from copy import deepcopy from datetime import datetime, timedelta from types import MappingProxyType @@ -50,6 +51,7 @@ from .conftest import ( ) from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform +from tests.test_util.aiohttp import AiohttpClientMocker WIRED_CLIENT = { "hostname": "Wired client", @@ -442,6 +444,27 @@ UPS_DEVICE_2.update( UPS_DEVICE_2["vbms_table"]["battpool"].pop("device_input_voltage") UPS_DEVICE_2["vbms_table"]["battpool"]["device_bypass_voltage"] = 121.7 +UPS_BATTERY_POOL_SENSORS = { + "batteryLevel": "battery_level", + "timeToRemain": "battery_runtime", + "device_total_power_output": "output_power", + "device_output_current": "output_current", + "device_output_voltage": "output_voltage", + "device_input_voltage": "input_voltage", + "device_bypass_voltage": "bypass_voltage", + "device_total_power_factor": "output_power_factor", +} + +UPS_BATTERY_POOL_FIELDS = [ + pytest.param([device], device_name, field, sensor, id=f"{device['model']}-{field}") + for device, device_name in ( + (UPS_DEVICE_1, "dummy_ups_2u_pro"), + (UPS_DEVICE_2, "dummy_ups_2u"), + ) + for field, sensor in UPS_BATTERY_POOL_SENSORS.items() + if field in device["vbms_table"]["battpool"] +] + @pytest.mark.parametrize( "config_entry_options", @@ -1109,9 +1132,18 @@ async def test_outlet_power_reading_extended_caps( ), ], ) -@pytest.mark.usefixtures("config_entry_setup") +@pytest.mark.parametrize( + "missing_telemetry", + [ + pytest.param({}, id="missing-table"), + pytest.param({"vbms_table": {}}, id="missing-pool"), + pytest.param({"vbms_table": {"battpool": {}}}, id="empty-pool"), + pytest.param({"vbms_table": {"battpool": None}}, id="null-pool"), + ], +) async def test_ups_battery_pool_sensors( hass: HomeAssistant, + config_entry_setup: MockConfigEntry, entity_registry: er.EntityRegistry, mock_websocket_message: WebsocketMessageMock, device_payload: list[dict[str, Any]], @@ -1120,6 +1152,7 @@ async def test_ups_battery_pool_sensors( voltage_value: str, missing_voltage_sensor: str, metered_outlets: tuple[int, ...], + missing_telemetry: dict[str, Any], ) -> None: """Test UPS battery pool telemetry sensors.""" assert { @@ -1139,6 +1172,10 @@ async def test_ups_battery_pool_sensors( hass.states.get(f"sensor.{device_name}_{voltage_sensor}").state == voltage_value ) assert hass.states.get(f"sensor.{device_name}_{missing_voltage_sensor}") is None + assert ( + entity_registry.async_get(f"sensor.{device_name}_{missing_voltage_sensor}") + is None + ) power_factor = hass.states.get(f"sensor.{device_name}_output_power_factor") assert power_factor is not None assert power_factor.state == "0.98" @@ -1152,12 +1189,131 @@ async def test_ups_battery_pool_sensors( assert hass.states.get(f"sensor.{device_name}_battery_level").state == "95" - updated_device_data["vbms_table"].pop("battpool") + expected_states = { + f"sensor.{device_name}_{UPS_BATTERY_POOL_SENSORS[field]}": str(value) + for field, value in device_payload[0]["vbms_table"]["battpool"].items() + } + registry_entries = { + entity_id: entity_registry.async_update_entity( + entity_id, name=f"Custom {entity_id}", icon="mdi:battery" + ) + for entity_id in expected_states + } + updated_device_data.pop("vbms_table") + updated_device_data.update(missing_telemetry) mock_websocket_message(message=MessageKey.DEVICE, data=updated_device_data) await hass.async_block_till_done() - assert hass.states.get(f"sensor.{device_name}_battery_level") is None - assert entity_registry.async_get(f"sensor.{device_name}_battery_level") is None + for entity_id, registry_entry in registry_entries.items(): + assert hass.states.get(entity_id).state == STATE_UNKNOWN + assert entity_registry.async_get(entity_id) == registry_entry + + mock_websocket_message(message=MessageKey.DEVICE, data=device_payload[0]) + await hass.async_block_till_done() + + for entity_id, expected_state in expected_states.items(): + assert hass.states.get(entity_id).state == expected_state + assert entity_registry.async_get(entity_id) == registry_entries[entity_id] + + config_entry_setup.runtime_data.api.devices.remove_item(device_payload[0]) + await hass.async_block_till_done() + + for entity_id in expected_states: + assert hass.states.get(entity_id) is None + assert entity_registry.async_get(entity_id) is None + + +@pytest.mark.parametrize( + ("device_payload", "device_name", "field", "sensor"), UPS_BATTERY_POOL_FIELDS +) +async def test_ups_battery_pool_readings( + hass: HomeAssistant, + config_entry_factory: ConfigEntryFactoryType, + entity_registry: er.EntityRegistry, + mock_websocket_message: WebsocketMessageMock, + device_payload: list[dict[str, Any]], + device_name: str, + field: str, + sensor: str, +) -> None: + """Test initial zero readings and recovery from missing or null fields.""" + original_device = deepcopy(device_payload[0]) + device_payload[0] = deepcopy(original_device) + device_payload[0]["vbms_table"]["battpool"][field] = 0 + await config_entry_factory() + + entity_id = f"sensor.{device_name}_{sensor}" + assert hass.states.get(entity_id).state == "0" + registry_entry = entity_registry.async_get(entity_id) + assert registry_entry is not None + + original_pool = original_device["vbms_table"]["battpool"] + missing_field_pool = deepcopy(original_pool) + missing_field_pool.pop(field) + for pool, expected_state in ( + (missing_field_pool, STATE_UNKNOWN), + (original_pool, str(original_pool[field])), + ({**original_pool, field: None}, STATE_UNKNOWN), + ({**original_pool, field: 0}, "0"), + ): + updated_device_data = deepcopy(original_device) + updated_device_data["vbms_table"]["battpool"] = pool + mock_websocket_message(message=MessageKey.DEVICE, data=updated_device_data) + await hass.async_block_till_done() + + assert hass.states.get(entity_id).state == expected_state + assert entity_registry.async_get(entity_id) == registry_entry + + +@pytest.mark.parametrize( + ("device_payload", "device_name", "field", "sensor"), UPS_BATTERY_POOL_FIELDS +) +@pytest.mark.parametrize( + "initial_readings", + [pytest.param((), id="missing"), pytest.param((None,), id="null")], +) +async def test_ups_battery_pool_late_field( + hass: HomeAssistant, + aioclient_mock: AiohttpClientMocker, + config_entry_factory: ConfigEntryFactoryType, + entity_registry: er.EntityRegistry, + mock_requests: Callable[[], None], + mock_websocket_message: WebsocketMessageMock, + device_payload: list[dict[str, Any]], + device_name: str, + field: str, + sensor: str, + initial_readings: tuple[None, ...], +) -> None: + """Test unsupported initial fields need a reload for later discovery.""" + original_device = deepcopy(device_payload[0]) + device_payload[0] = deepcopy(original_device) + pool = device_payload[0]["vbms_table"]["battpool"] + pool.pop(field) + for value in initial_readings: + pool[field] = value + config_entry = await config_entry_factory() + + entity_id = f"sensor.{device_name}_{sensor}" + assert hass.states.get(entity_id) is None + assert entity_registry.async_get(entity_id) is None + + mock_websocket_message(message=MessageKey.DEVICE, data=original_device) + await hass.async_block_till_done() + + assert hass.states.get(entity_id) is None + assert entity_registry.async_get(entity_id) is None + + device_payload[0] = original_device + aioclient_mock.clear_requests() + mock_requests() + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get(entity_id).state == str( + original_device["vbms_table"]["battpool"][field] + ) + assert entity_registry.async_get(entity_id) is not None @pytest.mark.parametrize( From 2d94bb9242ee7ee13e223f940bf1f1e7f2d557d0 Mon Sep 17 00:00:00 2001 From: Matthias Alphart Date: Mon, 5 Oct 2026 19:08:49 +0200 Subject: [PATCH 080/356] Update knx-frontend to 2026.10.5.160528 (#184338) --- homeassistant/components/knx/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/knx/manifest.json b/homeassistant/components/knx/manifest.json index e91b36f70f86..28ac16ee3d34 100644 --- a/homeassistant/components/knx/manifest.json +++ b/homeassistant/components/knx/manifest.json @@ -13,7 +13,7 @@ "requirements": [ "xknx==3.20.0", "xknxproject==3.10.0", - "knx-frontend==2026.9.29.213422", + "knx-frontend==2026.10.5.160528", "knx-telegram-store[sqlite,postgres]==0.14.0" ], "single_config_entry": true diff --git a/requirements_all.txt b/requirements_all.txt index 36a97f618455..df1147cc1d53 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1472,7 +1472,7 @@ kiwiki-client==0.1.2 knocki==0.4.2 # homeassistant.components.knx -knx-frontend==2026.9.29.213422 +knx-frontend==2026.10.5.160528 # homeassistant.components.knx knx-telegram-store[sqlite,postgres]==0.14.0 From 9b188cb136f7f048d492898e2b913ed5f31b4fd5 Mon Sep 17 00:00:00 2001 From: nicolaait Date: Mon, 5 Oct 2026 19:03:50 +0200 Subject: [PATCH 081/356] Bump renault-api to 0.5.15 (#184339) --- homeassistant/components/renault/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/renault/manifest.json b/homeassistant/components/renault/manifest.json index cb4c3420de54..c5214a2327ee 100644 --- a/homeassistant/components/renault/manifest.json +++ b/homeassistant/components/renault/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["renault_api"], "quality_scale": "silver", - "requirements": ["renault-api==0.5.14"] + "requirements": ["renault-api==0.5.15"] } diff --git a/requirements_all.txt b/requirements_all.txt index df1147cc1d53..f82ba3469b92 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2965,7 +2965,7 @@ refoss-ha==1.2.5 regenmaschine==2024.03.0 # homeassistant.components.renault -renault-api==0.5.14 +renault-api==0.5.15 # homeassistant.components.renson renson-endura-delta==1.7.2 From 1f35bc843174385ea4f36ef98835010a47636121 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 00:27:05 +0200 Subject: [PATCH 082/356] Bump wled to 1.0.0 (#184352) --- homeassistant/components/wled/light.py | 12 ++++-------- homeassistant/components/wled/manifest.json | 2 +- requirements_all.txt | 2 +- .../wled/snapshots/test_diagnostics.ambr | 5 +++++ tests/components/wled/test_light.py | 17 +++++++++++++++++ 5 files changed, 28 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/wled/light.py b/homeassistant/components/wled/light.py index 154a1d74b768..1cd6f940382d 100644 --- a/homeassistant/components/wled/light.py +++ b/homeassistant/components/wled/light.py @@ -159,14 +159,10 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): ) if ( - coordinator.data.info.leds.segment_light_capabilities is not None - and ( - color_modes := LIGHT_CAPABILITIES_COLOR_MODE_MAPPING.get( - coordinator.data.info.leds.segment_light_capabilities[segment] - ) - ) - is not None - ): + capabilities := coordinator.data.state.segments[segment].light_capabilities + ) is not None and ( + color_modes := LIGHT_CAPABILITIES_COLOR_MODE_MAPPING.get(capabilities) + ) is not None: self._attr_color_mode = color_modes[0] self._attr_supported_color_modes = set(color_modes) diff --git a/homeassistant/components/wled/manifest.json b/homeassistant/components/wled/manifest.json index fe7d16d968fb..47b87ddfc73b 100644 --- a/homeassistant/components/wled/manifest.json +++ b/homeassistant/components/wled/manifest.json @@ -7,6 +7,6 @@ "integration_type": "device", "iot_class": "local_push", "quality_scale": "platinum", - "requirements": ["wled==0.23.0"], + "requirements": ["wled==1.0.0"], "zeroconf": ["_wled._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index f82ba3469b92..afce6a31b349 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3457,7 +3457,7 @@ wiim==0.1.7 wirelesstagpy==0.8.1 # homeassistant.components.wled -wled==0.23.0 +wled==1.0.0 # homeassistant.components.wolflink wolf-comm==0.0.52 diff --git a/tests/components/wled/snapshots/test_diagnostics.ambr b/tests/components/wled/snapshots/test_diagnostics.ambr index cbcea893ee7e..0b2cca3bbcca 100644 --- a/tests/components/wled/snapshots/test_diagnostics.ambr +++ b/tests/components/wled/snapshots/test_diagnostics.ambr @@ -200,6 +200,7 @@ 'count': 30, 'fps': 5, 'light_capabilities': 1, + 'matrix': None, 'max_power': 850, 'max_segments': 32, 'power': 515, @@ -215,8 +216,10 @@ 'lm': '', 'mac': 'aabbccddeeff', 'name': 'WLED RGB Light', + 'opt': 79, 'palcount': 71, 'product': 'FOSS', + 'repo': 'wled/WLED', 'str': False, 'udpport': 21324, 'umpalcount': 0, @@ -345,6 +348,7 @@ 'grp': 1, 'id': 0, 'ix': 128, + 'lc': 1, 'len': 15, 'm12': 0, 'mY': False, @@ -397,6 +401,7 @@ 'grp': 1, 'id': 1, 'ix': 64, + 'lc': 1, 'len': 15, 'm12': 0, 'mY': False, diff --git a/tests/components/wled/test_light.py b/tests/components/wled/test_light.py index ad30b3f86101..e63799999d71 100644 --- a/tests/components/wled/test_light.py +++ b/tests/components/wled/test_light.py @@ -71,6 +71,23 @@ async def test_snapshots( await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) +async def test_segment_with_sparse_ids( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test segment lights still set up after a segment in the middle is deleted.""" + data = await async_load_json_object_fixture(hass, "rgb.json", DOMAIN) + data["state"]["seg"][1]["id"] = 2 + mock_wled.update.return_value = WLEDDevice.from_dict(data) + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("light.wled_rgb_light_segment_2")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.RGB] + + async def test_segment_change_state( hass: HomeAssistant, mock_wled: MagicMock, From ee45376062a183aa580e787b283034eb7e52896f Mon Sep 17 00:00:00 2001 From: G Johansson Date: Mon, 5 Oct 2026 21:35:39 +0200 Subject: [PATCH 083/356] Bump holidays to 0.105 (#184356) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/holiday/manifest.json | 2 +- homeassistant/components/workday/manifest.json | 2 +- requirements_all.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/holiday/manifest.json b/homeassistant/components/holiday/manifest.json index bf0fda4019bc..330d59f4f058 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.104", "babel==2.18.0"] + "requirements": ["holidays==0.105", "babel==2.18.0"] } diff --git a/homeassistant/components/workday/manifest.json b/homeassistant/components/workday/manifest.json index 018d73388c02..aaddbd02a9c9 100644 --- a/homeassistant/components/workday/manifest.json +++ b/homeassistant/components/workday/manifest.json @@ -8,5 +8,5 @@ "iot_class": "local_polling", "loggers": ["holidays"], "quality_scale": "internal", - "requirements": ["holidays==0.104"] + "requirements": ["holidays==0.105"] } diff --git a/requirements_all.txt b/requirements_all.txt index afce6a31b349..582b13091af3 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1309,7 +1309,7 @@ hole==0.9.2 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.104 +holidays==0.105 # homeassistant.components.frontend home-assistant-frontend==20260930.1 From 60de265c094bf51bcd87095a463b903b3750304e Mon Sep 17 00:00:00 2001 From: G Johansson Date: Tue, 6 Oct 2026 00:37:26 +0200 Subject: [PATCH 084/356] Bump holidays to 0.106 (#184358) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/holiday/manifest.json | 2 +- homeassistant/components/workday/manifest.json | 2 +- requirements_all.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/holiday/manifest.json b/homeassistant/components/holiday/manifest.json index 330d59f4f058..04fbce01dfe8 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.105", "babel==2.18.0"] + "requirements": ["holidays==0.106", "babel==2.18.0"] } diff --git a/homeassistant/components/workday/manifest.json b/homeassistant/components/workday/manifest.json index aaddbd02a9c9..79d6a4340b8c 100644 --- a/homeassistant/components/workday/manifest.json +++ b/homeassistant/components/workday/manifest.json @@ -8,5 +8,5 @@ "iot_class": "local_polling", "loggers": ["holidays"], "quality_scale": "internal", - "requirements": ["holidays==0.105"] + "requirements": ["holidays==0.106"] } diff --git a/requirements_all.txt b/requirements_all.txt index 582b13091af3..48ac57f43818 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1309,7 +1309,7 @@ hole==0.9.2 # homeassistant.components.holiday # homeassistant.components.workday -holidays==0.105 +holidays==0.106 # homeassistant.components.frontend home-assistant-frontend==20260930.1 From c6a21af2c6175fb6886cc1d40b69b8b15f65d677 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A5le=20Stor=C3=B8=20Hauknes?= <270292+LaStrada@users.noreply.github.com> Date: Tue, 6 Oct 2026 07:23:57 +0200 Subject: [PATCH 085/356] airthings_ble refresh firmware version (#184378) --- .../components/airthings_ble/coordinator.py | 9 +++++ tests/components/airthings_ble/test_sensor.py | 40 +++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/homeassistant/components/airthings_ble/coordinator.py b/homeassistant/components/airthings_ble/coordinator.py index 487fe635fa07..b1c071c89458 100644 --- a/homeassistant/components/airthings_ble/coordinator.py +++ b/homeassistant/components/airthings_ble/coordinator.py @@ -13,6 +13,7 @@ from homeassistant.components.bluetooth import BluetoothReachabilityIntent from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady +from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from .const import ( @@ -112,4 +113,12 @@ class AirthingsBLEDataUpdateCoordinator(DataUpdateCoordinator[AirthingsDevice]): translation_key="incomplete_read", ) + device_registry = dr.async_get(self.hass) + if ( + device := device_registry.async_get_device_by_connection( + (dr.CONNECTION_BLUETOOTH, data.address), self.config_entry.entry_id + ) + ) and device.sw_version != data.sw_version: + device_registry.async_update_device(device.id, sw_version=data.sw_version) + return data diff --git a/tests/components/airthings_ble/test_sensor.py b/tests/components/airthings_ble/test_sensor.py index 53595d62ae87..1e72947d4f5d 100644 --- a/tests/components/airthings_ble/test_sensor.py +++ b/tests/components/airthings_ble/test_sensor.py @@ -470,3 +470,43 @@ async def test_default_scan_interval_migration( async_fire_time_changed(hass) await hass.async_block_till_done() assert mock_update.call_count == 3 + + +async def test_device_registry_sw_version_updates_on_refresh( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, +) -> None: + """Test the device firmware version follows a firmware upgrade.""" + first_device = deepcopy(WAVE_DEVICE_INFO) + second_device = deepcopy(WAVE_DEVICE_INFO) + first_device.sw_version = "G-BLE-1.5.3-master+0" + second_device.sw_version = "G-BLE-2.2.3-master+0" + + entry = MockConfigEntry( + domain=DOMAIN, + unique_id=WAVE_SERVICE_INFO.address, + data={DEVICE_MODEL: first_device.model.value}, + ) + entry.add_to_hass(hass) + + inject_bluetooth_service_info(hass, WAVE_SERVICE_INFO) + + with ( + patch_async_ble_device_from_address(WAVE_SERVICE_INFO.device), + patch_airthings_ble(side_effect=[first_device, second_device]), + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + device = device_registry.async_get_device_by_connection( + (dr.CONNECTION_BLUETOOTH, WAVE_DEVICE_INFO.address), entry.entry_id + ) + assert device is not None + assert device.sw_version == "G-BLE-1.5.3-master+0" + + await entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + device = device_registry.async_get(device.id) + assert device is not None + assert device.sw_version == "G-BLE-2.2.3-master+0" From 50af977791b305e78ad30aec8789a9a26d951ced Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:07:47 +0200 Subject: [PATCH 086/356] Update aiohttp to 3.14.4 (#184382) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 610cfe9d70ae..fa13007cd785 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -6,7 +6,7 @@ aiodns==4.0.4 aiogithubapi==26.0.0 aiohttp-asyncmdnsresolver==0.2.0 aiohttp-fast-zlib==0.3.0 -aiohttp==3.14.3 +aiohttp==3.14.4 aiohttp_cors==0.8.1 aiousbwatcher==1.1.2 aiozoneinfo==0.2.3 diff --git a/pyproject.toml b/pyproject.toml index 3ccbd3d808d8..d539f2a903e4 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dependencies = [ # module level in `bootstrap.py` and its requirements thus need to be in # requirements.txt to ensure they are always installed "aiogithubapi==26.0.0", - "aiohttp==3.14.3", + "aiohttp==3.14.4", "aiohttp_cors==0.8.1", "aiohttp-fast-zlib==0.3.0", "aiohttp-asyncmdnsresolver==0.2.0", diff --git a/requirements.txt b/requirements.txt index f4ce0886261e..9a02e224c97a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ aiodns==4.0.4 aiogithubapi==26.0.0 aiohttp-asyncmdnsresolver==0.2.0 aiohttp-fast-zlib==0.3.0 -aiohttp==3.14.3 +aiohttp==3.14.4 aiohttp_cors==0.8.1 aiozoneinfo==0.2.3 annotatedyaml==1.0.2 From db0e4d1f478c93adcdd8aaa701449ec5b0f51c2e Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:08:17 +0200 Subject: [PATCH 087/356] Update uv to 0.12.23 (#184384) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index fa13007cd785..0c3c75b471a7 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -72,7 +72,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.20 +uv==0.12.23 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 diff --git a/pyproject.toml b/pyproject.toml index d539f2a903e4..fb0d668cc7f2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ dependencies = [ "typing-extensions>=4.16.0,<5.0", "ulid-transform==2.2.9", "urllib3>=2.0", - "uv==0.12.20", + "uv==0.12.23", "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", diff --git a/requirements.txt b/requirements.txt index 9a02e224c97a..d44315e35e8f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,7 +57,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.20 +uv==0.12.23 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 From d0c0f825e390271a4c9c5a10f5e03fb8eafc6575 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Tue, 6 Oct 2026 01:06:46 +0200 Subject: [PATCH 088/356] Update ical to 14.3.0 (#184385) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- homeassistant/components/google/manifest.json | 2 +- homeassistant/components/local_calendar/manifest.json | 2 +- homeassistant/components/local_todo/manifest.json | 2 +- homeassistant/components/remote_calendar/manifest.json | 2 +- requirements_all.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/google/manifest.json b/homeassistant/components/google/manifest.json index 335a0e5ea9e8..dfe147fa157e 100644 --- a/homeassistant/components/google/manifest.json +++ b/homeassistant/components/google/manifest.json @@ -8,5 +8,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["googleapiclient"], - "requirements": ["gcal-sync==9.2.0", "oauth2client==4.1.3", "ical==14.2.0"] + "requirements": ["gcal-sync==9.2.0", "oauth2client==4.1.3", "ical==14.3.0"] } diff --git a/homeassistant/components/local_calendar/manifest.json b/homeassistant/components/local_calendar/manifest.json index 6c8b74420057..2f9a7e60c4bc 100644 --- a/homeassistant/components/local_calendar/manifest.json +++ b/homeassistant/components/local_calendar/manifest.json @@ -7,5 +7,5 @@ "documentation": "https://www.home-assistant.io/integrations/local_calendar", "iot_class": "local_polling", "loggers": ["ical"], - "requirements": ["ical==14.2.0"] + "requirements": ["ical==14.3.0"] } diff --git a/homeassistant/components/local_todo/manifest.json b/homeassistant/components/local_todo/manifest.json index 2b5e7ce522c6..61fa916d6788 100644 --- a/homeassistant/components/local_todo/manifest.json +++ b/homeassistant/components/local_todo/manifest.json @@ -5,5 +5,5 @@ "config_flow": true, "documentation": "https://www.home-assistant.io/integrations/local_todo", "iot_class": "local_polling", - "requirements": ["ical==14.2.0"] + "requirements": ["ical==14.3.0"] } diff --git a/homeassistant/components/remote_calendar/manifest.json b/homeassistant/components/remote_calendar/manifest.json index 84fc117b01de..bd2cc564b7f4 100644 --- a/homeassistant/components/remote_calendar/manifest.json +++ b/homeassistant/components/remote_calendar/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["ical"], "quality_scale": "silver", - "requirements": ["ical==14.2.0"] + "requirements": ["ical==14.3.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 48ac57f43818..6e5a61431eff 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1357,7 +1357,7 @@ ibeacon-ble==1.2.0 # homeassistant.components.local_calendar # homeassistant.components.local_todo # homeassistant.components.remote_calendar -ical==14.2.0 +ical==14.3.0 # homeassistant.components.caldav icalendar==6.3.1 From a2ebb12561f4569e27c608bc3530eb4b98819b77 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 06:00:43 +0000 Subject: [PATCH 089/356] Bump version to 2026.10.0b2 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index d8e979a6cf83..8ee1cce3afca 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b1" +PATCH_VERSION: Final = "0b2" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index fb0d668cc7f2..39009b3b7a74 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b1" +version = "2026.10.0b2" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From fb5a13316053bc372f3937a782de9b05f1d6ef83 Mon Sep 17 00:00:00 2001 From: theorician Date: Tue, 6 Oct 2026 14:22:24 +0800 Subject: [PATCH 090/356] Fix MikroTik switch discovery for wifi interfaces (#181694) --- homeassistant/components/mikrotik/switch.py | 1 + .../mikrotik/snapshots/test_switch.ambr | 102 ++++++++++++++++++ tests/components/mikrotik/test_switch.py | 66 ++++++++++-- 3 files changed, 158 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/mikrotik/switch.py b/homeassistant/components/mikrotik/switch.py index 99da0d5f5aac..626420b40fe8 100644 --- a/homeassistant/components/mikrotik/switch.py +++ b/homeassistant/components/mikrotik/switch.py @@ -47,6 +47,7 @@ async def async_setup_entry( for switch_desc in SENSORS for interface in coordinator.api.interfaces if interface.get("type") == switch_desc.key + or (switch_desc.key == "wlan" and interface.get("type") == "wifi") ] async_add_entities(switch_list) diff --git a/tests/components/mikrotik/snapshots/test_switch.ambr b/tests/components/mikrotik/snapshots/test_switch.ambr index e4d464842c94..c594f8e8a572 100644 --- a/tests/components/mikrotik/snapshots/test_switch.ambr +++ b/tests/components/mikrotik/snapshots/test_switch.ambr @@ -50,6 +50,108 @@ 'state': 'on', }) # --- +# name: test_switch_entities_created[switch.wifi1_wlan-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + '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.wifi1_wlan', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'WLAN', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'WLAN', + 'platform': 'mikrotik', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'wlan', + 'unique_id': '02_00_00_00_00_04_wifi1', + 'unit_of_measurement': None, + }) +# --- +# name: test_switch_entities_created[switch.wifi1_wlan-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'switch', + : 'wifi1 WLAN', + }), + 'context': , + 'entity_id': 'switch.wifi1_wlan', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_switch_entities_created[switch.wifi2_wlan-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + '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.wifi2_wlan', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'WLAN', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'WLAN', + 'platform': 'mikrotik', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'wlan', + 'unique_id': '02_00_00_00_00_05_wifi2', + 'unit_of_measurement': None, + }) +# --- +# name: test_switch_entities_created[switch.wifi2_wlan-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'switch', + : 'wifi2 WLAN', + }), + 'context': , + 'entity_id': 'switch.wifi2_wlan', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- # name: test_switch_entities_created[switch.wlan1_wlan-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/mikrotik/test_switch.py b/tests/components/mikrotik/test_switch.py index c2f93374f02f..fc2560e28b03 100644 --- a/tests/components/mikrotik/test_switch.py +++ b/tests/components/mikrotik/test_switch.py @@ -20,6 +20,23 @@ from .const import BRIDGE1_INTERFACE, ETHER1_INTERFACE, INTERFACE_DATA, WLAN1_IN from tests.common import snapshot_platform +WIFI1_INTERFACE = { + ".id": "*4", + "name": "wifi1", + "type": "wifi", + "mac-address": "02:00:00:00:00:04", + "running": True, + "disabled": False, +} +WIFI2_INTERFACE = { + ".id": "*5", + "name": "wifi2", + "type": "wifi", + "mac-address": "02:00:00:00:00:05", + "running": False, + "disabled": True, +} + async def test_switch_entities_created( hass: HomeAssistant, @@ -28,23 +45,44 @@ async def test_switch_entities_created( ) -> None: """Test Mikrotik switch entities are created with expected values.""" with patch("homeassistant.components.mikrotik.PLATFORMS", [Platform.SWITCH]): - config_entry = await setup_mikrotik_entry(hass, interface_data=INTERFACE_DATA) + config_entry = await setup_mikrotik_entry( + hass, interface_data=[*INTERFACE_DATA, WIFI1_INTERFACE, WIFI2_INTERFACE] + ) + + assert sorted(hass.states.async_entity_ids(SWITCH_DOMAIN)) == [ + "switch.ether1_ethernet", + "switch.wifi1_wlan", + "switch.wifi2_wlan", + "switch.wlan1_wlan", + ] await snapshot_platform(hass, entity_registry, snapshot, config_entry.entry_id) -async def test_switch_no_matching_interfaces(hass: HomeAssistant) -> None: +@pytest.mark.parametrize("interface_type", ["bridge", "vlan", "wireguard", None]) +async def test_switch_no_matching_interfaces( + hass: HomeAssistant, interface_type: str | None +) -> None: """Test no switch entities are created for unsupported interface types.""" with patch("homeassistant.components.mikrotik.PLATFORMS", [Platform.SWITCH]): - await setup_mikrotik_entry(hass, interface_data=[BRIDGE1_INTERFACE]) + await setup_mikrotik_entry( + hass, interface_data=[{**BRIDGE1_INTERFACE, "type": interface_type}] + ) assert hass.states.async_entity_ids(SWITCH_DOMAIN) == [] +@pytest.mark.parametrize( + ("interface", "entity_id"), + [ + pytest.param(ETHER1_INTERFACE, "switch.ether1_ethernet", id="ether"), + pytest.param(WLAN1_INTERFACE, "switch.wlan1_wlan", id="wlan"), + pytest.param(WIFI1_INTERFACE, "switch.wifi1_wlan", id="wifi1"), + pytest.param(WIFI2_INTERFACE, "switch.wifi2_wlan", id="wifi2"), + ], +) @pytest.mark.parametrize( ( - "interface", - "entity_id", "initial_state", "service", "command", @@ -52,8 +90,6 @@ async def test_switch_no_matching_interfaces(hass: HomeAssistant) -> None: ), [ pytest.param( - ETHER1_INTERFACE, - "switch.ether1_ethernet", STATE_ON, SERVICE_TURN_OFF, "/interface/disable", @@ -61,8 +97,6 @@ async def test_switch_no_matching_interfaces(hass: HomeAssistant) -> None: id="turn_off", ), pytest.param( - WLAN1_INTERFACE, - "switch.wlan1_wlan", STATE_OFF, SERVICE_TURN_ON, "/interface/enable", @@ -83,13 +117,23 @@ async def test_switch_turn_on_off( ) -> None: """Test turning a Mikrotik switch on/off updates state via the coordinator.""" + interfaces = { + item[".id"]: {**item, "disabled": initial_state == STATE_OFF} + for item in ( + ETHER1_INTERFACE, + WLAN1_INTERFACE, + WIFI1_INTERFACE, + WIFI2_INTERFACE, + ) + } with patch("homeassistant.components.mikrotik.PLATFORMS", [Platform.SWITCH]): - await setup_mikrotik_entry(hass, interface_data=[interface]) + await setup_mikrotik_entry(hass, interface_data=list(interfaces.values())) assert (state := hass.states.get(entity_id)) assert state.state == initial_state - mock_api.return_value = [{**interface, "disabled": final_state == STATE_OFF}] + interfaces[interface[".id"]]["disabled"] = final_state == STATE_OFF + mock_api.return_value = list(interfaces.values()) await hass.services.async_call( SWITCH_DOMAIN, From e8307f85a59af7a253dcd8d12fe3f0fd9dae6a0d Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Sun, 4 Oct 2026 17:53:26 +1000 Subject: [PATCH 091/356] Clarify Teslemetry Bluetooth key enrolment (#184189) --- .../components/teslemetry/config_flow.py | 33 +++++++- .../components/teslemetry/strings.json | 13 ++- .../components/teslemetry/test_config_flow.py | 80 ++++++++++++++++++- 3 files changed, 120 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 9c3e4ba53bbf..04a8d0cb8fa5 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -24,6 +24,11 @@ from tesla_fleet_api.exceptions import ( SubscriptionRequired, TeslaFleetError, WhitelistOperationAttemptingToAddExistingKey, + WhitelistOperationCouldNotStartLocalEntityAuth, + WhitelistOperationLocalEntityAuthFailedCancelled, + WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForTap, + WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForUIAck, + WhitelistOperationLocalEntityAuthFailedUIDenied, ) from tesla_fleet_api.tesla import EnergySiteRouter from tesla_fleet_api.tesla.vehicle.bluetooth import VehicleBluetooth @@ -230,6 +235,7 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): self._vehicle: VehicleBluetooth | None = None self._pair_task: asyncio.Task[None] | None = None self._pair_error: dict[str, str] = {} + self._key_added = False async def async_step_user( self, user_input: dict[str, Any] | None = None @@ -339,7 +345,10 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): # The scan step owns the form; re-show it so a retry redoes scan and connect. return self.async_show_form( step_id="scan", - errors={"base": "cannot_connect"}, + # The key is already on the vehicle; say so rather than prompt a re-pair. + errors={ + "base": "key_unverified" if self._key_added else "cannot_connect" + }, description_placeholders={"vin": self._vin or ""}, ) if TYPE_CHECKING: @@ -398,6 +407,27 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): return self.async_show_progress_done(next_step_id="instructions") except WhitelistOperationAttemptingToAddExistingKey as err: LOGGER.debug("Virtual key is already on the whitelist: %s", err) + except WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForTap as err: + LOGGER.debug( + "No key card was tapped before the vehicle stopped waiting: %s", err + ) + self._pair_error = {"base": "tap_timeout"} + return self.async_show_progress_done(next_step_id="instructions") + except WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForUIAck as err: + LOGGER.debug("Key was not confirmed on the vehicle touchscreen: %s", err) + self._pair_error = {"base": "confirm_timeout"} + return self.async_show_progress_done(next_step_id="instructions") + except ( + WhitelistOperationLocalEntityAuthFailedUIDenied, + WhitelistOperationLocalEntityAuthFailedCancelled, + ) as err: + LOGGER.debug("Key was declined on the vehicle touchscreen: %s", err) + self._pair_error = {"base": "pair_denied"} + return self.async_show_progress_done(next_step_id="instructions") + except WhitelistOperationCouldNotStartLocalEntityAuth as err: + LOGGER.debug("Vehicle could not start the key card request: %s", err) + self._pair_error = {"base": "auth_not_started"} + return self.async_show_progress_done(next_step_id="instructions") except TeslaFleetError as err: LOGGER.error("Bluetooth pairing was rejected: %s", err) self._pair_error = {"base": "pair_failed"} @@ -406,6 +436,7 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): # async_remove() only runs if the flow is still tracked when this step raises. await self._async_disconnect() raise + self._key_added = True return self.async_show_progress_done(next_step_id="pair") async def _async_disconnect(self) -> None: diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index 6bbde906044f..df96137ffd1e 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -98,21 +98,26 @@ }, "entry_type": "Bluetooth vehicle", "error": { + "auth_not_started": "The vehicle could not start the key card request. Wake the vehicle, then select Submit to try again.", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "confirm_timeout": "The key was not confirmed on the vehicle's touchscreen in time. Select Submit, tap a key card, then confirm the prompt on the vehicle's touchscreen.", "device_not_found": "No matching Tesla vehicle was found nearby over Bluetooth. Make sure the vehicle is awake and within range, then try again.", + "key_unverified": "The key was added, but the vehicle's reply could not be verified. Select Submit to try again.", + "pair_denied": "The key was declined on the vehicle's touchscreen. Select Submit and tap a key card to try again.", "pair_failed": "The vehicle rejected the key. Make sure it is not in valet mode and does not already have the maximum number of keys, then try again.", - "timeout": "Timed out waiting for the vehicle to accept the key. Try again after approving the key on the vehicle's touchscreen." + "tap_timeout": "The key card was not tapped in time. Select Submit and tap a key card within 30 seconds.", + "timeout": "Timed out waiting for the vehicle to add the key. Select Submit and tap a key card on the center console card reader." }, "initiate_flow": { "user": "Add local vehicle" }, "progress": { - "pair": "Approve Home Assistant's virtual key on the vehicle's touchscreen. Waiting for the vehicle to accept the key." + "pair": "Tap a key card on the center console card reader now. The vehicle stops waiting after about 30 seconds." }, "step": { "instructions": { - "description": "Select **Submit**, then place your key card against the center console card reader of vehicle {vin} to approve Home Assistant's virtual key. This only needs to be done once.", - "title": "Approve the virtual key" + "description": "Vehicle {vin} does not have Home Assistant's Bluetooth key on its key list. This is expected the first time, and happens again if the key was removed from the vehicle. To add it, select **Submit**, then tap a key card on the center console card reader within about 30 seconds. The vehicle's touchscreen shows a prompt while it waits for the card.", + "title": "Add Home Assistant's key to the vehicle" }, "scan": { "description": "Home Assistant will look for vehicle {vin} over Bluetooth. Make sure the vehicle is within Bluetooth range of a Home Assistant Bluetooth adapter and has fewer than three phone keys in range, then continue.", diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 05011243c09d..4506d5eebe09 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -27,9 +27,15 @@ from tesla_fleet_api.exceptions import ( InvalidToken, NotOnWhitelistFault, PrivateKeyError, + SessionInfoAuthenticationFault, SubscriptionRequired, TeslaFleetError, WhitelistOperationAttemptingToAddExistingKey, + WhitelistOperationCouldNotStartLocalEntityAuth, + WhitelistOperationLocalEntityAuthFailedCancelled, + WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForTap, + WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForUIAck, + WhitelistOperationLocalEntityAuthFailedUIDenied, ) from tesla_fleet_api.tesla import VehicleRouter from tesla_fleet_api.tesla.bluetooth import TeslaBluetooth @@ -916,6 +922,61 @@ async def test_subentry_pairing_requires_key_approval(hass: HomeAssistant) -> No vehicle.pair.assert_awaited_once() +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_handshake_fails_after_pairing(hass: HomeAssistant) -> None: + """A handshake failure after the key was added says so; retrying finishes without re-pairing.""" + entry = await _setup_account_entry(hass) + vehicle = _mock_vehicle() + vehicle.handshakeVehicleSecurity = AsyncMock( + side_effect=[NotOnWhitelistFault(), SessionInfoAuthenticationFault(), None] + ) + release = asyncio.Event() + + async def _pair() -> None: + await release.wait() + + vehicle.pair = AsyncMock(side_effect=_pair) + + with ( + patch( + "homeassistant.components.teslemetry.config_flow.async_discovered_service_info", + return_value=[_discovered_info()], + ), + patch( + "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", + return_value=_mock_ble_parent(vehicle), + ), + patch.object(hass.config_entries, "async_schedule_reload"), + ): + result = await _start_pairing_at_scan(hass, entry) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + assert result["step_id"] == "instructions" + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + assert result["type"] is FlowResultType.SHOW_PROGRESS + + release.set() + await hass.async_block_till_done() + result = await hass.config_entries.subentries.async_configure(result["flow_id"]) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "scan" + assert result["errors"] == {"base": "key_unverified"} + assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert len(entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE)) == 1 + vehicle.pair.assert_awaited_once() + + @pytest.mark.usefixtures("enable_bluetooth") async def test_subentry_scan_connect_fails(hass: HomeAssistant) -> None: """The scan step re-shows the form with an error when BLE connect fails.""" @@ -951,9 +1012,26 @@ async def test_subentry_scan_connect_fails(hass: HomeAssistant) -> None: [ (BluetoothTimeout, "timeout"), (BluetoothTransportError, "cannot_connect"), + (WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForTap, "tap_timeout"), + ( + WhitelistOperationLocalEntityAuthFailedTimedOutWaitingForUIAck, + "confirm_timeout", + ), + (WhitelistOperationLocalEntityAuthFailedUIDenied, "pair_denied"), + (WhitelistOperationLocalEntityAuthFailedCancelled, "pair_denied"), + (WhitelistOperationCouldNotStartLocalEntityAuth, "auth_not_started"), (TeslaFleetError, "pair_failed"), ], - ids=["timeout", "transport", "rejected"], + ids=[ + "timeout", + "transport", + "tap_timeout", + "ui_ack_timeout", + "denied", + "cancelled", + "auth_not_started", + "rejected", + ], ) @pytest.mark.usefixtures("enable_bluetooth") async def test_subentry_authorize_failure( From e6eba7f72f663984071dd829217eeb57898ddedd Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Sun, 4 Oct 2026 23:08:17 +1000 Subject: [PATCH 092/356] Always disconnect Teslemetry Bluetooth after a failed pairing step (#184190) --- .../components/teslemetry/config_flow.py | 39 +++--- .../components/teslemetry/test_config_flow.py | 132 ++++++++++++++++-- 2 files changed, 144 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 04a8d0cb8fa5..5d728aa87b3a 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -341,7 +341,6 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): return await self.async_step_instructions() except (BleakError, TeslaFleetError, TimeoutError) as err: LOGGER.error("Bluetooth security handshake failed: %s", err) - await self._async_disconnect() # The scan step owns the form; re-show it so a retry redoes scan and connect. return self.async_show_form( step_id="scan", @@ -351,10 +350,13 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): }, description_placeholders={"vin": self._vin or ""}, ) + finally: + # Never hold the link while waiting on the user: a closed tab never removes the flow. + await self._async_disconnect() if TYPE_CHECKING: assert self._address is not None assert self._vin is not None - await self._async_disconnect() + self._vehicle = None return self.async_create_entry( title=self._title or self._vin, data={CONF_VIN: self._vin, CONF_ADDRESS: self._address}, @@ -380,10 +382,8 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): ) -> SubentryFlowResult: """Add the virtual key to the vehicle while showing pairing progress.""" if self._pair_task is None: - if TYPE_CHECKING: - assert self._vehicle is not None # pair() can take minutes, so run it as a progress task rather than blocking the flow. - self._pair_task = self.hass.async_create_task(self._vehicle.pair()) + self._pair_task = self.hass.async_create_task(self._async_pair()) if not self._pair_task.done(): return self.async_show_progress( @@ -432,31 +432,36 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): LOGGER.error("Bluetooth pairing was rejected: %s", err) self._pair_error = {"base": "pair_failed"} return self.async_show_progress_done(next_step_id="instructions") - except Exception: - # async_remove() only runs if the flow is still tracked when this step raises. - await self._async_disconnect() - raise self._key_added = True return self.async_show_progress_done(next_step_id="pair") + async def _async_pair(self) -> None: + """Add the key over a link that never outlives the attempt.""" + if TYPE_CHECKING: + assert self._vehicle is not None + try: + # The library reconnects on demand, so each attempt starts from a new link. + await self._vehicle.pair() + finally: + await self._async_disconnect() + async def _async_disconnect(self) -> None: - """Disconnect the BLE link, if any, and drop the reference to it.""" - vehicle = self._vehicle - if vehicle is not None: + """Disconnect the BLE link, if any.""" + # Keep the reference: a step may still be awaiting this vehicle when the flow is removed. + if self._vehicle is not None: try: - await vehicle.disconnect() + await self._vehicle.disconnect() except (BleakError, TeslaFleetError, TimeoutError) as err: LOGGER.debug("Error disconnecting Bluetooth: %s", err) - finally: - self._vehicle = None @callback @override def async_remove(self) -> None: """Release resources if the flow is abandoned mid-pairing.""" - if self._pair_task is not None and not self._pair_task.done(): + # The pair task disconnects when it ends, so only disconnect here without one. + if self._pair_task is not None: self._pair_task.cancel() - if self._vehicle is not None: + elif self._vehicle is not None: self.hass.async_create_task(self._async_disconnect()) diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 4506d5eebe09..f19316cb07e2 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -64,7 +64,7 @@ from homeassistant.config_entries import ( ) from homeassistant.const import CONF_ADDRESS, CONF_HOST, CONF_PASSWORD from homeassistant.core import HomeAssistant -from homeassistant.data_entry_flow import FlowResultType +from homeassistant.data_entry_flow import FlowResultType, UnknownFlow from homeassistant.helpers import ( config_entry_oauth2_flow, device_registry as dr, @@ -752,6 +752,15 @@ def _mock_ble_parent(vehicle: AsyncMock) -> MagicMock: return parent +def _link_calls(vehicle: AsyncMock) -> list[str]: + """Return the vehicle calls that open, use or close the BLE link, in order.""" + return [ + name + for name, _, _ in vehicle.mock_calls + if name in {"connect", "handshakeVehicleSecurity", "pair", "disconnect"} + ] + + async def _setup_account_entry(hass: HomeAssistant) -> MockConfigEntry: """Set up an account entry with no vehicle subentry.""" entry = mock_config_entry() @@ -903,6 +912,12 @@ async def test_subentry_pairing_requires_key_approval(hass: HomeAssistant) -> No ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "instructions" + # The link is not held while the form waits on the user. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + ] result = await hass.config_entries.subentries.async_configure( result["flow_id"], {} @@ -919,7 +934,16 @@ async def test_subentry_pairing_requires_key_approval(hass: HomeAssistant) -> No subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) assert len(subentries) == 1 assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} - vehicle.pair.assert_awaited_once() + # pair() and the follow-up handshake each reconnect on demand and disconnect after. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "pair", + "disconnect", + "handshakeVehicleSecurity", + "disconnect", + ] @pytest.mark.usefixtures("enable_bluetooth") @@ -1077,8 +1101,15 @@ async def test_subentry_authorize_failure( assert result["step_id"] == "instructions" assert result["errors"] == {"base": expected} assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) - # pair() is a single bounded op; it is never re-sent. - vehicle.pair.assert_awaited_once() + # pair() is a single bounded op; it is never re-sent, and its link is dropped + # before the form is re-shown. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "pair", + "disconnect", + ] @pytest.mark.usefixtures("enable_bluetooth") @@ -1109,7 +1140,13 @@ async def test_subentry_authorize_unexpected_error_disconnects( with pytest.raises(ValueError, match="boom"): await hass.config_entries.subentries.async_configure(result["flow_id"], {}) - vehicle.disconnect.assert_awaited_once() + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "pair", + "disconnect", + ] assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) @@ -1176,8 +1213,18 @@ async def test_subentry_authorize_existing_key_finishes(hass: HomeAssistant) -> subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) assert len(subentries) == 1 assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} - assert vehicle.pair.await_count == 2 - vehicle.disconnect.assert_awaited_once() + # The retry runs on a new link: the failed attempt disconnected first. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "pair", + "disconnect", + "pair", + "disconnect", + "handshakeVehicleSecurity", + "disconnect", + ] @pytest.mark.parametrize( @@ -1227,8 +1274,16 @@ async def test_subentry_handshake_error_recovers( subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) assert len(subentries) == 1 assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} - # Both the failed and successful attempts disconnected; the disconnect error is swallowed. - assert vehicle.disconnect.await_count == 2 + # The retry connects afresh after the failed attempt disconnected; the disconnect + # error is swallowed. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "connect", + "handshakeVehicleSecurity", + "disconnect", + ] @pytest.mark.usefixtures("enable_bluetooth") @@ -1270,11 +1325,68 @@ async def test_subentry_pairing_abandoned(hass: HomeAssistant) -> None: await hass.async_block_till_done() assert cancelled.is_set() - vehicle.disconnect.assert_awaited_once() + # The cancelled pair task owns the disconnect, so async_remove must not add a second one. + assert _link_calls(vehicle) == [ + "connect", + "handshakeVehicleSecurity", + "disconnect", + "pair", + "disconnect", + ] # An abandoned pairing never creates a subentry. assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_abandoned_during_connect_disconnects( + hass: HomeAssistant, +) -> None: + """Closing the dialog while connect is in flight still drops the link it opens.""" + entry = await _setup_account_entry(hass) + vehicle = _mock_vehicle(on_whitelist=False) + connecting = asyncio.Event() + release = asyncio.Event() + + async def _connect() -> None: + connecting.set() + await release.wait() + + vehicle.connect = AsyncMock(side_effect=_connect) + + with ( + patch( + "homeassistant.components.teslemetry.config_flow.async_discovered_service_info", + return_value=[_discovered_info()], + ), + patch( + "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", + return_value=_mock_ble_parent(vehicle), + ), + ): + result = await _start_pairing_at_scan(hass, entry) + flow_id = result["flow_id"] + configure = hass.async_create_task( + hass.config_entries.subentries.async_configure(flow_id, {}) + ) + await connecting.wait() + + hass.config_entries.subentries.async_abort(flow_id) + release.set() + with pytest.raises(UnknownFlow): + await configure + await hass.async_block_till_done() + + # The abort's disconnect ran before connect finished, so the step itself must + # close the link that connect then opened. + assert _link_calls(vehicle) == [ + "connect", + "disconnect", + "handshakeVehicleSecurity", + "disconnect", + ] + assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + + @pytest.mark.usefixtures("enable_bluetooth") async def test_subentry_scan_device_not_found(hass: HomeAssistant) -> None: """The scan step re-shows the form with an error when no device is found.""" From 0a9d09f4b6987b33b6e3acb7d2d5c0daa01d922d Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Tue, 6 Oct 2026 16:59:46 +1000 Subject: [PATCH 093/356] Make Teslemetry Bluetooth onboarding messages actionable (#184216) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- .../components/teslemetry/config_flow.py | 9 ++++++-- .../components/teslemetry/strings.json | 8 ++++--- .../components/teslemetry/test_config_flow.py | 22 ++++++++++++++++++- 3 files changed, 33 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 5d728aa87b3a..bd0e54a520cf 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -74,6 +74,7 @@ from .const import ( POWERWALL_KEY_FILE, SUBENTRY_TYPE_ENERGY_SITE, SUBENTRY_TYPE_VEHICLE, + VEHICLE_KEY_FILE, ) from .helpers import ( PowerwallKeyRejectedError, @@ -257,6 +258,8 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): if vehicle.vin not in already_added } if not choices: + if entry.runtime_data.vehicles: + return self.async_abort(reason="all_vehicles_added") return self.async_abort(reason="no_vehicles") if user_input is not None: @@ -288,13 +291,15 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): if TYPE_CHECKING: assert self._vin is not None errors: dict[str, str] = {} + placeholders = {"vin": self._vin} if user_input is not None: try: parent = await async_get_ble_parent(self.hass) except _BLE_KEY_ERRORS as err: LOGGER.debug("Bluetooth key load failed: %s", err) - errors["base"] = "cannot_connect" + errors["base"] = "key_load_failed" + placeholders["key_file"] = self.hass.config.path(VEHICLE_KEY_FILE) else: # The advertised BLE name is a hash of the VIN; match on its prefix. expected = parent.get_name(self._vin)[:17] @@ -326,7 +331,7 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): return self.async_show_form( step_id="scan", errors=errors, - description_placeholders={"vin": self._vin}, + description_placeholders=placeholders, ) async def async_step_pair( diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index df96137ffd1e..54ecb2ad94bb 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -91,17 +91,19 @@ }, "vehicle": { "abort": { + "all_vehicles_added": "Every accessible vehicle in your Teslemetry account has already been added as a local vehicle.", "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", - "bluetooth_not_available": "At least one Bluetooth adapter or remote Bluetooth proxy must be configured to add a vehicle over Bluetooth.", + "bluetooth_not_available": "Adding a vehicle over Bluetooth needs a Bluetooth adapter on the Home Assistant host or a remote Bluetooth proxy that supports active connections, such as an ESPHome Bluetooth proxy. Shelly devices only listen for Bluetooth devices and cannot connect to a vehicle.", "entry_not_loaded": "The Teslemetry configuration entry is not loaded. Please ensure it is set up correctly before adding a vehicle.", - "no_vehicles": "Every eligible vehicle in your Teslemetry account has already been added over Bluetooth." + "no_vehicles": "Home Assistant cannot access any vehicles in your Teslemetry account. Check that the vehicle is in your account and that Teslemetry has access to it." }, "entry_type": "Bluetooth vehicle", "error": { "auth_not_started": "The vehicle could not start the key card request. Wake the vehicle, then select Submit to try again.", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "confirm_timeout": "The key was not confirmed on the vehicle's touchscreen in time. Select Submit, tap a key card, then confirm the prompt on the vehicle's touchscreen.", - "device_not_found": "No matching Tesla vehicle was found nearby over Bluetooth. Make sure the vehicle is awake and within range, then try again.", + "device_not_found": "No matching Tesla vehicle was found nearby over Bluetooth. Make sure the vehicle is within range of a Bluetooth adapter or proxy, then try again.", + "key_load_failed": "The Bluetooth key file {key_file} could not be loaded. Make sure it is a valid private key and that Home Assistant has permission to read it, then try again.", "key_unverified": "The key was added, but the vehicle's reply could not be verified. Select Submit to try again.", "pair_denied": "The key was declined on the vehicle's touchscreen. Select Submit and tap a key card to try again.", "pair_failed": "The vehicle rejected the key. Make sure it is not in valet mode and does not already have the maximum number of keys, then try again.", diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index f19316cb07e2..b6ed63a474b7 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -54,6 +54,7 @@ from homeassistant.components.teslemetry.const import ( SUBENTRY_TYPE_ENERGY_SITE, SUBENTRY_TYPE_VEHICLE, TOKEN_URL, + VEHICLE_KEY_FILE, ) from homeassistant.config_entries import ( SOURCE_USER, @@ -1450,7 +1451,12 @@ async def test_subentry_scan_key_load_recovers( ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "scan" - assert result["errors"] == {"base": "cannot_connect"} + assert result["errors"] == {"base": "key_load_failed"} + # The error names the key file so the user knows what to fix. + assert result["description_placeholders"] == { + "vin": VIN, + "key_file": hass.config.path(VEHICLE_KEY_FILE), + } assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) result = await hass.config_entries.subentries.async_configure( @@ -1621,6 +1627,20 @@ async def test_subentry_add_flow_no_available_vehicles(hass: HomeAssistant) -> N context={"source": "user"}, ) + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "all_vehicles_added" + + +@pytest.mark.usefixtures("enable_bluetooth", "mock_energy_only") +async def test_subentry_add_flow_account_has_no_vehicles(hass: HomeAssistant) -> None: + """The add flow aborts when the account has no vehicles to add.""" + entry = await _setup_account_entry(hass) + + result = await hass.config_entries.subentries.async_init( + (entry.entry_id, SUBENTRY_TYPE_VEHICLE), + context={"source": "user"}, + ) + assert result["type"] is FlowResultType.ABORT assert result["reason"] == "no_vehicles" From 95d310b102fae1fea83e98a334e3c17b0fe56c98 Mon Sep 17 00:00:00 2001 From: Paul Bottein Date: Tue, 6 Oct 2026 13:47:03 +0200 Subject: [PATCH 094/356] Re-evaluate subscribed conditions on state changes (#184335) --- .../components/websocket_api/commands.py | 19 +- homeassistant/helpers/condition.py | 201 ++++++++++++- .../components/websocket_api/test_commands.py | 157 +++++++++- tests/helpers/test_condition.py | 284 ++++++++++++++++++ 4 files changed, 648 insertions(+), 13 deletions(-) diff --git a/homeassistant/components/websocket_api/commands.py b/homeassistant/components/websocket_api/commands.py index 3f2b8103c594..d769c7535ba0 100644 --- a/homeassistant/components/websocket_api/commands.py +++ b/homeassistant/components/websocket_api/commands.py @@ -1178,14 +1178,19 @@ async def handle_subscribe_condition( def unsubscribe() -> None: """Unsubscribe from condition updates.""" condition.async_unload() - unsub() + for unsub in unsubs: + unsub() - unsub = async_track_time_interval( - hass, - evaluate_condition, - timedelta(seconds=1), - name="websocket_api_condition_subscription", - ) + unsubs = [await condition.async_track_changes(partial(evaluate_condition, None))] + if condition.needs_polling: + unsubs.append( + async_track_time_interval( + hass, + evaluate_condition, + timedelta(seconds=1), + name="websocket_api_condition_subscription", + ) + ) connection.subscriptions[msg["id"]] = unsubscribe connection.send_result(msg["id"]) evaluate_condition(None) diff --git a/homeassistant/helpers/condition.py b/homeassistant/helpers/condition.py index e0c5c0b42e16..8ab6972f1f3d 100644 --- a/homeassistant/helpers/condition.py +++ b/homeassistant/helpers/condition.py @@ -4,6 +4,7 @@ import abc import asyncio from collections import deque from collections.abc import Callable, Container, Coroutine, Iterable, Mapping +from contextvars import copy_context from dataclasses import dataclass from datetime import datetime, time as dt_time, timedelta import functools as ft @@ -56,6 +57,9 @@ from homeassistant.const import ( EntityStateAttribute, ) from homeassistant.core import ( + CALLBACK_TYPE, + Event, + EventStateChangedData, HomeAssistant, State, callback, @@ -91,6 +95,7 @@ from .automation import ( get_relative_description_key, move_options_fields_to_top_level, ) +from .event import async_track_state_change_event from .integration_platform import async_process_integration_platforms from .recorder import get_instance from .selector import ( @@ -279,6 +284,11 @@ _CONDITION_SCHEMA = _CONDITION_BASE_SCHEMA.extend( ) +@callback +def _async_noop() -> None: + """Do nothing.""" + + class ConditionChecker(abc.ABC): """Base class for condition checkers.""" @@ -339,6 +349,35 @@ class ConditionChecker(abc.ABC): Intended to be overridden in derived classes that need to do unloading. """ + @property + def needs_polling(self) -> bool: + """Return if the result can change without async_track_changes reporting it.""" + return True + + @final + async def async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + """Call action when the result of the condition may have changed. + + Returns a callback to stop tracking. When needs_polling is True, the + result can also change without action being called (time, templates). + """ + if not self._set_up: + raise HomeAssistantError("Condition checker is not set up") + + @callback + def isolated_action() -> None: + # Run in a copied context so the trace of the run that changed the state is kept + copy_context().run(action) + + return await self._async_track_changes(isolated_action) + + async def _async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + """Call action when the result of the condition may have changed. + + Intended to be overridden in derived classes that can track changes. + """ + return _async_noop + @final def async_check( self, *, variables: TemplateVarsType = None, **kwargs: Never @@ -368,6 +407,27 @@ class LegacyConditionChecker(ConditionChecker): def _async_check(self, variables: TemplateVarsType = None, **kwargs: Any) -> bool: return self._checker(self._hass, variables) + @property + @override + def needs_polling(self) -> bool: + return ( + not isinstance(self._checker, _StateDependentChecker) + or self._checker.needs_polling + ) + + @override + async def _async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + if not isinstance(self._checker, _StateDependentChecker): + return _async_noop + + @callback + def state_changed(_: Event[EventStateChangedData]) -> None: + action() + + return async_track_state_change_event( + self._hass, self._checker.entity_ids, state_changed + ) + class DisabledConditionChecker(ConditionChecker): """Condition checker for disabled conditions.""" @@ -376,6 +436,11 @@ class DisabledConditionChecker(ConditionChecker): def _async_check(self, **kwargs: Unpack[ConditionCheckParams]) -> None: return None + @property + @override + def needs_polling(self) -> bool: + return False + class CompoundConditionChecker(ConditionChecker): """Base class for compound condition checkers (and/or/not).""" @@ -385,6 +450,25 @@ class CompoundConditionChecker(ConditionChecker): super().__init__(hass) self._conditions = conditions + @property + @override + def needs_polling(self) -> bool: + return any(condition.needs_polling for condition in self._conditions) + + @override + async def _async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + unsubs = [ + await condition.async_track_changes(action) + for condition in self._conditions + ] + + @callback + def unsubscribe() -> None: + for unsub in unsubs: + unsub() + + return unsubscribe + @override def _async_unload(self) -> None: """Clean up child conditions.""" @@ -626,6 +710,63 @@ class EntityConditionBase(Condition): self._priming.discard(entity_id) self._valid_since.pop(entity_id, None) + @property + @override + def needs_polling(self) -> bool: + """Return if the result can change without async_track_changes reporting it. + + Subclasses whose result depends on anything else than the states of the + targeted entities must override this. + """ + return self._duration is not None + + @override + async def _async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + @callback + def state_changed( + _: Event[EventStateChangedData] | TargetStateChangedData, + ) -> None: + action() + + selection = self._target_selection + # Explicit entity ids don't depend on the registries, skip the target tracker + if not ( + selection.area_ids + or selection.device_ids + or selection.floor_ids + or selection.label_ids + ): + return async_track_state_change_event( + self._hass, + { + entity_id + for entity_id in selection.entity_ids + if split_entity_id(entity_id)[0] in self._domain_specs + }, + state_changed, + ) + + tracking = False + + @callback + def entities_updated( + _added: set[str], _removed: set[str], _states: Mapping[str, State | None] + ) -> None: + # The tracker also reports the initial entities while it is set up + if tracking: + action() + + unsub = await async_track_target_selector_state_change_event( + self._hass, + self._target, + state_changed, + self.entity_filter, + entities_updated, + primary_entities_only=self._primary_entities_only, + ) + tracking = True + return unsub + @override async def _async_setup(self) -> None: """Set up state tracking for duration-based conditions.""" @@ -971,6 +1112,34 @@ class EntityNumericalConditionBase(EntityConditionBase): threshold_options.get("value_max") ) self._threshold_type = threshold_options["type"] + self._threshold_entity_ids = { + threshold.entity + for threshold in ( + self.threshold, + self.lower_threshold, + self.upper_threshold, + ) + if threshold is not None and threshold.entity is not None + } + + @override + async def _async_track_changes(self, action: Callable[[], None]) -> CALLBACK_TYPE: + unsub_target = await super()._async_track_changes(action) + + @callback + def threshold_changed(_: Event[EventStateChangedData]) -> None: + action() + + unsub_thresholds = async_track_state_change_event( + self._hass, self._threshold_entity_ids, threshold_changed + ) + + @callback + def unsubscribe() -> None: + unsub_target() + unsub_thresholds() + + return unsubscribe def _is_valid_unit(self, unit: str | None) -> bool: """Check if the given unit is valid for this condition.""" @@ -1197,6 +1366,19 @@ type ConditionCheckerTypeOptional = Callable[ ] +@dataclass(slots=True) +class _StateDependentChecker: + """Legacy condition checker whose result depends on entity states.""" + + checker: ConditionCheckerType + entity_ids: set[str] + needs_polling: bool + + def __call__(self, hass: HomeAssistant, variables: TemplateVarsType = None) -> bool: + """Check the condition.""" + return self.checker(hass, variables) + + def condition_trace_append(variables: TemplateVarsType, path: str) -> TraceElement: """Append a TraceElement to trace[path].""" trace_element = TraceElement(variables, path) @@ -1678,7 +1860,11 @@ def async_numeric_state_from_config(config: ConfigType) -> ConditionCheckerType: return True - return if_numeric_state + return _StateDependentChecker( + if_numeric_state, + {*entity_ids, *(value for value in (below, above) if isinstance(value, str))}, + needs_polling=value_template is not None, + ) def state( @@ -1792,7 +1978,18 @@ def state_from_config(config: ConfigType) -> ConditionCheckerType: return result - return if_state + return _StateDependentChecker( + if_state, + { + *entity_ids, + *( + req_state + for req_state in req_states + if isinstance(req_state, str) and cv.INPUT_ENTITY_ID.match(req_state) + ), + }, + needs_polling=for_period is not None, + ) def template( diff --git a/tests/components/websocket_api/test_commands.py b/tests/components/websocket_api/test_commands.py index 16f72f671064..d9d7a2bf543b 100644 --- a/tests/components/websocket_api/test_commands.py +++ b/tests/components/websocket_api/test_commands.py @@ -47,9 +47,13 @@ from homeassistant.helpers import ( device_registry as dr, entity_registry as er, label_registry as lr, + trace, ) from homeassistant.helpers.dispatcher import async_dispatcher_send -from homeassistant.helpers.event import async_track_state_change_event +from homeassistant.helpers.event import ( + async_track_state_change_event, + async_track_time_interval, +) from homeassistant.loader import Integration, async_get_integration from homeassistant.setup import async_set_domains_to_be_loaded, async_setup_component from homeassistant.util.json import json_loads @@ -3095,10 +3099,10 @@ async def test_test_condition_check_error_not_logged( assert "Error handling message" not in caplog.text +@pytest.mark.usefixtures("freezer") async def test_subscribe_condition( hass: HomeAssistant, websocket_client: MockHAClientWebSocket, - freezer: FrozenDateTimeFactory, ) -> None: """Test subscribing to a condition.""" hass.states.async_set("hello.world", "paulus") @@ -3123,14 +3127,15 @@ async def test_subscribe_condition( msg = await websocket_client.receive_json() assert msg == {"id": subscription_id, "type": "event", "event": {"result": True}} + caller_trace = trace.trace_get() hass.states.async_set("hello.world", "frenck") - freezer.tick(1.1) + # The evaluation must not replace the trace of whoever changed the state + assert trace.trace_get(clear=False) is caller_trace msg = await websocket_client.receive_json() assert msg == {"id": subscription_id, "type": "event", "event": {"result": False}} hass.states.async_remove("hello.world") - freezer.tick(1.1) msg = await websocket_client.receive_json() assert msg == { @@ -3142,6 +3147,150 @@ async def test_subscribe_condition( } +async def test_subscribe_condition_untracked_entity( + hass: HomeAssistant, + websocket_client: MockHAClientWebSocket, + freezer: FrozenDateTimeFactory, +) -> None: + """Test changes to entities used only in a template are polled.""" + hass.states.async_set("hello.world", "paulus") + hass.states.async_set("hello.other", "on") + + await websocket_client.send_json_auto_id( + { + "type": "subscribe_condition", + "condition": { + "condition": "and", + "conditions": [ + { + "condition": "state", + "entity_id": "hello.world", + "state": "paulus", + }, + { + "condition": "template", + "value_template": "{{ is_state('hello.other', 'on') }}", + }, + ], + }, + } + ) + + msg = await websocket_client.receive_json() + assert msg["type"] == const.TYPE_RESULT + assert msg["success"] + + subscription_id = msg["id"] + + msg = await websocket_client.receive_json() + assert msg == {"id": subscription_id, "type": "event", "event": {"result": True}} + + hass.states.async_set("hello.other", "off") + + # A pong as the next message shows the change did not send an event + await websocket_client.send_json_auto_id({"type": "ping"}) + msg = await websocket_client.receive_json() + assert msg["type"] == "pong" + + freezer.tick(1.1) + + msg = await websocket_client.receive_json() + assert msg == {"id": subscription_id, "type": "event", "event": {"result": False}} + + +@pytest.mark.parametrize( + ("condition", "needs_polling"), + [ + pytest.param( + {"condition": "state", "entity_id": "hello.world", "state": "paulus"}, + False, + id="state", + ), + pytest.param( + { + "condition": "template", + "value_template": "{{ is_state('hello.world', 'paulus') }}", + }, + True, + id="template", + ), + ], +) +async def test_subscribe_condition_polling( + hass: HomeAssistant, + websocket_client: MockHAClientWebSocket, + condition: dict[str, Any], + needs_polling: bool, +) -> None: + """Test a condition is only polled when it can change without a state change.""" + hass.states.async_set("hello.world", "paulus") + + with patch( + "homeassistant.components.websocket_api.commands.async_track_time_interval", + wraps=async_track_time_interval, + ) as mock_track_time_interval: + await websocket_client.send_json_auto_id( + {"type": "subscribe_condition", "condition": condition} + ) + msg = await websocket_client.receive_json() + + assert msg["type"] == const.TYPE_RESULT + assert msg["success"] + assert mock_track_time_interval.called is needs_polling + + +async def test_unsubscribe_condition( + hass: HomeAssistant, + websocket_client: MockHAClientWebSocket, + area_registry: ar.AreaRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test unsubscribing from a condition removes its listeners.""" + area = area_registry.async_create("Kitchen") + light = entity_registry.async_get_or_create("light", "test", "kitchen") + entity_registry.async_update_entity(light.entity_id, area_id=area.id) + hass.states.async_set(light.entity_id, "on") + hass.states.async_set("hello.world", "paulus") + init_count = sum(hass.bus.async_listeners().values()) + + await websocket_client.send_json_auto_id( + { + "type": "subscribe_condition", + "condition": { + "condition": "or", + "conditions": [ + { + "condition": "state", + "entity_id": "hello.world", + "state": "paulus", + }, + {"condition": "light.is_on", "target": {"area_id": area.id}}, + ], + }, + } + ) + + msg = await websocket_client.receive_json() + assert msg["type"] == const.TYPE_RESULT + assert msg["success"] + + subscription_id = msg["id"] + assert sum(hass.bus.async_listeners().values()) > init_count + + msg = await websocket_client.receive_json() + assert msg == {"id": subscription_id, "type": "event", "event": {"result": True}} + + await websocket_client.send_json_auto_id( + {"type": "unsubscribe_events", "subscription": subscription_id} + ) + + msg = await websocket_client.receive_json() + assert msg["type"] == const.TYPE_RESULT + assert msg["success"] + + assert sum(hass.bus.async_listeners().values()) == init_count + + async def test_subscribe_condition_non_admin( hass: HomeAssistant, websocket_client: MockHAClientWebSocket, diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index f28dd77dc37c..c5a624194a79 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -6582,3 +6582,287 @@ async def test_condition_entity_filter_no_device_class_means_match_all_in_domain entities = {"cover.door", "cover.garage", "cover.plain"} result = cond.entity_filter(entities) assert result == entities + + +_STATE_CONDITION = {"condition": "state", "entity_id": "light.kitchen", "state": "on"} +_TEMPLATE_CONDITION = {"condition": "template", "value_template": "{{ true }}"} + + +@pytest.mark.parametrize( + ("config", "needs_polling"), + [ + pytest.param(_STATE_CONDITION, False, id="state"), + pytest.param({**_STATE_CONDITION, "for": {"seconds": 5}}, True, id="state_for"), + pytest.param( + { + "condition": "numeric_state", + "entity_id": "sensor.temperature", + "above": 20, + }, + False, + id="numeric_state", + ), + pytest.param( + { + "condition": "numeric_state", + "entity_id": "sensor.temperature", + "above": 20, + "value_template": "{{ state.attributes.value }}", + }, + True, + id="numeric_state_template", + ), + pytest.param(_TEMPLATE_CONDITION, True, id="template"), + pytest.param( + {**_TEMPLATE_CONDITION, "enabled": False}, False, id="disabled_template" + ), + pytest.param( + {"condition": "and", "conditions": [_STATE_CONDITION, _STATE_CONDITION]}, + False, + id="and", + ), + pytest.param( + {"condition": "or", "conditions": [_STATE_CONDITION, _TEMPLATE_CONDITION]}, + True, + id="or_with_template", + ), + pytest.param( + {"condition": "light.is_on", "target": {"entity_id": "light.kitchen"}}, + False, + id="entity_condition", + ), + pytest.param( + { + "condition": "light.is_on", + "target": {"entity_id": "light.kitchen"}, + "options": {"for": {"seconds": 5}}, + }, + True, + id="entity_condition_for", + ), + ], +) +async def test_needs_polling( + hass: HomeAssistant, config: dict[str, Any], needs_polling: bool +) -> None: + """Test which conditions can change without a reported state change.""" + config = await async_validate_condition_config(hass, cv.CONDITION_SCHEMA(config)) + test = await condition.async_from_config(hass, config) + + assert test.needs_polling is needs_polling + + +@pytest.mark.parametrize( + ("config", "entity_id"), + [ + pytest.param( + {"condition": "state", "entity_id": "counter.value", "state": "10"}, + "counter.value", + id="state", + ), + pytest.param( + { + "condition": "state", + "entity_id": "counter.value", + "state": "input_number.threshold", + }, + "input_number.threshold", + id="state_entity", + ), + pytest.param( + { + "condition": "numeric_state", + "entity_id": "counter.value", + "above": "input_number.threshold", + }, + "input_number.threshold", + id="numeric_state_above", + ), + pytest.param( + { + "condition": "numeric_state", + "entity_id": "counter.value", + "below": "input_number.threshold", + }, + "input_number.threshold", + id="numeric_state_below", + ), + pytest.param( + { + "condition": "not", + "conditions": [ + {"condition": "state", "entity_id": "counter.value", "state": "10"} + ], + }, + "counter.value", + id="not", + ), + pytest.param( + { + "condition": "counter.is_value", + "target": {"entity_id": "counter.value"}, + "options": {"threshold": {"type": "above", "value": {"number": 5}}}, + }, + "counter.value", + id="entity_condition", + ), + pytest.param( + { + "condition": "counter.is_value", + "target": {"entity_id": "counter.value"}, + "options": { + "threshold": { + "type": "above", + "value": {"entity": "input_number.threshold"}, + } + }, + }, + "input_number.threshold", + id="threshold_entity", + ), + pytest.param( + { + "condition": "counter.is_value", + "target": {"entity_id": "counter.value"}, + "options": { + "threshold": { + "type": "between", + "value_min": {"entity": "input_number.threshold"}, + "value_max": {"number": 50}, + } + }, + }, + "input_number.threshold", + id="threshold_entity_min", + ), + pytest.param( + { + "condition": "counter.is_value", + "target": {"entity_id": "counter.value"}, + "options": { + "threshold": { + "type": "between", + "value_min": {"number": 0}, + "value_max": {"entity": "input_number.threshold"}, + } + }, + }, + "input_number.threshold", + id="threshold_entity_max", + ), + ], +) +async def test_track_changes( + hass: HomeAssistant, config: dict[str, Any], entity_id: str +) -> None: + """Test a state change of an entity the condition depends on is reported.""" + config = await async_validate_condition_config(hass, cv.CONDITION_SCHEMA(config)) + test = await condition.async_from_config(hass, config) + action = Mock() + unsub = await test.async_track_changes(action) + + hass.states.async_set("sensor.unrelated", "on") + action.assert_not_called() + + hass.states.async_set(entity_id, "15") + action.assert_called_once() + + unsub() + hass.states.async_set(entity_id, "20") + action.assert_called_once() + + +@pytest.mark.parametrize( + ("target", "registry_listeners"), + [ + pytest.param( + {"entity_id": ["light.kitchen", "sensor.kitchen"]}, 0, id="entity" + ), + pytest.param({"area_id": "kitchen"}, 1, id="area"), + ], +) +async def test_track_changes_target( + hass: HomeAssistant, + area_registry: ar.AreaRegistry, + entity_registry: er.EntityRegistry, + target: dict[str, Any], + registry_listeners: int, +) -> None: + """Test only targeted entities the condition can evaluate are tracked.""" + area = area_registry.async_create("Kitchen") + light = entity_registry.async_get_or_create( + "light", "test", "kitchen", suggested_object_id="kitchen" + ) + sensor = entity_registry.async_get_or_create( + "sensor", "test", "kitchen", suggested_object_id="kitchen" + ) + entity_registry.async_update_entity(light.entity_id, area_id=area.id) + entity_registry.async_update_entity(sensor.entity_id, area_id=area.id) + init_count = hass.bus.async_listeners()[er.EVENT_ENTITY_REGISTRY_UPDATED] + config = await async_validate_condition_config( + hass, cv.CONDITION_SCHEMA({"condition": "light.is_on", "target": target}) + ) + test = await condition.async_from_config(hass, config) + action = Mock() + unsub = await test.async_track_changes(action) + + assert ( + hass.bus.async_listeners()[er.EVENT_ENTITY_REGISTRY_UPDATED] + == init_count + registry_listeners + ) + + hass.states.async_set(sensor.entity_id, "20") + action.assert_not_called() + + hass.states.async_set(light.entity_id, "on") + action.assert_called_once() + + unsub() + assert hass.bus.async_listeners()[er.EVENT_ENTITY_REGISTRY_UPDATED] == init_count + + +async def test_track_changes_target_registry_update( + hass: HomeAssistant, + area_registry: ar.AreaRegistry, + entity_registry: er.EntityRegistry, +) -> None: + """Test a change of the entities in the target is reported.""" + area = area_registry.async_create("Kitchen") + kitchen = entity_registry.async_get_or_create( + "light", "test", "kitchen", suggested_object_id="kitchen" + ) + hallway = entity_registry.async_get_or_create( + "light", "test", "hallway", suggested_object_id="hallway" + ) + entity_registry.async_update_entity(kitchen.entity_id, area_id=area.id) + config = await async_validate_condition_config( + hass, + cv.CONDITION_SCHEMA( + {"condition": "light.is_on", "target": {"area_id": area.id}} + ), + ) + test = await condition.async_from_config(hass, config) + action = Mock() + unsub = await test.async_track_changes(action) + action.assert_not_called() + + entity_registry.async_update_entity(hallway.entity_id, area_id=area.id) + await hass.async_block_till_done() + action.assert_called_once() + + unsub() + + +async def test_track_changes_isolates_context(hass: HomeAssistant) -> None: + """Test the action does not run in the context of the state change caller.""" + config = await async_validate_condition_config( + hass, cv.CONDITION_SCHEMA(_STATE_CONDITION) + ) + test = await condition.async_from_config(hass, config) + unsub = await test.async_track_changes(trace.trace_clear) + + caller_trace = trace.trace_get() + hass.states.async_set("light.kitchen", "on") + assert trace.trace_get(clear=False) is caller_trace + + unsub() From 2063fed87e2c33cea8809d0b3521e7bc40c2ed05 Mon Sep 17 00:00:00 2001 From: Tom Date: Tue, 6 Oct 2026 08:32:14 +0200 Subject: [PATCH 095/356] Improve ProxmoxVE node offline handling (#184374) --- homeassistant/components/proxmoxve/sensor.py | 19 ++++++++++-- .../proxmoxve/fixtures/nodes/nodes.json | 19 ++++++------ .../proxmoxve/snapshots/test_sensor.ambr | 2 ++ tests/components/proxmoxve/test_init.py | 9 +++++- tests/components/proxmoxve/test_sensor.py | 30 ++++++++++++++++++- 5 files changed, 65 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/proxmoxve/sensor.py b/homeassistant/components/proxmoxve/sensor.py index efe605007cd1..b63e673abc6a 100644 --- a/homeassistant/components/proxmoxve/sensor.py +++ b/homeassistant/components/proxmoxve/sensor.py @@ -18,7 +18,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util -from .const import ProxmoxPermission +from .const import NODE_ONLINE, ProxmoxPermission from .coordinator import ProxmoxConfigEntry, ProxmoxNodeData from .entity import ( ProxmoxContainerEntity, @@ -38,6 +38,7 @@ class ProxmoxNodeSensorEntityDescription(SensorEntityDescription): value_fn: Callable[[ProxmoxNodeData], StateType | datetime] permission: ProxmoxPermission = ProxmoxPermission.SYSAUDIT permission_target: str = "nodes" + requires_online_node: bool = True @dataclass(frozen=True, kw_only=True) @@ -153,9 +154,10 @@ NODE_SENSORS: tuple[ProxmoxNodeSensorEntityDescription, ...] = ( translation_key="node_status", value_fn=lambda data: data.node["status"], device_class=SensorDeviceClass.ENUM, - options=["online", "offline"], + options=["online", "offline", "unknown"], permission=ProxmoxPermission.VMAUDIT, permission_target="vms", + requires_online_node=False, ), ProxmoxNodeSensorEntityDescription( key="node_backup_last_backup", @@ -578,6 +580,19 @@ class ProxmoxNodeSensor(ProxmoxNodeEntity, SensorEntity): """Return the native value of the sensor.""" return self.entity_description.value_fn(self.coordinator.data[self.device_name]) + @property + @override + def available(self) -> bool: + """Return if the sensor is available.""" + if not self.entity_description.requires_online_node: + return super().available + + return ( + super().available + and self.coordinator.data[self.device_name].node.get("status") + == NODE_ONLINE + ) + class ProxmoxVMSensor(ProxmoxVMEntity, SensorEntity): """Represents a Proxmox VE VM sensor.""" diff --git a/tests/components/proxmoxve/fixtures/nodes/nodes.json b/tests/components/proxmoxve/fixtures/nodes/nodes.json index 020c249f90df..96eb21cf0e6d 100644 --- a/tests/components/proxmoxve/fixtures/nodes/nodes.json +++ b/tests/components/proxmoxve/fixtures/nodes/nodes.json @@ -31,17 +31,16 @@ }, { "id": "node/pve3", - "node": "pve3", - "status": "offline", - "level": "", "type": "node", - "maxmem": 0, - "mem": 0, - "maxcpu": 0, - "cpu": 0, - "uptime": 0, - "maxdisk": 0, - "disk": 0, + "status": "offline", + "node": "pve3", "ssl_fingerprint": "3F:B9:CC:...:01" + }, + { + "id": "node/pve4", + "type": "node", + "status": "unknown", + "node": "pve4", + "ssl_fingerprint": "3F:B9:CC:...:04" } ] diff --git a/tests/components/proxmoxve/snapshots/test_sensor.ambr b/tests/components/proxmoxve/snapshots/test_sensor.ambr index dae6576fddd0..7447f80c8677 100644 --- a/tests/components/proxmoxve/snapshots/test_sensor.ambr +++ b/tests/components/proxmoxve/snapshots/test_sensor.ambr @@ -1824,6 +1824,7 @@ : list([ 'online', 'offline', + 'unknown', ]), }), 'config_entry_id': , @@ -1864,6 +1865,7 @@ : list([ 'online', 'offline', + 'unknown', ]), }), 'context': , diff --git a/tests/components/proxmoxve/test_init.py b/tests/components/proxmoxve/test_init.py index 7634bcbcaf09..33c7a0bcf57b 100644 --- a/tests/components/proxmoxve/test_init.py +++ b/tests/components/proxmoxve/test_init.py @@ -30,6 +30,7 @@ from homeassistant.const import ( CONF_VERIFY_SSL, STATE_OFF, STATE_ON, + STATE_UNAVAILABLE, ) from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er @@ -324,7 +325,7 @@ async def test_offline_node( mock_proxmox_client: MagicMock, mock_config_entry: MockConfigEntry, ) -> None: - """Test that an offline node doesn't cause the entire update to fail.""" + """Test that an offline or unknown state node doesn't cause the entire update to fail.""" mock_proxmox_client.nodes.get.return_value = mock_proxmox_client._all_nodes await setup_integration(hass, mock_config_entry) @@ -336,6 +337,12 @@ async def test_offline_node( state = hass.states.get("binary_sensor.pve3_status") assert state.state == STATE_OFF + state = hass.states.get("sensor.pve3_cpu_usage") + assert state.state == STATE_UNAVAILABLE + + state = hass.states.get("sensor.pve4_cpu_usage") + assert state.state == STATE_UNAVAILABLE + async def test_new_vm_creates_entity( hass: HomeAssistant, diff --git a/tests/components/proxmoxve/test_sensor.py b/tests/components/proxmoxve/test_sensor.py index 7d8714fff321..7d9a1038b05a 100644 --- a/tests/components/proxmoxve/test_sensor.py +++ b/tests/components/proxmoxve/test_sensor.py @@ -5,7 +5,7 @@ from unittest.mock import MagicMock, patch import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.const import STATE_UNKNOWN, Platform +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -92,3 +92,31 @@ async def test_sensors_according_to_permissions( assert "sensor.pve1_status" in {e.entity_id for e in entries} assert "sensor.pve1_cpu" not in {e.entity_id for e in entries} + + +async def test_sensors_for_offline_node( + hass: HomeAssistant, + mock_proxmox_client: MagicMock, + mock_config_entry: MockConfigEntry, + entity_registry: er.EntityRegistry, +) -> None: + """Test that node sensors except status are unavailable.""" + mock_proxmox_client.nodes.get.return_value = mock_proxmox_client._all_nodes + + with patch( + "homeassistant.components.proxmoxve.PLATFORMS", + [Platform.SENSOR], + ): + await setup_integration(hass, mock_config_entry) + + state = hass.states.get("sensor.pve3_status") + assert state.state == "offline" + + state = hass.states.get("sensor.pve3_disk_usage") + assert state.state == STATE_UNAVAILABLE + + state = hass.states.get("sensor.pve4_status") + assert state.state == "unknown" + + state = hass.states.get("sensor.pve4_disk_usage") + assert state.state == STATE_UNAVAILABLE From 163aed2c1a845aa7c3070b080019ee16d17e91e1 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Sun, 4 Oct 2026 16:22:44 +1000 Subject: [PATCH 096/356] Bump teslemetry-stream to 1.2.0 (#184181) --- .../components/teslemetry/manifest.json | 2 +- homeassistant/components/teslemetry/sensor.py | 12 +++- requirements_all.txt | 2 +- tests/components/teslemetry/test_sensor.py | 56 +++++++++++++++++++ 4 files changed, 67 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/teslemetry/manifest.json b/homeassistant/components/teslemetry/manifest.json index 061de63ca6ba..16028cb660e5 100644 --- a/homeassistant/components/teslemetry/manifest.json +++ b/homeassistant/components/teslemetry/manifest.json @@ -12,6 +12,6 @@ "requirements": [ "aiopowerwall==0.4.1", "tesla-fleet-api==1.17.2", - "teslemetry-stream==1.0.2" + "teslemetry-stream==1.2.0" ] } diff --git a/homeassistant/components/teslemetry/sensor.py b/homeassistant/components/teslemetry/sensor.py index d1b56b766661..a58ce014e519 100644 --- a/homeassistant/components/teslemetry/sensor.py +++ b/homeassistant/components/teslemetry/sensor.py @@ -3,7 +3,7 @@ from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timedelta -from typing import override +from typing import Any, override from tesla_fleet_api import firmware_at_least from tesla_fleet_api.const import Scope @@ -59,6 +59,12 @@ PARALLEL_UPDATES = 0 # vehicles, identified by this driver-assist capability in the vehicle config. DRIVER_ASSIST_HW4 = "TeslaAP4" + +def _tires_in_warning(warnings: dict[str, Any] | None) -> int | None: + """Count the tires flagged in a per-tire TPMS warning field.""" + return None if warnings is None else sum(bool(v) for v in warnings.values()) + + BMS_STATES = { "Standby": "standby", "Drive": "drive", @@ -1430,7 +1436,7 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryVehicleSensorEntityDescription, ...] = ( TeslemetryVehicleSensorEntityDescription( key="tpms_hard_warnings", streaming_listener=lambda vehicle, callback: vehicle.listen_TpmsHardWarnings( - callback + lambda value: callback(_tires_in_warning(value)) ), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, @@ -1438,7 +1444,7 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryVehicleSensorEntityDescription, ...] = ( TeslemetryVehicleSensorEntityDescription( key="tpms_soft_warnings", streaming_listener=lambda vehicle, callback: vehicle.listen_TpmsSoftWarnings( - callback + lambda value: callback(_tires_in_warning(value)) ), entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, diff --git a/requirements_all.txt b/requirements_all.txt index 6e5a61431eff..2b75a1842834 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3236,7 +3236,7 @@ tesla-powerwall==0.5.3 tesla-wall-connector==1.2.0 # homeassistant.components.teslemetry -teslemetry-stream==1.0.2 +teslemetry-stream==1.2.0 # homeassistant.components.tessie tessie-api==0.1.3 diff --git a/tests/components/teslemetry/test_sensor.py b/tests/components/teslemetry/test_sensor.py index 4eb8206358e7..8598025bc470 100644 --- a/tests/components/teslemetry/test_sensor.py +++ b/tests/components/teslemetry/test_sensor.py @@ -50,6 +50,20 @@ ENERGY_HISTORY_ENTITY = "sensor.energy_site_battery_discharged" # or from the event's created_at cannot produce this. SITE_MIDNIGHT = "2024-09-18T00:00:00+10:00" +# Per-tire TPMS warning objects including the Tesla Semi. +TPMS_NO_WARNINGS = { + "frontLeft": False, + "frontRight": False, + "rearLeft": False, + "rearRight": False, + "semiMiddleAxleLeft2": False, + "semiMiddleAxleRight2": False, + "semiRearAxleLeft": False, + "semiRearAxleLeft2": False, + "semiRearAxleRight": False, + "semiRearAxleRight2": False, +} + def _products_with_driver_assist(driver_assist: str) -> dict: """Return a products response with the vehicle's driver-assist capability set.""" @@ -460,6 +474,48 @@ async def test_sensors_streaming_tpms_none_clears_state( assert hass.states.get(entity_id).state == STATE_UNKNOWN +@pytest.mark.parametrize( + ("signal", "entity_id"), + [ + pytest.param( + Signal.TPMS_HARD_WARNINGS, + "sensor.test_tire_pressure_hard_warnings", + id="hard", + ), + pytest.param( + Signal.TPMS_SOFT_WARNINGS, + "sensor.test_tire_pressure_soft_warnings", + id="soft", + ), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_sensors_streaming_tpms_warnings( + hass: HomeAssistant, + mock_add_listener: AsyncMock, + signal: Signal, + entity_id: str, +) -> None: + """Test TPMS warning sensors report how many tires are in warning.""" + await setup_platform(hass, [Platform.SENSOR]) + vin = VEHICLE_DATA_ALT["response"]["vin"] + + for warnings, expected_state in ( + ({**TPMS_NO_WARNINGS, "frontRight": True, "rearLeft": True}, "2"), + (TPMS_NO_WARNINGS, "0"), + (None, STATE_UNKNOWN), + ): + mock_add_listener.send( + { + "vin": vin, + "data": {signal: warnings}, + "createdAt": "2024-10-04T10:45:17.537Z", + } + ) + await hass.async_block_till_done() + assert hass.states.get(entity_id).state == expected_state + + @pytest.mark.parametrize( "raw_value", [ From 053a4bfec416130d1efb02b583016d3885ffb007 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Tue, 6 Oct 2026 15:44:53 +1000 Subject: [PATCH 097/356] Bump tesla-fleet-api to 1.17.3 (#184394) --- homeassistant/components/tesla_fleet/manifest.json | 2 +- homeassistant/components/teslemetry/manifest.json | 2 +- homeassistant/components/tessie/manifest.json | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/tesla_fleet/manifest.json b/homeassistant/components/tesla_fleet/manifest.json index 79a6f2a2c587..ea4497dde32f 100644 --- a/homeassistant/components/tesla_fleet/manifest.json +++ b/homeassistant/components/tesla_fleet/manifest.json @@ -8,5 +8,5 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["tesla-fleet-api"], - "requirements": ["tesla-fleet-api==1.17.2"] + "requirements": ["tesla-fleet-api==1.17.3"] } diff --git a/homeassistant/components/teslemetry/manifest.json b/homeassistant/components/teslemetry/manifest.json index 16028cb660e5..9f9f5cbd89f7 100644 --- a/homeassistant/components/teslemetry/manifest.json +++ b/homeassistant/components/teslemetry/manifest.json @@ -11,7 +11,7 @@ "quality_scale": "platinum", "requirements": [ "aiopowerwall==0.4.1", - "tesla-fleet-api==1.17.2", + "tesla-fleet-api==1.17.3", "teslemetry-stream==1.2.0" ] } diff --git a/homeassistant/components/tessie/manifest.json b/homeassistant/components/tessie/manifest.json index 08cc4b3d4ec7..7be5e0ffd18d 100644 --- a/homeassistant/components/tessie/manifest.json +++ b/homeassistant/components/tessie/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["tessie", "tesla-fleet-api"], "quality_scale": "silver", - "requirements": ["tessie-api==0.1.3", "tesla-fleet-api==1.17.2"] + "requirements": ["tessie-api==0.1.3", "tesla-fleet-api==1.17.3"] } diff --git a/requirements_all.txt b/requirements_all.txt index 2b75a1842834..6133c2fc042b 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3227,7 +3227,7 @@ temperusb==1.6.1 # homeassistant.components.tesla_fleet # homeassistant.components.teslemetry # homeassistant.components.tessie -tesla-fleet-api==1.17.2 +tesla-fleet-api==1.17.3 # homeassistant.components.powerwall tesla-powerwall==0.5.3 From 374f78eba7ac461a3d0b7622c7e27c495401b939 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 08:36:07 +0200 Subject: [PATCH 098/356] Show a clear error when a WLED device doesn't respond like one (#184397) --- homeassistant/components/wled/config_flow.py | 12 ++++++++- homeassistant/components/wled/strings.json | 2 ++ tests/components/wled/test_config_flow.py | 27 +++++++++++++++++++- 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/wled/config_flow.py b/homeassistant/components/wled/config_flow.py index 09777d5693a9..ee32016199a1 100644 --- a/homeassistant/components/wled/config_flow.py +++ b/homeassistant/components/wled/config_flow.py @@ -3,7 +3,13 @@ from typing import Any, override import probatio -from wled import WLED, Device, WLEDConnectionError, WLEDUnsupportedVersionError +from wled import ( + WLED, + Device, + WLEDConnectionError, + WLEDError, + WLEDUnsupportedVersionError, +) import yarl from homeassistant.components import onboarding @@ -64,6 +70,8 @@ class WLEDFlowHandler(ConfigFlow, domain=DOMAIN): errors["base"] = "unsupported_version" except WLEDConnectionError: errors["base"] = "cannot_connect" + except WLEDError: + errors["base"] = "invalid_response" else: mac_address = normalize_mac_address(device.info.mac_address) await self.async_set_unique_id(mac_address, raise_on_progress=False) @@ -124,6 +132,8 @@ class WLEDFlowHandler(ConfigFlow, domain=DOMAIN): return self.async_abort(reason="unsupported_version") except WLEDConnectionError: return self.async_abort(reason="cannot_connect") + except WLEDError: + return self.async_abort(reason="invalid_response") device_mac_address = normalize_mac_address( self.discovered_device.info.mac_address diff --git a/homeassistant/components/wled/strings.json b/homeassistant/components/wled/strings.json index 852ceabb271e..80d8affd91b8 100644 --- a/homeassistant/components/wled/strings.json +++ b/homeassistant/components/wled/strings.json @@ -6,11 +6,13 @@ "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_response": "[%key:component::wled::config::error::invalid_response%]", "unique_id_mismatch": "MAC address does not match the configured device. Expected to connect to device with MAC: `{expected_mac}`, but connected to device with MAC: `{actual_mac}`. \n\nPlease ensure you reconfigure against the same device.", "unsupported_version": "[%key:component::wled::common::unsupported_version%]" }, "error": { "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_response": "The device didn't respond like a WLED device.", "unsupported_version": "[%key:component::wled::common::unsupported_version%]" }, "flow_title": "{name}", diff --git a/tests/components/wled/test_config_flow.py b/tests/components/wled/test_config_flow.py index e5fc5d235ffb..48dee1015c85 100644 --- a/tests/components/wled/test_config_flow.py +++ b/tests/components/wled/test_config_flow.py @@ -4,7 +4,7 @@ from ipaddress import ip_address from unittest.mock import AsyncMock, MagicMock import pytest -from wled import WLEDConnectionError, WLEDUnsupportedVersionError +from wled import WLEDConnectionError, WLEDError, WLEDUnsupportedVersionError from homeassistant.components.wled.const import CONF_KEEP_MAIN_LIGHT, DOMAIN from homeassistant.config_entries import SOURCE_USER, SOURCE_ZEROCONF @@ -219,6 +219,7 @@ async def test_zeroconf_during_onboarding( [ (WLEDConnectionError, {"base": "cannot_connect"}), (WLEDUnsupportedVersionError, {"base": "unsupported_version"}), + (WLEDError, {"base": "invalid_response"}), ], ) async def test_form_submission_errors( @@ -267,6 +268,30 @@ async def test_zeroconf_connection_error( assert result.get("reason") == "cannot_connect" +async def test_zeroconf_invalid_response( + hass: HomeAssistant, mock_wled: MagicMock +) -> None: + """Test we abort zeroconf flow when the device doesn't respond like WLED.""" + mock_wled.update.side_effect = WLEDError + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address("192.168.1.123"), + ip_addresses=[ip_address("192.168.1.123")], + hostname="example.local.", + name="mock_name", + port=None, + properties={CONF_MAC: "aabbccddeeff"}, + type="mock_type", + ), + ) + + assert result.get("type") is FlowResultType.ABORT + assert result.get("reason") == "invalid_response" + + async def test_zeroconf_unsupported_version_error( hass: HomeAssistant, mock_wled: MagicMock ) -> None: From e8f87c414b846ea242ea22fd5ebac04fc6a98a10 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 09:31:30 +0200 Subject: [PATCH 099/356] Only let WLED discovery change the host after the device answers on it (#184411) --- homeassistant/components/wled/config_flow.py | 15 +- tests/components/wled/test_config_flow.py | 154 ++++++++++++------- 2 files changed, 109 insertions(+), 60 deletions(-) diff --git a/homeassistant/components/wled/config_flow.py b/homeassistant/components/wled/config_flow.py index ee32016199a1..32c41acb74bb 100644 --- a/homeassistant/components/wled/config_flow.py +++ b/homeassistant/components/wled/config_flow.py @@ -118,12 +118,17 @@ class WLEDFlowHandler(ConfigFlow, domain=DOMAIN): self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle zeroconf discovery.""" - # Abort quick if the mac address is provided by discovery info + # A changed address has to answer as this device before it replaces + # the configured one, so only an unchanged address aborts right away. if mac := discovery_info.properties.get(CONF_MAC): - await self.async_set_unique_id(normalize_mac_address(mac)) - self._abort_if_unique_id_configured( - updates={CONF_HOST: discovery_info.host} - ) + unique_id = normalize_mac_address(mac) + await self.async_set_unique_id(unique_id) + if ( + entry := self.hass.config_entries.async_entry_for_domain_unique_id( + DOMAIN, unique_id + ) + ) and entry.data[CONF_HOST] == discovery_info.host: + return self.async_abort(reason="already_configured") self.discovered_host = discovery_info.host try: diff --git a/tests/components/wled/test_config_flow.py b/tests/components/wled/test_config_flow.py index 48dee1015c85..f9fb74164f3d 100644 --- a/tests/components/wled/test_config_flow.py +++ b/tests/components/wled/test_config_flow.py @@ -244,11 +244,19 @@ async def test_form_submission_errors( assert result.get("errors") == errors -async def test_zeroconf_connection_error( - hass: HomeAssistant, mock_wled: MagicMock +@pytest.mark.parametrize( + ("exception", "reason"), + [ + (WLEDConnectionError, "cannot_connect"), + (WLEDUnsupportedVersionError, "unsupported_version"), + (WLEDError, "invalid_response"), + ], +) +async def test_zeroconf_errors( + hass: HomeAssistant, mock_wled: MagicMock, exception: Exception, reason: str ) -> None: - """Test we abort zeroconf flow on WLED connection error.""" - mock_wled.update.side_effect = WLEDConnectionError + """Test we abort the zeroconf flow on errors from the WLED device.""" + mock_wled.update.side_effect = exception result = await hass.config_entries.flow.async_init( DOMAIN, @@ -265,58 +273,9 @@ async def test_zeroconf_connection_error( ) assert result.get("type") is FlowResultType.ABORT - assert result.get("reason") == "cannot_connect" + assert result.get("reason") == reason -async def test_zeroconf_invalid_response( - hass: HomeAssistant, mock_wled: MagicMock -) -> None: - """Test we abort zeroconf flow when the device doesn't respond like WLED.""" - mock_wled.update.side_effect = WLEDError - - result = await hass.config_entries.flow.async_init( - DOMAIN, - context={"source": SOURCE_ZEROCONF}, - data=ZeroconfServiceInfo( - ip_address=ip_address("192.168.1.123"), - ip_addresses=[ip_address("192.168.1.123")], - hostname="example.local.", - name="mock_name", - port=None, - properties={CONF_MAC: "aabbccddeeff"}, - type="mock_type", - ), - ) - - assert result.get("type") is FlowResultType.ABORT - assert result.get("reason") == "invalid_response" - - -async def test_zeroconf_unsupported_version_error( - hass: HomeAssistant, mock_wled: MagicMock -) -> None: - """Test we abort zeroconf flow on WLED unsupported version error.""" - mock_wled.update.side_effect = WLEDUnsupportedVersionError - - result = await hass.config_entries.flow.async_init( - DOMAIN, - context={"source": SOURCE_ZEROCONF}, - data=ZeroconfServiceInfo( - ip_address=ip_address("192.168.1.123"), - ip_addresses=[ip_address("192.168.1.123")], - hostname="example.local.", - name="mock_name", - port=None, - properties={CONF_MAC: "aabbccddeeff"}, - type="mock_type", - ), - ) - - assert result.get("type") is FlowResultType.ABORT - assert result.get("reason") == "unsupported_version" - - -@pytest.mark.usefixtures("mock_wled") @pytest.mark.parametrize("device_mac", ["aabbccddeeff", "AABBCCDDEEFF"]) async def test_user_device_exists_abort( hass: HomeAssistant, @@ -375,7 +334,7 @@ async def test_zeroconf_with_mac_device_exists_abort( mock_wled: MagicMock, device_mac: str, ) -> None: - """Test we abort zeroconf flow if WLED device already configured.""" + """Test we abort zeroconf flow, without asking the device, if already configured.""" mock_config_entry.add_to_hass(hass) result = await hass.config_entries.flow.async_init( DOMAIN, @@ -393,6 +352,91 @@ async def test_zeroconf_with_mac_device_exists_abort( assert result.get("type") is FlowResultType.ABORT assert result.get("reason") == "already_configured" + assert mock_wled.update.call_count == 0 + + +async def test_zeroconf_with_mac_updates_host( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: MagicMock, +) -> None: + """Test zeroconf updates the host after the device answers on it.""" + mock_config_entry.add_to_hass(hass) + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address("192.168.1.124"), + ip_addresses=[ip_address("192.168.1.124")], + hostname="example.local.", + name="mock_name", + port=None, + properties={CONF_MAC: "aabbccddeeff"}, + type="mock_type", + ), + ) + + assert result.get("type") is FlowResultType.ABORT + assert result.get("reason") == "already_configured" + assert mock_config_entry.data[CONF_HOST] == "192.168.1.124" + assert mock_wled.update.call_count == 1 + + +async def test_zeroconf_with_mac_keeps_host_for_another_device( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: MagicMock, +) -> None: + """Test zeroconf keeps the host when another device answers on the new one.""" + mock_config_entry.add_to_hass(hass) + mock_wled.update.return_value.info.mac_address = "112233445566" + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address("192.168.1.124"), + ip_addresses=[ip_address("192.168.1.124")], + hostname="example.local.", + name="mock_name", + port=None, + properties={CONF_MAC: "aabbccddeeff"}, + type="mock_type", + ), + ) + + # Offered as the new device it is, without touching the configured one. + assert result.get("type") is FlowResultType.FORM + assert result.get("step_id") == "zeroconf_confirm" + assert mock_config_entry.data[CONF_HOST] == "192.168.1.123" + + +async def test_zeroconf_with_mac_keeps_host_when_unreachable( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: MagicMock, +) -> None: + """Test zeroconf keeps the host when the device doesn't answer on the new one.""" + mock_config_entry.add_to_hass(hass) + mock_wled.update.side_effect = WLEDConnectionError + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": SOURCE_ZEROCONF}, + data=ZeroconfServiceInfo( + ip_address=ip_address("192.168.1.124"), + ip_addresses=[ip_address("192.168.1.124")], + hostname="example.local.", + name="mock_name", + port=None, + properties={CONF_MAC: "aabbccddeeff"}, + type="mock_type", + ), + ) + + assert result.get("type") is FlowResultType.ABORT + assert result.get("reason") == "cannot_connect" + assert mock_config_entry.data[CONF_HOST] == "192.168.1.123" @pytest.mark.usefixtures("mock_wled") From aa1d4c0ac44706290ad7f9d80cdc00836829802c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 09:15:16 +0200 Subject: [PATCH 100/356] Don't remove the WLED stop listener twice on unload (#184412) --- homeassistant/components/wled/__init__.py | 4 ++- tests/components/wled/test_init.py | 37 ++++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/wled/__init__.py b/homeassistant/components/wled/__init__.py index a592720cd64d..a1ab32aa4512 100644 --- a/homeassistant/components/wled/__init__.py +++ b/homeassistant/components/wled/__init__.py @@ -63,10 +63,12 @@ async def async_unload_entry(hass: HomeAssistant, entry: WLEDConfigEntry) -> boo if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS): coordinator = entry.runtime_data - # Ensure disconnected and cleanup stop sub + # Ensure disconnected and cleanup stop sub. Cleared once called, as the + # WebSocket listener also cleans it up when the disconnect ends it. await coordinator.wled.disconnect() if coordinator.unsub: coordinator.unsub() + coordinator.unsub = None return unload_ok diff --git a/tests/components/wled/test_init.py b/tests/components/wled/test_init.py index 1aaf2606c04c..b3f3be598005 100644 --- a/tests/components/wled/test_init.py +++ b/tests/components/wled/test_init.py @@ -5,7 +5,7 @@ from collections.abc import Callable from unittest.mock import AsyncMock, MagicMock, patch import pytest -from wled import WLEDConnectionError +from wled import WLEDConnectionClosedError, WLEDConnectionError from homeassistant.components.wled.const import DOMAIN from homeassistant.config_entries import SOURCE_IGNORE, ConfigEntryState @@ -47,6 +47,41 @@ async def test_load_unload_config_entry( assert mock_wled.disconnect.call_count == 1 +@pytest.mark.parametrize("device_fixture", ["rgb_websocket"]) +async def test_unload_while_listening( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: AsyncMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test unloading ends the WebSocket listener without errors.""" + connection_connected = asyncio.Future() + connection_closed = asyncio.Future() + + async def listen(callback: Callable) -> None: + connection_connected.set_result(None) + await connection_closed + + async def disconnect() -> None: + # Disconnecting ends the listener, like a closed WebSocket does. + if not connection_closed.done(): + connection_closed.set_exception(WLEDConnectionClosedError("closed")) + + mock_wled.listen.side_effect = listen + mock_wled.disconnect.side_effect = disconnect + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + await connection_connected + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + assert "Unable to remove unknown job listener" not in caplog.text + + @patch( "homeassistant.components.wled.coordinator.WLED.request", side_effect=WLEDConnectionError, From 2cd59ef003962629025139c8efb360b17a37d6c3 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 08:56:53 +0200 Subject: [PATCH 101/356] Fix maintenance typo in rehlko (#184413) --- homeassistant/components/rehlko/sensor.py | 4 +-- homeassistant/components/rehlko/strings.json | 8 ++--- .../rehlko/snapshots/test_sensor.ambr | 32 +++++++++---------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/homeassistant/components/rehlko/sensor.py b/homeassistant/components/rehlko/sensor.py index 8dd5457acf18..cb90b67b1def 100644 --- a/homeassistant/components/rehlko/sensor.py +++ b/homeassistant/components/rehlko/sensor.py @@ -196,7 +196,7 @@ SENSORS: tuple[RehlkoSensorEntityDescription, ...] = ( ), RehlkoSensorEntityDescription( key="lastMaintenanceTimestamp", - translation_key="last_maintainance", + translation_key="last_maintenance", device_class=SensorDeviceClass.TIMESTAMP, document_key=GENERATOR_DATA_DEVICE, value_fn=datetime.fromisoformat, @@ -204,7 +204,7 @@ SENSORS: tuple[RehlkoSensorEntityDescription, ...] = ( ), RehlkoSensorEntityDescription( key="nextMaintenanceTimestamp", - translation_key="next_maintainance", + translation_key="next_maintenance", device_class=SensorDeviceClass.TIMESTAMP, document_key=GENERATOR_DATA_DEVICE, value_fn=datetime.fromisoformat, diff --git a/homeassistant/components/rehlko/strings.json b/homeassistant/components/rehlko/strings.json index 8cdb35a4ba80..bae1ec7a78a5 100644 --- a/homeassistant/components/rehlko/strings.json +++ b/homeassistant/components/rehlko/strings.json @@ -84,8 +84,8 @@ "last_exercise": { "name": "Last exercise" }, - "last_maintainance": { - "name": "Last maintainance" + "last_maintenance": { + "name": "Last maintenance" }, "last_run": { "name": "Last run" @@ -96,8 +96,8 @@ "next_exercise": { "name": "Next exercise" }, - "next_maintainance": { - "name": "Next maintainance" + "next_maintenance": { + "name": "Next maintenance" }, "power_source": { "name": "Power source" diff --git a/tests/components/rehlko/snapshots/test_sensor.ambr b/tests/components/rehlko/snapshots/test_sensor.ambr index ee603388aebc..a0cc5e5399d1 100644 --- a/tests/components/rehlko/snapshots/test_sensor.ambr +++ b/tests/components/rehlko/snapshots/test_sensor.ambr @@ -717,7 +717,7 @@ 'state': '2025-04-12T14:00:00+00:00', }) # --- -# name: test_sensors[sensor.generator_1_last_maintainance-entry] +# name: test_sensors[sensor.generator_1_last_maintenance-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ None, @@ -731,7 +731,7 @@ 'disabled_by': None, 'domain': 'sensor', 'entity_category': None, - 'entity_id': 'sensor.generator_1_last_maintainance', + 'entity_id': 'sensor.generator_1_last_maintenance', 'has_entity_name': True, 'hidden_by': None, 'icon': None, @@ -739,29 +739,29 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Last maintainance', + 'object_id_base': 'Last maintenance', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Last maintainance', + 'original_name': 'Last maintenance', 'platform': 'rehlko', 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'last_maintainance', + 'translation_key': 'last_maintenance', 'unique_id': 'myemail@email.com_12345_lastMaintenanceTimestamp', 'unit_of_measurement': None, }) # --- -# name: test_sensors[sensor.generator_1_last_maintainance-state] +# name: test_sensors[sensor.generator_1_last_maintenance-state] StateSnapshot({ 'attributes': ReadOnlyDict({ : 'timestamp', - : 'Generator 1 Last maintainance', + : 'Generator 1 Last maintenance', }), 'context': , - 'entity_id': 'sensor.generator_1_last_maintainance', + 'entity_id': 'sensor.generator_1_last_maintenance', 'last_changed': , 'last_reported': , 'last_updated': , @@ -928,7 +928,7 @@ 'state': '2025-04-19T14:00:00+00:00', }) # --- -# name: test_sensors[sensor.generator_1_next_maintainance-entry] +# name: test_sensors[sensor.generator_1_next_maintenance-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ None, @@ -942,7 +942,7 @@ 'disabled_by': None, 'domain': 'sensor', 'entity_category': None, - 'entity_id': 'sensor.generator_1_next_maintainance', + 'entity_id': 'sensor.generator_1_next_maintenance', 'has_entity_name': True, 'hidden_by': None, 'icon': None, @@ -950,29 +950,29 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Next maintainance', + 'object_id_base': 'Next maintenance', 'options': dict({ }), 'original_device_class': , 'original_icon': None, - 'original_name': 'Next maintainance', + 'original_name': 'Next maintenance', 'platform': 'rehlko', 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'next_maintainance', + 'translation_key': 'next_maintenance', 'unique_id': 'myemail@email.com_12345_nextMaintenanceTimestamp', 'unit_of_measurement': None, }) # --- -# name: test_sensors[sensor.generator_1_next_maintainance-state] +# name: test_sensors[sensor.generator_1_next_maintenance-state] StateSnapshot({ 'attributes': ReadOnlyDict({ : 'timestamp', - : 'Generator 1 Next maintainance', + : 'Generator 1 Next maintenance', }), 'context': , - 'entity_id': 'sensor.generator_1_next_maintainance', + 'entity_id': 'sensor.generator_1_next_maintenance', 'last_changed': , 'last_reported': , 'last_updated': , From 83dbb5213cf7bfb0239258d1e6328801b613a0ed Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 10:18:02 +0200 Subject: [PATCH 102/356] Only offer WLED firmware updates the device can install (#184415) --- homeassistant/components/wled/__init__.py | 11 +- homeassistant/components/wled/coordinator.py | 12 +- homeassistant/components/wled/strings.json | 3 + homeassistant/components/wled/update.py | 112 +++++++++++++-- tests/components/wled/conftest.py | 1 + tests/components/wled/test_update.py | 140 ++++++++++++++++++- 6 files changed, 257 insertions(+), 22 deletions(-) diff --git a/homeassistant/components/wled/__init__.py b/homeassistant/components/wled/__init__.py index a1ab32aa4512..193d9954938f 100644 --- a/homeassistant/components/wled/__init__.py +++ b/homeassistant/components/wled/__init__.py @@ -31,19 +31,18 @@ PLATFORMS = ( Platform.UPDATE, ) -WLED_KEY: HassKey[WLEDReleasesDataUpdateCoordinator] = HassKey(DOMAIN) +WLED_KEY: HassKey[dict[str, WLEDReleasesDataUpdateCoordinator]] = HassKey(DOMAIN) CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the WLED integration. - We set up a single coordinator for fetching WLED releases, which - is used across all WLED devices (and config entries) to avoid - fetching the same data multiple times for each. + Releases are fetched by one coordinator per firmware repository, shared + across all WLED devices (and config entries) using it, to avoid fetching + the same data multiple times for each. """ - hass.data[WLED_KEY] = WLEDReleasesDataUpdateCoordinator(hass) - await hass.data[WLED_KEY].async_request_refresh() + hass.data[WLED_KEY] = {} return True diff --git a/homeassistant/components/wled/coordinator.py b/homeassistant/components/wled/coordinator.py index 30344f154d89..b988287d2b40 100644 --- a/homeassistant/components/wled/coordinator.py +++ b/homeassistant/components/wled/coordinator.py @@ -173,6 +173,11 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): }, ) + # Firmware from another repository changes which updates can be offered, + # like after flashing a fork; set the integration up again for it. + if self.data is not None and device.info.repo != self.data.info.repo: + self.hass.config_entries.async_schedule_reload(self.config_entry.entry_id) + # If the device supports a WebSocket, try activating it. if ( device.info.websocket is not None @@ -187,9 +192,10 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): class WLEDReleasesDataUpdateCoordinator(DataUpdateCoordinator[Releases]): """Class to manage fetching WLED releases.""" - def __init__(self, hass: HomeAssistant) -> None: - """Initialize global WLED releases updater.""" - self.wled = WLEDReleases(session=async_get_clientsession(hass)) + def __init__(self, hass: HomeAssistant, repo: str) -> None: + """Initialize the WLED releases updater for a firmware repository.""" + self.repo = repo + self.wled = WLEDReleases(session=async_get_clientsession(hass), repo=repo) super().__init__( hass, LOGGER, diff --git a/homeassistant/components/wled/strings.json b/homeassistant/components/wled/strings.json index 80d8affd91b8..1085e26bf0c8 100644 --- a/homeassistant/components/wled/strings.json +++ b/homeassistant/components/wled/strings.json @@ -140,6 +140,9 @@ "connection_error": { "message": "Error communicating with WLED API: {error}" }, + "firmware_upgrade_failed": { + "message": "Updating the WLED firmware failed: {error}" + }, "invalid_response_github_error": { "message": "Invalid response from GitHub API: {error}" }, diff --git a/homeassistant/components/wled/update.py b/homeassistant/components/wled/update.py index a8a639c187d0..9eddd1b0d0e7 100644 --- a/homeassistant/components/wled/update.py +++ b/homeassistant/components/wled/update.py @@ -2,15 +2,21 @@ from typing import Any, cast, override +from wled import Releases, WLEDError, WLEDUpgradeError + from homeassistant.components.update import ( + DOMAIN as UPDATE_DOMAIN, UpdateDeviceClass, UpdateEntity, UpdateEntityFeature, ) -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import WLED_KEY +from .const import DOMAIN from .coordinator import ( WLEDConfigEntry, WLEDDataUpdateCoordinator, @@ -28,7 +34,26 @@ async def async_setup_entry( async_add_entities: AddConfigEntryEntitiesCallback, ) -> None: """Set up WLED update based on a config entry.""" - async_add_entities([WLEDUpdateEntity(entry.runtime_data, hass.data[WLED_KEY])]) + coordinator = entry.runtime_data + + # Without knowing where its firmware comes from, there is nothing to offer; + # that includes removing an update entity it had before. + if (repo := coordinator.data.info.repo) is None: + entity_registry = er.async_get(hass) + if entity_id := entity_registry.async_get_entity_id( + UPDATE_DOMAIN, DOMAIN, coordinator.data.info.mac_address + ): + entity_registry.async_remove(entity_id) + return + + releases = hass.data[WLED_KEY] + if (releases_coordinator := releases.get(repo)) is None: + releases_coordinator = releases[repo] = WLEDReleasesDataUpdateCoordinator( + hass, repo + ) + await releases_coordinator.async_request_refresh() + + async_add_entities([WLEDUpdateEntity(coordinator, releases_coordinator)]) class WLEDUpdateEntity(WLEDEntity, UpdateEntity): @@ -49,6 +74,9 @@ class WLEDUpdateEntity(WLEDEntity, UpdateEntity): super().__init__(coordinator=coordinator) self.releases_coordinator = releases_coordinator self._attr_unique_id = coordinator.data.info.mac_address + # Whether a release has a firmware file for this device, by version. + self._firmware_available: dict[str, bool] = {} + self._firmware_checks: set[str] = set() @override async def async_added_to_hass(self) -> None: @@ -58,10 +86,47 @@ class WLEDUpdateEntity(WLEDEntity, UpdateEntity): """ await super().async_added_to_hass() self.async_on_remove( - self.releases_coordinator.async_add_listener( - self._handle_coordinator_update - ) + self.releases_coordinator.async_add_listener(self._handle_releases_update) ) + self._async_check_firmware() + + @callback + def _handle_releases_update(self) -> None: + """Handle new release information.""" + self._async_check_firmware() + self._handle_coordinator_update() + + @callback + def _async_check_firmware(self) -> None: + """Check whether this device has a firmware file for the newest version. + + Only once per version: a custom build, for example, has no file in any + release, so that version can't be installed and isn't offered. + """ + if ( + (version := self._newest_version()) is None + or version == self.installed_version + or version in self._firmware_available + or version in self._firmware_checks + ): + return + + self._firmware_checks.add(version) + self.hass.async_create_task(self._async_firmware_available(version)) + + async def _async_firmware_available(self, version: str) -> None: + """Ask the release whether it has a firmware file for this device.""" + try: + available = await self.coordinator.wled.firmware_available(version=version) + except WLEDError: + # GitHub couldn't tell; keep offering it, and ask again with the + # next release information. Installing tells for sure. + return + finally: + self._firmware_checks.discard(version) + + self._firmware_available[version] = available + self.async_write_ha_state() @property @override @@ -81,20 +146,37 @@ class WLEDUpdateEntity(WLEDEntity, UpdateEntity): @override def latest_version(self) -> str | None: """Latest version available for install.""" + if (version := self._newest_version()) is None: + return None + + # A version without a firmware file for this device isn't an update. + if self._firmware_available.get(version) is False: + return self.installed_version + + return version + + def _newest_version(self) -> str | None: + """Return the newest version released for this device's channel.""" + # Another device from the same repository may still be fetching them; + # until then, the shared coordinator has no data. + releases: Releases | None = self.releases_coordinator.data + if releases is None: + return None + # If we already run a pre-release, we consider being on the beta channel. # Offer beta version upgrade, unless stable is newer if ( - (beta := self.releases_coordinator.data.beta) is not None + (beta := releases.beta) is not None and (current := self.coordinator.data.info.version) is not None and (current.alpha or current.beta or current.release_candidate) and ( - (stable := self.releases_coordinator.data.stable) is None + (stable := releases.stable) is None or (stable is not None and stable < beta and current > stable) ) ): return str(beta) - if (stable := self.releases_coordinator.data.stable) is not None: + if (stable := releases.stable) is not None: return str(stable) return None @@ -105,7 +187,10 @@ class WLEDUpdateEntity(WLEDEntity, UpdateEntity): """URL to the full release notes of the latest version available.""" if (version := self.latest_version) is None: return None - return f"https://github.com/wled/WLED/releases/tag/v{version}" + return ( + f"https://github.com/{self.releases_coordinator.repo}" + f"/releases/tag/v{version}" + ) @wled_exception_handler @override @@ -116,7 +201,14 @@ class WLEDUpdateEntity(WLEDEntity, UpdateEntity): if version is None: # We cast here, as we know that the latest_version is a string. version = cast(str, self.latest_version) - await self.coordinator.wled.upgrade(version=version) + try: + await self.coordinator.wled.upgrade(version=version) + except WLEDUpgradeError as error: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="firmware_upgrade_failed", + translation_placeholders={"error": str(error)}, + ) from error await self.coordinator.async_refresh() @override diff --git a/tests/components/wled/conftest.py b/tests/components/wled/conftest.py index 91cb7dd8afed..d0073342433a 100644 --- a/tests/components/wled/conftest.py +++ b/tests/components/wled/conftest.py @@ -85,6 +85,7 @@ def mock_wled( ) wled.connected = False wled.host = "127.0.0.1" + wled.firmware_available.return_value = True yield wled diff --git a/tests/components/wled/test_update.py b/tests/components/wled/test_update.py index c486230139a4..2c7eb3a79c2e 100644 --- a/tests/components/wled/test_update.py +++ b/tests/components/wled/test_update.py @@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion -from wled import Releases, WLEDError +from wled import Device as WLEDDevice, Releases, WLEDError, WLEDUpgradeError from homeassistant.components.homeassistant import ( DOMAIN as HOME_ASSISTANT_DOMAIN, @@ -15,10 +15,13 @@ from homeassistant.components.homeassistant import ( from homeassistant.components.update import ( ATTR_INSTALLED_VERSION, ATTR_LATEST_VERSION, + ATTR_RELEASE_URL, DOMAIN as UPDATE_DOMAIN, SERVICE_INSTALL, ) -from homeassistant.components.wled.const import RELEASES_SCAN_INTERVAL +from homeassistant.components.wled import WLED_KEY +from homeassistant.components.wled.const import DOMAIN, RELEASES_SCAN_INTERVAL +from homeassistant.components.wled.coordinator import WLEDReleasesDataUpdateCoordinator from homeassistant.const import ( ATTR_ENTITY_ID, STATE_OFF, @@ -28,11 +31,17 @@ from homeassistant.const import ( Platform, ) from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from homeassistant.helpers.update_coordinator import REQUEST_REFRESH_DEFAULT_COOLDOWN from homeassistant.setup import async_setup_component -from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform +from tests.common import ( + MockConfigEntry, + async_fire_time_changed, + async_load_json_object_fixture, + snapshot_platform, +) pytestmark = pytest.mark.usefixtures("init_integration") @@ -233,3 +242,128 @@ async def test_update_entities( assert (state := hass.states.get("update.wled_rgb_light_firmware")) assert state.state == STATE_ON assert state.attributes[ATTR_LATEST_VERSION] == "16.0.0" + + +async def test_update_without_known_repo( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test there is no update entity when the firmware's origin isn't known.""" + assert entity_registry.async_get("update.wled_rgb_light_firmware") + mock_wled.update.return_value.info.repo = None + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + # The update entity it had before is removed, not left unavailable. + assert entity_registry.async_get("update.wled_rgb_light_firmware") is None + assert hass.states.get("update.wled_rgb_light_firmware") is None + + +async def test_update_release_url_from_repo( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the release notes link to the repository the firmware comes from.""" + mock_wled.update.return_value.info.repo = "MoonModules/WLED-MM" + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert state.attributes[ATTR_RELEASE_URL] == ( + "https://github.com/MoonModules/WLED-MM/releases/tag/v0.99.0" + ) + + +async def test_update_without_firmware_for_device( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a version without a firmware file for the device isn't offered.""" + mock_wled.firmware_available.return_value = False + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert state.state == STATE_OFF + assert state.attributes[ATTR_LATEST_VERSION] == "0.14.4" + mock_wled.firmware_available.assert_called_with(version="0.99.0") + + +async def test_update_when_firmware_check_fails( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the update is still offered when GitHub can't tell.""" + mock_wled.firmware_available.side_effect = WLEDError + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert state.state == STATE_ON + assert state.attributes[ATTR_LATEST_VERSION] == "0.99.0" + + +async def test_update_install_refused( + hass: HomeAssistant, + mock_wled: MagicMock, +) -> None: + """Test a firmware update the device refuses shows why.""" + mock_wled.upgrade.side_effect = WLEDUpgradeError("Client is not on local subnet") + + with pytest.raises( + HomeAssistantError, match="Client is not on local subnet" + ) as exc_info: + await hass.services.async_call( + UPDATE_DOMAIN, + SERVICE_INSTALL, + {ATTR_ENTITY_ID: "update.wled_rgb_light_firmware"}, + blocking=True, + ) + + assert exc_info.value.translation_key == "firmware_upgrade_failed" + + +async def test_update_follows_firmware_repository_change( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the update entity follows a device flashed with another firmware.""" + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert "github.com/wled/WLED/" in state.attributes[ATTR_RELEASE_URL] + + # A new device object, as the device answers after being flashed. + data = await async_load_json_object_fixture(hass, "rgb.json", DOMAIN) + data["info"]["repo"] = "MoonModules/WLED-MM" + mock_wled.update.return_value = WLEDDevice.from_dict(data) + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert "github.com/MoonModules/WLED-MM/" in state.attributes[ATTR_RELEASE_URL] + + +async def test_update_while_releases_are_still_coming( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a device set up while the shared releases aren't fetched yet.""" + # Another device from the same repository is still fetching the releases. + hass.data[WLED_KEY]["wled/WLED"] = WLEDReleasesDataUpdateCoordinator( + hass, "wled/WLED" + ) + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("update.wled_rgb_light_firmware")) + assert state.state == STATE_UNKNOWN From bc99d0ac61a105355a47e0b696f1e2bea805fb09 Mon Sep 17 00:00:00 2001 From: Arie Catsman <120491684+catsmanac@users.noreply.github.com> Date: Tue, 6 Oct 2026 09:34:25 +0200 Subject: [PATCH 103/356] Remove battery device class from enphase envoy reserve_soc (#184418) --- homeassistant/components/enphase_envoy/sensor.py | 1 - .../enphase_envoy/snapshots/test_diagnostics.ambr | 3 +-- .../components/enphase_envoy/snapshots/test_sensor.ambr | 9 +++------ 3 files changed, 4 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/enphase_envoy/sensor.py b/homeassistant/components/enphase_envoy/sensor.py index d5d9d6518526..667039924ea6 100644 --- a/homeassistant/components/enphase_envoy/sensor.py +++ b/homeassistant/components/enphase_envoy/sensor.py @@ -804,7 +804,6 @@ ENCHARGE_AGGREGATE_SENSORS = ( translation_key="reserve_soc", native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, - device_class=SensorDeviceClass.BATTERY, value_fn=attrgetter("reserve_state_of_charge"), ), EnvoyEnchargeAggregateSensorEntityDescription( diff --git a/tests/components/enphase_envoy/snapshots/test_diagnostics.ambr b/tests/components/enphase_envoy/snapshots/test_diagnostics.ambr index 23f7fb3655bd..e7edd3ba9a36 100644 --- a/tests/components/enphase_envoy/snapshots/test_diagnostics.ambr +++ b/tests/components/enphase_envoy/snapshots/test_diagnostics.ambr @@ -16673,7 +16673,7 @@ 'object_id_base': 'Reserve battery level', 'options': dict({ }), - 'original_device_class': 'battery', + 'original_device_class': None, 'original_icon': None, 'original_name': 'Reserve battery level', 'platform': 'enphase_envoy', @@ -16686,7 +16686,6 @@ }), 'state': dict({ 'attributes': dict({ - 'device_class': 'battery', 'friendly_name': 'Envoy <> Reserve battery level', 'state_class': 'measurement', 'unit_of_measurement': '%', diff --git a/tests/components/enphase_envoy/snapshots/test_sensor.ambr b/tests/components/enphase_envoy/snapshots/test_sensor.ambr index 1adb7ff38b1a..e48e1da757be 100644 --- a/tests/components/enphase_envoy/snapshots/test_sensor.ambr +++ b/tests/components/enphase_envoy/snapshots/test_sensor.ambr @@ -9578,7 +9578,7 @@ 'object_id_base': 'Reserve battery level', 'options': dict({ }), - 'original_device_class': , + 'original_device_class': None, 'original_icon': None, 'original_name': 'Reserve battery level', 'platform': 'enphase_envoy', @@ -9593,7 +9593,6 @@ # name: test_sensor[envoy_acb_batt][sensor.envoy_1234_reserve_battery_level-state] StateSnapshot({ 'attributes': ReadOnlyDict({ - : 'battery', : 'Envoy 1234 Reserve battery level', : , : '%', @@ -15749,7 +15748,7 @@ 'object_id_base': 'Reserve battery level', 'options': dict({ }), - 'original_device_class': , + 'original_device_class': None, 'original_icon': None, 'original_name': 'Reserve battery level', 'platform': 'enphase_envoy', @@ -15764,7 +15763,6 @@ # name: test_sensor[envoy_eu_batt][sensor.envoy_1234_reserve_battery_level-state] StateSnapshot({ 'attributes': ReadOnlyDict({ - : 'battery', : 'Envoy 1234 Reserve battery level', : , : '%', @@ -33327,7 +33325,7 @@ 'object_id_base': 'Reserve battery level', 'options': dict({ }), - 'original_device_class': , + 'original_device_class': None, 'original_icon': None, 'original_name': 'Reserve battery level', 'platform': 'enphase_envoy', @@ -33342,7 +33340,6 @@ # name: test_sensor[envoy_metered_batt_relay][sensor.envoy_1234_reserve_battery_level-state] StateSnapshot({ 'attributes': ReadOnlyDict({ - : 'battery', : 'Envoy 1234 Reserve battery level', : , : '%', From 1b65a280b7a6bec9c9f2afd985c8281bf4d720a6 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 14:31:54 +0200 Subject: [PATCH 104/356] Add the WLED current sensors once the device reports a current (#184435) --- homeassistant/components/wled/sensor.py | 44 +++++++++++++++--- tests/components/wled/test_sensor.py | 59 +++++++++++++++++++++++++ 2 files changed, 97 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/wled/sensor.py b/homeassistant/components/wled/sensor.py index 74aed519c705..d36a0989a12f 100644 --- a/homeassistant/components/wled/sensor.py +++ b/homeassistant/components/wled/sensor.py @@ -8,6 +8,7 @@ from typing import override from wled import Device as WLEDDevice from homeassistant.components.sensor import ( + DOMAIN as SENSOR_DOMAIN, SensorDeviceClass, SensorEntity, SensorEntityDescription, @@ -20,7 +21,8 @@ from homeassistant.const import ( UnitOfElectricCurrent, UnitOfInformation, ) -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback +from homeassistant.helpers import entity_registry as er from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType from homeassistant.util.dt import utcnow @@ -135,11 +137,41 @@ async def async_setup_entry( ) -> None: """Set up WLED sensor based on a config entry.""" coordinator = entry.runtime_data - async_add_entities( - WLEDSensorEntity(coordinator, description) - for description in SENSORS - if description.exists_fn(coordinator.data) - ) + added: set[str] = set() + + # Sensors added before stay, even when the device doesn't report what they + # need right now, like the current while the light is off. + registered = { + registry_entry.unique_id + for registry_entry in er.async_entries_for_config_entry( + er.async_get(hass), entry.entry_id + ) + if registry_entry.domain == SENSOR_DOMAIN + } + mac_address = coordinator.data.info.mac_address + + @callback + def _async_add_sensors() -> None: + """Add the sensors the device reports, as soon as it does. + + Some only show up later: WLED reports no current while the light is + off, so a device that's off when set up gets those sensors once it's on. + """ + sensors = [ + WLEDSensorEntity(coordinator, description) + for description in SENSORS + if description.key not in added + and ( + description.exists_fn(coordinator.data) + or f"{mac_address}_{description.key}" in registered + ) + ] + added.update(sensor.entity_description.key for sensor in sensors) + if sensors: + async_add_entities(sensors) + + _async_add_sensors() + entry.async_on_unload(coordinator.async_add_listener(_async_add_sensors)) class WLEDSensorEntity(WLEDEntity, SensorEntity): diff --git a/tests/components/wled/test_sensor.py b/tests/components/wled/test_sensor.py index e7065d91c8dc..4b9f088bd7b5 100644 --- a/tests/components/wled/test_sensor.py +++ b/tests/components/wled/test_sensor.py @@ -106,6 +106,65 @@ async def test_no_current_measurement( assert hass.states.get("sensor.wled_rgb_light_estimated_current") is None +async def test_current_measurement_once_reported( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: MagicMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test the current sensors are added once the device reports a current.""" + # WLED reports no current while the light is off. + device = mock_wled.update.return_value + device.info.leds.max_power = 0 + device.info.leds.power = 0 + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get("sensor.wled_rgb_light_max_current") is None + assert hass.states.get("sensor.wled_rgb_light_estimated_current") is None + + device.info.leds.max_power = 850 + device.info.leds.power = 470 + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + assert (state := hass.states.get("sensor.wled_rgb_light_max_current")) + assert state.state == "850" + assert (state := hass.states.get("sensor.wled_rgb_light_estimated_current")) + assert state.state == "470" + + # Later updates don't add them again. + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + assert "does not generate unique IDs" not in caplog.text + + +async def test_current_measurement_kept_when_not_reported( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_wled: MagicMock, +) -> None: + """Test current sensors added before stay while the device reports none.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert hass.states.get("sensor.wled_rgb_light_estimated_current") + + # The light is off when Home Assistant starts again. + device = mock_wled.update.return_value + device.info.leds.max_power = 0 + device.info.leds.power = 0 + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("sensor.wled_rgb_light_max_current")) + assert state.state == "0" + assert (state := hass.states.get("sensor.wled_rgb_light_estimated_current")) + assert state.state == "0" + + async def test_current_measurement_with_per_output_limiters( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 4599267dbe1679b407ba64c51bb1f88e65165246 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 18:05:58 +0200 Subject: [PATCH 105/356] Follow the WLED color mode from the light's color (#184478) --- homeassistant/components/wled/const.py | 7 +- homeassistant/components/wled/light.py | 44 ++++++- tests/components/wled/test_light.py | 167 +++++++++++++++++++++++++ 3 files changed, 213 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/wled/const.py b/homeassistant/components/wled/const.py index 6d768577d955..5591b682fa76 100644 --- a/homeassistant/components/wled/const.py +++ b/homeassistant/components/wled/const.py @@ -53,11 +53,10 @@ LIGHT_CAPABILITIES_COLOR_MODE_MAPPING: dict[LightCapability, list[ColorMode]] = ColorMode.COLOR_TEMP, ], LightCapability.RGB_COLOR | LightCapability.COLOR_TEMPERATURE: [ - # Technically this is RGBWW but wled does not - # support RGBWW colors (with warm and cold white - # separately) - # but rather RGB + CCT which does not have a direct mapping in HA + # WLED doesn't report warm and cold white separately, so this isn't + # RGBWW: either the RGB color or the color temperature is in use. ColorMode.RGB, + ColorMode.COLOR_TEMP, ], LightCapability.WHITE_CHANNEL | LightCapability.COLOR_TEMPERATURE: [ ColorMode.COLOR_TEMP, diff --git a/homeassistant/components/wled/light.py b/homeassistant/components/wled/light.py index 1cd6f940382d..1cb5748f9bda 100644 --- a/homeassistant/components/wled/light.py +++ b/homeassistant/components/wled/light.py @@ -3,6 +3,8 @@ from functools import partial from typing import Any, cast, override +from wled import LightCapability + from homeassistant.components.light import ( ATTR_BRIGHTNESS, ATTR_COLOR_TEMP_KELVIN, @@ -158,13 +160,47 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): f"{self.coordinator.data.info.mac_address}_{self._segment}" ) + self._color_modes: list[ColorMode] = [] + self._has_white_channel = False if ( capabilities := coordinator.data.state.segments[segment].light_capabilities ) is not None and ( color_modes := LIGHT_CAPABILITIES_COLOR_MODE_MAPPING.get(capabilities) ) is not None: - self._attr_color_mode = color_modes[0] + self._color_modes = color_modes self._attr_supported_color_modes = set(color_modes) + self._has_white_channel = LightCapability.WHITE_CHANNEL in capabilities + + @property + @override + def color_mode(self) -> ColorMode | None: + """Return the color mode the segment is in right now. + + WLED doesn't tell, so it follows from the color: a color temperature + shows as full white, on the white channel when there is one. + """ + if not self._color_modes: + return None + + if len(self._color_modes) == 1: + return self._color_modes[0] + + # A color temperature shows as exactly the white this light sends for + # it. A dimmed white channel is a color, so restoring it doesn't turn + # it into full white. + color = self.coordinator.data.state.segments[self._segment].color + if ColorMode.COLOR_TEMP in self._color_modes and color is not None: + primary = color.primary + if ( + primary == (0, 0, 0, 255) + if self._has_white_channel + else primary[:3] == (255, 255, 255) + ): + return ColorMode.COLOR_TEMP + + return next( + mode for mode in self._color_modes if mode is not ColorMode.COLOR_TEMP + ) @property @override @@ -275,6 +311,12 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): data[ATTR_CCT] = kelvin_to_255( kwargs[ATTR_COLOR_TEMP_KELVIN], COLOR_TEMP_K_MIN, COLOR_TEMP_K_MAX ) + # A color temperature only shows on white light: the white channel + # where there is one, otherwise full white. + if self._color_modes: + data[ATTR_COLOR_PRIMARY] = ( + (0, 0, 0, 255) if self._has_white_channel else (255, 255, 255) + ) if ATTR_TRANSITION in kwargs: # WLED uses 100ms per unit, so 10 = 1 second. diff --git a/tests/components/wled/test_light.py b/tests/components/wled/test_light.py index e63799999d71..2b9c2ff8945d 100644 --- a/tests/components/wled/test_light.py +++ b/tests/components/wled/test_light.py @@ -1,6 +1,7 @@ """Tests for the WLED light platform.""" from collections.abc import Generator +from typing import Any from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory @@ -405,6 +406,7 @@ async def test_cct_light(hass: HomeAssistant, mock_wled: MagicMock) -> None: assert mock_wled.segment.call_count == 1 mock_wled.segment.assert_called_with( cct=130, + color_primary=(0, 0, 0, 255), on=True, segment_id=0, ) @@ -457,3 +459,168 @@ async def test_main_light_group_updates_when_segments_change( # Back to 1 segment: group should contain only segment 0 again assert (state := hass.states.get("light.wled_rgb_light_main")) assert state.attributes[ATTR_GROUP_ENTITIES] == ["light.wled_rgb_light"] + + +async def _async_load_segment( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + light_capabilities: int, + color: list[int], +) -> None: + """Load the CCT device with one segment of the given capabilities and color.""" + data = await async_load_json_object_fixture(hass, "cct.json", DOMAIN) + data["info"]["leds"]["seglc"] = [light_capabilities] + data["state"]["seg"][0]["col"] = [color, [0, 0, 0, 0], [0, 0, 0, 0]] + mock_wled.update.return_value = WLEDDevice.from_dict(data) + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +@pytest.mark.parametrize( + ("light_capabilities", "color", "supported_color_modes", "color_mode"), + [ + # RGB + white channel + color temperature + ( + 7, + [0, 0, 0, 255], + [ColorMode.COLOR_TEMP, ColorMode.RGBW], + ColorMode.COLOR_TEMP, + ), + (7, [255, 0, 0, 0], [ColorMode.COLOR_TEMP, ColorMode.RGBW], ColorMode.RGBW), + (7, [255, 0, 0, 128], [ColorMode.COLOR_TEMP, ColorMode.RGBW], ColorMode.RGBW), + # A dimmed white channel is an RGBW color, not a color temperature. + (7, [0, 0, 0, 64], [ColorMode.COLOR_TEMP, ColorMode.RGBW], ColorMode.RGBW), + (7, [0, 0, 0, 0], [ColorMode.COLOR_TEMP, ColorMode.RGBW], ColorMode.RGBW), + # RGB + color temperature + ( + 5, + [255, 255, 255], + [ColorMode.COLOR_TEMP, ColorMode.RGB], + ColorMode.COLOR_TEMP, + ), + (5, [255, 0, 0], [ColorMode.COLOR_TEMP, ColorMode.RGB], ColorMode.RGB), + (5, [128, 128, 128], [ColorMode.COLOR_TEMP, ColorMode.RGB], ColorMode.RGB), + # Single color modes + (1, [255, 0, 0], [ColorMode.RGB], ColorMode.RGB), + (3, [255, 0, 0, 128], [ColorMode.RGBW], ColorMode.RGBW), + (6, [0, 0, 0, 255], [ColorMode.COLOR_TEMP], ColorMode.COLOR_TEMP), + # Manual white (bit 8, not set by current firmware) never gives an + # unsupported color mode, and recognizes the white it sends. + (11, [0, 0, 0, 255], [ColorMode.RGBW, ColorMode.WHITE], ColorMode.RGBW), + ( + 13, + [255, 255, 255], + [ColorMode.COLOR_TEMP, ColorMode.RGBW], + ColorMode.COLOR_TEMP, + ), + ], +) +async def test_color_mode_follows_color( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + light_capabilities: int, + color: list[int], + supported_color_modes: list[ColorMode], + color_mode: ColorMode, +) -> None: + """Test the color mode follows the segment's capabilities and color.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, light_capabilities, color + ) + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == supported_color_modes + assert state.attributes[ATTR_COLOR_MODE] == color_mode + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_mode_changes_with_the_device( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the color mode follows a color change on the device.""" + await _async_load_segment(hass, mock_wled, mock_config_entry, 7, [0, 0, 0, 255]) + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + + data = await async_load_json_object_fixture(hass, "cct.json", DOMAIN) + data["state"]["seg"][0]["col"] = [[255, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] + mock_wled.update.return_value = WLEDDevice.from_dict(data) + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.RGBW + assert state.attributes[ATTR_RGBW_COLOR] == (255, 0, 0, 0) + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +@pytest.mark.parametrize( + ("light_capabilities", "color", "color_primary"), + [ + (7, [255, 0, 0, 0], (0, 0, 0, 255)), + (6, [0, 0, 0, 255], (0, 0, 0, 255)), + (5, [255, 0, 0], (255, 255, 255)), + ], +) +async def test_color_temp_sets_white( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + light_capabilities: int, + color: list[int], + color_primary: tuple[int, ...], +) -> None: + """Test a color temperature turns on the white it shows on.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, light_capabilities, color + ) + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.wled_cct_light", ATTR_COLOR_TEMP_KELVIN: 4321}, + blocking=True, + ) + + mock_wled.segment.assert_called_with( + cct=130, color_primary=color_primary, on=True, segment_id=0 + ) + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +@pytest.mark.parametrize( + ("light_capabilities", "color", "service_data", "color_primary"), + [ + (7, [0, 0, 0, 255], {ATTR_RGBW_COLOR: (255, 0, 0, 0)}, (255, 0, 0, 0)), + (5, [255, 255, 255], {ATTR_RGB_COLOR: (255, 0, 0)}, (255, 0, 0)), + ], +) +async def test_color_leaves_color_temp_alone( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + light_capabilities: int, + color: list[int], + service_data: dict[str, Any], + color_primary: tuple[int, ...], +) -> None: + """Test setting a color doesn't change the color temperature.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, light_capabilities, color + ) + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "light.wled_cct_light", **service_data}, + blocking=True, + ) + + mock_wled.segment.assert_called_with( + color_primary=color_primary, on=True, segment_id=0 + ) From 95a070add4bd62f501efdf7eee2995623edb1281 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:48:33 +0200 Subject: [PATCH 106/356] Fix the SSL option description in the Transmission config flow (#184509) --- homeassistant/components/transmission/strings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/transmission/strings.json b/homeassistant/components/transmission/strings.json index 4fef7b8f92b2..31ff7ce5f663 100644 --- a/homeassistant/components/transmission/strings.json +++ b/homeassistant/components/transmission/strings.json @@ -33,7 +33,7 @@ "password": "The password to authenticate with the Transmission instance, if set.", "path": "The RPC request target path, for example, `/transmission/rpc`.", "port": "The port number of the Transmission instance.", - "ssl": "Whether to verify SSL certificates. Disable this for self-signed certificates.", + "ssl": "Connect to the Transmission RPC interface using HTTPS.", "username": "The username to authenticate with the Transmission instance, if set." }, "title": "Set up Transmission client" From d6d6b999dead210e5767f0ef591eeb4064859105 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 21:00:56 +0200 Subject: [PATCH 107/356] Send the ESPHome imported state when the entity is created after subscribing (#184510) --- homeassistant/components/esphome/manager.py | 16 ++++++++------ tests/components/esphome/test_manager.py | 23 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index a0a8fdea1ac1..0bf49f3585a6 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -511,14 +511,18 @@ class ESPHomeManager: new_state = event_data["new_state"] old_state = event_data["old_state"] - if new_state is None or old_state is None: + if new_state is None: return - # Only communicate changes to the state or attribute tracked - if (not attribute and old_state.state == new_state.state) or ( - attribute - and old_state.attributes.get(attribute) - == new_state.attributes.get(attribute) + # Only communicate changes to the state or attribute tracked, an entity + # created after the subscription has no old state and is always sent + if old_state is not None and ( + (not attribute and old_state.state == new_state.state) + or ( + attribute + and old_state.attributes.get(attribute) + == new_state.attributes.get(attribute) + ) ): return diff --git a/tests/components/esphome/test_manager.py b/tests/components/esphome/test_manager.py index 5ec39aa80fb4..a8ae67b2fafc 100644 --- a/tests/components/esphome/test_manager.py +++ b/tests/components/esphome/test_manager.py @@ -1775,6 +1775,29 @@ async def test_state_subscription( assert mock_client.send_home_assistant_state.mock_calls == [] +async def test_state_subscription_entity_added_later( + mock_client: APIClient, + hass: HomeAssistant, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test the state is sent once a subscribed entity is created.""" + device = await mock_esphome_device( + mock_client=mock_client, + ) + await hass.async_block_till_done() + device.mock_home_assistant_state_subscription("cover.garage_door", None) + device.mock_home_assistant_state_subscription("cover.garage_door", "position") + await hass.async_block_till_done() + assert mock_client.send_home_assistant_state.mock_calls == [] + + hass.states.async_set("cover.garage_door", "closed", {"position": 0}) + await hass.async_block_till_done() + assert mock_client.send_home_assistant_state.mock_calls == [ + call("cover.garage_door", None, "closed"), + call("cover.garage_door", "position", "0"), + ] + + async def test_state_request( mock_client: APIClient, hass: HomeAssistant, From 69e7b587c2234b5ba1afd9ec2f7bfce7596bba5b Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:42:10 +0200 Subject: [PATCH 108/356] Check Music Assistant player configs before forwarding the platforms (#184520) --- .../components/music_assistant/__init__.py | 41 +++++++----- tests/components/music_assistant/test_init.py | 66 +++++++++++++++++++ 2 files changed, 91 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/music_assistant/__init__.py b/homeassistant/components/music_assistant/__init__.py index c23d5c59ed86..f531eb5a896b 100644 --- a/homeassistant/components/music_assistant/__init__.py +++ b/homeassistant/components/music_assistant/__init__.py @@ -157,13 +157,23 @@ async def async_setup_entry( # noqa: C901 # store the listen task and mass client in the entry data entry.runtime_data = MusicAssistantEntryData(mass, listen_task) - # If the listen task is already failed, we need to raise ConfigEntryNotReady - if listen_task.done() and (listen_error := listen_task.exception()) is not None: - await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - try: - await mass.disconnect() - finally: - raise ConfigEntryNotReady(listen_error) from listen_error + # check if any playerconfigs have been removed while we were disconnected, + # before forwarding the platforms, as the server can still go away here. + try: + all_player_configs = await mass.config.get_player_configs() + except (MusicAssistantClientException, MusicAssistantError) as err: + listen_task.cancel() + await mass.disconnect() + raise ConfigEntryNotReady( + f"Lost connection to music assistant server {mass_url}: {err}" + ) from err + player_ids = {player.player_id for player in all_player_configs} + dev_reg = dr.async_get(hass) + dev_entries = dr.async_entries_for_config_entry(dev_reg, entry.entry_id) + for device in dev_entries: + for identifier in device.identifiers: + if identifier[0] == DOMAIN and identifier[1] not in player_ids: + dev_reg.async_remove_device(device.id) # initialize platforms await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) @@ -240,15 +250,14 @@ async def async_setup_entry( # noqa: C901 mass.subscribe(handle_player_config_updated, EventType.PLAYER_CONFIG_UPDATED) ) - # check if any playerconfigs have been removed while we were disconnected - all_player_configs = await mass.config.get_player_configs() - player_ids = {player.player_id for player in all_player_configs} - dev_reg = dr.async_get(hass) - dev_entries = dr.async_entries_for_config_entry(dev_reg, entry.entry_id) - for device in dev_entries: - for identifier in device.identifiers: - if identifier[0] == DOMAIN and identifier[1] not in player_ids: - dev_reg.async_remove_device(device.id) + # The listen task skips its reload when it fails with an exception while + # the entry is still being set up, so that case has to be caught here + if listen_task.done() and (listen_error := listen_task.exception()) is not None: + await hass.config_entries.async_unload_platforms(entry, PLATFORMS) + try: + await mass.disconnect() + finally: + raise ConfigEntryNotReady(listen_error) from listen_error return True diff --git a/tests/components/music_assistant/test_init.py b/tests/components/music_assistant/test_init.py index 51496fad1955..de423e9e0a6a 100644 --- a/tests/components/music_assistant/test_init.py +++ b/tests/components/music_assistant/test_init.py @@ -1,9 +1,13 @@ """Test the Music Assistant integration init.""" +import asyncio from unittest.mock import AsyncMock, MagicMock +from music_assistant_client.exceptions import ConnectionFailed, InvalidState +from music_assistant_models.config_entries import PlayerConfig from music_assistant_models.enums import EventType from music_assistant_models.errors import ActionUnavailable, AuthenticationRequired +import pytest from homeassistant.components.music_assistant.const import ( ATTR_CONF_EXPOSE_PLAYER_TO_HA, @@ -217,3 +221,65 @@ async def test_authentication_required_addon_no_reauth( issue_id = f"config_entry_reauth_{DOMAIN}_{config_entry.entry_id}" assert issue_registry.async_get_issue("homeassistant", issue_id) is None + + +async def test_server_lost_during_setup_retries( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + music_assistant_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test losing the server during setup leaves no platforms set up.""" + get_player_configs = music_assistant_client.config.get_player_configs + music_assistant_client.config.get_player_configs = AsyncMock( + side_effect=InvalidState("Not connected") + ) + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + music_assistant_client.disconnect.assert_awaited_once() + + music_assistant_client.config.get_player_configs = get_player_configs + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert "has already been setup" not in caplog.text + + +async def test_server_lost_late_in_setup_retries( + hass: HomeAssistant, + music_assistant_client: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test losing the server after the last server call during setup retries.""" + connection_lost = asyncio.Event() + + async def listen(init_ready: asyncio.Event) -> None: + init_ready.set() + await connection_lost.wait() + raise ConnectionFailed + + get_player_configs = music_assistant_client.config.get_player_configs + + async def get_player_configs_then_lose_server() -> list[PlayerConfig]: + player_configs = await get_player_configs() + connection_lost.set() + # Let the listen task fail before setup continues + await asyncio.sleep(0) + return player_configs + + music_assistant_client.start_listening.side_effect = listen + music_assistant_client.config.get_player_configs = ( + get_player_configs_then_lose_server + ) + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + music_assistant_client.disconnect.assert_awaited_once() From 78f95f20a36c1562734f5975e17624065e5fc21c Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Mon, 5 Oct 2026 21:28:33 +1000 Subject: [PATCH 109/356] Explain why Teslemetry Bluetooth pairing failed (#184172) --- .../components/teslemetry/config_flow.py | 25 +++- .../components/teslemetry/strings.json | 5 +- .../components/teslemetry/test_config_flow.py | 140 ++++++++++++++++-- 3 files changed, 156 insertions(+), 14 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index bd0e54a520cf..5d8373b5c87a 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -9,6 +9,8 @@ from typing import TYPE_CHECKING, Any, cast, override from aiohttp import ClientError from aiopowerwall import PowerwallAuthenticationError, PowerwallError from bleak.exc import BleakError +from bleak_retry_connector import BleakNotFoundError, BleakOutOfConnectionSlotsError +from habluetooth.const import STRONG_OWNER_STALE_RSSI import probatio from tesla_fleet_api.const import ( AuthorizedClientKeyType, @@ -41,6 +43,7 @@ from homeassistant.components.application_credentials import ( ) from homeassistant.components.bluetooth import ( async_discovered_service_info, + async_last_service_info, async_request_active_scan, async_scanner_count, ) @@ -324,7 +327,27 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): except (BleakError, TeslaFleetError, TimeoutError) as err: LOGGER.error("Failed to connect over Bluetooth: %s", err) await self._async_disconnect() - errors["base"] = "cannot_connect" + cause = err.__cause__ + last_info = async_last_service_info( + self.hass, device.address, connectable=True + ) + if not isinstance( + cause, BleakNotFoundError | BleakOutOfConnectionSlotsError + ): + errors["base"] = "cannot_connect" + # bleak-retry-connector also raises BleakNotFoundError from a final connect timeout. + elif last_info is None or ( + isinstance(cause, BleakNotFoundError) + and not isinstance(cause.__cause__, TimeoutError) + ): + errors["base"] = "device_not_found" + elif isinstance(cause, BleakOutOfConnectionSlotsError): + errors["base"] = "no_connection_slot" + # habluetooth treats this signal as a close device, so the timeout is not about range. + elif last_info.rssi >= STRONG_OWNER_STALE_RSSI: + errors["base"] = "vehicle_busy" + else: + errors["base"] = "weak_signal" else: return await self.async_step_pair() diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index 54ecb2ad94bb..a4b4626c7a52 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -105,10 +105,13 @@ "device_not_found": "No matching Tesla vehicle was found nearby over Bluetooth. Make sure the vehicle is within range of a Bluetooth adapter or proxy, then try again.", "key_load_failed": "The Bluetooth key file {key_file} could not be loaded. Make sure it is a valid private key and that Home Assistant has permission to read it, then try again.", "key_unverified": "The key was added, but the vehicle's reply could not be verified. Select Submit to try again.", + "no_connection_slot": "Every Bluetooth adapter or proxy that can reach the vehicle has no free connection slot. Free a connection slot on a Bluetooth proxy, or add another proxy near the vehicle, then try again.", "pair_denied": "The key was declined on the vehicle's touchscreen. Select Submit and tap a key card to try again.", "pair_failed": "The vehicle rejected the key. Make sure it is not in valet mode and does not already have the maximum number of keys, then try again.", "tap_timeout": "The key card was not tapped in time. Select Submit and tap a key card within 30 seconds.", - "timeout": "Timed out waiting for the vehicle to add the key. Select Submit and tap a key card on the center console card reader." + "timeout": "Timed out waiting for the vehicle to add the key. Select Submit and tap a key card on the center console card reader.", + "vehicle_busy": "The vehicle is busy and may already have its maximum number of Bluetooth connections. Disconnect other phones or devices from the vehicle, then try again.", + "weak_signal": "The vehicle's Bluetooth signal is too weak to connect. Move the vehicle closer to a Bluetooth adapter, or add a Bluetooth proxy near it, then try again." }, "initiate_flow": { "user": "Add local vehicle" diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index b6ed63a474b7..0f78dddcfa77 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -14,7 +14,12 @@ from aiopowerwall import ( PowerwallConnectionError, PowerwallFaultError, ) -from bleak.exc import BleakError +from bleak.exc import BleakDeviceNotFoundError, BleakError +from bleak_retry_connector import ( + BleakConnectionError, + BleakNotFoundError, + BleakOutOfConnectionSlotsError, +) from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa import probatio @@ -77,6 +82,11 @@ from . import mock_config_entry, setup_platform from .const import CONFIG_V1, METADATA, PRODUCTS, UNIQUE_ID from tests.common import MockConfigEntry +from tests.components.bluetooth import ( + generate_advertisement_data, + generate_ble_device, + inject_advertisement, +) from tests.test_util.aiohttp import AiohttpClientMocker from tests.typing import ClientSessionGenerator @@ -729,7 +739,7 @@ def _discovered_info() -> MagicMock: info = MagicMock() info.name = TeslaBluetooth().get_name(VIN) info.address = ADDRESS - info.device = MagicMock() + info.device = generate_ble_device(ADDRESS, info.name) return info @@ -1002,12 +1012,23 @@ async def test_subentry_handshake_fails_after_pairing(hass: HomeAssistant) -> No vehicle.pair.assert_awaited_once() -@pytest.mark.usefixtures("enable_bluetooth") -async def test_subentry_scan_connect_fails(hass: HomeAssistant) -> None: - """The scan step re-shows the form with an error when BLE connect fails.""" +def _connect_failure(*chain: BaseException) -> BluetoothTransportError: + """Return the connect error tesla_fleet_api raises, caused by the given chain.""" + error = BluetoothTransportError() + outer: BaseException = error + for cause in chain: + outer.__cause__ = cause + outer = cause + return error + + +async def _connect_fails_then_pairs( + hass: HomeAssistant, error: BaseException, expected: str +) -> None: + """Fail the first Bluetooth connect, check the error, then pair on retry.""" entry = await _setup_account_entry(hass) vehicle = _mock_vehicle() - vehicle.connect = AsyncMock(side_effect=BleakError("nope")) + vehicle.connect = AsyncMock(side_effect=[error, None]) with ( patch( @@ -1018,18 +1039,113 @@ async def test_subentry_scan_connect_fails(hass: HomeAssistant) -> None: "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", return_value=_mock_ble_parent(vehicle), ), + patch.object(hass.config_entries, "async_schedule_reload"), ): result = await _start_pairing_at_scan(hass, entry) result = await hass.config_entries.subentries.async_configure( result["flow_id"], {} ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "scan" + assert result["errors"] == {"base": expected} + # A failed pairing never creates a subentry. + assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + vehicle.disconnect.assert_awaited_once() - assert result["type"] is FlowResultType.FORM - assert result["step_id"] == "scan" - assert result["errors"] == {"base": "cannot_connect"} - # A failed pairing never creates a subentry. - assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) - vehicle.disconnect.assert_awaited_once() + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + assert len(subentries) == 1 + assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} + + +@pytest.mark.parametrize( + ("error", "rssi", "expected"), + [ + pytest.param( + _connect_failure( + BleakOutOfConnectionSlotsError("no slot"), BleakError("no slot") + ), + -60, + "no_connection_slot", + id="out_of_slots", + ), + pytest.param( + _connect_failure(BleakNotFoundError("timeout"), TimeoutError()), + -62, + "vehicle_busy", + id="timeout_strong_signal", + ), + pytest.param( + _connect_failure(BleakNotFoundError("timeout"), TimeoutError()), + -70, + "vehicle_busy", + id="timeout_at_strong_threshold", + ), + pytest.param( + _connect_failure(BleakNotFoundError("timeout"), TimeoutError()), + -71, + "weak_signal", + id="timeout_weak_signal", + ), + pytest.param( + _connect_failure( + BleakNotFoundError("missing"), BleakDeviceNotFoundError(ADDRESS) + ), + -60, + "device_not_found", + id="device_vanished", + ), + pytest.param( + _connect_failure(BleakConnectionError("failed")), + -60, + "cannot_connect", + id="other_connection_error", + ), + pytest.param(BleakError("nope"), -60, "cannot_connect", id="unwrapped_error"), + ], +) +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_scan_connect_fails( + hass: HomeAssistant, + error: BleakError | BluetoothTransportError, + rssi: int, + expected: str, +) -> None: + """The scan step explains why the Bluetooth connect failed, then pairs on retry.""" + inject_advertisement( + hass, + generate_ble_device(ADDRESS, TeslaBluetooth().get_name(VIN)), + generate_advertisement_data(rssi=rssi), + ) + await _connect_fails_then_pairs(hass, error, expected) + + +@pytest.mark.parametrize( + "error", + [ + pytest.param( + _connect_failure( + BleakOutOfConnectionSlotsError("no slot"), BleakError("no slot") + ), + id="out_of_slots", + ), + pytest.param( + _connect_failure(BleakNotFoundError("timeout"), TimeoutError()), + id="timeout", + ), + ], +) +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_scan_connect_fails_vehicle_gone( + hass: HomeAssistant, error: BluetoothTransportError +) -> None: + """A vehicle no longer advertising when the connect fails is reported not found.""" + await _connect_fails_then_pairs(hass, error, "device_not_found") @pytest.mark.parametrize( From 2ccf5458bba81667bfb54419287c05acd845aa31 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:22:18 +0200 Subject: [PATCH 110/356] Fix quadratic time in the statistics average characteristics (#184522) --- homeassistant/components/statistics/sensor.py | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/statistics/sensor.py b/homeassistant/components/statistics/sensor.py index b2dd0d2df2b0..f6489561c66a 100644 --- a/homeassistant/components/statistics/sensor.py +++ b/homeassistant/components/statistics/sensor.py @@ -4,6 +4,7 @@ from collections import deque from collections.abc import Callable, Mapping import contextlib from datetime import datetime, timedelta +from itertools import pairwise import logging import math import statistics @@ -120,8 +121,10 @@ def _stat_average_linear( return states[0] if len(states) >= 2: area: float = 0 - for i in range(1, len(states)): - area += 0.5 * (states[i] + states[i - 1]) * (ages[i] - ages[i - 1]) + for (previous_state, previous_age), (state, age) in pairwise( + zip(states, ages, strict=True) + ): + area += 0.5 * (state + previous_state) * (age - previous_age) age_range_seconds = ages[-1] - ages[0] return area / age_range_seconds return None @@ -134,8 +137,10 @@ def _stat_average_step( return states[0] if len(states) >= 2: area: float = 0 - for i in range(1, len(states)): - area += states[i - 1] * (ages[i] - ages[i - 1]) + for (previous_state, previous_age), (_, age) in pairwise( + zip(states, ages, strict=True) + ): + area += previous_state * (age - previous_age) age_range_seconds = ages[-1] - ages[0] return area / age_range_seconds return None @@ -373,9 +378,11 @@ def _stat_binary_average_step( return 100.0 * int(states[0] is True) if len(states) >= 2: on_seconds: float = 0 - for i in range(1, len(states)): - if states[i - 1] is True: - on_seconds += ages[i] - ages[i - 1] + for (previous_state, previous_age), (_, age) in pairwise( + zip(states, ages, strict=True) + ): + if previous_state is True: + on_seconds += age - previous_age age_range_seconds = ages[-1] - ages[0] return 100 / age_range_seconds * on_seconds return None From 486dff541160f42d616b06654c73001d4092b81f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 23:04:22 +0200 Subject: [PATCH 111/356] Report unknown for out of spec Matter air quality values (#184528) --- homeassistant/components/matter/sensor.py | 2 +- tests/components/matter/test_sensor.py | 35 ++++++++++++++++++++++- 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/matter/sensor.py b/homeassistant/components/matter/sensor.py index b51ba8d1d5cd..68c7057b20de 100644 --- a/homeassistant/components/matter/sensor.py +++ b/homeassistant/components/matter/sensor.py @@ -741,7 +741,7 @@ DISCOVERY_SCHEMAS = [ translation_key="air_quality", device_class=SensorDeviceClass.ENUM, options=[x for x in AIR_QUALITY_MAP.values() if x is not None], - device_to_ha=lambda x: AIR_QUALITY_MAP[x], + device_to_ha=AIR_QUALITY_MAP.get, ), entity_class=MatterSensor, required_attributes=(clusters.AirQuality.Attributes.AirQuality,), diff --git a/tests/components/matter/test_sensor.py b/tests/components/matter/test_sensor.py index 268b802d6441..7f01ac794c6f 100644 --- a/tests/components/matter/test_sensor.py +++ b/tests/components/matter/test_sensor.py @@ -8,7 +8,13 @@ from matter_server.client.models.node import MatterNode import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.const import STATE_UNAVAILABLE, EntityCategory, Platform +from homeassistant.components.matter.sensor import AIR_QUALITY_MAP +from homeassistant.const import ( + STATE_UNAVAILABLE, + STATE_UNKNOWN, + EntityCategory, + Platform, +) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -312,6 +318,33 @@ async def test_eve_weather_sensor_custom_cluster( assert state.state == "800.0" +def test_air_quality_map_complete() -> None: + """Test every Matter air quality value is mapped.""" + assert set(AIR_QUALITY_MAP) == set(clusters.AirQuality.Enums.AirQualityEnum) + + +@pytest.mark.parametrize("node_fixture", ["air_quality_sensor"]) +async def test_air_quality_out_of_range( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, +) -> None: + """Test an out of spec AirQuality value reports unknown.""" + set_node_attribute(matter_node, 1, 91, 0, 1) + await trigger_subscription_callback(hass, matter_client) + + state = hass.states.get("sensor.lightfi_aq1_air_quality_sensor_air_quality") + assert state + assert state.state == "good" + + set_node_attribute(matter_node, 1, 91, 0, 255) + await trigger_subscription_callback(hass, matter_client) + + state = hass.states.get("sensor.lightfi_aq1_air_quality_sensor_air_quality") + assert state + assert state.state == STATE_UNKNOWN + + @pytest.mark.parametrize("node_fixture", ["air_quality_sensor"]) async def test_air_quality_sensor( hass: HomeAssistant, From 685129861d17234a8af9b7597ce3b68d5ac53785 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 23:16:09 +0200 Subject: [PATCH 112/356] Fall back to all button values for SmartThings buttons that don't report them (#184530) --- homeassistant/components/smartthings/event.py | 38 +++++- .../smartthings/snapshots/test_event.ambr | 116 +++++++++++++++++- tests/components/smartthings/test_event.py | 39 +++++- 3 files changed, 186 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/smartthings/event.py b/homeassistant/components/smartthings/event.py index a00accdcf751..9554fad98e19 100644 --- a/homeassistant/components/smartthings/event.py +++ b/homeassistant/components/smartthings/event.py @@ -11,6 +11,37 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from . import FullDevice, SmartThingsConfigEntry from .entity import SmartThingsEntity +# All values of the button capability, for buttons that don't report which they +# support, like cloud-to-cloud buttons +BUTTON_EVENT_TYPES = [ + "pushed", + "held", + "double", + "pushed_2x", + "pushed_3x", + "pushed_4x", + "pushed_5x", + "pushed_6x", + "down", + "down_2x", + "down_3x", + "down_4x", + "down_5x", + "down_6x", + "down_hold", + "up", + "up_2x", + "up_3x", + "up_4x", + "up_5x", + "up_6x", + "up_hold", + "swipe_up", + "swipe_down", + "swipe_left", + "swipe_right", +] + async def async_setup_entry( hass: HomeAssistant, @@ -52,8 +83,11 @@ class SmartThingsButtonEvent(SmartThingsEntity, EventEntity): @override def event_types(self) -> list[str]: """Return the event types.""" - return self.get_attribute_value( - Capability.BUTTON, Attribute.SUPPORTED_BUTTON_VALUES + return ( + self.get_attribute_value( + Capability.BUTTON, Attribute.SUPPORTED_BUTTON_VALUES + ) + or BUTTON_EVENT_TYPES ) @override diff --git a/tests/components/smartthings/snapshots/test_event.ambr b/tests/components/smartthings/snapshots/test_event.ambr index 594383184155..bac305925978 100644 --- a/tests/components/smartthings/snapshots/test_event.ambr +++ b/tests/components/smartthings/snapshots/test_event.ambr @@ -6,7 +6,34 @@ ]), 'area_id': None, 'capabilities': dict({ - : None, + : list([ + 'pushed', + 'held', + 'double', + 'pushed_2x', + 'pushed_3x', + 'pushed_4x', + 'pushed_5x', + 'pushed_6x', + 'down', + 'down_2x', + 'down_3x', + 'down_4x', + 'down_5x', + 'down_6x', + 'down_hold', + 'up', + 'up_2x', + 'up_3x', + 'up_4x', + 'up_5x', + 'up_6x', + 'up_hold', + 'swipe_up', + 'swipe_down', + 'swipe_left', + 'swipe_right', + ]), }), 'config_entry_id': , 'config_subentry_id': , @@ -43,7 +70,34 @@ 'attributes': ReadOnlyDict({ : 'button', : None, - : None, + : list([ + 'pushed', + 'held', + 'double', + 'pushed_2x', + 'pushed_3x', + 'pushed_4x', + 'pushed_5x', + 'pushed_6x', + 'down', + 'down_2x', + 'down_3x', + 'down_4x', + 'down_5x', + 'down_6x', + 'down_hold', + 'up', + 'up_2x', + 'up_3x', + 'up_4x', + 'up_5x', + 'up_6x', + 'up_hold', + 'swipe_up', + 'swipe_down', + 'swipe_left', + 'swipe_right', + ]), : 'Dimmer entré 1 1 button1', }), 'context': , @@ -61,7 +115,34 @@ ]), 'area_id': None, 'capabilities': dict({ - : None, + : list([ + 'pushed', + 'held', + 'double', + 'pushed_2x', + 'pushed_3x', + 'pushed_4x', + 'pushed_5x', + 'pushed_6x', + 'down', + 'down_2x', + 'down_3x', + 'down_4x', + 'down_5x', + 'down_6x', + 'down_hold', + 'up', + 'up_2x', + 'up_3x', + 'up_4x', + 'up_5x', + 'up_6x', + 'up_hold', + 'swipe_up', + 'swipe_down', + 'swipe_left', + 'swipe_right', + ]), }), 'config_entry_id': , 'config_subentry_id': , @@ -98,7 +179,34 @@ 'attributes': ReadOnlyDict({ : 'button', : None, - : None, + : list([ + 'pushed', + 'held', + 'double', + 'pushed_2x', + 'pushed_3x', + 'pushed_4x', + 'pushed_5x', + 'pushed_6x', + 'down', + 'down_2x', + 'down_3x', + 'down_4x', + 'down_5x', + 'down_6x', + 'down_hold', + 'up', + 'up_2x', + 'up_3x', + 'up_4x', + 'up_5x', + 'up_6x', + 'up_hold', + 'swipe_up', + 'swipe_down', + 'swipe_left', + 'swipe_right', + ]), : 'Dimmer entré 1 1 button2', }), 'context': , diff --git a/tests/components/smartthings/test_event.py b/tests/components/smartthings/test_event.py index 96b66036906c..6004fe5c1700 100644 --- a/tests/components/smartthings/test_event.py +++ b/tests/components/smartthings/test_event.py @@ -8,7 +8,7 @@ from pysmartthings.models import HealthStatus import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components.event import ATTR_EVENT_TYPES +from homeassistant.components.event import ATTR_EVENT_TYPE, ATTR_EVENT_TYPES from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -105,6 +105,43 @@ async def test_supported_button_values_update( ] == ["pushed", "held", "down_hold", "pushed_2x"] +@pytest.mark.parametrize("device_fixture", ["heatit_zpushwall"]) +async def test_no_supported_button_values( + hass: HomeAssistant, + devices: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a button without supported values, like cloud-to-cloud buttons.""" + await setup_integration(hass, mock_config_entry) + + freezer.move_to("2023-10-21") + + await trigger_update( + hass, + devices, + "5e5b97f3-3094-44e6-abc0-f61283412d6a", + Capability.BUTTON, + Attribute.SUPPORTED_BUTTON_VALUES, + None, + component="button1", + ) + await trigger_update( + hass, + devices, + "5e5b97f3-3094-44e6-abc0-f61283412d6a", + Capability.BUTTON, + Attribute.BUTTON, + "pushed", + component="button1", + ) + + state = hass.states.get("event.livingroom_smart_switch_button1") + assert state.state == "2023-10-21T00:00:00.000+00:00" + assert state.attributes[ATTR_EVENT_TYPE] == "pushed" + assert "pushed_6x" in state.attributes[ATTR_EVENT_TYPES] + + @pytest.mark.parametrize("device_fixture", ["heatit_zpushwall"]) async def test_availability( hass: HomeAssistant, From bc84d1277ad6696555fb0d8102885e4e5e762242 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:37:42 +0200 Subject: [PATCH 113/356] Bump wled to 1.1.0 (#184532) --- homeassistant/components/wled/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/wled/manifest.json b/homeassistant/components/wled/manifest.json index 47b87ddfc73b..a59f54c62161 100644 --- a/homeassistant/components/wled/manifest.json +++ b/homeassistant/components/wled/manifest.json @@ -7,6 +7,6 @@ "integration_type": "device", "iot_class": "local_push", "quality_scale": "platinum", - "requirements": ["wled==1.0.0"], + "requirements": ["wled==1.1.0"], "zeroconf": ["_wled._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 6133c2fc042b..480ac216a523 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3457,7 +3457,7 @@ wiim==0.1.7 wirelesstagpy==0.8.1 # homeassistant.components.wled -wled==1.0.0 +wled==1.1.0 # homeassistant.components.wolflink wolf-comm==0.0.52 From 4438223e83b89526cd2d4de5c500e1ab86351285 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:41:33 +0200 Subject: [PATCH 114/356] Mux H.265 streams and recordings as hvc1 again (#184537) --- homeassistant/components/stream/recorder.py | 2 ++ homeassistant/components/stream/worker.py | 2 +- tests/components/stream/test_recorder.py | 31 +++++++++++++++++++++ tests/components/stream/test_worker.py | 2 +- 4 files changed, 35 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/stream/recorder.py b/homeassistant/components/stream/recorder.py index e47c031d9839..6d6ece44e58e 100644 --- a/homeassistant/components/stream/recorder.py +++ b/homeassistant/components/stream/recorder.py @@ -124,6 +124,8 @@ class RecorderOutput(StreamOutput): # Add output streams if necessary if not output_v: output_v = output.add_stream_from_template(source_v) + if source_v.name == "hevc": + output_v.codec_context.codec_tag = "hvc1" if source_a and not output_a: output_a = output.add_stream_from_template(source_a) diff --git a/homeassistant/components/stream/worker.py b/homeassistant/components/stream/worker.py index 6b555fa2a958..70bf93aef187 100644 --- a/homeassistant/components/stream/worker.py +++ b/homeassistant/components/stream/worker.py @@ -281,7 +281,7 @@ class StreamMuxer: input_vstream=self._input_video_stream, input_astream=self._input_audio_stream, ) - if self._output_video_stream.name == "hevc": + if self._input_video_stream.name == "hevc": self._output_video_stream.codec_context.codec_tag = "hvc1" def mux_packet(self, packet: av.Packet) -> None: diff --git a/tests/components/stream/test_recorder.py b/tests/components/stream/test_recorder.py index dc3373de2e5c..4f515225e171 100644 --- a/tests/components/stream/test_recorder.py +++ b/tests/components/stream/test_recorder.py @@ -29,6 +29,7 @@ from .common import ( assert_mp4_has_transform_matrix, dynamic_stream_settings, generate_h264_video, + generate_h265_video, remux_with_audio, ) @@ -81,6 +82,36 @@ async def test_record_stream(hass: HomeAssistant, filename, h264_video) -> None: assert os.path.exists(filename) +async def test_record_stream_h265_is_hvc1(hass: HomeAssistant, filename: str) -> None: + """Test a h265 recording gets muxed as hvc1, so Apple devices can play it.""" + worker_finished = asyncio.Event() + + class MockStream(Stream): + """Mock Stream so we can patch remove_provider.""" + + async def remove_provider(self, provider): + """Add a finished event to Stream.remove_provider.""" + await Stream.remove_provider(self, provider) + worker_finished.set() + + source = await hass.async_add_executor_job(generate_h265_video) + with patch("homeassistant.components.stream.Stream", wraps=MockStream): + stream = create_stream(hass, source, {}, dynamic_stream_settings()) + + with patch.object(hass.config, "is_allowed_path", return_value=True): + make_recording = hass.async_create_task(stream.async_record(filename)) + await worker_finished.wait() + + # Fire the IdleTimer + future = dt_util.utcnow() + timedelta(seconds=30) + async_fire_time_changed(hass, future) + + await make_recording + + with av.open(filename) as recording: + assert recording.streams.video[0].codec_tag == "hvc1" + + async def test_record_lookback(hass: HomeAssistant, filename, h264_video) -> None: """Exercise record with lookback.""" diff --git a/tests/components/stream/test_worker.py b/tests/components/stream/test_worker.py index e91102278e44..f2ddb961d366 100644 --- a/tests/components/stream/test_worker.py +++ b/tests/components/stream/test_worker.py @@ -1051,7 +1051,7 @@ async def test_h265_video_is_hvc1(hass: HomeAssistant, worker_finished_stream) - segment = complete_segments[0] part = segment.parts[0] av_part = av.open(io.BytesIO(segment.init + part.data)) - assert av_part.streams.video[0].codec_tag == "hev1" + assert av_part.streams.video[0].codec_tag == "hvc1" av_part.close() await stream.stop() From 30840c614b70cf4c7a2bac48b47238c296b9b8d6 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:44:23 +0200 Subject: [PATCH 115/356] Retry Sense setup when the monitor is not available yet (#184539) --- homeassistant/components/sense/__init__.py | 6 ++++++ tests/components/sense/test_init.py | 2 ++ 2 files changed, 8 insertions(+) diff --git a/homeassistant/components/sense/__init__.py b/homeassistant/components/sense/__init__.py index 95f9165f8cfd..42075441da92 100644 --- a/homeassistant/components/sense/__init__.py +++ b/homeassistant/components/sense/__init__.py @@ -95,6 +95,12 @@ async def async_setup_entry(hass: HomeAssistant, entry: SenseConfigEntry) -> boo raise ConfigEntryNotReady( str(err) or "API error retrieving realtime data" ) from err + except SenseAuthenticationException as err: + # We just authenticated, sense_energy also raises this for a 404 while + # the monitor is reconnecting + raise ConfigEntryNotReady( + str(err) or "Monitor not available for realtime data" + ) from err trends_coordinator = SenseTrendCoordinator(hass, entry, gateway) realtime_coordinator = SenseRealtimeCoordinator(hass, entry, gateway) diff --git a/tests/components/sense/test_init.py b/tests/components/sense/test_init.py index d50b23a2e363..8ee941d1a4c3 100644 --- a/tests/components/sense/test_init.py +++ b/tests/components/sense/test_init.py @@ -133,6 +133,8 @@ async def test_setup_get_monitor_data_retry_exceptions( socket.gaierror(), SenseWebsocketException("ws error"), SenseAPIException(), + # Returned for a 404 while the monitor reconnects, after authenticating + SenseAuthenticationException("API Return Code: 404"), ], ) async def test_setup_get_realtime_retry_exceptions( From 9eb03e659def99c43221f12dcca272f10a3147d5 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:43:25 +0200 Subject: [PATCH 116/356] Fix the API key instructions link in the OpenAI Conversation config flow (#184541) --- homeassistant/components/openai_conversation/config_flow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/openai_conversation/config_flow.py b/homeassistant/components/openai_conversation/config_flow.py index a851c4e2522d..b4c76ac28237 100644 --- a/homeassistant/components/openai_conversation/config_flow.py +++ b/homeassistant/components/openai_conversation/config_flow.py @@ -206,7 +206,7 @@ class OpenAIConfigFlow(ConfigFlow, domain=DOMAIN): ), errors=errors, description_placeholders={ - "instructions_url": "https://www.home-assistant.io/integrations/openai_conversation/#generate-an-api-key", + "instructions_url": "https://www.home-assistant.io/integrations/openai_conversation/#prerequisites", }, ) From 788f0e83f377b7fa68db3f6e9a2140530cfa8322 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:41:29 +0200 Subject: [PATCH 117/356] Handle Liebherr timeouts during setup and the device scan (#184542) --- homeassistant/components/liebherr/__init__.py | 9 +++++++-- tests/components/liebherr/test_init.py | 11 ++++++++--- 2 files changed, 15 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/liebherr/__init__.py b/homeassistant/components/liebherr/__init__.py index 2fb8bdf096bb..6729207188f4 100644 --- a/homeassistant/components/liebherr/__init__.py +++ b/homeassistant/components/liebherr/__init__.py @@ -8,6 +8,7 @@ from pyliebherrhomeapi import LiebherrClient from pyliebherrhomeapi.exceptions import ( LiebherrAuthenticationError, LiebherrConnectionError, + LiebherrTimeoutError, ) from homeassistant.const import CONF_API_KEY, Platform @@ -49,7 +50,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: LiebherrConfigEntry) -> translation_domain=DOMAIN, translation_key="invalid_api_key", ) from err - except LiebherrConnectionError as err: + except (LiebherrConnectionError, LiebherrTimeoutError) as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="cannot_connect", @@ -87,7 +88,11 @@ async def async_setup_entry(hass: HomeAssistant, entry: LiebherrConfigEntry) -> """Scan for new devices added to the account.""" try: devices = await client.get_devices() - except LiebherrAuthenticationError, LiebherrConnectionError: + except ( + LiebherrAuthenticationError, + LiebherrConnectionError, + LiebherrTimeoutError, + ): _LOGGER.debug("Failed to scan for new devices") return except Exception: diff --git a/tests/components/liebherr/test_init.py b/tests/components/liebherr/test_init.py index a78ae05e2478..630dec4ac6ea 100644 --- a/tests/components/liebherr/test_init.py +++ b/tests/components/liebherr/test_init.py @@ -45,8 +45,9 @@ from tests.common import MockConfigEntry, async_fire_time_changed [ (LiebherrAuthenticationError("Invalid API key"), ConfigEntryState.SETUP_ERROR), (LiebherrConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY), + (LiebherrTimeoutError("Request timed out"), ConfigEntryState.SETUP_RETRY), ], - ids=["auth_failed", "connection_error"], + ids=["auth_failed", "connection_error", "timeout"], ) async def test_setup_entry_errors( hass: HomeAssistant, @@ -72,8 +73,9 @@ async def test_setup_entry_errors( [ (LiebherrAuthenticationError("Invalid API key"), ConfigEntryState.SETUP_ERROR), (LiebherrConnectionError("Connection failed"), ConfigEntryState.SETUP_RETRY), + (LiebherrTimeoutError("Request timed out"), ConfigEntryState.SETUP_RETRY), ], - ids=["auth_failed", "connection_error"], + ids=["auth_failed", "connection_error", "timeout"], ) async def test_coordinator_setup_errors( hass: HomeAssistant, @@ -305,11 +307,13 @@ async def test_dynamic_device_discovery_no_new_devices( [ LiebherrConnectionError("Connection failed"), LiebherrAuthenticationError("Auth failed"), + LiebherrTimeoutError("Request timed out"), ], - ids=["connection_error", "auth_error"], + ids=["connection_error", "auth_error", "timeout"], ) async def test_dynamic_device_discovery_api_error( hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, mock_liebherr_client: MagicMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, @@ -327,6 +331,7 @@ async def test_dynamic_device_discovery_api_error( # No crash, no new entities assert len(hass.states.async_all()) == initial_states assert mock_config_entry.state is ConfigEntryState.LOADED + assert "Unexpected error scanning for new devices" not in caplog.text @pytest.mark.usefixtures("init_integration") From fb1a967619495e3655bf65b7e8d3bb71b616358a Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:42:32 +0200 Subject: [PATCH 118/356] Retry EcoNet setup when logging in fails with a connection error (#184544) --- homeassistant/components/econet/__init__.py | 2 +- tests/components/econet/test_init.py | 38 +++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 tests/components/econet/test_init.py diff --git a/homeassistant/components/econet/__init__.py b/homeassistant/components/econet/__init__.py index e2f15ee75644..442e8fe88153 100644 --- a/homeassistant/components/econet/__init__.py +++ b/homeassistant/components/econet/__init__.py @@ -53,7 +53,7 @@ async def async_setup_entry( except InvalidCredentialsError: _LOGGER.error("Invalid credentials provided") return False - except PyeconetError as err: + except (ClientError, PyeconetError) as err: _LOGGER.error("Config entry failed: %s", err) raise ConfigEntryNotReady from err diff --git a/tests/components/econet/test_init.py b/tests/components/econet/test_init.py new file mode 100644 index 000000000000..0d7fab240cca --- /dev/null +++ b/tests/components/econet/test_init.py @@ -0,0 +1,38 @@ +"""Tests for the EcoNet integration setup.""" + +from unittest.mock import patch + +from aiohttp import ClientError +from pyeconet.errors import PyeconetError +import pytest + +from homeassistant.components.econet.const import DOMAIN +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import CONF_EMAIL, CONF_PASSWORD +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry + + +@pytest.mark.parametrize( + "exception", + [ + pytest.param(PyeconetError(), id="library_error"), + pytest.param(ClientError("certificate has expired"), id="client_error"), + ], +) +async def test_login_error_retries_setup( + hass: HomeAssistant, exception: Exception +) -> None: + """Test setup is retried when logging in fails.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_EMAIL: "admin@localhost.com", CONF_PASSWORD: "password0"}, + ) + entry.add_to_hass(hass) + + with patch("pyeconet.EcoNetApiInterface.login", side_effect=exception): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.SETUP_RETRY From dc4cca0f073aa8ca5182cfd2db5c3c921e6c8c16 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:40:21 +0200 Subject: [PATCH 119/356] Don't let a Hue button without a device abort the event platform (#184546) --- homeassistant/components/hue/event.py | 17 +++++++------ tests/components/hue/test_event.py | 36 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/hue/event.py b/homeassistant/components/hue/event.py index 7dc5a246dbd4..1fe678513039 100644 --- a/homeassistant/components/hue/event.py +++ b/homeassistant/components/hue/event.py @@ -5,7 +5,7 @@ from typing import Any, override from aiohue.v2 import HueBridgeV2 from aiohue.v2.controllers.events import EventType from aiohue.v2.models.bell_button import BellButton -from aiohue.v2.models.button import Button +from aiohue.v2.models.button import Button, ButtonEvent from aiohue.v2.models.relative_rotary import RelativeRotary, RelativeRotaryDirection from homeassistant.components.event import ( @@ -86,14 +86,15 @@ class HueButtonEventEntity(HueBaseEntity, EventEntity): def __init__(self, *args: Any, **kwargs: Any) -> None: """Initialize the entity.""" super().__init__(*args, **kwargs) - # fill the event types based on the features the switch supports - hue_dev_id = self.controller.get_device(self.resource.id).id - model_id = self.bridge.api.devices[hue_dev_id].product_data.product_name - self._attr_event_types: list[str] = [ - event_type.value - for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get( - model_id, DEFAULT_BUTTON_EVENT_TYPES + # fill the event types based on the features the switch supports, + # the bridge can return button resources no device lists + event_types: tuple[ButtonEvent, ...] = DEFAULT_BUTTON_EVENT_TYPES + if self.device is not None: + event_types = DEVICE_SPECIFIC_EVENT_TYPES.get( + self.device.product_data.product_name, event_types ) + self._attr_event_types: list[str] = [ + event_type.value for event_type in event_types ] self._attr_translation_placeholders = { "button_id": self.resource.metadata.control_id diff --git a/tests/components/hue/test_event.py b/tests/components/hue/test_event.py index 73ae1e5d1d52..cf315e32ad6c 100644 --- a/tests/components/hue/test_event.py +++ b/tests/components/hue/test_event.py @@ -5,6 +5,7 @@ from unittest.mock import Mock from homeassistant.components.event import ATTR_EVENT_TYPE, ATTR_EVENT_TYPES from homeassistant.const import Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er from homeassistant.util.json import JsonArrayType from .conftest import setup_platform @@ -112,3 +113,38 @@ async def test_sensor_add_update(hass: HomeAssistant, mock_bridge_v2: Mock) -> N assert state.attributes["action"] == "repeat" assert state.attributes["steps"] == 60 assert state.attributes["duration"] == 400 + + +async def test_button_without_device( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_bridge_v2: Mock, + v2_resources_test_data: JsonArrayType, +) -> None: + """Test a button resource no device lists does not abort the platform.""" + orphan_button = { + "button": {"button_report": {"event": "short_release"}}, + "id": "8c47a1b2-6b0e-4f6e-9d2a-3f6e2b1c0d9e", + "metadata": {"control_id": 2}, + "owner": {"rid": "3ff06175-29e8-44a8-8fe7-af591b0025da", "rtype": "device"}, + "type": "button", + } + await mock_bridge_v2.api.load_test_data([orphan_button, *v2_resources_test_data]) + await setup_platform(hass, mock_bridge_v2, Platform.EVENT) + + # The 8 entities from the test data and the orphan button + assert len(hass.states.async_all()) == 9 + + entity_id = entity_registry.async_get_entity_id( + Platform.EVENT, "hue", "8c47a1b2-6b0e-4f6e-9d2a-3f6e2b1c0d9e" + ) + assert entity_id + state = hass.states.get(entity_id) + assert state + assert state.attributes[ATTR_EVENT_TYPES] == [ + "initial_press", + "repeat", + "short_release", + "long_press", + "long_release", + ] From 0a01d112cf770a3f5245229be500d16a83b55064 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:53:14 +0200 Subject: [PATCH 120/356] Start polling HomeKit Controller BLE accessories after a reload (#184547) --- .../homekit_controller/connection.py | 11 ++--- .../homekit_controller/test_init.py | 41 ++++++++++++++++++- 2 files changed, 43 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/homekit_controller/connection.py b/homeassistant/components/homekit_controller/connection.py index 322ebc05b3b1..2006170b9f12 100644 --- a/homeassistant/components/homekit_controller/connection.py +++ b/homeassistant/components/homekit_controller/connection.py @@ -28,13 +28,13 @@ from aiohomekit.model.services import Service, ServicesTypes from homeassistant.components.thread import async_get_preferred_dataset from homeassistant.config_entries import ConfigEntry -from homeassistant.const import EVENT_HOMEASSISTANT_STARTED -from homeassistant.core import CALLBACK_TYPE, CoreState, Event, HomeAssistant, callback +from homeassistant.core import CALLBACK_TYPE, CoreState, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.debounce import Debouncer from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.event import async_call_later, async_track_time_interval +from homeassistant.helpers.start import async_at_started from .config_flow import normalize_hkid from .const import ( @@ -258,7 +258,7 @@ class HKDevice: for callback_ in self._availability_callbacks: callback_() - async def _async_populate_ble_accessory_state(self, event: Event) -> None: + async def _async_populate_ble_accessory_state(self, hass: HomeAssistant) -> None: """Populate the BLE accessory state without blocking startup. If the accessory was asleep at startup we need to retry @@ -309,10 +309,7 @@ class HKDevice: # previously we force an update after startup # is complete. entry.async_on_unload( - self.hass.bus.async_listen( - EVENT_HOMEASSISTANT_STARTED, - self._async_populate_ble_accessory_state, - ) + async_at_started(self.hass, self._async_populate_ble_accessory_state) ) else: await self.pairing.async_populate_accessories_state( diff --git a/tests/components/homekit_controller/test_init.py b/tests/components/homekit_controller/test_init.py index 6f8bf6e0932c..cf2caf02e1f2 100644 --- a/tests/components/homekit_controller/test_init.py +++ b/tests/components/homekit_controller/test_init.py @@ -9,11 +9,15 @@ from aiohomekit import AccessoryNotFoundError from aiohomekit.model import Accessory, Transport from aiohomekit.model.characteristics import CharacteristicsTypes from aiohomekit.model.services import Service, ServicesTypes -from aiohomekit.testing import FakePairing +from aiohomekit.testing import FakeController, FakePairing import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components.homekit_controller.const import DOMAIN, ENTITY_MAP +from homeassistant.components.homekit_controller.const import ( + DEBOUNCE_COOLDOWN, + DOMAIN, + ENTITY_MAP, +) from homeassistant.config_entries import ConfigEntryState from homeassistant.const import EVENT_HOMEASSISTANT_STOP, STATE_OFF, STATE_UNAVAILABLE from homeassistant.core import HomeAssistant @@ -318,3 +322,36 @@ async def test_snapshots( devices.append({"device": device, "entities": entities}) assert snapshot == devices + + +@pytest.mark.usefixtures("fake_ble_discovery", "fake_ble_pairing") +async def test_ble_device_polls_after_reload( + hass: HomeAssistant, controller: FakeController +) -> None: + """Test a BLE device is polled again after its entry is reloaded.""" + accessory = Accessory.create_with_info( + 1, "TestDevice", "example.com", "Test", "0001", "0.1" + ) + create_alive_service(accessory) + await async_setup_component(hass, DOMAIN, {}) + config_entry, pairing = await setup_test_accessories_with_controller( + hass, [accessory], controller + ) + + assert await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.LOADED + + with patch.object( + pairing, "get_characteristics", wraps=pairing.get_characteristics + ) as mock_get_characteristics: + # The poll requests a debounced update, which runs after its cooldown + async_fire_time_changed(hass, utcnow() + pairing.poll_interval) + await hass.async_block_till_done() + async_fire_time_changed( + hass, + utcnow() + pairing.poll_interval + timedelta(seconds=DEBOUNCE_COOLDOWN), + ) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_get_characteristics.assert_called() From 4dbb3b4f74844e1cc9a79d40cc91db170e8b39ad Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 23:25:32 +0200 Subject: [PATCH 121/356] Load the stored camera orientation as an Orientation (#184551) --- homeassistant/components/camera/prefs.py | 5 ++++- tests/components/camera/test_prefs.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/camera/prefs.py b/homeassistant/components/camera/prefs.py index 8fdafe7886dc..232c196ad0db 100644 --- a/homeassistant/components/camera/prefs.py +++ b/homeassistant/components/camera/prefs.py @@ -100,7 +100,10 @@ class CameraPreferences: bool, self._preload_prefs.get(entity_id, {}).get(PREF_PRELOAD_STREAM, False), ), - orientation=er_prefs.get(PREF_ORIENTATION, Orientation.NO_TRANSFORM), + # Stored in the entity registry, where it is loaded as a plain int + orientation=Orientation( + er_prefs.get(PREF_ORIENTATION, Orientation.NO_TRANSFORM) + ), ) self._dynamic_stream_settings_by_entity_id[entity_id] = settings return settings diff --git a/tests/components/camera/test_prefs.py b/tests/components/camera/test_prefs.py index e4b3e67f15d1..ad87e7cc2262 100644 --- a/tests/components/camera/test_prefs.py +++ b/tests/components/camera/test_prefs.py @@ -11,6 +11,7 @@ from homeassistant.components.camera.prefs import ( from homeassistant.components.stream import Orientation from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er async def test_get_dynamic_camera_stream_settings_missing_prefs( @@ -74,3 +75,26 @@ async def test_get_dynamic_camera_stream_settings_with_preload_stream( settings = await get_dynamic_camera_stream_settings(hass, "camera.test") assert settings.orientation == Orientation.NO_TRANSFORM assert settings.preload_stream is True + + +@pytest.mark.parametrize( + "orientation", [Orientation.NO_TRANSFORM, Orientation.ROTATE_LEFT] +) +async def test_get_dynamic_camera_stream_settings_stored_orientation( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + orientation: Orientation, +) -> None: + """Test a stored orientation is loaded as an Orientation.""" + prefs = CameraPreferences(hass) + await prefs.async_load() + hass.data[DATA_CAMERA_PREFS] = prefs + + entry = entity_registry.async_get_or_create("camera", "test", "unique_id") + # Entity registry options are loaded from JSON as a plain int + entity_registry.async_update_entity_options( + entry.entity_id, "camera", {"orientation": int(orientation)} + ) + + settings = await get_dynamic_camera_stream_settings(hass, entry.entity_id) + assert settings.orientation is orientation From 7184ce36a62592872018f202cb95ed82544e43ff Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 23:41:06 +0200 Subject: [PATCH 122/356] Accept Matrix room IDs without a server name (#184556) --- homeassistant/components/matrix/const.py | 3 +- tests/components/matrix/test_rooms.py | 49 +++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/matrix/const.py b/homeassistant/components/matrix/const.py index d18536e94822..4cc13513962e 100644 --- a/homeassistant/components/matrix/const.py +++ b/homeassistant/components/matrix/const.py @@ -16,4 +16,5 @@ ATTR_REACTION = "reaction" # reaction ATTR_ROOM = "room" # room id ATTR_MESSAGE_ID = "message_id" # message id -CONF_ROOMS_REGEX = "^[!|#][^:]*:.*" +# Room IDs from room version 12 on no longer include the server name +CONF_ROOMS_REGEX = "^(![^:]+(:.+)?|#[^:]+:.+)$" diff --git a/tests/components/matrix/test_rooms.py b/tests/components/matrix/test_rooms.py index b345959a0548..31a55b9dfd56 100644 --- a/tests/components/matrix/test_rooms.py +++ b/tests/components/matrix/test_rooms.py @@ -1,8 +1,9 @@ """Test MatrixBot._join.""" +import probatio import pytest -from homeassistant.components.matrix import MatrixBot +from homeassistant.components.matrix import CONFIG_SCHEMA, MatrixBot from homeassistant.components.matrix.const import DOMAIN from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN from homeassistant.const import EVENT_HOMEASSISTANT_START @@ -46,3 +47,49 @@ async def test_resolve_aliases(hass: HomeAssistant, matrix_bot: MatrixBot) -> No await hass.async_start() assert matrix_bot._listening_rooms == TEST_JOINABLE_ROOMS + + +@pytest.mark.parametrize( + "room", + [ + pytest.param("!roomid:example.com", id="room_id_with_server"), + pytest.param("!roomid", id="room_id_v12"), + pytest.param("#alias:example.com", id="room_alias"), + ], +) +def test_config_room_valid(room: str) -> None: + """Test room IDs and aliases are accepted in the configuration.""" + config = { + DOMAIN: { + "homeserver": "https://matrix.example.com", + "username": "@bot:example.com", + "password": "password", + "rooms": [room], + } + } + + assert CONFIG_SCHEMA(config)[DOMAIN]["rooms"] == [room] + + +@pytest.mark.parametrize( + "room", + [ + pytest.param("#alias", id="alias_without_server"), + pytest.param("!", id="empty_room_id"), + pytest.param("roomid:example.com", id="no_sigil"), + pytest.param("|roomid:example.com", id="pipe_sigil"), + ], +) +def test_config_room_invalid(room: str) -> None: + """Test invalid room IDs and aliases are rejected in the configuration.""" + config = { + DOMAIN: { + "homeserver": "https://matrix.example.com", + "username": "@bot:example.com", + "password": "password", + "rooms": [room], + } + } + + with pytest.raises(probatio.Invalid): + CONFIG_SCHEMA(config) From bf9af76edd69313f3930ec5b83695fc46bc15c98 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Wed, 7 Oct 2026 01:55:32 +1000 Subject: [PATCH 123/356] Hide Teslemetry vehicles without Bluetooth command support (#184223) --- .../components/teslemetry/config_flow.py | 5 ++ .../components/teslemetry/test_config_flow.py | 88 ++++++++++++++++++- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 5d8373b5c87a..73b648adbc13 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -255,10 +255,15 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): for subentry in entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) if CONF_VIN in subentry.data } + vehicle_metadata = entry.runtime_data.metadata_coordinator.data["vehicles"] choices = { vehicle.vin: vehicle.device["name"] or vehicle.vin for vehicle in entry.runtime_data.vehicles if vehicle.vin not in already_added + # Vehicles without the command protocol (pre-2021 Model S/X) report + # False and cannot be controlled over Bluetooth; None or a VIN not + # yet in the metadata means unknown. + and vehicle_metadata.get(vehicle.vin, {}).get("proxy") is not False } if not choices: if entry.runtime_data.vehicles: diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 0f78dddcfa77..3664954ab590 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -22,6 +22,7 @@ from bleak_retry_connector import ( ) from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import rsa +from freezegun.api import FrozenDateTimeFactory import probatio import pytest from tesla_fleet_api.const import AuthorizedClientState @@ -61,6 +62,7 @@ from homeassistant.components.teslemetry.const import ( TOKEN_URL, VEHICLE_KEY_FILE, ) +from homeassistant.components.teslemetry.coordinator import METADATA_INTERVAL from homeassistant.config_entries import ( SOURCE_USER, ConfigEntryState, @@ -81,7 +83,7 @@ from homeassistant.setup import async_setup_component from . import mock_config_entry, setup_platform from .const import CONFIG_V1, METADATA, PRODUCTS, UNIQUE_ID -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_fire_time_changed from tests.components.bluetooth import ( generate_advertisement_data, generate_ble_device, @@ -1761,6 +1763,90 @@ async def test_subentry_add_flow_account_has_no_vehicles(hass: HomeAssistant) -> assert result["reason"] == "no_vehicles" +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_add_flow_hides_unsupported_vehicles( + hass: HomeAssistant, mock_products: AsyncMock, mock_metadata: AsyncMock +) -> None: + """Only vehicles that report no command protocol support are left out.""" + products = deepcopy(PRODUCTS) + metadata = deepcopy(METADATA) + vehicle_product = products["response"][0] + vehicle_metadata = metadata["vehicles"][VIN] + products["response"] = products["response"][1:] + metadata["vehicles"] = {} + for vin, name, proxy in ( + ("LRW3F7EK4NC700001", "Supported", True), + ("LRW3F7EK4NC700002", "Unsupported", False), + ("LRW3F7EK4NC700003", "Unknown", None), + ): + products["response"].append( + {**vehicle_product, "vin": vin, "display_name": name} + ) + metadata["vehicles"][vin] = {**vehicle_metadata, "proxy": proxy} + mock_products.return_value = products + mock_metadata.return_value = metadata + entry = await _setup_account_entry(hass) + + result = await hass.config_entries.subentries.async_init( + (entry.entry_id, SUBENTRY_TYPE_VEHICLE), + context={"source": "user"}, + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["data_schema"].schema[CONF_VIN].container == { + "LRW3F7EK4NC700001": "Supported", + "LRW3F7EK4NC700003": "Unknown", + } + + +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_add_flow_keeps_vehicle_without_metadata( + hass: HomeAssistant, mock_metadata: AsyncMock, freezer: FrozenDateTimeFactory +) -> None: + """A vehicle missing from refreshed metadata is offered as unknown support.""" + entry = await _setup_account_entry(hass) + metadata = deepcopy(METADATA) + del metadata["vehicles"][VIN] + mock_metadata.return_value = metadata + + # The flow can open after the metadata refresh but before its reload runs. + with patch.object(hass.config_entries, "async_schedule_reload") as mock_reload: + freezer.tick(METADATA_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + result = await hass.config_entries.subentries.async_init( + (entry.entry_id, SUBENTRY_TYPE_VEHICLE), + context={"source": "user"}, + ) + + mock_reload.assert_called_once_with(entry.entry_id) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + assert result["data_schema"].schema[CONF_VIN].container == {VIN: "Test"} + + +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_add_flow_only_unsupported_vehicles( + hass: HomeAssistant, mock_metadata: AsyncMock +) -> None: + """The add flow aborts when no account vehicle supports the command protocol.""" + metadata = deepcopy(METADATA) + metadata["vehicles"][VIN]["proxy"] = False + mock_metadata.return_value = metadata + entry = await _setup_account_entry(hass) + + result = await hass.config_entries.subentries.async_init( + (entry.entry_id, SUBENTRY_TYPE_VEHICLE), + context={"source": "user"}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "no_vehicles" + + async def test_subentry_add_flow_no_bluetooth(hass: HomeAssistant) -> None: """The add flow aborts immediately when no Bluetooth integration is set up.""" entry = await _setup_account_entry(hass) From 0f61021c34a739c20d1503b10c54d00a32de74e7 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 00:04:47 +0200 Subject: [PATCH 124/356] Pass the Hunter Douglas PowerView shade model as a string (#184560) --- .../hunterdouglas_powerview/entity.py | 3 +- .../hunterdouglas_powerview/test_entity.py | 38 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) create mode 100644 tests/components/hunterdouglas_powerview/test_entity.py diff --git a/homeassistant/components/hunterdouglas_powerview/entity.py b/homeassistant/components/hunterdouglas_powerview/entity.py index fdf9b35cbc00..6af8c703be0b 100644 --- a/homeassistant/components/hunterdouglas_powerview/entity.py +++ b/homeassistant/components/hunterdouglas_powerview/entity.py @@ -88,7 +88,8 @@ class ShadeEntity(HDEntity): name=self._shade_name, suggested_area=self._room_name, manufacturer=MANUFACTURER, - model=self._shade.type_name, + # aiopvapi returns the integer type id for unknown shade types + model=str(self._shade.type_name), sw_version=self._shade.firmware, via_device_id=dr.async_get_device_id_by_identifier( self.coordinator.hass, diff --git a/tests/components/hunterdouglas_powerview/test_entity.py b/tests/components/hunterdouglas_powerview/test_entity.py new file mode 100644 index 000000000000..da7157248742 --- /dev/null +++ b/tests/components/hunterdouglas_powerview/test_entity.py @@ -0,0 +1,38 @@ +"""Test the Hunter Douglas Powerview entities.""" + +from unittest.mock import PropertyMock, patch + +import pytest + +from homeassistant.components.hunterdouglas_powerview.const import DOMAIN +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr + +from .const import MOCK_MAC + +from tests.common import MockConfigEntry + + +@pytest.mark.usefixtures("mock_hunterdouglas_hub") +@pytest.mark.parametrize("api_version", [3]) +async def test_unknown_shade_type_model( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + device_registry: dr.DeviceRegistry, +) -> None: + """Test a shade of an unknown type gets its type id as a string model.""" + entry = MockConfigEntry(domain=DOMAIN, data={"host": "1.2.3.4"}, unique_id=MOCK_MAC) + entry.add_to_hass(hass) + + # aiopvapi returns the integer type id for shade types it doesn't know + with patch( + "aiopvapi.resources.shade.BaseShade.type_name", + new_callable=PropertyMock, + return_value=999, + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + devices = dr.async_entries_for_config_entry(device_registry, entry.entry_id) + assert "999" in {device.model for device in devices} + assert "non-string value" not in caplog.text From 3c2165145a3f776fec068ce8f3ff046331d122c7 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 00:29:51 +0200 Subject: [PATCH 125/356] Resolve a pre-migration composite source device for Bluetooth scanners (#184568) --- .../components/bluetooth/__init__.py | 16 +++++ .../components/bluetooth/test_config_flow.py | 64 +++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/homeassistant/components/bluetooth/__init__.py b/homeassistant/components/bluetooth/__init__.py index 41640d3b4242..d94d9ebfd9a5 100644 --- a/homeassistant/components/bluetooth/__init__.py +++ b/homeassistant/components/bluetooth/__init__.py @@ -346,6 +346,22 @@ async def async_update_device( sw_version=details.get(ADAPTER_SW_VERSION), hw_version=details.get(ADAPTER_HW_VERSION), ) + if via_device_id and ( + split_devices := device_registry.async_get_devices_for_composite_device_id( + via_device_id + ) + ): + # The stored source device id can predate a device split, link to the + # device of the config entry that provides the scanner + source_entry_id = entry.data.get(CONF_SOURCE_CONFIG_ENTRY_ID) + via_device_id = next( + ( + split_device.id + for split_device in split_devices + if split_device.config_entry_id == source_entry_id + ), + None, + ) if via_device_id and (via_device_entry := device_registry.async_get(via_device_id)): # The bluetooth scanner may be child device; link to its parent. if isinstance(via_device_entry, dr.ChildDeviceEntry): diff --git a/tests/components/bluetooth/test_config_flow.py b/tests/components/bluetooth/test_config_flow.py index d3cb1a3186a4..78022b5901e8 100644 --- a/tests/components/bluetooth/test_config_flow.py +++ b/tests/components/bluetooth/test_config_flow.py @@ -3,6 +3,7 @@ from typing import Any from unittest.mock import patch +import attr from bluetooth_adapters import DEFAULT_ADDRESS, AdapterDetails import pytest @@ -629,6 +630,69 @@ async def test_async_step_integration_discovery_remote_adapter( await hass.async_block_till_done() +@pytest.mark.usefixtures("enable_bluetooth") +async def test_async_step_integration_discovery_remote_adapter_composite_source( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + device_registry: dr.DeviceRegistry, +) -> None: + """Test a remote adapter whose stored source device was split since.""" + entry = MockConfigEntry(domain="test") + entry.add_to_hass(hass) + other_entry = MockConfigEntry(domain="other") + other_entry.add_to_hass(hass) + connector = ( + HaBluetoothConnector(MockBleakClient, "mock_bleak_client", lambda: False), + ) + scanner = FakeRemoteScanner("esp32", "esp32", connector, True) + manager = _get_manager() + cancel_scanner = manager.async_register_scanner(scanner) + device_entry = device_registry.async_get_or_create( + config_entry_id=entry.entry_id, + identifiers={("test", "BB:BB:BB:BB:BB:BB")}, + ) + other_device_entry = device_registry.async_get_or_create( + config_entry_id=other_entry.entry_id, + identifiers={("other", "BB:BB:BB:BB:BB:BB")}, + ) + # Simulate a device split: both devices carry the pre-migration composite id + composite_device_id = "composite00000000000000000000ab" + device_registry._devices[device_entry.id] = attr.evolve( + device_entry, composite_device_id=composite_device_id + ) + device_registry._devices[other_device_entry.id] = attr.evolve( + other_device_entry, composite_device_id=composite_device_id + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_INTEGRATION_DISCOVERY}, + data={ + CONF_SOURCE: scanner.source, + CONF_SOURCE_DOMAIN: "test", + CONF_SOURCE_MODEL: "test", + CONF_SOURCE_CONFIG_ENTRY_ID: entry.entry_id, + CONF_SOURCE_DEVICE_ID: composite_device_id, + }, + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + await hass.async_block_till_done() + + new_entry = result["result"] + ble_device_entry = device_registry.async_get_device_by_connection( + (dr.CONNECTION_BLUETOOTH, scanner.source), new_entry.entry_id + ) + assert ble_device_entry is not None + assert ble_device_entry.via_device_id == device_entry.id + assert "pre-migration composite device" not in caplog.text + + await hass.config_entries.async_unload(new_entry.entry_id) + await hass.config_entries.async_unload(entry.entry_id) + await hass.async_block_till_done() + cancel_scanner() + await hass.async_block_till_done() + + @pytest.mark.usefixtures("enable_bluetooth") async def test_async_step_integration_discovery_remote_adapter_child_source( hass: HomeAssistant, From 6009b3164af8d460693078e32fdcd1fb8f349a9d Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Wed, 7 Oct 2026 01:54:35 +1000 Subject: [PATCH 126/356] Wait for a fresh Teslemetry advertisement before connecting over Bluetooth (#184193) --- .../components/teslemetry/config_flow.py | 75 ++++++-- homeassistant/components/teslemetry/const.py | 1 + .../components/teslemetry/test_config_flow.py | 164 +++++++++++++++++- 3 files changed, 220 insertions(+), 20 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 73b648adbc13..38b6ab342324 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -42,8 +42,12 @@ from homeassistant.components.application_credentials import ( async_import_client_credential, ) from homeassistant.components.bluetooth import ( + BluetoothScanningMode, + BluetoothServiceInfoBleak, + async_current_scanners, async_discovered_service_info, async_last_service_info, + async_register_advertisement_callback, async_request_active_scan, async_scanner_count, ) @@ -69,6 +73,7 @@ from homeassistant.helpers.selector import ( from . import _BLE_KEY_ERRORS, TeslemetryConfigEntry from .const import ( + BLE_ADVERTISEMENT_TIMEOUT, CLIENT_ID, CONF_SITE_ID, CONF_VIN, @@ -311,21 +316,57 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): else: # The advertised BLE name is a hash of the VIN; match on its prefix. expected = parent.get_name(self._vin)[:17] - device = None - # The name is only in scan responses, so an active scan may be needed to see it. - await async_request_active_scan(self.hass) - for info in async_discovered_service_info(self.hass, connectable=True): - if info.name and info.name.startswith(expected): - device = info.device - self._address = info.address - break + if (info := self._async_find_vehicle(expected)) is None: + # The name is only in scan responses, so an active scan may be needed to see it. + await async_request_active_scan(self.hass) + if (info := self._async_find_vehicle(expected)) is None: + LOGGER.debug( + "No connectable advertisement matched Bluetooth name %s", + expected, + ) + else: + # Ending the active scan drops the vehicle from a local adapter until its next advertisement. + heard: asyncio.Future[BluetoothServiceInfoBleak] = ( + self.hass.loop.create_future() + ) - if device is None: + @callback + def _async_heard( + service_info: BluetoothServiceInfoBleak, + ) -> None: + # An Auto scanner still in the scan's active window has yet to restart discovery. + if ( + service_info.connectable + and not heard.done() + and not any( + scanner.requested_mode is BluetoothScanningMode.AUTO + and scanner.current_mode + is BluetoothScanningMode.ACTIVE + for scanner in async_current_scanners(self.hass) + ) + ): + heard.set_result(service_info) + + cancel = async_register_advertisement_callback( + self.hass, _async_heard, info.address + ) + try: + async with asyncio.timeout(BLE_ADVERTISEMENT_TIMEOUT): + info = await heard + except TimeoutError: + LOGGER.debug( + "Vehicle not heard again after the active scan" + ) + finally: + cancel() + + if info is None: errors["base"] = "device_not_found" else: + self._address = info.address # Uses default keepalive so the link survives the on-screen key-approval wait. self._vehicle = parent.vehicles.createBluetooth( - self._vin, device=device + self._vin, device=info.device ) try: await self._vehicle.connect() @@ -334,7 +375,7 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): await self._async_disconnect() cause = err.__cause__ last_info = async_last_service_info( - self.hass, device.address, connectable=True + self.hass, info.address, connectable=True ) if not isinstance( cause, BleakNotFoundError | BleakOutOfConnectionSlotsError @@ -362,6 +403,18 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): description_placeholders=placeholders, ) + @callback + def _async_find_vehicle(self, name_prefix: str) -> BluetoothServiceInfoBleak | None: + """Return the discovered vehicle whose advertised name matches, if any.""" + return next( + ( + info + for info in async_discovered_service_info(self.hass, connectable=True) + if info.name and info.name.startswith(name_prefix) + ), + None, + ) + async def async_step_pair( self, user_input: dict[str, Any] | None = None ) -> SubentryFlowResult: diff --git a/homeassistant/components/teslemetry/const.py b/homeassistant/components/teslemetry/const.py index d14c26f0a459..d4e04b31ece9 100644 --- a/homeassistant/components/teslemetry/const.py +++ b/homeassistant/components/teslemetry/const.py @@ -18,6 +18,7 @@ VEHICLE_KEY_FILE = "tesla_vehicle.key" BLE_PARENT_KEY = f"{DOMAIN}_ble_parent" BLE_PARENT_LOCK_KEY = f"{DOMAIN}_ble_parent_lock" BLE_DISCONNECT_TIMEOUT = 10 +BLE_ADVERTISEMENT_TIMEOUT = 5 SUBENTRY_TYPE_ENERGY_SITE = "energy_site" CONF_SITE_ID = "site_id" diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 3664954ab590..f3a8a55d4012 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -3,6 +3,7 @@ import asyncio from collections.abc import Generator from copy import deepcopy +import logging import time from typing import Any from unittest.mock import AsyncMock, MagicMock, PropertyMock, patch @@ -14,6 +15,7 @@ from aiopowerwall import ( PowerwallConnectionError, PowerwallFaultError, ) +from bleak.backends.device import BLEDevice from bleak.exc import BleakDeviceNotFoundError, BleakError from bleak_retry_connector import ( BleakConnectionError, @@ -51,6 +53,10 @@ from homeassistant.components.application_credentials import ( ClientCredential, async_import_client_credential, ) +from homeassistant.components.bluetooth import ( + BluetoothScanningMode, + async_register_scanner, +) from homeassistant.components.teslemetry.const import ( AUTHORIZE_URL, CLIENT_ID, @@ -85,9 +91,11 @@ from .const import CONFIG_V1, METADATA, PRODUCTS, UNIQUE_ID from tests.common import MockConfigEntry, async_fire_time_changed from tests.components.bluetooth import ( + FakeScanner, generate_advertisement_data, generate_ble_device, inject_advertisement, + inject_advertisement_with_time_and_source_connectable, ) from tests.test_util.aiohttp import AiohttpClientMocker from tests.typing import ClientSessionGenerator @@ -1507,18 +1515,24 @@ async def test_subentry_abandoned_during_connect_disconnects( @pytest.mark.usefixtures("enable_bluetooth") -async def test_subentry_scan_device_not_found(hass: HomeAssistant) -> None: +async def test_subentry_scan_device_not_found( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: """The scan step re-shows the form with an error when no device is found.""" entry = await _setup_account_entry(hass) + caplog.set_level(logging.DEBUG, logger="homeassistant.components.teslemetry") with ( patch( "homeassistant.components.teslemetry.config_flow.async_discovered_service_info", return_value=[], ), + patch( + "homeassistant.components.teslemetry.config_flow.async_request_active_scan", + ), patch( "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", - return_value=MagicMock(), + return_value=_mock_ble_parent(_mock_vehicle()), ), ): result = await _start_pairing_at_scan(hass, entry) @@ -1530,6 +1544,9 @@ async def test_subentry_scan_device_not_found(hass: HomeAssistant) -> None: assert result["step_id"] == "scan" assert result["errors"] == {"base": "device_not_found"} assert not entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + assert "No connectable advertisement matched Bluetooth name Sdcdcb1a343110fba" in ( + caplog.text + ) @pytest.mark.parametrize( @@ -1591,26 +1608,155 @@ async def test_subentry_scan_key_load_recovers( vehicle.connect.assert_awaited_once() +def _inject_vehicle_advertisement(hass: HomeAssistant) -> None: + """Inject an advertisement carrying the test vehicle's BLE name.""" + name = TeslaBluetooth().get_name(VIN) + inject_advertisement( + hass, + generate_ble_device(ADDRESS, name), + generate_advertisement_data(local_name=name), + ) + + @pytest.mark.usefixtures("enable_bluetooth") -async def test_subentry_scan_finds_device_after_active_scan( +async def test_subentry_scan_waits_for_advertisement_after_active_scan( hass: HomeAssistant, ) -> None: - """An awake in-range car only in scan responses is found via active scan.""" + """A vehicle found by the active scan is connected only once it is heard again.""" entry = await _setup_account_entry(hass) vehicle = _mock_vehicle() - mock_discovered = MagicMock(return_value=[]) + parent = _mock_ble_parent(vehicle) + fresh_device = generate_ble_device(ADDRESS) + events: list[str] = [] + auto_scanner = FakeScanner( + "AA:BB:CC:00:00:02", + "hci1", + connectable=True, + requested_mode=BluetoothScanningMode.AUTO, + current_mode=BluetoothScanningMode.ACTIVE, + ) + unregister_scanner = async_register_scanner(hass, auto_scanner) + + def _advertise( + source: str, connectable: bool, device: BLEDevice | None = None + ) -> None: + inject_advertisement_with_time_and_source_connectable( + hass, + device or generate_ble_device(ADDRESS), + generate_advertisement_data(), + time.monotonic(), + source, + connectable, + ) + + def _advertise_before_window_ends() -> None: + events.append("proxy advertisement before the active window ends") + _advertise("AA:BB:CC:00:00:03", True) + hass.loop.call_soon(_advertise_non_connectable_after_window_ends) + + def _advertise_non_connectable_after_window_ends() -> None: + events.append("non-connectable advertisement after the active window ends") + auto_scanner.set_current_mode(BluetoothScanningMode.PASSIVE) + _advertise("AA:BB:CC:00:00:01", False) + hass.loop.call_soon(_advertise_after_window_ends) + + def _advertise_after_window_ends() -> None: + events.append("advertisement after the active window ends") + _advertise(auto_scanner.source, True, fresh_device) async def _active_scan(hass: HomeAssistant) -> None: - mock_discovered.return_value = [_discovered_info()] + events.append("active scan") + # The name is only in the scan response, so the vehicle first appears during the active scan. + _inject_vehicle_advertisement(hass) + hass.loop.call_soon(_advertise_before_window_ends) + + async def _connect() -> None: + events.append("connect") + + vehicle.connect = AsyncMock(side_effect=_connect) with ( patch( - "homeassistant.components.teslemetry.config_flow.async_discovered_service_info", - mock_discovered, + "homeassistant.components.teslemetry.config_flow.async_request_active_scan", + AsyncMock(side_effect=_active_scan), + ), + patch( + "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", + return_value=parent, + ), + patch.object(hass.config_entries, "async_schedule_reload"), + ): + result = await _start_pairing_at_scan(hass, entry) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + await hass.async_block_till_done() + + unregister_scanner() + # Connecting before the active window ends races a local adapter dropping the vehicle. + assert events == [ + "active scan", + "proxy advertisement before the active window ends", + "non-connectable advertisement after the active window ends", + "advertisement after the active window ends", + "connect", + ] + # The pre-scan handle may be stale, so the connection uses the advertisement heard afterwards. + parent.vehicles.createBluetooth.assert_called_once_with(VIN, device=fresh_device) + assert result["type"] is FlowResultType.CREATE_ENTRY + subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) + assert len(subentries) == 1 + assert subentries[0].data == {CONF_VIN: VIN, CONF_ADDRESS: ADDRESS} + + +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_scan_connects_when_not_heard_after_active_scan( + hass: HomeAssistant, +) -> None: + """The flow still connects when the vehicle is not heard again after the active scan.""" + entry = await _setup_account_entry(hass) + vehicle = _mock_vehicle() + + async def _active_scan(hass: HomeAssistant) -> None: + _inject_vehicle_advertisement(hass) + + with ( + patch( + "homeassistant.components.teslemetry.config_flow.BLE_ADVERTISEMENT_TIMEOUT", + 0, ), patch( "homeassistant.components.teslemetry.config_flow.async_request_active_scan", AsyncMock(side_effect=_active_scan), + ), + patch( + "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", + return_value=_mock_ble_parent(vehicle), + ), + patch.object(hass.config_entries, "async_schedule_reload"), + ): + result = await _start_pairing_at_scan(hass, entry) + result = await hass.config_entries.subentries.async_configure( + result["flow_id"], {} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + vehicle.connect.assert_awaited_once() + + +@pytest.mark.usefixtures("enable_bluetooth") +async def test_subentry_scan_known_vehicle_skips_active_scan( + hass: HomeAssistant, +) -> None: + """A vehicle whose name is already known is connected without an active scan.""" + entry = await _setup_account_entry(hass) + vehicle = _mock_vehicle() + _inject_vehicle_advertisement(hass) + + with ( + patch( + "homeassistant.components.teslemetry.config_flow.async_request_active_scan", ) as mock_active_scan, patch( "homeassistant.components.teslemetry.config_flow.async_get_ble_parent", @@ -1624,7 +1770,7 @@ async def test_subentry_scan_finds_device_after_active_scan( ) await hass.async_block_till_done() - mock_active_scan.assert_awaited_once() + mock_active_scan.assert_not_called() assert result["type"] is FlowResultType.CREATE_ENTRY subentries = entry.get_subentries_of_type(SUBENTRY_TYPE_VEHICLE) assert len(subentries) == 1 From f62820b143c52271ee88e392ed8bcd9455193c7c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:52:21 +0200 Subject: [PATCH 127/356] Fix Teslemetry vehicle flow abort when no vehicle supports Bluetooth (#184521) --- homeassistant/components/teslemetry/config_flow.py | 11 ++++++++--- homeassistant/components/teslemetry/strings.json | 1 + tests/components/teslemetry/test_config_flow.py | 2 +- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 38b6ab342324..36ead311071f 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -271,9 +271,14 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): and vehicle_metadata.get(vehicle.vin, {}).get("proxy") is not False } if not choices: - if entry.runtime_data.vehicles: - return self.async_abort(reason="all_vehicles_added") - return self.async_abort(reason="no_vehicles") + if not entry.runtime_data.vehicles: + return self.async_abort(reason="no_vehicles") + if any( + vehicle.vin not in already_added + for vehicle in entry.runtime_data.vehicles + ): + return self.async_abort(reason="no_supported_vehicles") + return self.async_abort(reason="all_vehicles_added") if user_input is not None: self._vin = user_input[CONF_VIN] diff --git a/homeassistant/components/teslemetry/strings.json b/homeassistant/components/teslemetry/strings.json index a4b4626c7a52..d2303ceb740b 100644 --- a/homeassistant/components/teslemetry/strings.json +++ b/homeassistant/components/teslemetry/strings.json @@ -95,6 +95,7 @@ "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", "bluetooth_not_available": "Adding a vehicle over Bluetooth needs a Bluetooth adapter on the Home Assistant host or a remote Bluetooth proxy that supports active connections, such as an ESPHome Bluetooth proxy. Shelly devices only listen for Bluetooth devices and cannot connect to a vehicle.", "entry_not_loaded": "The Teslemetry configuration entry is not loaded. Please ensure it is set up correctly before adding a vehicle.", + "no_supported_vehicles": "None of the vehicles left to add support Bluetooth commands. Vehicles without the vehicle command protocol, such as Model S and Model X built before 2021, cannot be added as a local vehicle.", "no_vehicles": "Home Assistant cannot access any vehicles in your Teslemetry account. Check that the vehicle is in your account and that Teslemetry has access to it." }, "entry_type": "Bluetooth vehicle", diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index f3a8a55d4012..8cfd227e7077 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -1990,7 +1990,7 @@ async def test_subentry_add_flow_only_unsupported_vehicles( ) assert result["type"] is FlowResultType.ABORT - assert result["reason"] == "no_vehicles" + assert result["reason"] == "no_supported_vehicles" async def test_subentry_add_flow_no_bluetooth(hass: HomeAssistant) -> None: From 2ce9f39b664dccb134e4944e5dbea5a404356fc7 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Tue, 6 Oct 2026 22:47:07 +0000 Subject: [PATCH 128/356] Bump version to 2026.10.0b3 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 8ee1cce3afca..92151d09452c 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b2" +PATCH_VERSION: Final = "0b3" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 39009b3b7a74..b36ceac8f47e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b2" +version = "2026.10.0b3" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 47ef1ed8c55be5dff3d00810c1a8569433f6626f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:06:43 +0200 Subject: [PATCH 129/356] Stop the UPnP notify server when unloading the config entry (#184515) --- homeassistant/components/upnp/__init__.py | 3 +-- homeassistant/components/upnp/device.py | 14 ++++++++++++-- tests/components/upnp/conftest.py | 15 +++++++++++---- tests/components/upnp/test_init.py | 18 ++++++++++++++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/upnp/__init__.py b/homeassistant/components/upnp/__init__.py index 636a93194bf3..61cb67fd8465 100644 --- a/homeassistant/components/upnp/__init__.py +++ b/homeassistant/components/upnp/__init__.py @@ -90,8 +90,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: UpnpConfigEntry) -> bool if not force_poll: await device.async_subscribe_services() - # Unsubscribe services on unload. - entry.async_on_unload(device.async_unsubscribe_services) + entry.async_on_unload(device.async_stop) # Track the original UDN such that existing sensors do not change their unique_id. if CONFIG_ENTRY_ORIGINAL_UDN not in entry.data: diff --git a/homeassistant/components/upnp/device.py b/homeassistant/components/upnp/device.py index a93a7a61f981..ab18d031dfab 100644 --- a/homeassistant/components/upnp/device.py +++ b/homeassistant/components/upnp/device.py @@ -108,18 +108,23 @@ async def async_create_device( # Create profile wrapper. igd_device = IgdDevice(upnp_device, notify_server.event_handler) - return Device(hass, igd_device, force_poll) + return Device(hass, igd_device, notify_server, force_poll) class Device: """Home Assistant representation of a UPnP/IGD device.""" def __init__( - self, hass: HomeAssistant, igd_device: IgdDevice, force_poll: bool + self, + hass: HomeAssistant, + igd_device: IgdDevice, + notify_server: AiohttpNotifyServer, + force_poll: bool, ) -> None: """Initialize UPnP/IGD device.""" self.hass = hass self._igd_device = igd_device + self._notify_server = notify_server self._force_poll = force_poll self.coordinator: ( @@ -222,6 +227,11 @@ class Device: except UpnpCommunicationError as ex: _LOGGER.debug("Error unsubscribing to services: %s", ex) + async def async_stop(self) -> None: + """Unsubscribe from services and stop the notify server.""" + await self.async_unsubscribe_services() + await self._notify_server.async_stop_server() + async def async_get_data( self, entity_description_keys: list[str] | None ) -> dict[str, str | datetime | int | float | None]: diff --git a/tests/components/upnp/conftest.py b/tests/components/upnp/conftest.py index b4525bf8dfd6..c0300dae88d0 100644 --- a/tests/components/upnp/conftest.py +++ b/tests/components/upnp/conftest.py @@ -77,8 +77,18 @@ def mock_async_create_device(): yield mock_create +@pytest.fixture +def mock_notify_server() -> AiohttpNotifyServer: + """Mock async_upnp_client notify server.""" + notify_server = create_autospec(AiohttpNotifyServer) + notify_server.event_handler = MagicMock() + return notify_server + + @pytest.fixture(autouse=True) -def mock_igd_device(mock_async_create_device) -> IgdDevice: +def mock_igd_device( + mock_async_create_device, mock_notify_server: AiohttpNotifyServer +) -> IgdDevice: """Mock async_upnp_client device.""" mock_upnp_device = create_autospec(UpnpDevice, instance=True) mock_upnp_device.device_url = TEST_DISCOVERY.ssdp_location @@ -115,9 +125,6 @@ def mock_igd_device(mock_async_create_device) -> IgdDevice: mock_igd_device.async_subscribe_services = AsyncMock() - mock_notify_server = create_autospec(AiohttpNotifyServer) - mock_notify_server.event_handler = MagicMock() - with ( patch( "homeassistant.components.upnp.device.async_get_local_ip", diff --git a/tests/components/upnp/test_init.py b/tests/components/upnp/test_init.py index c225a799b00f..a16b9c8e334b 100644 --- a/tests/components/upnp/test_init.py +++ b/tests/components/upnp/test_init.py @@ -5,6 +5,7 @@ import copy from typing import Any from unittest.mock import AsyncMock, MagicMock, patch +from async_upnp_client.aiohttp import AiohttpNotifyServer from async_upnp_client.exceptions import UpnpCommunicationError from async_upnp_client.profiles.igd import IgdDevice import pytest @@ -19,6 +20,7 @@ from homeassistant.components.upnp.const import ( CONFIG_ENTRY_UDN, DOMAIN, ) +from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers.service_info.ssdp import ATTR_UPNP_UDN, SsdpServiceInfo @@ -62,6 +64,22 @@ async def test_async_setup_entry_default( assert entry.update_listeners == [] +async def test_unload_stops_notify_server( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_igd_device: IgdDevice, + mock_notify_server: AiohttpNotifyServer, +) -> None: + """Test unloading stops the notify server started during setup.""" + assert mock_config_entry.state is ConfigEntryState.LOADED + mock_notify_server.async_start_server.assert_awaited_once() + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + + mock_igd_device.async_unsubscribe_services.assert_awaited_once() + mock_notify_server.async_stop_server.assert_awaited_once() + + @pytest.mark.usefixtures("ssdp_instant_discovery", "mock_no_mac_address_from_host") async def test_async_setup_entry_default_no_mac_address(hass: HomeAssistant) -> None: """Test async_setup_entry.""" From c099b5f7ccc8d5e420c4f7adff9a527348e2f261 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 6 Oct 2026 22:15:10 -0400 Subject: [PATCH 130/356] Hide the LLM API picker when all MCP server LLM APIs are exposed (#184516) Co-authored-by: Claude --- .../components/mcp_server/config_flow.py | 97 +++++++++---------- .../components/mcp_server/strings.json | 4 +- .../components/mcp_server/test_config_flow.py | 59 +++++++++-- 3 files changed, 103 insertions(+), 57 deletions(-) diff --git a/homeassistant/components/mcp_server/config_flow.py b/homeassistant/components/mcp_server/config_flow.py index 4e2a86d27d3c..11fd1394dfe5 100644 --- a/homeassistant/components/mcp_server/config_flow.py +++ b/homeassistant/components/mcp_server/config_flow.py @@ -58,31 +58,26 @@ def _options_schema( require_admin: bool, ) -> probatio.Schema: """Return the schema for the options flow.""" - return probatio.Schema( - { - probatio.Required( - CONF_ALL_LLM_APIS, default=all_llm_apis - ): BooleanSelector(), - probatio.Optional( - CONF_LLM_HASS_API, - default=default, - ): SelectSelector( - SelectSelectorConfig( - options=[ - SelectOptionDict( - label=name, - value=llm_api_id, - ) - for llm_api_id, name in llm_apis.items() - ], - multiple=True, - ) - ), - probatio.Required( - CONF_REQUIRE_ADMIN, default=require_admin - ): BooleanSelector(), - } + schema: dict[probatio.Marker, Any] = { + probatio.Required(CONF_ALL_LLM_APIS, default=all_llm_apis): BooleanSelector(), + } + if not all_llm_apis: + schema[probatio.Optional(CONF_LLM_HASS_API, default=default)] = SelectSelector( + SelectSelectorConfig( + options=[ + SelectOptionDict( + label=name, + value=llm_api_id, + ) + for llm_api_id, name in llm_apis.items() + ], + multiple=True, + ) + ) + schema[probatio.Required(CONF_REQUIRE_ADMIN, default=require_admin)] = ( + BooleanSelector() ) + return probatio.Schema(schema) class ModelContextServerProtocolConfigFlow(ConfigFlow, domain=DOMAIN): @@ -123,46 +118,50 @@ class ModelContextServerProtocolConfigFlow(ConfigFlow, domain=DOMAIN): class ModelContextServerProtocolOptionsFlow(OptionsFlow): """Handle an options flow to change the exposed LLM APIs.""" + last_rendered_all_llm_apis = False + async def async_step_init( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle the options step.""" errors: dict[str, str] = {} llm_apis = _llm_api_names(self.hass) + current = _selected_llm_apis(self.config_entry, llm_apis) # A disabled config entry has not migrated yet current_all = self.config_entry.data.get(CONF_ALL_LLM_APIS, False) - current = _selected_llm_apis(self.config_entry, llm_apis) - if user_input is not None: - if not user_input[CONF_ALL_LLM_APIS] and not user_input[CONF_LLM_HASS_API]: - errors[CONF_LLM_HASS_API] = "llm_api_required" - else: - updates: dict[str, Any] = { - "data": {**self.config_entry.data, **user_input} - } - # Keep a title the user renamed, only refresh a generated one. - if self.config_entry.title == _llm_api_title( - llm_apis, current_all, current - ): - updates["title"] = _llm_api_title( - llm_apis, - user_input[CONF_ALL_LLM_APIS], - user_input[CONF_LLM_HASS_API], - ) - self.hass.config_entries.async_update_entry( - self.config_entry, **updates + require_admin = self.config_entry.data.get(CONF_REQUIRE_ADMIN, False) + + if user_input is None: + self.last_rendered_all_llm_apis = current_all + elif user_input[CONF_ALL_LLM_APIS] != self.last_rendered_all_llm_apis: + # Re-render the form to show or hide the LLM API picker + self.last_rendered_all_llm_apis = user_input[CONF_ALL_LLM_APIS] + require_admin = user_input[CONF_REQUIRE_ADMIN] + elif not user_input[CONF_ALL_LLM_APIS] and not user_input[CONF_LLM_HASS_API]: + errors[CONF_LLM_HASS_API] = "llm_api_required" + else: + updates: dict[str, Any] = {"data": {**self.config_entry.data, **user_input}} + # Keep a title the user renamed, only refresh a generated one. + if self.config_entry.title == _llm_api_title( + llm_apis, current_all, current + ): + updates["title"] = _llm_api_title( + llm_apis, + user_input[CONF_ALL_LLM_APIS], + user_input.get(CONF_LLM_HASS_API, []), ) - # An open SSE session keeps serving the APIs it started with. - await self.hass.config_entries.async_reload(self.config_entry.entry_id) - return self.async_create_entry(data={}) + self.hass.config_entries.async_update_entry(self.config_entry, **updates) + # An open SSE session keeps serving the APIs it started with. + await self.hass.config_entries.async_reload(self.config_entry.entry_id) + return self.async_create_entry(data={}) return self.async_show_form( step_id="init", data_schema=_options_schema( llm_apis, - current_all, + self.last_rendered_all_llm_apis, current, - # A disabled config entry has not migrated yet - self.config_entry.data.get(CONF_REQUIRE_ADMIN, False), + require_admin, ), description_placeholders={"more_info_url": MORE_INFO_URL}, errors=errors, diff --git a/homeassistant/components/mcp_server/strings.json b/homeassistant/components/mcp_server/strings.json index a912671de70b..53ca5648024f 100644 --- a/homeassistant/components/mcp_server/strings.json +++ b/homeassistant/components/mcp_server/strings.json @@ -24,9 +24,9 @@ "require_admin": "Require an administrator account" }, "data_description": { - "all_llm_apis": "Expose every LLM API, including LLM APIs added later. When enabled, the selected LLM APIs are ignored.", + "all_llm_apis": "Expose every LLM API, including LLM APIs added later.", "llm_hass_api": "The methods for controlling Home Assistant to expose with the Model Context Protocol.", - "require_admin": "Only allow administrator accounts to use the Model Context Protocol endpoint." + "require_admin": "Only allow administrator accounts to use this Model Context Protocol endpoint." }, "description": "See the [integration documentation]({more_info_url}) for setup instructions." } diff --git a/tests/components/mcp_server/test_config_flow.py b/tests/components/mcp_server/test_config_flow.py index 2caa12f8665a..4ce657e47965 100644 --- a/tests/components/mcp_server/test_config_flow.py +++ b/tests/components/mcp_server/test_config_flow.py @@ -193,13 +193,33 @@ async def test_options_flow_unmigrated_entry(hass: HomeAssistant) -> None: @pytest.mark.parametrize( - ("all_llm_apis", "llm_hass_api", "title", "user_input", "expected_title"), + ( + "all_llm_apis", + "llm_hass_api", + "title", + "initial_form", + "rerendered_form", + "user_input", + "expected_data", + "expected_title", + ), [ pytest.param( False, [llm.LLM_API_ASSIST], "Assist", - {CONF_ALL_LLM_APIS: True, CONF_LLM_HASS_API: []}, + { + CONF_ALL_LLM_APIS: False, + CONF_LLM_HASS_API: [llm.LLM_API_ASSIST], + CONF_REQUIRE_ADMIN: False, + }, + {CONF_ALL_LLM_APIS: True, CONF_REQUIRE_ADMIN: True}, + {}, + { + CONF_ALL_LLM_APIS: True, + CONF_LLM_HASS_API: [llm.LLM_API_ASSIST], + CONF_REQUIRE_ADMIN: True, + }, "All LLM APIs", id="select_all", ), @@ -207,7 +227,18 @@ async def test_options_flow_unmigrated_entry(hass: HomeAssistant) -> None: True, [], "All LLM APIs", - {CONF_ALL_LLM_APIS: False, CONF_LLM_HASS_API: [TEST_LLM_API_ID]}, + {CONF_ALL_LLM_APIS: True, CONF_REQUIRE_ADMIN: False}, + { + CONF_ALL_LLM_APIS: False, + CONF_LLM_HASS_API: [], + CONF_REQUIRE_ADMIN: True, + }, + {CONF_LLM_HASS_API: [TEST_LLM_API_ID]}, + { + CONF_ALL_LLM_APIS: False, + CONF_LLM_HASS_API: [TEST_LLM_API_ID], + CONF_REQUIRE_ADMIN: True, + }, "Test", id="select_individual", ), @@ -216,8 +247,12 @@ async def test_options_flow_unmigrated_entry(hass: HomeAssistant) -> None: async def test_options_flow_all_llm_apis( hass: HomeAssistant, config_entry: MockConfigEntry, + all_llm_apis: bool, title: str, - user_input: dict[str, bool | list[str]], + initial_form: dict[str, bool | list[str]], + rerendered_form: dict[str, bool | list[str]], + user_input: dict[str, list[str]], + expected_data: dict[str, bool | list[str]], expected_title: str, ) -> None: """Test switching between all LLM APIs and individual LLM APIs.""" @@ -226,11 +261,23 @@ async def test_options_flow_all_llm_apis( assert await hass.config_entries.async_setup(config_entry.entry_id) result = await hass.config_entries.options.async_init(config_entry.entry_id) + assert result["data_schema"]({}) == initial_form + + # Changing the toggle re-renders the form to show or hide the LLM API picker result = await hass.config_entries.options.async_configure( - result["flow_id"], {**user_input, CONF_REQUIRE_ADMIN: True} + result["flow_id"], + {CONF_ALL_LLM_APIS: not all_llm_apis, CONF_REQUIRE_ADMIN: True}, + ) + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "init" + assert result["data_schema"]({}) == rerendered_form + assert config_entry.data[CONF_ALL_LLM_APIS] is all_llm_apis + + result = await hass.config_entries.options.async_configure( + result["flow_id"], {**rerendered_form, **user_input} ) await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY - assert config_entry.data == {**user_input, CONF_REQUIRE_ADMIN: True} + assert config_entry.data == expected_data assert config_entry.title == expected_title From d046379fec3bccdb75749e360c9cc5c27cc2c805 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:30:52 +0200 Subject: [PATCH 131/356] Skip Jellyfin sessions that report the server as their device (#184518) --- .../components/jellyfin/coordinator.py | 2 ++ .../components/jellyfin/test_media_player.py | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/homeassistant/components/jellyfin/coordinator.py b/homeassistant/components/jellyfin/coordinator.py index ca5333961126..e3ff08e8f837 100644 --- a/homeassistant/components/jellyfin/coordinator.py +++ b/homeassistant/components/jellyfin/coordinator.py @@ -61,6 +61,8 @@ class JellyfinDataUpdateCoordinator(DataUpdateCoordinator[dict[str, dict[str, An for session in sessions if session["DeviceId"] != self.client_device_id and session["Client"] != USER_APP_NAME + # Tools like Jellystat report sessions as the server itself + and session["DeviceId"] != self.server_id } self.device_ids = {session["DeviceId"] for session in sessions_by_id.values()} diff --git a/tests/components/jellyfin/test_media_player.py b/tests/components/jellyfin/test_media_player.py index a33d68d71ae4..65e1f1e32845 100644 --- a/tests/components/jellyfin/test_media_player.py +++ b/tests/components/jellyfin/test_media_player.py @@ -894,3 +894,39 @@ async def test_mute_requires_both_commands( # But should still have other features assert features_six & MediaPlayerEntityFeature.PLAY assert features_six & MediaPlayerEntityFeature.VOLUME_SET + + +async def test_session_with_server_device_id_skipped( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + device_registry: dr.DeviceRegistry, + entity_registry: er.EntityRegistry, + mock_config_entry: MockConfigEntry, + mock_jellyfin: MagicMock, + mock_api: MagicMock, +) -> None: + """Test a session using the server ID as device ID is not a client device.""" + sessions = mock_api.sessions.return_value + jellystat_session = { + **sessions[0], + "Id": "SESSION-UUID-JELLYSTAT", + "Client": "jellystat", + "DeviceName": "Jellyfin Server", + "DeviceId": "SERVER-UUID", + } + mock_api.sessions.return_value = [*sessions, jellystat_session] + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert "can not be its own via device" not in caplog.text + assert not entity_registry.async_get_entity_id( + MP_DOMAIN, DOMAIN, "SERVER-UUID-SESSION-UUID-JELLYSTAT" + ) + + server_device = device_registry.async_get_device_by_identifier( + (DOMAIN, "SERVER-UUID"), mock_config_entry.entry_id + ) + assert server_device + assert server_device.model != "jellystat" From 2c41884d655268d2bd2da1674aafacda03588752 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:30:11 +0200 Subject: [PATCH 132/356] Stop refreshing Nest WebRTC streams that can't be extended (#184525) --- homeassistant/components/nest/camera.py | 14 +++++- tests/components/nest/test_camera.py | 63 +++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nest/camera.py b/homeassistant/components/nest/camera.py index db71f28b0ea5..0de196a5f7af 100644 --- a/homeassistant/components/nest/camera.py +++ b/homeassistant/components/nest/camera.py @@ -16,7 +16,7 @@ from google_nest_sdm.camera_traits import ( WebRtcStream, ) from google_nest_sdm.device import Device -from google_nest_sdm.exceptions import ApiException +from google_nest_sdm.exceptions import ApiException, FailedPreconditionException from webrtc_models import RTCIceCandidateInit from homeassistant.components.camera import ( @@ -266,7 +266,17 @@ class NestWebRTCEntity(NestCameraBaseEntity): if not (webrtc_stream := self._webrtc_sessions.get(session_id)): return None _LOGGER.debug("Extending WebRTC stream %s", webrtc_stream.media_session_id) - webrtc_stream = await webrtc_stream.extend_stream() + try: + webrtc_stream = await webrtc_stream.extend_stream() + except FailedPreconditionException as err: + # The session is no longer valid or the device does not support + # extending it, retrying only runs into the API rate limit + _LOGGER.debug( + "Not refreshing WebRTC stream %s: %s", + webrtc_stream.media_session_id, + err, + ) + return None if session_id in self._webrtc_sessions: self._webrtc_sessions[session_id] = webrtc_stream return webrtc_stream.expires_at diff --git a/tests/components/nest/test_camera.py b/tests/components/nest/test_camera.py index e49f16ec9467..13693b47b3a8 100644 --- a/tests/components/nest/test_camera.py +++ b/tests/components/nest/test_camera.py @@ -969,3 +969,66 @@ async def test_webrtc_refresh_expired_stream( auth.captured_requests[1][2].get("command") == "sdm.devices.commands.CameraLiveStream.ExtendWebRtcStream" ) + + +@pytest.mark.usefixtures("webrtc_camera_device") +async def test_webrtc_refresh_failed_precondition( + hass: HomeAssistant, + setup_platform: PlatformSetup, + hass_ws_client: WebSocketGenerator, + auth: FakeAuth, +) -> None: + """Test a WebRTC stream that can't be extended is not refreshed again.""" + now = utcnow() + auth.responses = [ + aiohttp.web.json_response( + { + "results": { + "answerSdp": "v=0\r\ns=-\r\n", + "mediaSessionId": "yP2grqz0Y1V_wgiX9KEbMWHoLd...", + "expiresAt": (now + datetime.timedelta(seconds=90)).isoformat( + timespec="seconds" + ), + }, + } + ), + aiohttp.web.json_response( + { + "error": { + "code": 400, + "message": ( + "WebRtc error caused by invalid session or user id mismatch." + ), + "status": "FAILED_PRECONDITION", + } + }, + status=HTTPStatus.BAD_REQUEST, + ), + ] + await setup_platform() + await hass.async_block_till_done() + + client = await hass_ws_client(hass) + await client.send_json_auto_id( + { + "type": "camera/webrtc/offer", + "entity_id": "camera.my_camera", + "offer": "a=recvonly", + } + ) + response = await client.receive_json() + assert response["success"] + + # The stream extension fails because the session is no longer valid + await fire_alarm(hass, now + datetime.timedelta(seconds=60)) + # Retrying the extension can't succeed, so it is not attempted again + await fire_alarm(hass, now + datetime.timedelta(minutes=10)) + await fire_alarm(hass, now + datetime.timedelta(hours=1)) + + extend_requests = [ + request + for request in auth.captured_requests + if request[2].get("command") + == "sdm.devices.commands.CameraLiveStream.ExtendWebRtcStream" + ] + assert len(extend_requests) == 1 From 73c80cf853ec15a5d707e3616ed4dc406df6a6eb Mon Sep 17 00:00:00 2001 From: Artur Pragacz <49985303+arturpragacz@users.noreply.github.com> Date: Wed, 7 Oct 2026 07:39:33 +0200 Subject: [PATCH 133/356] Consider next name part when unprefixing entity name (#184526) Co-authored-by: Robert Resch --- homeassistant/helpers/entity_registry.py | 3 ++- tests/helpers/test_entity_registry.py | 13 +++++-------- 2 files changed, 7 insertions(+), 9 deletions(-) diff --git a/homeassistant/helpers/entity_registry.py b/homeassistant/helpers/entity_registry.py index 6872874483f6..1f30e6cf629b 100644 --- a/homeassistant/helpers/entity_registry.py +++ b/homeassistant/helpers/entity_registry.py @@ -507,7 +507,8 @@ def async_get_unprefixed_name(hass: HomeAssistant, entry: RegistryEntry) -> str: name = entry.name if name is not None: if ( - entry.device_id is not None + entry.next_name_part is NextNamePart.DEVICE + and entry.device_id is not None and (device := dr.async_get(hass).async_get(entry.device_id)) is not None ): device_name = device.name_by_user or device.name diff --git a/tests/helpers/test_entity_registry.py b/tests/helpers/test_entity_registry.py index 25cce2a434e5..1ac1043b48e4 100644 --- a/tests/helpers/test_entity_registry.py +++ b/tests/helpers/test_entity_registry.py @@ -2995,18 +2995,15 @@ async def test_update_entity_own_area_without_own_name( entity_registry.async_update_entity(entry.entity_id, area_id="kitchen") assert entity_registry.async_get(entry.entity_id).area_id is None - # A name equal to the device name is not a name of its own - with pytest.raises(ValueError, match="without a name of its own"): - entity_registry.async_update_entity( - entry.entity_id, area_id="kitchen", name="Device" - ) - - # Naming the entity in the same update makes the area valid + # Naming the entity in the same update makes the area valid, also with a + # name equal to the device name, which is not consulted for an own area entry = entity_registry.async_update_entity( - entry.entity_id, area_id="kitchen", name="Light" + entry.entity_id, area_id="kitchen", name="Device" ) assert entry.area_id == "kitchen" + entry = entity_registry.async_update_entity(entry.entity_id, name="Light") + # Clearing the name would leave the area without a name with pytest.raises(ValueError, match="without a name of its own"): entity_registry.async_update_entity(entry.entity_id, name=None) From daf3b78ecf9c425e962fc80d3c1989b55ffadce8 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:29:37 +0200 Subject: [PATCH 134/356] Separate streamed assistant messages in the Assist pipeline TTS input (#184535) --- .../assist_pipeline/default_pipeline.py | 14 +- .../snapshots/test_pipeline.ambr | 365 ++++++++++++++++++ .../assist_pipeline/test_pipeline.py | 61 ++- 3 files changed, 437 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/assist_pipeline/default_pipeline.py b/homeassistant/components/assist_pipeline/default_pipeline.py index 8dccf8c93ced..25cbb9817bbb 100644 --- a/homeassistant/components/assist_pipeline/default_pipeline.py +++ b/homeassistant/components/assist_pipeline/default_pipeline.py @@ -612,6 +612,7 @@ class _DefaultPipelineProcessor: tts_input_stream = None chat_log_role = None delta_character_count = 0 + last_assistant_content = "" @callback def chat_log_delta_listener( @@ -629,17 +630,28 @@ class _DefaultPipelineProcessor: if tts_input_stream is None: return - nonlocal chat_log_role + nonlocal chat_log_role, last_assistant_content if role := delta.get("role"): chat_log_role = role + # Keep TTS from running a new assistant message into the + # previous one, for example around a tool call + if ( + role == "assistant" + and last_assistant_content + and not last_assistant_content[-1].isspace() + ): + tts_input_stream.put_nowait(" ") + last_assistant_content = " " + # We are only interested in assistant deltas if chat_log_role != "assistant": return if content := delta.get("content"): tts_input_stream.put_nowait(content) + last_assistant_content = content if self._streamed_response_text: return diff --git a/tests/components/assist_pipeline/snapshots/test_pipeline.ambr b/tests/components/assist_pipeline/snapshots/test_pipeline.ambr index bdc90ace9a3d..e02554a4f741 100644 --- a/tests/components/assist_pipeline/snapshots/test_pipeline.ambr +++ b/tests/components/assist_pipeline/snapshots/test_pipeline.ambr @@ -621,6 +621,371 @@ }), ]) # --- +# name: test_chat_log_tts_streaming[to_stream_deltas3-4-Let me check the temperature. It is 25 degrees.] + list([ + dict({ + 'data': dict({ + 'conversation_id': 'mock-ulid', + 'language': 'en', + 'pipeline': , + 'tts_output': dict({ + 'mime_type': 'audio/mpeg', + 'stream_response': True, + 'token': 'mocked-token.mp3', + 'url': '/api/tts_proxy/mocked-token.mp3', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'conversation_id': 'mock-ulid', + 'device_id': None, + 'engine': 'test-agent', + 'intent_input': 'Set a timer', + 'language': 'en', + 'prefer_local_intents': False, + 'satellite_id': None, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'role': 'assistant', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': 'Let me check the temperature.', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'tool_calls': list([ + dict({ + 'external': False, + 'id': 'test_tool_id', + 'tool_args': dict({ + }), + 'tool_name': 'test_tool', + }), + ]), + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'tts_start_streaming': True, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'agent_id': 'test-agent', + 'created': HAFakeDatetime(2025, 10, 31, 12, 0, tzinfo=datetime.timezone.utc), + 'result': dict({ + 'data': 'Test response', + 'error': False, + }), + 'role': 'tool_result', + 'tool_call_id': 'test_tool_id', + 'tool_name': 'test_tool', + 'tool_result': 'Test response', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'role': 'assistant', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': 'It is ', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': '25 degrees.', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'intent_output': dict({ + 'continue_conversation': False, + 'conversation_id': , + 'response': dict({ + 'card': dict({ + }), + 'data': dict({ + 'failed': list([ + ]), + 'success': list([ + ]), + }), + 'language': 'en', + 'response_type': 'action_done', + 'speech': dict({ + 'plain': dict({ + 'extra_data': None, + 'speech': 'It is 25 degrees.', + }), + }), + }), + }), + 'processed_locally': False, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'acknowledge_override': False, + 'engine': 'tts.test', + 'language': 'en_US', + 'tts_input': 'It is 25 degrees.', + 'voice': None, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'tts_output': dict({ + 'media_id': 'media-source://tts/-stream-/mocked-token.mp3', + 'mime_type': 'audio/mpeg', + 'token': 'mocked-token.mp3', + 'url': '/api/tts_proxy/mocked-token.mp3', + }), + }), + 'type': , + }), + dict({ + 'data': None, + 'type': , + }), + ]) +# --- +# name: test_chat_log_tts_streaming[to_stream_deltas4-4-Let me check the temperature. It is 25 degrees.] + list([ + dict({ + 'data': dict({ + 'conversation_id': 'mock-ulid', + 'language': 'en', + 'pipeline': , + 'tts_output': dict({ + 'mime_type': 'audio/mpeg', + 'stream_response': True, + 'token': 'mocked-token.mp3', + 'url': '/api/tts_proxy/mocked-token.mp3', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'conversation_id': 'mock-ulid', + 'device_id': None, + 'engine': 'test-agent', + 'intent_input': 'Set a timer', + 'language': 'en', + 'prefer_local_intents': False, + 'satellite_id': None, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'role': 'assistant', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': 'Let me check the temperature.', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'tool_calls': list([ + dict({ + 'external': False, + 'id': 'test_tool_id', + 'tool_args': dict({ + }), + 'tool_name': 'test_tool', + }), + ]), + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'tts_start_streaming': True, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'agent_id': 'test-agent', + 'created': HAFakeDatetime(2025, 10, 31, 12, 0, tzinfo=datetime.timezone.utc), + 'result': dict({ + 'data': 'Test response', + 'error': False, + }), + 'role': 'tool_result', + 'tool_call_id': 'test_tool_id', + 'tool_name': 'test_tool', + 'tool_result': 'Test response', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'role': 'assistant', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'tool_calls': list([ + dict({ + 'external': False, + 'id': 'test_tool_id_2', + 'tool_args': dict({ + }), + 'tool_name': 'test_tool', + }), + ]), + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'agent_id': 'test-agent', + 'created': HAFakeDatetime(2025, 10, 31, 12, 0, tzinfo=datetime.timezone.utc), + 'result': dict({ + 'data': 'Test response', + 'error': False, + }), + 'role': 'tool_result', + 'tool_call_id': 'test_tool_id_2', + 'tool_name': 'test_tool', + 'tool_result': 'Test response', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'role': 'assistant', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': 'It is ', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'chat_log_delta': dict({ + 'content': '25 degrees.', + }), + }), + 'type': , + }), + dict({ + 'data': dict({ + 'intent_output': dict({ + 'continue_conversation': False, + 'conversation_id': , + 'response': dict({ + 'card': dict({ + }), + 'data': dict({ + 'failed': list([ + ]), + 'success': list([ + ]), + }), + 'language': 'en', + 'response_type': 'action_done', + 'speech': dict({ + 'plain': dict({ + 'extra_data': None, + 'speech': 'It is 25 degrees.', + }), + }), + }), + }), + 'processed_locally': False, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'acknowledge_override': False, + 'engine': 'tts.test', + 'language': 'en_US', + 'tts_input': 'It is 25 degrees.', + 'voice': None, + }), + 'type': , + }), + dict({ + 'data': dict({ + 'tts_output': dict({ + 'media_id': 'media-source://tts/-stream-/mocked-token.mp3', + 'mime_type': 'audio/mpeg', + 'token': 'mocked-token.mp3', + 'url': '/api/tts_proxy/mocked-token.mp3', + }), + }), + 'type': , + }), + dict({ + 'data': None, + 'type': , + }), + ]) +# --- # name: test_pipeline_language_used_instead_of_conversation_language list([ dict({ diff --git a/tests/components/assist_pipeline/test_pipeline.py b/tests/components/assist_pipeline/test_pipeline.py index c24cab61953a..3425180a5164 100644 --- a/tests/components/assist_pipeline/test_pipeline.py +++ b/tests/components/assist_pipeline/test_pipeline.py @@ -1722,6 +1722,64 @@ async def test_pipeline_language_used_instead_of_conversation_language( 8, "hello, how are you? I'm doing well, thank you.", ), + # Text ending without whitespace, a tool call, then more text + ( + ( + [ + "Let me check the temperature.", + ], + { + "tool_calls": [ + llm.ToolInput( + tool_name="test_tool", + tool_args={}, + id="test_tool_id", + ) + ], + }, + [ + "It is ", + "25 degrees.", + ], + ), + # 1 chunk before tool call, the separator, then 2 after + 4, + "Let me check the temperature. It is 25 degrees.", + ), + # Text, then an assistant message with only another tool call + ( + ( + [ + "Let me check the temperature.", + ], + { + "tool_calls": [ + llm.ToolInput( + tool_name="test_tool", + tool_args={}, + id="test_tool_id", + ) + ], + }, + [], + { + "tool_calls": [ + llm.ToolInput( + tool_name="test_tool", + tool_args={}, + id="test_tool_id_2", + ) + ], + }, + [ + "It is ", + "25 degrees.", + ], + ), + # 1 chunk before the tool calls, one separator, then 2 after + 4, + "Let me check the temperature. It is 25 degrees.", + ), ], ) @freeze_time("2025-10-31 12:00:00") @@ -1890,8 +1948,7 @@ async def test_chat_log_tts_streaming( [chunk.decode() async for chunk in stream.async_stream_result()] ) - streamed_text = "".join(text_deltas) - assert tts_result == streamed_text + assert tts_result == chunk_text assert len(received_tts) == expected_chunks assert "".join(received_tts) == chunk_text From 9d57fa8a88e51c5e5da4d61b4f01a2d3a8f6ea49 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:33:12 +0200 Subject: [PATCH 135/356] Fix color and white control of WLED lights with warm and cold white (#184536) --- homeassistant/components/wled/light.py | 59 ++++++++++++- tests/components/wled/test_light.py | 111 +++++++++++++++++++++++++ 2 files changed, 169 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/wled/light.py b/homeassistant/components/wled/light.py index 1cb5748f9bda..e466d17dacd9 100644 --- a/homeassistant/components/wled/light.py +++ b/homeassistant/components/wled/light.py @@ -3,7 +3,7 @@ from functools import partial from typing import Any, cast, override -from wled import LightCapability +from wled import Device as WLEDDevice, LightCapability, combine_white, split_white from homeassistant.components.light import ( ATTR_BRIGHTNESS, @@ -11,6 +11,7 @@ from homeassistant.components.light import ( ATTR_EFFECT, ATTR_RGB_COLOR, ATTR_RGBW_COLOR, + ATTR_RGBWW_COLOR, ATTR_TRANSITION, ColorMode, LightEntity, @@ -132,6 +133,33 @@ class WLEDMainLight(WLEDEntity, LightEntity): super()._handle_coordinator_update() +def _has_warm_and_cold_white(device: WLEDDevice, segment: int) -> bool: + """Return whether a segment's white is split over warm and cold white. + + That takes LEDs with separate warm and cold white on every output the + segment is on, and WLED using the color temperature for them, rather + than calculating it from the RGB color. + """ + capabilities = device.state.segments[segment].light_capabilities + if ( + capabilities is None + or ( + LightCapability.RGB_COLOR + | LightCapability.WHITE_CHANNEL + | LightCapability.COLOR_TEMPERATURE + ) + not in capabilities + or device.led_config is None + or device.led_config.cct_from_rgb + ): + return False + + outputs = device.segment_led_outputs(segment) + return bool(outputs) and all( + output.has_rgb and output.has_white and output.has_cct for output in outputs + ) + + class WLEDSegmentLight(WLEDEntity, LightEntity): """Defines a WLED light based on a segment.""" @@ -167,6 +195,9 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): ) is not None and ( color_modes := LIGHT_CAPABILITIES_COLOR_MODE_MAPPING.get(capabilities) ) is not None: + # With separate warm and cold white, the white channel holds both. + if _has_warm_and_cold_white(coordinator.data, segment): + color_modes = [ColorMode.COLOR_TEMP, ColorMode.RGBWW] self._color_modes = color_modes self._attr_supported_color_modes = set(color_modes) self._has_white_channel = LightCapability.WHITE_CHANNEL in capabilities @@ -226,6 +257,27 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): return None return cast(tuple[int, int, int, int], color.primary) + @property + @override + def rgbww_color(self) -> tuple[int, int, int, int, int] | None: + """Return the color value, with the white split over cold and warm.""" + segment = self.coordinator.data.state.segments[self._segment] + if not (color := segment.color): + return None + + red, green, blue, *white = color.primary + warm, cold = split_white( + white[0] if white else 0, segment.cct, cct_blend=self._cct_blend + ) + return (red, green, blue, cold, warm) + + @property + def _cct_blend(self) -> int: + """Return how the device blends warm and cold white, in percent.""" + if (led_config := self.coordinator.data.led_config) is None: + return 0 + return led_config.cct_blend + @property @override def color_temp_kelvin(self) -> int | None: @@ -307,6 +359,11 @@ class WLEDSegmentLight(WLEDEntity, LightEntity): if ATTR_RGBW_COLOR in kwargs: data[ATTR_COLOR_PRIMARY] = kwargs[ATTR_RGBW_COLOR] + if ATTR_RGBWW_COLOR in kwargs: + red, green, blue, cold, warm = kwargs[ATTR_RGBWW_COLOR] + white, data[ATTR_CCT] = combine_white(warm, cold, cct_blend=self._cct_blend) + data[ATTR_COLOR_PRIMARY] = (red, green, blue, white) + if ATTR_COLOR_TEMP_KELVIN in kwargs: data[ATTR_CCT] = kelvin_to_255( kwargs[ATTR_COLOR_TEMP_KELVIN], COLOR_TEMP_K_MIN, COLOR_TEMP_K_MAX diff --git a/tests/components/wled/test_light.py b/tests/components/wled/test_light.py index 2b9c2ff8945d..f2233565241f 100644 --- a/tests/components/wled/test_light.py +++ b/tests/components/wled/test_light.py @@ -18,6 +18,7 @@ from homeassistant.components.light import ( ATTR_MIN_COLOR_TEMP_KELVIN, ATTR_RGB_COLOR, ATTR_RGBW_COLOR, + ATTR_RGBWW_COLOR, ATTR_SUPPORTED_COLOR_MODES, ATTR_TRANSITION, DOMAIN as LIGHT_DOMAIN, @@ -467,11 +468,15 @@ async def _async_load_segment( mock_config_entry: MockConfigEntry, light_capabilities: int, color: list[int], + led_config: dict[str, Any] | None = None, ) -> None: """Load the CCT device with one segment of the given capabilities and color.""" data = await async_load_json_object_fixture(hass, "cct.json", DOMAIN) data["info"]["leds"]["seglc"] = [light_capabilities] data["state"]["seg"][0]["col"] = [color, [0, 0, 0, 0], [0, 0, 0, 0]] + data["state"]["seg"][0]["cct"] = 127 + if led_config is not None: + data["cfg"] = {"hw": {"led": led_config}} mock_wled.update.return_value = WLEDDevice.from_dict(data) await hass.config_entries.async_reload(mock_config_entry.entry_id) await hass.async_block_till_done() @@ -624,3 +629,109 @@ async def test_color_leaves_color_temp_alone( mock_wled.segment.assert_called_with( color_primary=color_primary, on=True, segment_id=0 ) + + +# A WS2805 strip (RGB plus warm and cold white), blending the whites by 30%. +WS2805 = {"cb": 30, "ins": [{"start": 0, "len": 178, "type": 32}]} + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_rgbww_light( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test LEDs with warm and cold white show the white split over both.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], WS2805 + ) + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ + ColorMode.COLOR_TEMP, + ColorMode.RGBWW, + ] + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.RGBWW + # WLED splits full white at the middle color temperature into 150 warm + # and 149 cold with a 30% blend. + assert state.attributes[ATTR_RGBWW_COLOR] == (255, 0, 0, 149, 150) + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_rgbww_light_color_temp( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test LEDs with warm and cold white still show a color temperature.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [0, 0, 0, 255], WS2805 + ) + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_rgbww_light_turn_on( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test setting warm and cold white sends the white and color temperature.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], WS2805 + ) + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + { + ATTR_ENTITY_ID: "light.wled_cct_light", + ATTR_RGBWW_COLOR: (0, 0, 255, 149, 150), + }, + blocking=True, + ) + + mock_wled.segment.assert_called_with( + cct=127, color_primary=(0, 0, 255, 255), on=True, segment_id=0 + ) + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +@pytest.mark.parametrize( + "led_config", + [ + # Not known + None, + # RGBW LEDs (SK6812), which also report color temperature when WLED + # corrects their white balance. + {"cct": True, "ins": [{"start": 0, "len": 178, "type": 30}]}, + # WLED calculates the color temperature from the RGB color. + {"cr": True, "ins": [{"start": 0, "len": 178, "type": 32}]}, + # Only part of the segment is on LEDs with warm and cold white. + { + "ins": [ + {"start": 0, "len": 100, "type": 32}, + {"start": 100, "len": 78, "type": 30}, + ] + }, + ], +) +async def test_no_rgbww_light( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + led_config: dict[str, Any] | None, +) -> None: + """Test LEDs without (only) warm and cold white stay RGBW.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], led_config + ) + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ + ColorMode.COLOR_TEMP, + ColorMode.RGBW, + ] + assert state.attributes[ATTR_COLOR_MODE] == ColorMode.RGBW From 280e892e42ed7792fc6b3a0cacf647d31f54dadd Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:31:11 +0200 Subject: [PATCH 136/356] Remove the ElevenLabs update listener when the entry is unloaded (#184552) --- .../components/elevenlabs/__init__.py | 2 +- tests/components/elevenlabs/test_setup.py | 25 +++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/elevenlabs/__init__.py b/homeassistant/components/elevenlabs/__init__.py index ef480e8ed492..edf8152d70ce 100644 --- a/homeassistant/components/elevenlabs/__init__.py +++ b/homeassistant/components/elevenlabs/__init__.py @@ -51,7 +51,7 @@ type ElevenLabsConfigEntry = ConfigEntry[ElevenLabsData] async def async_setup_entry(hass: HomeAssistant, entry: ElevenLabsConfigEntry) -> bool: """Set up ElevenLabs text-to-speech from a config entry.""" - entry.add_update_listener(update_listener) + entry.async_on_unload(entry.add_update_listener(update_listener)) httpx_client = get_async_client(hass) client = AsyncElevenLabs( api_key=entry.data[CONF_API_KEY], httpx_client=httpx_client diff --git a/tests/components/elevenlabs/test_setup.py b/tests/components/elevenlabs/test_setup.py index c373e04e955a..5ff85fae7e01 100644 --- a/tests/components/elevenlabs/test_setup.py +++ b/tests/components/elevenlabs/test_setup.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock +from homeassistant.components.elevenlabs.const import CONF_VOICE from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant @@ -32,3 +33,27 @@ async def test_setup_connect_error( await hass.config_entries.async_setup(mock_entry.entry_id) # Ensure is not ready assert mock_entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_options_update_reloads_once( + hass: HomeAssistant, + mock_async_client: MagicMock, + mock_entry: MockConfigEntry, +) -> None: + """Test an options update reloads the entry once after earlier reloads.""" + mock_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_entry.entry_id) + await hass.config_entries.async_reload(mock_entry.entry_id) + await hass.config_entries.async_reload(mock_entry.entry_id) + await hass.async_block_till_done() + + models_list = mock_async_client.return_value.models.list + models_list.reset_mock() + + hass.config_entries.async_update_entry( + mock_entry, options={**mock_entry.options, CONF_VOICE: "voice2"} + ) + await hass.async_block_till_done() + + assert mock_entry.state is ConfigEntryState.LOADED + assert models_list.await_count == 1 From 01b102cd81c289b80d06a935e23f00031a6a837f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:08:10 +0200 Subject: [PATCH 137/356] Don't write the Cast entity state while it is being removed (#184553) --- homeassistant/components/cast/media_player.py | 7 +++++++ tests/components/cast/test_media_player.py | 21 +++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/homeassistant/components/cast/media_player.py b/homeassistant/components/cast/media_player.py index 8020a714eec6..952198cc8128 100644 --- a/homeassistant/components/cast/media_player.py +++ b/homeassistant/components/cast/media_player.py @@ -378,6 +378,13 @@ class CastMediaPlayerEntity(CastDevice, MediaPlayerEntity): await super()._async_disconnect() self._attr_available = False + + @override + async def _async_stop(self, event: Event) -> None: + """Disconnect socket and mark the entity unavailable on stop.""" + await super()._async_stop(event) + + # Not in _async_disconnect, which also runs while the entity is removed self.async_write_ha_state() @override diff --git a/tests/components/cast/test_media_player.py b/tests/components/cast/test_media_player.py index bccb7daf162e..b889220e12a6 100644 --- a/tests/components/cast/test_media_player.py +++ b/tests/components/cast/test_media_player.py @@ -35,6 +35,7 @@ from homeassistant.const import ( ATTR_ENTITY_ID, CAST_APP_ID_HOMEASSISTANT_LOVELACE, EVENT_HOMEASSISTANT_STOP, + STATE_UNAVAILABLE, ) from homeassistant.core import HomeAssistant from homeassistant.core_config import async_process_ha_core_config @@ -2113,6 +2114,26 @@ async def test_disconnect_on_stop(hass: HomeAssistant) -> None: hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) await hass.async_block_till_done() assert chromecast.disconnect.call_count == 1 + assert hass.states.get("media_player.speaker").state == STATE_UNAVAILABLE + + +async def test_disable_entity_does_not_write_state( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + entity_registry: er.EntityRegistry, +) -> None: + """Test disabling the entity doesn't write its state while it is removed.""" + info = get_fake_chromecast_info() + chromecast, _ = await async_setup_media_player_cast(hass, info) + + entity_registry.async_update_entity( + "media_player.speaker", disabled_by=er.RegistryEntryDisabler.USER + ) + await hass.async_block_till_done() + + assert chromecast.disconnect.call_count == 1 + assert hass.states.get("media_player.speaker") is None + assert "incorrectly being triggered" not in caplog.text async def test_stop_listener_removed_with_entity(hass: HomeAssistant) -> None: From 85073ccf9193fb71bf8b9f1739d9e3e3108c4fe0 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:33:42 +0200 Subject: [PATCH 138/356] Pass the Genius Hub switch override duration in seconds (#184554) --- homeassistant/components/geniushub/switch.py | 3 +- tests/components/geniushub/test_switch.py | 47 +++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/geniushub/switch.py b/homeassistant/components/geniushub/switch.py index d24c699d96b4..4d2b87096bef 100644 --- a/homeassistant/components/geniushub/switch.py +++ b/homeassistant/components/geniushub/switch.py @@ -84,4 +84,5 @@ class GeniusSwitch(GeniusZone, SwitchEntity): @override async def async_turn_on(self, **kwargs: Any) -> None: """Set the zone to override/on ({'setpoint': true}) for x seconds.""" - await self._zone.set_override(1, kwargs.get(ATTR_DURATION, 3600)) + duration: timedelta = kwargs.get(ATTR_DURATION, timedelta(hours=1)) + await self._zone.set_override(1, int(duration.total_seconds())) diff --git a/tests/components/geniushub/test_switch.py b/tests/components/geniushub/test_switch.py index 905c32e0c353..a2a1be6da6e1 100644 --- a/tests/components/geniushub/test_switch.py +++ b/tests/components/geniushub/test_switch.py @@ -1,11 +1,13 @@ """Tests for the Geniushub switch platform.""" -from unittest.mock import patch +from unittest.mock import ANY, patch import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.const import Platform +from homeassistant.components.geniushub.const import DOMAIN +from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TURN_ON, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -28,3 +30,44 @@ async def test_cloud_all_sensors( await snapshot_platform( hass, entity_registry, snapshot, mock_cloud_config_entry.entry_id ) + + +@pytest.mark.usefixtures("mock_geniushub_cloud") +@pytest.mark.parametrize( + ("domain", "service", "service_data", "expected_duration"), + [ + pytest.param( + SWITCH_DOMAIN, SERVICE_TURN_ON, {}, 3600, id="turn_on_default_duration" + ), + pytest.param( + DOMAIN, + "set_switch_override", + {"duration": 36000}, + 36000, + id="set_switch_override_duration", + ), + ], +) +async def test_turn_on_override_duration( + hass: HomeAssistant, + mock_cloud_config_entry: MockConfigEntry, + domain: str, + service: str, + service_data: dict[str, int], + expected_duration: int, +) -> None: + """Test turning on a switch zone overrides it for a duration in seconds.""" + with patch("homeassistant.components.geniushub.PLATFORMS", [Platform.SWITCH]): + await setup_integration(hass, mock_cloud_config_entry) + + with patch( + "geniushubclient.zone.GeniusZone.set_override", autospec=True + ) as mock_set_override: + await hass.services.async_call( + domain, + service, + {ATTR_ENTITY_ID: "switch.bedroom_socket", **service_data}, + blocking=True, + ) + + mock_set_override.assert_awaited_once_with(ANY, 1, expected_duration) From 5bf4dd37a22ecb0d29e29399744fdaa739521dd4 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:27:47 +0200 Subject: [PATCH 139/356] Connect LG ThinQ MQTT before forwarding the platforms (#184555) --- homeassistant/components/lg_thinq/__init__.py | 13 ++-- tests/components/lg_thinq/conftest.py | 11 ++-- tests/components/lg_thinq/test_init.py | 60 +++++++++++++++++++ 3 files changed, 73 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/lg_thinq/__init__.py b/homeassistant/components/lg_thinq/__init__.py index 13e9793aa771..d59ede65ddf7 100644 --- a/homeassistant/components/lg_thinq/__init__.py +++ b/homeassistant/components/lg_thinq/__init__.py @@ -71,12 +71,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: ThinqConfigEntry) -> boo # Setup coordinators and register devices. await async_setup_coordinators(hass, entry, thinq_api) + # Set up MQTT connection before the platforms, as it can still raise + # ConfigEntryNotReady and forwarded platforms would not be unloaded. + await async_setup_mqtt(hass, entry, thinq_api, client_id) + # Set up all platforms for this device/entry. await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) - # Set up MQTT connection. - await async_setup_mqtt(hass, entry, thinq_api, client_id) - # Clean up devices they are no longer in use. async_cleanup_device_registry(hass, entry) @@ -156,6 +157,9 @@ async def async_setup_mqtt( translation_key="connection_error", ) from exc + # Also runs when setup fails after this point, unlike async_unload_entry + entry.async_on_unload(mqtt_client.async_disconnect) + if not result: _LOGGER.error("Failed to set up mqtt connection") return @@ -180,7 +184,4 @@ async def async_setup_mqtt( async def async_unload_entry(hass: HomeAssistant, entry: ThinqConfigEntry) -> bool: """Unload the entry.""" - if entry.runtime_data.mqtt_client: - await entry.runtime_data.mqtt_client.async_disconnect() - return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) diff --git a/tests/components/lg_thinq/conftest.py b/tests/components/lg_thinq/conftest.py index 96c916a64a98..7f89822229f7 100644 --- a/tests/components/lg_thinq/conftest.py +++ b/tests/components/lg_thinq/conftest.py @@ -94,7 +94,7 @@ def mock_invalid_thinq_api(mock_config_thinq_api: AsyncMock) -> AsyncMock: @pytest.fixture -def mock_thinq_api(mock_thinq_mqtt_client: None) -> Generator[AsyncMock]: +def mock_thinq_api(mock_thinq_mqtt_client: AsyncMock) -> Generator[AsyncMock]: """Mock a thinq api.""" with patch("homeassistant.components.lg_thinq.ThinQApi", autospec=True) as mock_api: thinq_api = mock_api.return_value @@ -102,14 +102,15 @@ def mock_thinq_api(mock_thinq_mqtt_client: None) -> Generator[AsyncMock]: @pytest.fixture -def mock_thinq_mqtt_client() -> Generator[None]: +def mock_thinq_mqtt_client() -> Generator[AsyncMock]: """Mock a thinq mqtt client.""" + client = AsyncMock() + client.async_prepare_mqtt.return_value = True with patch( "homeassistant.components.lg_thinq.mqtt.ThinQMQTTClient", - autospec=True, - return_value=True, + new=AsyncMock(return_value=client), ): - yield + yield client @pytest.fixture( diff --git a/tests/components/lg_thinq/test_init.py b/tests/components/lg_thinq/test_init.py index 00c742b226b6..fa914f451e78 100644 --- a/tests/components/lg_thinq/test_init.py +++ b/tests/components/lg_thinq/test_init.py @@ -8,6 +8,7 @@ from thinqconnect import ThinQAPIException from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant +from homeassistant.exceptions import ConfigEntryNotReady from . import setup_integration @@ -111,3 +112,62 @@ async def test_config_not_ready_bridge_list( await setup_integration(hass, mock_config_entry) assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + + +async def test_retry_after_mqtt_failure( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_thinq_api: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test setup succeeds on retry after the MQTT connection failed.""" + with patch( + "homeassistant.components.lg_thinq.ThinQMQTT.async_connect", + side_effect=[ + ThinQAPIException(code="1309", message="Not allowed api call", headers={}), + True, + ], + ): + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert "has already been setup" not in caplog.text + + +async def test_mqtt_disconnected_when_setup_fails_after_connecting( + hass: HomeAssistant, + mock_thinq_api: AsyncMock, + mock_thinq_mqtt_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test MQTT is disconnected when setup fails after it connected.""" + with patch.object( + hass.config_entries, + "async_forward_entry_setups", + side_effect=ConfigEntryNotReady, + ): + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + mock_thinq_mqtt_client.async_disconnect.assert_awaited_once() + + +async def test_mqtt_disconnected_on_unload_when_not_prepared( + hass: HomeAssistant, + mock_thinq_api: AsyncMock, + mock_thinq_mqtt_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the MQTT client is disconnected on unload when it failed to prepare.""" + mock_thinq_mqtt_client.async_prepare_mqtt.return_value = False + await setup_integration(hass, mock_config_entry) + assert mock_config_entry.state is ConfigEntryState.LOADED + + assert await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_thinq_mqtt_client.async_disconnect.assert_awaited_once() From 4511b211631832014224d694d0bad01b2022de17 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:34:14 +0200 Subject: [PATCH 140/356] Round the Songpal volume level instead of truncating it (#184558) --- .../components/songpal/media_player.py | 2 +- tests/components/songpal/test_media_player.py | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/songpal/media_player.py b/homeassistant/components/songpal/media_player.py index 5430589b4719..0526b178a099 100644 --- a/homeassistant/components/songpal/media_player.py +++ b/homeassistant/components/songpal/media_player.py @@ -405,7 +405,7 @@ class SongpalEntity(MediaPlayerEntity): @override async def async_set_volume_level(self, volume: float) -> None: """Set volume level.""" - volume = int(volume * self._volume_max) + volume = round(volume * self._volume_max) _LOGGER.debug("Setting volume to %s", volume) return await self._volume_control.set_volume(volume) diff --git a/tests/components/songpal/test_media_player.py b/tests/components/songpal/test_media_player.py index 619cb3fcaf57..9b37bf34a208 100644 --- a/tests/components/songpal/test_media_player.py +++ b/tests/components/songpal/test_media_player.py @@ -493,3 +493,33 @@ async def test_error_swallowing( else: with pytest.raises(SongpalException): await _call(hass, service) + + +@pytest.mark.parametrize( + ("max_volume", "volume", "service", "expected_volume"), + [ + pytest.param(95, 28, media_player.SERVICE_VOLUME_UP, 29, id="up_max_95"), + pytest.param(14, 4, media_player.SERVICE_VOLUME_UP, 5, id="up_max_14"), + pytest.param(95, 30, media_player.SERVICE_VOLUME_DOWN, 29, id="down_max_95"), + ], +) +async def test_volume_step( + hass: HomeAssistant, + max_volume: int, + volume: int, + service: str, + expected_volume: int, +) -> None: + """Test a volume step moves exactly one device volume step.""" + mocked_device = _create_mocked_device() + mocked_device.volume1.maxVolume = max_volume + mocked_device.volume1.volume = volume + entry = MockConfigEntry(domain=songpal.DOMAIN, data=CONF_DATA) + entry.add_to_hass(hass) + + with _patch_media_player_device(mocked_device): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + await _call(hass, service) + mocked_device.volume1.set_volume.assert_called_once_with(expected_volume) From 94ffde0b65c1905df4dc7b864363000e65249fdf Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 06:41:38 +0200 Subject: [PATCH 141/356] Always create the APC UPS Daemon battery transfer sensors (#184559) --- homeassistant/components/apcupsd/sensor.py | 18 ++++++++---------- tests/components/apcupsd/test_sensor.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/apcupsd/sensor.py b/homeassistant/components/apcupsd/sensor.py index 6abad3646c50..56be7af27dbe 100644 --- a/homeassistant/components/apcupsd/sensor.py +++ b/homeassistant/components/apcupsd/sensor.py @@ -47,6 +47,11 @@ IGNORED_SENSORS: Final = { "serialno", } +# Sensors that only appear after an event since the last daemon restart: a self +# test for "laststest", a transfer to or from the battery for "xonbatt" and +# "xoffbatt". They are always added, and stay unknown until the event happens. +EVENT_SENSORS: Final = {LAST_S_TEST, "xoffbatt", "xonbatt"} + SENSORS: dict[str, SensorEntityDescription] = { "alarmdel": SensorEntityDescription( key="alarmdel", @@ -430,16 +435,9 @@ async def async_setup_entry( entities = [] - # "laststest" is a special sensor that only appears when - # the APC UPS daemon has done a periodical (or manual) self - # test since last daemon restart. It might not be available - # when we set up the integration, and we do not know if it - # would ever be available. Here we add it anyway and mark it - # as unknown initially. - # - # We also sort the resources to ensure the order of entities - # created is deterministic - for resource in sorted(available_resources | {LAST_S_TEST}): + # We sort the resources to ensure the order of entities created is + # deterministic + for resource in sorted(available_resources | EVENT_SENSORS): if resource in IGNORED_SENSORS: continue if resource not in SENSORS: diff --git a/tests/components/apcupsd/test_sensor.py b/tests/components/apcupsd/test_sensor.py index c302e64e0864..4a08b36a1f20 100644 --- a/tests/components/apcupsd/test_sensor.py +++ b/tests/components/apcupsd/test_sensor.py @@ -147,6 +147,20 @@ async def test_manual_update_entity( MOCK_MINIMAL_STATUS | {"LASTSTEST": "1970-01-01 00:00:00 +0000"}, id="last_self_test_missing", ), + pytest.param( + # The transfer fields only appear after a transfer to or from the + # battery since the daemon started. + MOCK_MINIMAL_STATUS, + "sensor.apc_ups_transfer_to_battery", + MOCK_MINIMAL_STATUS | {"XONBATT": "1970-01-01 00:00:00 +0000"}, + id="xonbatt_missing", + ), + pytest.param( + MOCK_MINIMAL_STATUS, + "sensor.apc_ups_transfer_from_battery", + MOCK_MINIMAL_STATUS | {"XOFFBATT": "1970-01-01 00:00:00 +0000"}, + id="xoffbatt_missing", + ), pytest.param( MOCK_MINIMAL_STATUS | {"XOFFBATT": "N/A"}, "sensor.apc_ups_transfer_from_battery", From 86133d3af536cc0e87866337589de11987c3cf7f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 06:33:29 +0200 Subject: [PATCH 142/356] Show a connection error for an unsupported DSMR serial port URL (#184561) --- homeassistant/components/dsmr/config_flow.py | 3 ++- tests/components/dsmr/test_config_flow.py | 14 +++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/dsmr/config_flow.py b/homeassistant/components/dsmr/config_flow.py index 45b851ea1b1a..89ab0e4dda8e 100644 --- a/homeassistant/components/dsmr/config_flow.py +++ b/homeassistant/components/dsmr/config_flow.py @@ -10,6 +10,7 @@ from dsmr_parser.clients.protocol import create_dsmr_reader from dsmr_parser.clients.rfxtrx_protocol import create_rfxtrx_dsmr_reader from dsmr_parser.objects import DSMRObject import probatio +from serialx import SerialException from homeassistant.config_entries import ( ConfigEntry, @@ -120,7 +121,7 @@ class DSMRConnection: try: transport, protocol = await reader_factory() - except OSError: + except OSError, SerialException: LOGGER.exception("Error connecting to DSMR") return False diff --git a/tests/components/dsmr/test_config_flow.py b/tests/components/dsmr/test_config_flow.py index 4b5d323b03ad..034138fbbcec 100644 --- a/tests/components/dsmr/test_config_flow.py +++ b/tests/components/dsmr/test_config_flow.py @@ -6,6 +6,7 @@ from unittest.mock import DEFAULT, AsyncMock, MagicMock, patch from dsmr_parser.exceptions import DecryptionError import pytest +from serialx.common import UnknownUriScheme from homeassistant import config_entries from homeassistant.components.dsmr.config_flow import CannotCommunicate @@ -409,9 +410,20 @@ async def test_setup_serial_rfxtrx( assert result["data"] == {**entry_data, **SERIAL_DATA} +@pytest.mark.parametrize( + "exception", + [ + pytest.param(OSError, id="os_error"), + pytest.param( + UnknownUriScheme("No handler registered for URI scheme 'http://'"), + id="unknown_uri_scheme", + ), + ], +) async def test_setup_serial_fail( hass: HomeAssistant, dsmr_connection_send_validate_fixture: tuple[MagicMock, MagicMock, MagicMock], + exception: Exception | type[Exception], ) -> None: """Test failed serial connection.""" (_connection_factory, transport, protocol) = dsmr_connection_send_validate_fixture @@ -425,7 +437,7 @@ async def test_setup_serial_fail( # override the mock to have it fail the first time and succeed after first_fail_connection_factory = AsyncMock( return_value=(transport, protocol), - side_effect=chain([OSError], repeat(DEFAULT)), + side_effect=chain([exception], repeat(DEFAULT)), ) assert result["type"] is FlowResultType.FORM From f6e2b3f2aa9e571d53ca4736fe5c99b281530760 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 06:31:29 +0200 Subject: [PATCH 143/356] Accept form posts from Traccar Client in the Traccar webhook (#184562) --- homeassistant/components/traccar/__init__.py | 21 +++++++++------ tests/components/traccar/test_init.py | 28 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/traccar/__init__.py b/homeassistant/components/traccar/__init__.py index 85ab2b8a90e0..bfd8c56aa5e8 100644 --- a/homeassistant/components/traccar/__init__.py +++ b/homeassistant/components/traccar/__init__.py @@ -87,14 +87,19 @@ async def handle_webhook( ) -> web.Response: """Handle incoming webhook with Traccar Client request.""" if not (requestdata := dict(request.query)): - try: - requestdata = _parse_json_body(await request.json()) - except JSONDecodeError as error: - LOGGER.error("Error parsing JSON body: %s", error) - return web.Response( - text="Invalid JSON", - status=HTTPStatus.UNPROCESSABLE_ENTITY, - ) + # Traccar Client 10 posts its data as a form + if request.content_type == "application/x-www-form-urlencoded": + form = await request.post() + requestdata = {key: str(value) for key, value in form.items()} + else: + try: + requestdata = _parse_json_body(await request.json()) + except JSONDecodeError as error: + LOGGER.error("Error parsing JSON body: %s", error) + return web.Response( + text="Invalid JSON", + status=HTTPStatus.UNPROCESSABLE_ENTITY, + ) try: data = WEBHOOK_SCHEMA(requestdata) except probatio.MultipleInvalid as error: diff --git a/tests/components/traccar/test_init.py b/tests/components/traccar/test_init.py index bb264023c83b..5f278411d531 100644 --- a/tests/components/traccar/test_init.py +++ b/tests/components/traccar/test_init.py @@ -201,6 +201,34 @@ async def test_enter_with_attrs_as_query( assert state.attributes["altitude"] == 123 +async def test_enter_with_attrs_as_form( + hass: HomeAssistant, client: TestClient, webhook_id: str +) -> None: + """Test when the attributes are posted as a form, like Traccar Client 10 does.""" + url = f"/api/webhook/{webhook_id}" + data = { + "id": "123", + "lat": "1.0", + "lon": "1.1", + "timestamp": "1788110243", + "accuracy": "100.0", + "altitude": "88.0", + "batt": "77", + "speed": "0.0", + "bearing": "0.0", + } + + req = await client.post(url, data=data) + await hass.async_block_till_done() + assert req.status == HTTPStatus.OK + state = hass.states.get(f"{DEVICE_TRACKER_DOMAIN}.{data['id']}") + assert state.state == STATE_NOT_HOME + assert state.attributes["latitude"] == 1.0 + assert state.attributes["longitude"] == 1.1 + assert state.attributes["gps_accuracy"] == 100.0 + assert state.attributes["battery_level"] == 77.0 + + async def test_enter_with_attrs_as_payload( hass: HomeAssistant, client, webhook_id ) -> None: From d30556482eec69be34ca31632825d3e08bd4562a Mon Sep 17 00:00:00 2001 From: Michael Hansen Date: Tue, 6 Oct 2026 21:22:27 -0500 Subject: [PATCH 144/356] Bump intents to 2026.10.6 (#184563) Co-authored-by: Franck Nijhof --- homeassistant/components/conversation/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- requirements.txt | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/conversation/manifest.json b/homeassistant/components/conversation/manifest.json index 338ba7bb64fb..bb0e3e8dde94 100644 --- a/homeassistant/components/conversation/manifest.json +++ b/homeassistant/components/conversation/manifest.json @@ -9,6 +9,6 @@ "requirements": [ "gazetteer-matcher==1.1.0", "hassil==3.12.1", - "home-assistant-intents==2026.9.30" + "home-assistant-intents==2026.10.6" ] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 0c3c75b471a7..817486d0ebec 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -41,7 +41,7 @@ hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 home-assistant-frontend==20260930.1 -home-assistant-intents==2026.9.30 +home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 Jinja2==3.1.6 diff --git a/requirements.txt b/requirements.txt index d44315e35e8f..2bd1fe3f0a70 100644 --- a/requirements.txt +++ b/requirements.txt @@ -28,7 +28,7 @@ ha-ffmpeg==3.2.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-intents==2026.9.30 +home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 infrared-protocols==10.1.0 diff --git a/requirements_all.txt b/requirements_all.txt index 480ac216a523..40e2a64d8ab8 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1315,7 +1315,7 @@ holidays==0.106 home-assistant-frontend==20260930.1 # homeassistant.components.conversation -home-assistant-intents==2026.9.30 +home-assistant-intents==2026.10.6 # homeassistant.components.homekit homekit-audio-proxy==1.2.1 From 58f9940028e45b24c73e59c7bb3db4371ba49ffd Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:23:08 +0200 Subject: [PATCH 145/356] Apply the parse mode to Telegram media group captions (#184566) --- homeassistant/components/telegram_bot/bot.py | 16 ++++-- .../telegram_bot/test_telegram_bot.py | 55 +++++++++++++++++++ 2 files changed, 65 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/telegram_bot/bot.py b/homeassistant/components/telegram_bot/bot.py index e1d38b15a514..45813a1c620f 100644 --- a/homeassistant/components/telegram_bot/bot.py +++ b/homeassistant/components/telegram_bot/bot.py @@ -585,15 +585,20 @@ class TelegramNotificationService: ) _LOGGER.debug("downloaded: %s", entry.get(ATTR_URL) or entry.get(ATTR_FILE)) - caption: str | None = entry.get(ATTR_CAPTION) + # The parse mode of the media group itself only applies to a caption + # of the whole group, so each caption needs its own + caption_kwargs: dict[str, Any] = { + "caption": entry.get(ATTR_CAPTION), + "parse_mode": params[ATTR_PARSER], + } if entry[ATTR_MEDIA_TYPE] == InputMediaType.AUDIO: - media.append(InputMediaAudio(file_content, caption=caption)) + media.append(InputMediaAudio(file_content, **caption_kwargs)) elif entry[ATTR_MEDIA_TYPE] == InputMediaType.DOCUMENT: - media.append(InputMediaDocument(file_content, caption=caption)) + media.append(InputMediaDocument(file_content, **caption_kwargs)) elif entry[ATTR_MEDIA_TYPE] == InputMediaType.PHOTO: - media.append(InputMediaPhoto(file_content, caption=caption)) + media.append(InputMediaPhoto(file_content, **caption_kwargs)) else: - media.append(InputMediaVideo(file_content, caption=caption)) + media.append(InputMediaVideo(file_content, **caption_kwargs)) return await self._send_msg_formatted( self.bot.send_media_group, @@ -604,7 +609,6 @@ class TelegramNotificationService: protect_content=kwargs.get(ATTR_PROTECT_CONTENT, False), message_thread_id=params[ATTR_MESSAGE_THREAD_ID], reply_to_message_id=params[ATTR_REPLY_TO_MSGID], - parse_mode=params[ATTR_PARSER], context=context, ) diff --git a/tests/components/telegram_bot/test_telegram_bot.py b/tests/components/telegram_bot/test_telegram_bot.py index 0ecea74df54e..b7c3ba3ba2ec 100644 --- a/tests/components/telegram_bot/test_telegram_bot.py +++ b/tests/components/telegram_bot/test_telegram_bot.py @@ -2732,6 +2732,61 @@ async def test_send_media_group( } +async def test_send_media_group_caption_parse_mode( + hass: HomeAssistant, + mock_broadcast_config_entry: MockConfigEntry, + mock_external_calls: None, +) -> None: + """Test the parse mode applies to the captions of the media items.""" + mock_broadcast_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_broadcast_config_entry.entry_id) + await hass.async_block_till_done() + + with ( + patch( + "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get" + ) as mock_get, + patch( + "homeassistant.components.telegram_bot.bot.Bot.send_media_group", + AsyncMock( + return_value=[ + Message( + message_id=12345, + date=dt_util.utcnow(), + chat=Chat(id=123456, type=ChatType.PRIVATE), + ) + ] + ), + ) as mock_send_media_group, + ): + mock_get.return_value = AsyncMock(status_code=200, content=b"mock content") + + await hass.services.async_call( + DOMAIN, + SERVICE_SEND_MEDIA_GROUP, + { + ATTR_PARSER: PARSER_MD, + ATTR_MEDIA: [ + { + ATTR_MEDIA_TYPE: InputMediaType.PHOTO, + ATTR_URL: "https://mock/photo.jpg", + ATTR_CAPTION: "*bold*", + }, + { + ATTR_MEDIA_TYPE: InputMediaType.PHOTO, + ATTR_URL: "https://mock/photo2.jpg", + }, + ], + }, + blocking=True, + return_response=True, + ) + + media = mock_send_media_group.call_args.kwargs[ATTR_MEDIA] + assert media[0].caption == "*bold*" + assert media[0].parse_mode == PARSER_MD + + @pytest.mark.parametrize( "subdirectory", ["outside", "nested/deeper"], From d055cd67480e9ebd4d2dd9147c67e18db694c5c7 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:23:53 +0200 Subject: [PATCH 146/356] Set up Tractive trackers that have no position yet (#184567) --- homeassistant/components/tractive/__init__.py | 2 +- .../components/tractive/device_tracker.py | 10 +++-- .../tractive/test_device_tracker.py | 38 ++++++++++++++++++- 3 files changed, 44 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/tractive/__init__.py b/homeassistant/components/tractive/__init__.py index b0c65eea9185..63594c86ed64 100644 --- a/homeassistant/components/tractive/__init__.py +++ b/homeassistant/components/tractive/__init__.py @@ -61,7 +61,7 @@ class Trackables: trackable: dict[str, Any] tracker_details: dict[str, Any] hw_info: dict[str, Any] - pos_report: dict[str, Any] + pos_report: dict[str, Any] | None health_overview: dict[str, Any] diff --git a/homeassistant/components/tractive/device_tracker.py b/homeassistant/components/tractive/device_tracker.py index 0b3880152e96..236947e7f040 100644 --- a/homeassistant/components/tractive/device_tracker.py +++ b/homeassistant/components/tractive/device_tracker.py @@ -49,10 +49,12 @@ class TractiveDeviceTracker(TractiveEntity, TrackerEntity): f"{TRACKER_POSITION_UPDATED}-{item.tracker_details['_id']}", ) - self._attr_latitude = item.pos_report["latlong"][0] - self._attr_longitude = item.pos_report["latlong"][1] - self._attr_location_accuracy: float = item.pos_report["pos_uncertainty"] - self._source_type: str = item.pos_report["sensor_used"] + # A tracker that has been switched off for a while has no position + pos_report = item.pos_report or {} + if latlong := pos_report.get("latlong"): + self._attr_latitude, self._attr_longitude = latlong + self._attr_location_accuracy: float = pos_report.get("pos_uncertainty") or 0 + self._source_type: str | None = pos_report.get("sensor_used") self._attr_unique_id = item.trackable["_id"] @property diff --git a/tests/components/tractive/test_device_tracker.py b/tests/components/tractive/test_device_tracker.py index 8e3d818f5f17..9d22c0f24854 100644 --- a/tests/components/tractive/test_device_tracker.py +++ b/tests/components/tractive/test_device_tracker.py @@ -2,11 +2,12 @@ from unittest.mock import AsyncMock, patch +import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.components.device_tracker import SourceType from homeassistant.components.tractive.const import DOMAIN -from homeassistant.const import Platform +from homeassistant.const import STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er @@ -115,3 +116,38 @@ async def test_device_tracker_device_assignment( entry = entity_registry.async_get("device_tracker.tracker_device_id_123") assert entry is not None assert entry.device_id == tracker_device.id + + +@pytest.mark.parametrize( + "pos_report", + [ + pytest.param(None, id="none"), + pytest.param({}, id="empty"), + pytest.param( + {"latlong": None, "pos_uncertainty": None, "sensor_used": None}, + id="no_location", + ), + ], +) +async def test_device_tracker_without_position( + hass: HomeAssistant, + mock_tractive_client: AsyncMock, + mock_config_entry: MockConfigEntry, + pos_report: dict[str, None] | None, +) -> None: + """Test a tracker without a position, like a switched off one, is set up.""" + mock_tractive_client.tracker.return_value.pos_report.return_value = pos_report + with patch( + "homeassistant.components.tractive.PLATFORMS", [Platform.DEVICE_TRACKER] + ): + await init_integration(hass, mock_config_entry) + + state = hass.states.get("device_tracker.tracker_device_id_123") + assert state + assert state.state == STATE_UNKNOWN + + mock_tractive_client.send_position_event(mock_config_entry) + await hass.async_block_till_done() + + state = hass.states.get("device_tracker.tracker_device_id_123") + assert state.state != STATE_UNKNOWN From 521c9c331a236561255ddad2b1acdc103ddef687 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:24:25 +0200 Subject: [PATCH 147/356] Explain how to pair a Nanoleaf Skylight in the link step (#184569) --- homeassistant/components/nanoleaf/strings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/nanoleaf/strings.json b/homeassistant/components/nanoleaf/strings.json index 9744bf0dff32..e8daaab9da9b 100644 --- a/homeassistant/components/nanoleaf/strings.json +++ b/homeassistant/components/nanoleaf/strings.json @@ -14,7 +14,7 @@ "flow_title": "{name}", "step": { "link": { - "description": "Press and hold the power button on your Nanoleaf for 5 seconds until the button LEDs start flashing, then select **Submit** within 30 seconds.", + "description": "Press and hold the power button on your Nanoleaf for 5 seconds until the button LEDs start flashing. For devices without a power button, such as the Skylight, select **Connect to API** in the device settings of the Nanoleaf app instead. Then select **Submit** within 30 seconds.", "title": "Link Nanoleaf" }, "user": { From f41a0ccc9988d05e96ea07f6fbbd1ae626275e68 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:24:54 +0200 Subject: [PATCH 148/356] Quote the credentials in the Freebox camera stream URL (#184572) --- homeassistant/components/freebox/camera.py | 20 +++++++++++- tests/components/freebox/test_camera.py | 37 ++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/freebox/camera.py b/homeassistant/components/freebox/camera.py index cd54c8c99376..1e9471994035 100644 --- a/homeassistant/components/freebox/camera.py +++ b/homeassistant/components/freebox/camera.py @@ -1,6 +1,7 @@ """Support for Freebox cameras.""" from typing import Any, override +from urllib.parse import quote from aiohttp import web from haffmpeg.camera import CameraMjpeg @@ -62,6 +63,23 @@ def add_entities( async_add_entities(new_tracked, True) +def _quote_credentials(url: str) -> str: + """Quote the credentials in a stream URL. + + The Freebox generates the camera password, which can contain characters like + a slash that break parsing the URL if they are not percent-encoded. + """ + scheme, separator, rest = url.partition("://") + credentials, at_sign, location = rest.rpartition("@") + if not separator or not at_sign: + return url + + user, colon, password = credentials.partition(":") + return ( + f"{scheme}://{quote(user, safe='')}{colon}{quote(password, safe='')}@{location}" + ) + + class FreeboxCamera(FreeboxHomeEntity, Camera): """Representation of a Freebox camera.""" @@ -87,7 +105,7 @@ class FreeboxCamera(FreeboxHomeEntity, Camera): @override async def stream_source(self) -> str: """Return the stream source.""" - return self._input.split(" ")[-1] + return _quote_credentials(self._input.split(" ")[-1]) @override async def async_camera_image( diff --git a/tests/components/freebox/test_camera.py b/tests/components/freebox/test_camera.py index fc72b8ce5db9..b621f3f7f7d4 100644 --- a/tests/components/freebox/test_camera.py +++ b/tests/components/freebox/test_camera.py @@ -4,11 +4,13 @@ from copy import deepcopy from unittest.mock import Mock from freezegun.api import FrozenDateTimeFactory +import pytest from homeassistant.components.camera import ( DOMAIN as CAMERA_DOMAIN, SERVICE_DISABLE_MOTION, SERVICE_ENABLE_MOTION, + async_get_stream_source, ) from homeassistant.components.freebox import SCAN_INTERVAL from homeassistant.components.freebox.const import DOMAIN @@ -115,3 +117,38 @@ async def test_motion_detection_toggle( blocking=True, ) router().home.set_home_endpoint_value.assert_called_with(15, 0, {"value": True}) + + +@pytest.mark.parametrize( + ("stream", "expected_source"), + [ + pytest.param( + "http://freeboxcam:AaaA/1A1@192.168.1.10/img/stream.m3u8", + "http://freeboxcam:AaaA%2F1A1@192.168.1.10/img/stream.m3u8", + id="slash_in_password", + ), + pytest.param( + "http://freeboxcam:Aa%1A@192.168.1.10/img/stream.m3u8", + "http://freeboxcam:Aa%251A@192.168.1.10/img/stream.m3u8", + id="percent_in_password", + ), + pytest.param( + "http://freeboxcam:AaaA1A1@192.168.1.10/img/stream.m3u8", + "http://freeboxcam:AaaA1A1@192.168.1.10/img/stream.m3u8", + id="plain_password", + ), + ], +) +async def test_stream_source_quotes_credentials( + hass: HomeAssistant, router: Mock, stream: str, expected_source: str +) -> None: + """Test the stream source has the credentials generated by the Freebox quoted.""" + nodes = deepcopy(DATA_HOME_GET_NODES) + for node in nodes: + if node["id"] == 15: # Caméra I from fixture + node["props"]["Stream"] = stream + break + router().home.get_home_nodes.return_value = nodes + await setup_platform(hass, CAMERA_DOMAIN) + + assert await async_get_stream_source(hass, "camera.camera_i") == expected_source From ca59bd27975b47c537fe1d8cb8fc6f295dcd2a0c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:26:55 +0200 Subject: [PATCH 149/356] Keep a TTS stream available once its message is set (#184574) --- homeassistant/components/tts/__init__.py | 15 ++++++ tests/components/tts/test_init.py | 64 +++++++++++++++++++++++- 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index fc5fe4ffe23c..4dff1e456f0f 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -510,6 +510,18 @@ class ResultStream: """Get the future that returns the cache.""" return asyncio.Future() + @callback + def _async_mark_used(self) -> None: + """Keep the stream available now that its result is about to be used. + + A pipeline creates its stream when the run starts, for example before + waiting for a wake word, which can be longer ago than the memory cache + keeps an unused stream around. + """ + self.last_used = monotonic() + self._manager.token_to_stream[self.token] = self + self._manager.token_to_stream_cleanup.schedule() + @callback def async_set_message(self, message: str) -> None: """Set message to be generated. @@ -518,6 +530,7 @@ class ResultStream: """ if self._result_cache.done(): return + self._async_mark_used() self._result_cache.set_result( self._manager.async_cache_message_in_memory( engine=self.engine, @@ -536,6 +549,7 @@ class ResultStream: """ if self._result_cache.done(): return + self._async_mark_used() self._result_cache.set_result( self._manager.async_cache_message_stream_in_memory( engine=self.engine, @@ -563,6 +577,7 @@ class ResultStream: def async_override_result(self, media_path: str | Path) -> None: """Override the TTS stream with a different media path.""" + self._async_mark_used() self._override_media_path = Path(media_path) @property diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py index 3382c63f69b0..32f665268bb5 100644 --- a/tests/components/tts/test_init.py +++ b/tests/components/tts/test_init.py @@ -1,7 +1,7 @@ """The tests for the TTS component.""" import asyncio -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, Callable from http import HTTPStatus import io from pathlib import Path @@ -25,6 +25,7 @@ from homeassistant.components.media_player import ( MediaType, ) from homeassistant.components.tts import DOMAIN +from homeassistant.components.tts.const import DEFAULT_TIME_MEMORY from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN from homeassistant.core import HomeAssistant @@ -48,6 +49,7 @@ from .common import ( from tests.common import ( MockModule, + async_fire_time_changed, async_mock_service, load_fixture_bytes, mock_integration, @@ -2084,6 +2086,66 @@ async def test_stream(hass: HomeAssistant, mock_tts_entity: MockTTSEntity) -> No assert result_data == data +async def _message_stream() -> AsyncGenerator[str]: + """Stream a message.""" + yield "beer" + + +@pytest.mark.parametrize( + "set_message", + [ + pytest.param(lambda stream: stream.async_set_message("beer"), id="message"), + pytest.param( + lambda stream: stream.async_set_message_stream(_message_stream()), + id="message_stream", + ), + ], +) +async def test_stream_set_message_after_memory_cache_age( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_tts_entity: MockTTSEntity, + set_message: Callable[[tts.ResultStream], None], +) -> None: + """Test a stream created long before its message is set can still be fetched. + + A pipeline creates its stream when the run starts, for example before + waiting for the wake word, which can be long before the message is known. + """ + await mock_config_entry_setup(hass, mock_tts_entity) + stream = tts.async_create_stream(hass, mock_tts_entity.entity_id) + + freezer.tick(DEFAULT_TIME_MEMORY + 2) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + set_message(stream) + + assert tts.async_get_stream(hass, stream.token) is stream + result_data = b"".join([chunk async for chunk in stream.async_stream_result()]) + assert result_data + + +async def test_stream_override_result_after_memory_cache_age( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_tts_entity: MockTTSEntity, + tmp_path: Path, +) -> None: + """Test a stream overridden long after it was created can still be fetched.""" + await mock_config_entry_setup(hass, mock_tts_entity) + stream = tts.async_create_stream(hass, mock_tts_entity.entity_id) + + freezer.tick(DEFAULT_TIME_MEMORY + 2) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + # The Assist pipeline overrides the result for its local acknowledgment + stream.async_override_result(tmp_path / "acknowledge.mp3") + + assert tts.async_get_stream(hass, stream.token) is stream + + async def test_result_stream_message_set_idempotent( hass: HomeAssistant, mock_tts_entity: MockTTSEntity ) -> None: From 93f8145ea6ddd2beb4da496f6975fbde88cb5fb8 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 01:16:50 +0200 Subject: [PATCH 150/356] Wait for the ESPHome assist satellite platform before finishing setup (#184575) --- homeassistant/components/esphome/manager.py | 5 +- tests/components/esphome/test_manager.py | 53 +++++++++++++++++++++ 2 files changed, 56 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 0bf49f3585a6..46ec6540d4e2 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -765,8 +765,6 @@ class ESPHomeManager: hass, device_info.bluetooth_mac_address or device_info.mac_address ) - entry_data.first_connect_done.set() - if device_info.voice_assistant_feature_flags_compat(api_version) and ( Platform.ASSIST_SATELLITE not in entry_data.loaded_platforms ): @@ -776,6 +774,9 @@ class ESPHomeManager: ) entry_data.loaded_platforms.add(Platform.ASSIST_SATELLITE) + # Setup can wait for this, so only after the platforms are forwarded + entry_data.first_connect_done.set() + if device_info.zwave_proxy_feature_flags: entry_data.disconnect_callbacks.add( cli.subscribe_zwave_proxy_request(self._async_zwave_proxy_request) diff --git a/tests/components/esphome/test_manager.py b/tests/components/esphome/test_manager.py index a8ae67b2fafc..c7cf4eae894d 100644 --- a/tests/components/esphome/test_manager.py +++ b/tests/components/esphome/test_manager.py @@ -38,6 +38,7 @@ from aioesphomeapi import ( UserService, UserServiceArg, UserServiceArgType, + VoiceAssistantFeature, ZWaveProxyRequest, ZWaveProxyRequestType, build_device_unique_id, @@ -77,6 +78,7 @@ from homeassistant.const import ( STATE_ON, STATE_UNAVAILABLE, STATE_UNKNOWN, + Platform, ) from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse from homeassistant.data_entry_flow import FlowResultType @@ -4703,6 +4705,57 @@ async def test_bluetooth_proxy_waits_for_scanner_at_startup( assert entry.runtime_data.first_connect_done.is_set() +@pytest.mark.usefixtures("mock_zeroconf") +async def test_bluetooth_proxy_with_voice_assistant_awaits_forward( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + mock_client: APIClient, + hass_storage: dict[str, Any], +) -> None: + """Test setup waits for the assist satellite platform of a bluetooth proxy.""" + entry, device_info = _create_cached_bluetooth_proxy_entry( + hass, hass_storage, BluetoothProxyFeature.PASSIVE_SCAN + ) + device_info = DeviceInfo( + **{ + **device_info.to_dict(), + "voice_assistant_feature_flags": VoiceAssistantFeature.VOICE_ASSISTANT, + } + ) + connect_event = asyncio.Event() + reached_connect = asyncio.Event() + + async def _block_until_released() -> tuple[DeviceInfo, list[Any], list[Any]]: + reached_connect.set() + await connect_event.wait() + return (device_info, [], []) + + mock_client.device_info_and_list_entities = _block_until_released + + async def _slow_satellite_setup(*args: Any) -> None: + """Take a moment to set up, like a real assist satellite.""" + await asyncio.sleep(0.01) + + # Connect only once setup is waiting for the scanner, like at startup + with patch( + "homeassistant.components.esphome.assist_satellite.async_setup_entry", + _slow_satellite_setup, + ): + setup_task = hass.async_create_task( + hass.config_entries.async_setup(entry.entry_id) + ) + async with asyncio.timeout(2): + await reached_connect.wait() + connect_event.set() + async with asyncio.timeout(2): + assert await setup_task is True + # The connection runs outside of the tasks Home Assistant tracks + while Platform.ASSIST_SATELLITE not in entry.runtime_data.loaded_platforms: + await asyncio.sleep(0.01) + + assert "without awaiting async_forward_entry_setups" not in caplog.text + + @pytest.mark.usefixtures("mock_zeroconf") async def test_bluetooth_proxy_startup_wait_times_out( hass: HomeAssistant, From 3fe17fc4d2cbbb5953d69f4fe863651f0042d233 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 06:45:50 +0200 Subject: [PATCH 151/356] Pass the Freebox home node firmware version as a string (#184577) --- homeassistant/components/freebox/entity.py | 4 +++- .../components/freebox/test_binary_sensor.py | 20 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/freebox/entity.py b/homeassistant/components/freebox/entity.py index ddc694014e9e..af6110d846c1 100644 --- a/homeassistant/components/freebox/entity.py +++ b/homeassistant/components/freebox/entity.py @@ -36,7 +36,9 @@ class FreeboxHomeEntity(Entity): self._attr_unique_id += "-" + sub_node["name"].strip() self._available = True - self._firmware = node["props"].get("FwVersion") + # The Freebox reports the firmware version of home nodes as a number + firmware = node["props"].get("FwVersion") + self._firmware = str(firmware) if firmware is not None else None self._manufacturer = "Freebox SAS" self._model = CATEGORY_TO_MODEL.get(node["category"]) diff --git a/tests/components/freebox/test_binary_sensor.py b/tests/components/freebox/test_binary_sensor.py index 593b3cd9c287..1b66870d0647 100644 --- a/tests/components/freebox/test_binary_sensor.py +++ b/tests/components/freebox/test_binary_sensor.py @@ -11,8 +11,10 @@ from homeassistant.components.binary_sensor import ( BinarySensorDeviceClass, ) from homeassistant.components.freebox import SCAN_INTERVAL +from homeassistant.components.freebox.const import DOMAIN from homeassistant.const import ATTR_DEVICE_CLASS from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr from .common import setup_platform from .const import DATA_HOME_PIR_GET_VALUE, DATA_STORAGE_GET_RAIDS @@ -89,3 +91,21 @@ async def test_home( assert hass.states.get("binary_sensor.detecteur_cover").state == "on" assert hass.states.get("binary_sensor.ouverture_porte").state == "off" assert hass.states.get("binary_sensor.ouverture_porte_cover").state == "on" + + +@pytest.mark.usefixtures("router") +async def test_home_node_firmware_version( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + device_registry: dr.DeviceRegistry, +) -> None: + """Test the firmware version of a home node is passed as a string.""" + entry = await setup_platform(hass, BINARY_SENSOR_DOMAIN) + + # The PIR detector from the fixture reports its firmware version as a number + device = device_registry.async_get_device_by_identifier( + (DOMAIN, 26), entry.entry_id + ) + assert device is not None + assert device.sw_version == "29871925" + assert "non-string value" not in caplog.text From e2aebfe238ff766b8d2e17d962fe353451dfbfc2 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 04:34:43 +0200 Subject: [PATCH 152/356] Handle errors in the periodic Freebox update (#184578) --- homeassistant/components/freebox/__init__.py | 21 +++++++++++++-- .../components/freebox/test_device_tracker.py | 27 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/freebox/__init__.py b/homeassistant/components/freebox/__init__.py index f2804665ac9d..6b761519f884 100644 --- a/homeassistant/components/freebox/__init__.py +++ b/homeassistant/components/freebox/__init__.py @@ -1,6 +1,6 @@ """Support for Freebox devices (Freebox v6 and Freebox mini 4K).""" -from datetime import timedelta +from datetime import datetime, timedelta import logging from aiohttp import ClientError @@ -92,8 +92,25 @@ async def async_setup_entry(hass: HomeAssistant, entry: FreeboxConfigEntry) -> b except (HttpRequestError, ClientError, TimeoutError) as err: raise ConfigEntryNotReady from err + update_failed = False + + async def _async_update_all(now: datetime) -> None: + """Update the router, logging a failure once until it recovers.""" + nonlocal update_failed + try: + await router.update_all() + except (HttpRequestError, ClientError, TimeoutError) as err: + if not update_failed: + _LOGGER.warning("Error updating the Freebox: %r", err) + update_failed = True + return + + if update_failed: + _LOGGER.info("Updating the Freebox works again") + update_failed = False + entry.async_on_unload( - async_track_time_interval(hass, router.update_all, SCAN_INTERVAL) + async_track_time_interval(hass, _async_update_all, SCAN_INTERVAL) ) entry.runtime_data = router diff --git a/tests/components/freebox/test_device_tracker.py b/tests/components/freebox/test_device_tracker.py index f0821daabc32..356dff1fdcaa 100644 --- a/tests/components/freebox/test_device_tracker.py +++ b/tests/components/freebox/test_device_tracker.py @@ -3,6 +3,7 @@ from unittest.mock import Mock from freezegun.api import FrozenDateTimeFactory +import pytest from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN from homeassistant.components.freebox import SCAN_INTERVAL @@ -48,3 +49,29 @@ async def test_bridge_mode( # If get_interfaces failed, not called again assert router_bridge_mode().lan.get_interfaces.call_count == 1 + + +async def test_update_timeout( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, + router: Mock, +) -> None: + """Test a failing periodic update is logged once and recovers.""" + await setup_platform(hass, DEVICE_TRACKER_DOMAIN) + + router().lan.get_hosts_list.side_effect = TimeoutError + for _ in range(2): + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert "Task exception was never retrieved" not in caplog.text + assert caplog.text.count("Error updating the Freebox") == 1 + + router().lan.get_hosts_list.side_effect = None + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert "Updating the Freebox works again" in caplog.text From 4e998d313c271e3806906529575196d2ad65a445 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 06:51:34 +0200 Subject: [PATCH 153/356] =?UTF-8?q?Keep=20the=20Lutron=20Cas=C3=A9ta=20bri?= =?UTF-8?q?dge=20connected=20on=20an=20unmapped=20button=20number=20(#1845?= =?UTF-8?q?79)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/lutron_caseta/__init__.py | 7 ++-- .../lutron_caseta/test_device_trigger.py | 32 +++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/lutron_caseta/__init__.py b/homeassistant/components/lutron_caseta/__init__.py index 8171dd04e4b5..e1c566973501 100644 --- a/homeassistant/components/lutron_caseta/__init__.py +++ b/homeassistant/components/lutron_caseta/__init__.py @@ -438,7 +438,10 @@ def async_get_lip_button(device_type: str, leap_button: int) -> int | None: leap_button_num_to_name := LEAP_TO_DEVICE_TYPE_SUBTYPE_MAP.get(device_type) ) is None: return None - return lip_buttons_name_to_num[leap_button_num_to_name[leap_button]] + # Some devices report button numbers their mapping doesn't list + if (button_name := leap_button_num_to_name.get(leap_button)) is None: + return None + return lip_buttons_name_to_num.get(button_name) @callback @@ -473,7 +476,7 @@ def _async_subscribe_keypad_events( lip_button_number = async_get_lip_button(keypad_type, leap_button_number) button_type = LEAP_TO_DEVICE_TYPE_SUBTYPE_MAP.get( keypad_type, leap_to_keypad_button_names[keypad_device_id] - )[leap_button_number] + ).get(leap_button_number) hass.bus.async_fire( LUTRON_CASETA_BUTTON_EVENT, diff --git a/tests/components/lutron_caseta/test_device_trigger.py b/tests/components/lutron_caseta/test_device_trigger.py index 7015e4540954..1f275325e320 100644 --- a/tests/components/lutron_caseta/test_device_trigger.py +++ b/tests/components/lutron_caseta/test_device_trigger.py @@ -1,5 +1,6 @@ """The tests for Lutron Caséta device triggers.""" +from pylutron_caseta import BUTTON_STATUS_PRESSED import pytest from pytest_unordered import unordered @@ -14,7 +15,9 @@ from homeassistant.components.lutron_caseta import ( ) from homeassistant.components.lutron_caseta.const import ( ACTION_LONG_PRESS, + ACTION_PRESS, ACTION_RELEASE, + ATTR_BUTTON_NUMBER, ATTR_BUTTON_TYPE, ATTR_LEAP_BUTTON_NUMBER, BUTTON_STATUS_LONG_HOLD, @@ -407,6 +410,35 @@ async def test_unknown_leap_event_type_maps_to_release_action( assert captured[0].data[ATTR_ACTION] == ACTION_RELEASE +class MockUnknownButtonBridge(MockBridge): + """Mock bridge with a button number its keypad type doesn't list.""" + + def load_buttons(self): + """Load mock buttons with an unknown button number.""" + buttons = super().load_buttons() + buttons["111"]["button_number"] = 26 + return buttons + + +async def test_unknown_leap_button_number_fires_event( + hass: HomeAssistant, +) -> None: + """Test a button number missing from the keypad mapping still fires an event.""" + config_entry_id = await _async_setup_lutron_with_picos( + hass, MockUnknownButtonBridge + ) + bridge = hass.config_entries.async_get_entry(config_entry_id).runtime_data.bridge + captured = async_capture_events(hass, LUTRON_CASETA_BUTTON_EVENT) + + bridge.call_button_subscribers("111", BUTTON_STATUS_PRESSED) + await hass.async_block_till_done() + + assert len(captured) == 1 + assert captured[0].data[ATTR_LEAP_BUTTON_NUMBER] == 26 + assert captured[0].data[ATTR_BUTTON_NUMBER] is None + assert captured[0].data[ATTR_ACTION] == ACTION_PRESS + + async def test_if_fires_on_button_event_without_lip( hass: HomeAssistant, service_calls: list[ServiceCall], From 86dc71e108c13291c8ccd0b2271fc6697b723790 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:10:07 +0200 Subject: [PATCH 154/356] Create an Apple TV entry for a device that was ignored before (#184580) --- .../components/apple_tv/config_flow.py | 5 ++-- tests/components/apple_tv/test_config_flow.py | 27 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/apple_tv/config_flow.py b/homeassistant/components/apple_tv/config_flow.py index 06a7443ad324..6ad8d1512f31 100644 --- a/homeassistant/components/apple_tv/config_flow.py +++ b/homeassistant/components/apple_tv/config_flow.py @@ -619,8 +619,9 @@ class AppleTVConfigFlow(ConfigFlow, domain=DOMAIN): self.device_identifier, raise_on_progress=False ) - # If an existing config entry is updated, then this was a re-auth - if existing_entry: + # If an existing config entry is updated, then this was a re-auth. An + # ignored entry is replaced by the new entry instead. + if existing_entry and existing_entry.source != SOURCE_IGNORE: return self.async_update_reload_and_abort( existing_entry, data=data, unique_id=self.unique_id ) diff --git a/tests/components/apple_tv/test_config_flow.py b/tests/components/apple_tv/test_config_flow.py index d896cd59f3ab..edf47df63497 100644 --- a/tests/components/apple_tv/test_config_flow.py +++ b/tests/components/apple_tv/test_config_flow.py @@ -178,6 +178,33 @@ async def test_user_pair_leading_zero_pin( assert result["type"] is FlowResultType.CREATE_ENTRY +@pytest.mark.usefixtures("mrp_device", "pairing") +async def test_user_adds_previously_ignored_device(hass: HomeAssistant) -> None: + """Test adding a device that was ignored before creates an entry.""" + MockConfigEntry( + domain=DOMAIN, + unique_id="mrpid", + source=config_entries.SOURCE_IGNORE, + ).add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + await hass.config_entries.flow.async_configure( + result["flow_id"], + {"device_input": "MRP Device"}, + ) + result = await hass.config_entries.flow.async_configure(result["flow_id"], {}) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], {"pin": "1111"} + ) + assert result["type"] is FlowResultType.CREATE_ENTRY + + entries = hass.config_entries.async_entries(DOMAIN, include_ignore=True) + assert len(entries) == 1 + assert entries[0].source == config_entries.SOURCE_USER + + @pytest.mark.usefixtures("mrp_device") @pytest.mark.parametrize("invalid_pin", ["abcd", "12ab", "١٢٣٤", "123\n"]) async def test_user_pair_non_numeric_pin( From cd62845e3af763a668310db3ef9cc02a37ff914b Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:11:02 +0200 Subject: [PATCH 155/356] Don't parse the Pushsafer response just to log it (#184581) --- homeassistant/components/pushsafer/notify.py | 2 +- tests/components/pushsafer/__init__.py | 1 + tests/components/pushsafer/test_notify.py | 45 ++++++++++++++++++++ 3 files changed, 47 insertions(+), 1 deletion(-) create mode 100644 tests/components/pushsafer/__init__.py create mode 100644 tests/components/pushsafer/test_notify.py diff --git a/homeassistant/components/pushsafer/notify.py b/homeassistant/components/pushsafer/notify.py index 0e88168cb1d2..1f1f486dd72e 100644 --- a/homeassistant/components/pushsafer/notify.py +++ b/homeassistant/components/pushsafer/notify.py @@ -136,7 +136,7 @@ class PushsaferNotificationService(BaseNotificationService): if response.status_code != HTTPStatus.OK: _LOGGER.error("Pushsafer failed with: %s", response.text) else: - _LOGGER.debug("Push send: %s", response.json()) + _LOGGER.debug("Push send: %s", response.text) @classmethod def get_base64(cls, filebyte, mimetype): diff --git a/tests/components/pushsafer/__init__.py b/tests/components/pushsafer/__init__.py new file mode 100644 index 000000000000..90f9304ccca5 --- /dev/null +++ b/tests/components/pushsafer/__init__.py @@ -0,0 +1 @@ +"""Tests for the Pushsafer integration.""" diff --git a/tests/components/pushsafer/test_notify.py b/tests/components/pushsafer/test_notify.py new file mode 100644 index 000000000000..a32918a4dac8 --- /dev/null +++ b/tests/components/pushsafer/test_notify.py @@ -0,0 +1,45 @@ +"""Tests for the Pushsafer notify platform.""" + +from http import HTTPStatus +from unittest.mock import patch + +import requests + +from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + + +def _response(body: bytes) -> requests.Response: + """Return a Pushsafer API response.""" + response = requests.Response() + response.status_code = HTTPStatus.OK + response._content = body + return response + + +async def test_send_message_with_unparsable_response(hass: HomeAssistant) -> None: + """Test a sent message doesn't fail on a response that isn't a single JSON object.""" + assert await async_setup_component( + hass, + NOTIFY_DOMAIN, + { + NOTIFY_DOMAIN: [ + {"platform": "pushsafer", "name": "pushsafer", "private_key": "key"} + ] + }, + ) + await hass.async_block_till_done() + + # Pushsafer can answer with more than one JSON object in a single response + with patch( + "homeassistant.components.pushsafer.notify.requests.post", + return_value=_response( + b'{"status":1,"success":"message transmitted"}{"available":{"a":{"x":"y"}}}' + ), + ) as mock_post: + await hass.services.async_call( + NOTIFY_DOMAIN, "pushsafer", {"message": "Hello"}, blocking=True + ) + + mock_post.assert_called_once() From 10cf2c8b9d3b18f9fdeb0bab4616c408663968f1 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:12:03 +0200 Subject: [PATCH 156/356] Show a connection error when the Automower BLE device info can't be read (#184585) --- .../husqvarna_automower_ble/config_flow.py | 5 +++++ .../husqvarna_automower_ble/test_config_flow.py | 14 ++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/husqvarna_automower_ble/config_flow.py b/homeassistant/components/husqvarna_automower_ble/config_flow.py index 6757ee2a67f7..1eb09d7c4412 100644 --- a/homeassistant/components/husqvarna_automower_ble/config_flow.py +++ b/homeassistant/components/husqvarna_automower_ble/config_flow.py @@ -170,6 +170,11 @@ class HusqvarnaAutomowerBleConfigFlow(ConfigFlow, domain=DOMAIN): LOGGER.exception("Failed to probe device (%s): %s", self.address, exception) return None + # The library returns None for the values it couldn't read + if manufacturer is None or device_type is None: + LOGGER.debug("Failed to read the device info of %s", self.address) + return None + title = manufacturer + " " + device_type LOGGER.debug("Found device: %s", title) diff --git a/tests/components/husqvarna_automower_ble/test_config_flow.py b/tests/components/husqvarna_automower_ble/test_config_flow.py index e44a5e988a4c..5ca6af886c76 100644 --- a/tests/components/husqvarna_automower_ble/test_config_flow.py +++ b/tests/components/husqvarna_automower_ble/test_config_flow.py @@ -537,16 +537,26 @@ async def test_duplicate_entry( assert result["reason"] == "already_configured" +@pytest.mark.parametrize( + "probe_side_effect", + [ + pytest.param(BleakError, id="bleak_error"), + # The library returns None for the values it failed to read + pytest.param([(None, "Automower", "305")], id="no_manufacturer"), + pytest.param([("Husqvarna", None, "305")], id="no_device_type"), + ], +) async def test_exception_probe( hass: HomeAssistant, mock_automower_client: Mock, + probe_side_effect: type[Exception] | list[tuple[str | None, str | None, str]], ) -> None: - """Test we can select a device.""" + """Test a failing probe shows an error.""" inject_bluetooth_service_info(hass, AUTOMOWER_UNNAMED_SERVICE_INFO) await hass.async_block_till_done(wait_background_tasks=True) - mock_automower_client.probe_gatts.side_effect = BleakError + mock_automower_client.probe_gatts.side_effect = probe_side_effect result = hass.config_entries.flow.async_progress_by_handler(DOMAIN)[0] assert result["step_id"] == "bluetooth_confirm" From 81528ce5e3e5bce2ecb3e10494253e02cb799913 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:13:01 +0200 Subject: [PATCH 157/356] Clarify that the trigger behavior repair only applies to triggers (#184586) --- homeassistant/components/homeassistant/strings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/homeassistant/strings.json b/homeassistant/components/homeassistant/strings.json index 8979ef33c6e0..78825455c095 100644 --- a/homeassistant/components/homeassistant/strings.json +++ b/homeassistant/components/homeassistant/strings.json @@ -168,7 +168,7 @@ "title": "The {integration_title} integration is being removed" }, "deprecated_trigger_behavior": { - "description": "An automation, script or template entity uses the trigger behavior option `{deprecated_behavior}`, which has been renamed to `{new_behavior}`. The old value still works for now, but support for it will be removed in a future release.\n\nTo fix this issue, open each affected automation or script in the editor and save it again; Home Assistant will automatically detect and update the deprecated option. Alternatively, edit your configuration files (for example `automations.yaml`) directly and change `behavior: {deprecated_behavior}` to `behavior: {new_behavior}`. Restart Home Assistant afterwards.", + "description": "An automation, script or template entity uses the trigger behavior option `{deprecated_behavior}`, which has been renamed to `{new_behavior}`. The old value still works for now, but support for it will be removed in a future release.\n\nTo fix this issue, open each affected automation or script in the editor and save it again; Home Assistant will automatically detect and update the deprecated option. Alternatively, edit your configuration files (for example `automations.yaml`) directly and change `behavior: {deprecated_behavior}` to `behavior: {new_behavior}` in the options of your triggers. Leave the `behavior` option of conditions unchanged, as conditions still use `any` and `all`. Restart Home Assistant afterwards.", "title": "Deprecated trigger behavior option in use" }, "deprecated_yaml": { From a2a8c641c22afcc2a11217f264e8a51710750223 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:14:19 +0200 Subject: [PATCH 158/356] Allow the GoodWe export limit up to the inverter's rated power (#184587) --- homeassistant/components/goodwe/number.py | 6 +++ tests/components/goodwe/test_number.py | 54 +++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 tests/components/goodwe/test_number.py diff --git a/homeassistant/components/goodwe/number.py b/homeassistant/components/goodwe/number.py index 51b7729a4c86..0bd69be3836a 100644 --- a/homeassistant/components/goodwe/number.py +++ b/homeassistant/components/goodwe/number.py @@ -129,6 +129,12 @@ class InverterNumberEntity(NumberEntity): self._attr_device_info = device_info self._attr_native_value = float(current_value) self._inverter: Inverter = inverter + # Larger inverters can export more than the default maximum; inverter + # families that don't report their rated power leave it at 0 + if description.native_unit_of_measurement == UnitOfPower.WATT: + self._attr_native_max_value = max( + description.native_max_value, inverter.rated_power + ) async def async_update(self) -> None: """Get the current value from inverter.""" diff --git a/tests/components/goodwe/test_number.py b/tests/components/goodwe/test_number.py new file mode 100644 index 000000000000..e9f846475e2f --- /dev/null +++ b/tests/components/goodwe/test_number.py @@ -0,0 +1,54 @@ +"""Test the GoodWe number platform.""" + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from homeassistant.components.goodwe import CONF_MODEL_FAMILY, DOMAIN +from homeassistant.components.number import ATTR_MAX +from homeassistant.const import CONF_HOST, CONF_PORT, Platform +from homeassistant.core import HomeAssistant +from homeassistant.helpers import entity_registry as er + +from .conftest import TEST_HOST, TEST_PORT, TEST_SERIAL + +from tests.common import MockConfigEntry + + +@pytest.mark.parametrize( + ("rated_power", "expected_max"), + [ + pytest.param(29900, 29900, id="above_default_max"), + pytest.param(5000, 10000, id="below_default_max"), + ], +) +async def test_grid_export_limit_max( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_inverter: MagicMock, + rated_power: int, + expected_max: int, +) -> None: + """Test the export limit in watts goes up to the rated power of the inverter.""" + mock_inverter.rated_power = rated_power + mock_inverter.settings.return_value = [] + mock_inverter.get_grid_export_limit = AsyncMock(return_value=14400) + mock_inverter.get_ongrid_battery_dod = AsyncMock(return_value=50) + config_entry = MockConfigEntry( + version=2, + domain=DOMAIN, + data={CONF_HOST: TEST_HOST, CONF_PORT: TEST_PORT, CONF_MODEL_FAMILY: "ET"}, + ) + config_entry.add_to_hass(hass) + + with patch("homeassistant.components.goodwe.PLATFORMS", [Platform.NUMBER]): + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + entity_id = entity_registry.async_get_entity_id( + Platform.NUMBER, DOMAIN, f"{DOMAIN}-grid_export_limit-{TEST_SERIAL}" + ) + assert entity_id + state = hass.states.get(entity_id) + assert state + assert state.attributes[ATTR_MAX] == expected_max From a7d01ba6e3db272e6ca1d9991ccd32105fd4f39c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:15:18 +0200 Subject: [PATCH 159/356] Raise a translated error when an Apple TV command fails (#184588) --- .../components/apple_tv/media_player.py | 41 +++++++++++++++- .../components/apple_tv/strings.json | 3 ++ .../components/apple_tv/test_media_player.py | 49 ++++++++++++++++++- 3 files changed, 91 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/apple_tv/media_player.py b/homeassistant/components/apple_tv/media_player.py index d905b3214bde..3f2df8996da1 100644 --- a/homeassistant/components/apple_tv/media_player.py +++ b/homeassistant/components/apple_tv/media_player.py @@ -1,8 +1,10 @@ """Support for Apple TV media player.""" +from collections.abc import Callable, Coroutine from datetime import datetime +from functools import wraps import logging -from typing import Any, override +from typing import Any, Concatenate, override from pyatv import exceptions from pyatv.const import ( @@ -110,6 +112,31 @@ async def async_setup_entry( async_add_entities([AppleTvMediaPlayer(name, config_entry.unique_id, manager)]) +def _catch_command_errors[_T: AppleTvMediaPlayer, **_P]( + func: Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]], +) -> Callable[Concatenate[_T, _P], Coroutine[Any, Any, None]]: + """Raise a HomeAssistantError when a command can't be sent to the Apple TV.""" + + @wraps(func) + async def wrapper(self: _T, *args: _P.args, **kwargs: _P.kwargs) -> None: + try: + await func(self, *args, **kwargs) + except ( + TimeoutError, + exceptions.BlockedStateError, + exceptions.ConnectionLostError, + exceptions.InvalidStateError, + exceptions.OperationTimeoutError, + exceptions.ProtocolError, + ) as ex: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key="command_failed", + ) from ex + + return wrapper + + class AppleTvMediaPlayer( AppleTVEntity, MediaPlayerEntity, PowerListener, AudioListener, PushListener ): @@ -574,60 +601,70 @@ class AppleTvMediaPlayer( await self.atv.power.turn_off() @override + @_catch_command_errors async def async_media_play_pause(self) -> None: """Pause media on media player.""" if self.atv and self._playing: await self.atv.remote_control.play_pause() @override + @_catch_command_errors async def async_media_play(self) -> None: """Play media.""" if self.atv: await self.atv.remote_control.play() @override + @_catch_command_errors async def async_media_stop(self) -> None: """Stop the media player.""" if self.atv: await self.atv.remote_control.stop() @override + @_catch_command_errors async def async_media_pause(self) -> None: """Pause the media player.""" if self.atv: await self.atv.remote_control.pause() @override + @_catch_command_errors async def async_media_next_track(self) -> None: """Send next track command.""" if self.atv: await self.atv.remote_control.next() @override + @_catch_command_errors async def async_media_previous_track(self) -> None: """Send previous track command.""" if self.atv: await self.atv.remote_control.previous() @override + @_catch_command_errors async def async_media_seek(self, position: float) -> None: """Send seek command.""" if self.atv: await self.atv.remote_control.set_position(round(position)) @override + @_catch_command_errors async def async_volume_up(self) -> None: """Turn volume up for media player.""" if self.atv: await self.atv.audio.volume_up() @override + @_catch_command_errors async def async_volume_down(self) -> None: """Turn volume down for media player.""" if self.atv: await self.atv.audio.volume_down() @override + @_catch_command_errors async def async_set_volume_level(self, volume: float) -> None: """Set volume level, range 0..1.""" if self.atv: @@ -635,6 +672,7 @@ class AppleTvMediaPlayer( await self.atv.audio.set_volume(volume * 100.0) @override + @_catch_command_errors async def async_set_repeat(self, repeat: RepeatMode) -> None: """Set repeat mode.""" if self.atv: @@ -645,6 +683,7 @@ class AppleTvMediaPlayer( await self.atv.remote_control.set_repeat(mode) @override + @_catch_command_errors async def async_set_shuffle(self, shuffle: bool) -> None: """Enable/disable shuffle mode.""" if self.atv: diff --git a/homeassistant/components/apple_tv/strings.json b/homeassistant/components/apple_tv/strings.json index 8b0a43496624..585ff6ec4be6 100644 --- a/homeassistant/components/apple_tv/strings.json +++ b/homeassistant/components/apple_tv/strings.json @@ -69,6 +69,9 @@ } }, "exceptions": { + "command_failed": { + "message": "Failed to send the command to the Apple TV" + }, "keyboard_error": { "message": "An error occurred while sending text to the Apple TV" }, diff --git a/tests/components/apple_tv/test_media_player.py b/tests/components/apple_tv/test_media_player.py index 1f72c218e391..a2b28b13f25c 100644 --- a/tests/components/apple_tv/test_media_player.py +++ b/tests/components/apple_tv/test_media_player.py @@ -19,6 +19,7 @@ from homeassistant.components.apple_tv.const import DOMAIN from homeassistant.components.media_player import ( ATTR_MEDIA_CONTENT_ID, ATTR_MEDIA_CONTENT_TYPE, + ATTR_MEDIA_VOLUME_LEVEL, DOMAIN as MP_DOMAIN, SERVICE_PLAY_MEDIA, BrowseMedia, @@ -26,7 +27,12 @@ from homeassistant.components.media_player import ( MediaType, ) from homeassistant.components.media_source import PlayMedia -from homeassistant.const import ATTR_ENTITY_ID +from homeassistant.const import ( + ATTR_ENTITY_ID, + SERVICE_MEDIA_NEXT_TRACK, + SERVICE_MEDIA_PAUSE, + SERVICE_VOLUME_SET, +) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -257,6 +263,47 @@ async def test_play_media_raises_ha_error_on_pyatv_failure( assert exc_info.value.translation_domain == DOMAIN +@pytest.mark.parametrize( + ("service", "service_data", "interface", "method"), + [ + pytest.param(SERVICE_MEDIA_PAUSE, {}, "remote_control", "pause", id="pause"), + pytest.param( + SERVICE_MEDIA_NEXT_TRACK, {}, "remote_control", "next", id="next_track" + ), + pytest.param( + SERVICE_VOLUME_SET, + {ATTR_MEDIA_VOLUME_LEVEL: 0.5}, + "audio", + "set_volume", + id="volume_set", + ), + ], +) +@pytest.mark.parametrize("exc_class", [TimeoutError, ConnectionLostError]) +async def test_command_raises_ha_error_on_failure( + hass: HomeAssistant, + mock_atv: AsyncMock, + service: str, + service_data: dict[str, float], + interface: str, + method: str, + exc_class: type[Exception], +) -> None: + """Test a failing command surfaces as a translated HomeAssistantError.""" + getattr(getattr(mock_atv, interface), method).side_effect = exc_class("error") + + with pytest.raises(HomeAssistantError) as exc_info: + await hass.services.async_call( + MP_DOMAIN, + service, + {ATTR_ENTITY_ID: ENTITY_ID, **service_data}, + blocking=True, + ) + + assert exc_info.value.translation_key == "command_failed" + assert exc_info.value.translation_domain == DOMAIN + + async def test_browse_media_uses_media_source( hass: HomeAssistant, hass_ws_client: WebSocketGenerator, From ced26a9116720829474e16bcd27d88877d3a9d50 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 01:42:22 +0200 Subject: [PATCH 160/356] Add Hisense AC (0x138C/0x3601) to Matter dry and fan mode device lists (#184589) --- homeassistant/components/matter/climate.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/homeassistant/components/matter/climate.py b/homeassistant/components/matter/climate.py index 7d677b5374dc..353c9d8e641d 100644 --- a/homeassistant/components/matter/climate.py +++ b/homeassistant/components/matter/climate.py @@ -132,6 +132,7 @@ SUPPORT_DRY_MODE_DEVICES: set[tuple[int, int]] = { (0x1209, 0x8028), (0x1209, 0x8029), (0x138C, 0x0101), + (0x138C, 0x3601), } SUPPORT_FAN_MODE_DEVICES: set[tuple[int, int]] = { @@ -174,6 +175,7 @@ SUPPORT_FAN_MODE_DEVICES: set[tuple[int, int]] = { (0x1209, 0x8029), (0x131A, 0x1000), (0x138C, 0x0101), + (0x138C, 0x3601), } SystemModeEnum = clusters.Thermostat.Enums.SystemModeEnum From 8fff2ad25c85529845c909d9d53deed7bf3e357c Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 6 Oct 2026 22:20:52 -0400 Subject: [PATCH 161/356] Do not set a unique ID for MCP OAuth config entries (#184594) Co-authored-by: Claude --- homeassistant/components/mcp/config_flow.py | 5 ----- tests/components/mcp/test_config_flow.py | 1 + 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/homeassistant/components/mcp/config_flow.py b/homeassistant/components/mcp/config_flow.py index b9c14afd0d40..7a37ca8946e8 100644 --- a/homeassistant/components/mcp/config_flow.py +++ b/homeassistant/components/mcp/config_flow.py @@ -389,11 +389,6 @@ class ModelContextProtocolConfigFlow(AbstractOAuth2FlowHandler, domain=DOMAIN): return self.async_update_reload_and_abort( self._get_reauth_entry(), data=config_entry_data ) - if self.unique_id is None: - # Unique id based on the application credentials OAuth Client ID. A - # discovered server keeps the Supervisor uuid instead, so that the - # entry is removed together with the app. - await self.async_set_unique_id(config_entry_data["auth_implementation"]) return self.async_create_entry( title=info["title"], data=config_entry_data, diff --git a/tests/components/mcp/test_config_flow.py b/tests/components/mcp/test_config_flow.py index 32047940ec4e..4bb1f6f6ed1c 100644 --- a/tests/components/mcp/test_config_flow.py +++ b/tests/components/mcp/test_config_flow.py @@ -459,6 +459,7 @@ async def test_authentication_flow( result = await hass.config_entries.flow.async_configure(result["flow_id"]) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == TEST_API_NAME + assert result["result"].unique_id is None data = result["data"] token = data.pop(CONF_TOKEN) assert data == { From bae39d151352baab2268624897909684b5375afd Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 07:39:48 +0200 Subject: [PATCH 162/356] Fix the HomeWorks light address description (#184614) --- homeassistant/components/homeworks/strings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/homeworks/strings.json b/homeassistant/components/homeworks/strings.json index a77cc071d001..43b277cbca14 100644 --- a/homeassistant/components/homeworks/strings.json +++ b/homeassistant/components/homeworks/strings.json @@ -95,7 +95,7 @@ "rate": "Fade rate" }, "data_description": { - "addr": "Keypad address, must be formatted as `[##:##:##:##]`", + "addr": "Dimmer or switch address, like `[01:01:03:02:04]`, with two digits per part", "rate": "Time in seconds for the light to transition to a new brightness level" }, "title": "[%key:component::homeworks::options::step::init::menu_options::add_light%]" From e692d385440cdda4f5b95e7fc67d905f93125467 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 05:52:33 +0000 Subject: [PATCH 163/356] Bump version to 2026.10.0b4 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 92151d09452c..1131f0c76ff7 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b3" +PATCH_VERSION: Final = "0b4" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index b36ceac8f47e..8e7e96a2db4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b3" +version = "2026.10.0b4" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From d17e3a99a4c655b8950cbf537d2f693de88eca0f Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Sun, 4 Oct 2026 15:05:40 +0200 Subject: [PATCH 164/356] Bump uiprotect to 20.2.1 (#184208) --- .../components/unifiprotect/manifest.json | 2 +- requirements_all.txt | 2 +- .../snapshots/test_diagnostics.ambr | 238 ------------------ 3 files changed, 2 insertions(+), 240 deletions(-) diff --git a/homeassistant/components/unifiprotect/manifest.json b/homeassistant/components/unifiprotect/manifest.json index ecb20e847812..1f1353ac9bd5 100644 --- a/homeassistant/components/unifiprotect/manifest.json +++ b/homeassistant/components/unifiprotect/manifest.json @@ -9,5 +9,5 @@ "iot_class": "local_push", "loggers": ["uiprotect"], "quality_scale": "platinum", - "requirements": ["uiprotect==17.7.0"] + "requirements": ["uiprotect==20.2.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 40e2a64d8ab8..37afbd874ed7 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3326,7 +3326,7 @@ uasiren==0.0.1 uhooapi==1.2.8 # homeassistant.components.unifiprotect -uiprotect==17.7.0 +uiprotect==20.2.1 # homeassistant.components.landisgyr_heat_meter ultraheat-api==0.6.1 diff --git a/tests/components/unifiprotect/snapshots/test_diagnostics.ambr b/tests/components/unifiprotect/snapshots/test_diagnostics.ambr index b48b6b05e183..50af62fd558e 100644 --- a/tests/components/unifiprotect/snapshots/test_diagnostics.ambr +++ b/tests/components/unifiprotect/snapshots/test_diagnostics.ambr @@ -2,36 +2,23 @@ # name: test_diagnostics dict({ 'bootstrap': dict({ - 'accessKey': '**REDACTED**', 'authUserId': '**REDACTED_ID**', 'bridges': list([ dict({ - 'anonymousDeviceId': None, 'bridge': None, 'canAdopt': False, - 'connectedSince': 1642374159304, 'connectionHost': '**REDACTED_IP**', - 'firmwareBuild': None, 'firmwareVersion': '0.3.1', - 'fwUpdateState': None, 'guid': None, - 'hardwareRevision': '19', 'host': '**REDACTED_IP**', 'id': '**REDACTED_ID**', 'isAdopted': True, 'isAdoptedByOther': False, 'isAdopting': False, - 'isAttemptingToConnect': False, 'isConnected': True, - 'isDownloadingFW': None, - 'isProvisioned': False, 'isRebooting': False, - 'isRestoring': None, 'isSshEnabled': False, 'isUpdating': False, - 'lastDisconnect': None, - 'lastSeen': 1643055759891, - 'latestFirmwareVersion': None, 'mac': '**REDACTED_MAC**', 'marketName': None, 'modelKey': 'bridge', @@ -47,32 +34,20 @@ }), }), dict({ - 'anonymousDeviceId': None, 'bridge': None, 'canAdopt': False, - 'connectedSince': 1643052754695, 'connectionHost': '**REDACTED_IP**', - 'firmwareBuild': None, 'firmwareVersion': '0.3.1', - 'fwUpdateState': None, 'guid': None, - 'hardwareRevision': '19', 'host': '**REDACTED_IP**', 'id': '**REDACTED_ID**', 'isAdopted': True, 'isAdoptedByOther': False, 'isAdopting': False, - 'isAttemptingToConnect': False, 'isConnected': True, - 'isDownloadingFW': None, - 'isProvisioned': False, 'isRebooting': False, - 'isRestoring': None, 'isSshEnabled': False, 'isUpdating': False, - 'lastDisconnect': None, - 'lastSeen': 1643052750862, - 'latestFirmwareVersion': None, 'mac': '**REDACTED_MAC**', 'marketName': None, 'modelKey': 'bridge', @@ -145,43 +120,28 @@ 'lastUpdateId': '**REDACTED_UUID**', 'lights': list([ dict({ - 'anonymousDeviceId': None, 'bridge': None, 'camera': None, 'canAdopt': False, - 'connectedSince': 1640020579711, 'connectionHost': '**REDACTED_IP**', - 'firmwareBuild': 'g990c553.211105.251', 'firmwareVersion': '1.9.3', - 'fwUpdateState': None, 'guid': None, - 'hardwareRevision': None, 'host': '**REDACTED_IP**', 'id': '**REDACTED_ID**', 'isAdopted': True, 'isAdoptedByOther': False, 'isAdopting': False, - 'isAttemptingToConnect': False, - 'isCameraPaired': True, 'isConnected': True, 'isDark': False, - 'isDownloadingFW': None, 'isLightOn': False, - 'isLocating': False, 'isPirMotionDetected': False, - 'isProvisioned': False, 'isRebooting': False, - 'isRestoring': None, 'isSshEnabled': False, 'isUpdating': False, - 'lastDisconnect': None, 'lastMotion': 1640022006069, - 'lastSeen': 1640023881022, - 'latestFirmwareVersion': '1.9.3', 'lightDeviceSettings': dict({ 'isIndicatorEnabled': False, 'ledLevel': 6, - 'luxSensitivity': 'medium', 'pirDuration': 45000, 'pirSensitivity': 45, }), @@ -189,9 +149,6 @@ 'enableAt': 'fulltime', 'mode': 'motion', }), - 'lightOnSettings': dict({ - 'isLedForceOn': False, - }), 'mac': '**REDACTED_MAC**', 'marketName': 'UP FloodLight', 'modelKey': 'light', @@ -210,13 +167,6 @@ ]), 'nvr': dict({ 'analyticsData': 'anonymous', - 'anonymousDeviceId': '**REDACTED_UUID**', - 'cameraUtilization': 30, - 'canAutoUpdate': True, - 'corruptionState': None, - 'countryCode': None, - 'disableAudio': False, - 'disableAutoLink': False, 'doorbellSettings': dict({ 'allMessages': list([ dict({ @@ -236,116 +186,36 @@ 'Come In!', 'Use Other Door', ]), - 'defaultMessageResetTimeoutMs': 60000, 'defaultMessageText': 'Welcome', }), - 'enableAutomaticBackups': True, - 'enableBridgeAutoAdoption': True, - 'enableCrashReporting': True, - 'enableStatsReporting': False, 'featureFlags': dict({ 'beta': False, - 'detectionLabels': None, 'dev': False, - 'hasTwoWayAudioMediaStreams': None, - 'homekitPaired': None, - 'notificationsV2': True, - 'ulpRoleManagement': None, }), 'firmwareVersion': '2.3.10', 'globalCameraSettings': None, - 'hardDriveState': None, - 'hardwareId': '**REDACTED_UUID**', - 'hardwarePlatform': 'al324', - 'hardwareRevision': '113-03137-22', - 'hasGateway': None, 'host': '**REDACTED_IP**', - 'hostShortname': 'UNVRPRO', - 'hostType': 59936, 'hosts': list([ '**REDACTED_IP**', ]), 'id': '**REDACTED_ID**', - 'isAway': True, - 'isDbAvailable': None, - 'isHardware': True, 'isInsightsEnabled': True, - 'isNetworkInstalled': None, - 'isPrimary': None, - 'isProtectUpdatable': None, - 'isRecordingDisabled': False, - 'isRecordingMotionOnly': False, - 'isRecycling': False, - 'isSetup': True, 'isSshEnabled': False, - 'isStacked': None, - 'isStation': False, - 'isStatsGatheringEnabled': True, - 'isUCoreSetup': None, - 'isUCoreStacked': None, - 'isUcoreUpdatable': None, 'isUpdating': False, - 'isVaultRegistered': None, - 'isWirelessUplinkEnabled': False, - 'lastDeviceFWUpdatesCheckedAt': None, - 'lastDriveSlowEvent': None, - 'lastSeen': 1641269019283, - 'lastUpdateAt': None, - 'locationSettings': dict({ - 'isAway': True, - 'isGeofencingEnabled': False, - 'latitude': 41.4519, - 'longitude': -81.921, - 'radius': 200, - }), 'mac': '**REDACTED_MAC**', 'marketName': None, - 'maxCameraCapacity': dict({ - '2K': 30, - '4K': 20, - 'HD': 60, - }), 'modelKey': 'nvr', 'name': '**REDACTED_NAME**', 'network': 'Ethernet', 'ports': dict({ - 'aiFeatureConsole': None, - 'cameraEvents': 7551, - 'cameraHttps': 7444, - 'devicesWss': 7442, - 'discoveryClient': 0, - 'emsCLI': 7440, - 'emsJsonCLI': None, - 'emsLiveFLV': 7550, 'http': 7080, 'https': 7443, - 'liveWs': 7445, - 'liveWss': 7446, - 'piongw': None, 'playback': 7450, - 'rtmp': 1935, - 'rtsp': 7447, 'rtsps': 7441, - 'stacking': None, - 'tcpBridge': 7888, - 'tcpStreams': 7448, - 'ucore': 11081, - 'ump': 7449, }), - 'publicIp': None, - 'recordingRetentionDurationMs': None, - 'releaseChannel': 'release', - 'skipFirmwareUpdate': False, 'smartDetection': None, - 'ssoChannel': None, 'storageStats': dict({ 'capacity': 5706909122, - 'recordingSpace': dict({ - 'available': 23327455092736, - 'total': 31787269955584, - 'used': 8459814862848, - }), - 'remainingCapacity': 4188081155, 'storageDistribution': dict({ 'recordingTypeDistributions': list([ dict({ @@ -384,7 +254,6 @@ }), 'utilization': 26.61384533704469, }), - 'streamSharingAvailable': None, 'systemInfo': dict({ 'cpu': dict({ 'averageLoad': 5, @@ -415,17 +284,10 @@ 'size': 16000900661248, }), ]), - 'isRecycling': False, 'size': 31855989432320, 'type': 'raid', 'used': 8459815895040, }), - 'tmpfs': dict({ - 'available': 934204, - 'path': '/var/opt/unifi-protect/tmp', - 'total': 1048576, - 'used': 114372, - }), 'ustorage': dict({ 'disks': list([ dict({ @@ -566,62 +428,14 @@ 'type': 'HDD', }), ]), - 'space': list([ - dict({ - 'action': 'expanding', - 'device': 'md3', - 'estimate': 234395.733, - 'health': None, - 'progress': 21.390607518939174, - 'space_type': None, - 'total_bytes': 63713403555840, - 'used_bytes': 57006577086464, - }), - dict({ - 'action': 'syncing', - 'device': 'md0', - 'estimate': None, - 'health': None, - 'progress': 0, - 'space_type': None, - 'total_bytes': 0, - 'used_bytes': 0, - }), - ]), }), }), - 'temperatureUnit': 'C', - 'timeFormat': '24h', 'timezone': 'America/New_York', 'type': 'UNVR-PRO', - 'ucoreVersion': '2.3.26', - 'uiVersion': None, - 'ulpVersion': None, 'upSince': 1640077503063, 'uptime': 1191516000, - 'vaultCameras': list([ - ]), 'version': '7.2.105', - 'wanIp': None, }), - 'ringtones': list([ - dict({ - 'id': '**REDACTED_ID**', - 'isDefault': True, - 'modelKey': 'ringtone', - 'name': '**REDACTED_NAME**', - 'nvrMac': '**REDACTED_MAC**', - 'size': 208, - }), - dict({ - 'id': '**REDACTED_ID**', - 'isDefault': False, - 'modelKey': 'ringtone', - 'name': '**REDACTED_NAME**', - 'nvrMac': '**REDACTED_MAC**', - 'size': 180, - }), - ]), 'sensors': list([ ]), 'ulpUsers': dict({ @@ -659,26 +473,19 @@ 'user': '**REDACTED_ID**', }), 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', ]), - 'hasAcceptedInvite': True, 'id': '**REDACTED_ID**', - 'isOwner': True, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -712,27 +519,20 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -759,25 +559,16 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'location': dict({ - 'isAway': True, - 'latitude': None, - 'longitude': None, }), 'modelKey': 'user', 'name': '**REDACTED_NAME**', @@ -787,7 +578,6 @@ 'liveview:*:**REDACTED_ID**', 'liveview:*:**REDACTED_ID**', ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -805,26 +595,19 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -858,27 +641,20 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -912,27 +688,20 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), dict({ 'allPermissions': list([ @@ -950,26 +719,19 @@ ]), 'cloudAccount': None, 'email': '**REDACTED**@example.com', - 'enableNotifications': False, 'featureFlags': dict({ - 'notificationsV2': True, }), 'firstName': '**REDACTED_NAME**', 'groups': list([ '**REDACTED_ID**', ]), - 'hasAcceptedInvite': False, 'id': '**REDACTED_ID**', - 'isOwner': False, - 'lastLoginIp': None, - 'lastLoginTime': None, 'lastName': '**REDACTED_NAME**', 'localUsername': '**REDACTED_NAME**', 'modelKey': 'user', 'name': '**REDACTED_NAME**', 'permissions': list([ ]), - 'scopes': None, }), ]), 'viewers': list([ From 6d956cce90f91cd49fb9c0cef58180d6d204ad4f Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Sun, 4 Oct 2026 21:08:31 +0200 Subject: [PATCH 165/356] Bump uiprotect to 23.0.0 (#184233) --- homeassistant/components/unifiprotect/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/unifiprotect/test_services.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/unifiprotect/manifest.json b/homeassistant/components/unifiprotect/manifest.json index 1f1353ac9bd5..3a94273a8243 100644 --- a/homeassistant/components/unifiprotect/manifest.json +++ b/homeassistant/components/unifiprotect/manifest.json @@ -9,5 +9,5 @@ "iot_class": "local_push", "loggers": ["uiprotect"], "quality_scale": "platinum", - "requirements": ["uiprotect==20.2.1"] + "requirements": ["uiprotect==23.0.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 37afbd874ed7..0545745f3de9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3326,7 +3326,7 @@ uasiren==0.0.1 uhooapi==1.2.8 # homeassistant.components.unifiprotect -uiprotect==20.2.1 +uiprotect==23.0.0 # homeassistant.components.landisgyr_heat_meter ultraheat-api==0.6.1 diff --git a/tests/components/unifiprotect/test_services.py b/tests/components/unifiprotect/test_services.py index ef7fb8d62a02..e737e12fe997 100644 --- a/tests/components/unifiprotect/test_services.py +++ b/tests/components/unifiprotect/test_services.py @@ -5,7 +5,7 @@ from typing import Any from unittest.mock import AsyncMock, Mock import pytest -from uiprotect.data import Camera, Chime, Color, Light, ModelType, PTZPreset +from uiprotect.data import Camera, Chime, Light, ModelType, PTZPreset from uiprotect.data.devices import CameraZone from uiprotect.exceptions import BadRequest, ClientError @@ -283,7 +283,7 @@ async def test_remove_privacy_zone( ufp.api.update_device = AsyncMock() doorbell.privacy_zones = [ - CameraZone(id=0, name="Testing", color=Color("red"), points=[(0, 0), (1, 1)]) + CameraZone(id=0, name="Testing", color="#FF0000", points=[(0, 0), (1, 1)]) ] await init_entry(hass, ufp, [doorbell]) From 8dded2becd96f993f8f935b4164fd1bc05a36312 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Wed, 7 Oct 2026 08:50:42 +0200 Subject: [PATCH 166/356] Bump my-pv version (#184517) --- homeassistant/components/my_pv/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/my_pv/manifest.json b/homeassistant/components/my_pv/manifest.json index fa75649d8f7d..c2900328f9ac 100644 --- a/homeassistant/components/my_pv/manifest.json +++ b/homeassistant/components/my_pv/manifest.json @@ -16,6 +16,6 @@ "iot_class": "local_polling", "loggers": ["my_pv"], "quality_scale": "bronze", - "requirements": ["my-pv==0.0.10"], + "requirements": ["my-pv==0.0.11"], "zeroconf": ["_mypv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 0545745f3de9..57076f7274ad 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1686,7 +1686,7 @@ mutesync==0.0.1 mvg==1.6.0 # homeassistant.components.my_pv -my-pv==0.0.10 +my-pv==0.0.11 # homeassistant.components.myuplink myuplink==0.7.0 From def0f5cb90dc5e99d1b9aeda7b31c2c83c7bd708 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 11:46:48 +0200 Subject: [PATCH 167/356] Send the preset mode when turning on an ESPHome fan (#184557) --- homeassistant/components/esphome/fan.py | 8 ++++++-- tests/components/esphome/test_fan.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/esphome/fan.py b/homeassistant/components/esphome/fan.py index 80aecffa0231..ecaaa99a98fa 100644 --- a/homeassistant/components/esphome/fan.py +++ b/homeassistant/components/esphome/fan.py @@ -52,7 +52,9 @@ class EsphomeFan(EsphomeEntity[FanInfo, FanState], FanEntity): await self._async_set_percentage(percentage) @convert_api_error_ha_error - async def _async_set_percentage(self, percentage: int | None) -> None: + async def _async_set_percentage( + self, percentage: int | None, preset_mode: str | None = None + ) -> None: if percentage == 0: await self.async_turn_off() return @@ -70,6 +72,8 @@ class EsphomeFan(EsphomeEntity[FanInfo, FanState], FanEntity): ORDERED_NAMED_FAN_SPEEDS, percentage ) data["speed"] = named_speed + if preset_mode is not None: + data["preset_mode"] = preset_mode self._client.fan_command(**data, device_id=self._static_info.device_id) @override @@ -80,7 +84,7 @@ class EsphomeFan(EsphomeEntity[FanInfo, FanState], FanEntity): **kwargs: Any, ) -> None: """Turn on the fan.""" - await self._async_set_percentage(percentage) + await self._async_set_percentage(percentage, preset_mode) @convert_api_error_ha_error @override diff --git a/tests/components/esphome/test_fan.py b/tests/components/esphome/test_fan.py index 763e95d3e6fb..16af8d728f34 100644 --- a/tests/components/esphome/test_fan.py +++ b/tests/components/esphome/test_fan.py @@ -302,6 +302,17 @@ async def test_fan_entity_with_all_features_new_api( ) mock_client.fan_command.reset_mock() + await hass.services.async_call( + FAN_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "fan.test_my_fan", ATTR_PRESET_MODE: "Preset2"}, + blocking=True, + ) + mock_client.fan_command.assert_called_once_with( + key=1, state=True, preset_mode="Preset2", device_id=0 + ) + mock_client.fan_command.reset_mock() + async def test_fan_entity_with_no_features_new_api( hass: HomeAssistant, From 96255e3b22799d4e62890f0e985a98d36b5f9992 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 08:00:37 +0200 Subject: [PATCH 168/356] Don't end the ESPHome voice audio stream on an empty frame (#184583) --- .../components/esphome/assist_satellite.py | 6 ++- .../esphome/test_assist_satellite.py | 45 +++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/esphome/assist_satellite.py b/homeassistant/components/esphome/assist_satellite.py index 94ad3438c1e2..c696fde999ae 100644 --- a/homeassistant/components/esphome/assist_satellite.py +++ b/homeassistant/components/esphome/assist_satellite.py @@ -782,9 +782,13 @@ class EsphomeAssistSatellite( """Yield audio chunks from the queue until None.""" while True: chunk = await self._audio_queue.get() - if not chunk: + if chunk is None: break + # The device can send an empty frame in the middle of the audio + if not chunk: + continue + yield chunk def _stop_pipeline(self) -> None: diff --git a/tests/components/esphome/test_assist_satellite.py b/tests/components/esphome/test_assist_satellite.py index 412ebcfd948f..6c93c8ec55c0 100644 --- a/tests/components/esphome/test_assist_satellite.py +++ b/tests/components/esphome/test_assist_satellite.py @@ -2369,6 +2369,51 @@ async def test_multichannel_audio( await pipeline_finished.wait() +async def test_empty_audio_frame_does_not_end_stream( + hass: HomeAssistant, + mock_client: APIClient, + mock_esphome_device: MockESPHomeDeviceType, +) -> None: + """Test an empty audio frame from the device doesn't end the audio stream.""" + mock_device = await mock_esphome_device( + mock_client=mock_client, + device_info={ + "voice_assistant_feature_flags": VoiceAssistantFeature.VOICE_ASSISTANT + | VoiceAssistantFeature.API_AUDIO + }, + ) + await hass.async_block_till_done() + + satellite = get_satellite_entity(hass, mock_device.device_info.mac_address) + assert satellite is not None + + received_chunks: list[bytes] = [] + pipeline_finished = asyncio.Event() + + async def async_pipeline_from_audio_stream(*args, **kwargs): + received_chunks.extend([chunk async for chunk in kwargs["stt_stream"]]) + pipeline_finished.set() + + with patch( + "homeassistant.components.assist_satellite.entity.async_pipeline_from_audio_stream", + new=async_pipeline_from_audio_stream, + ): + async with asyncio.timeout(1): + await satellite.handle_pipeline_start( + conversation_id="", + flags=VoiceAssistantCommandFlag(0), # stt + audio_settings=VoiceAssistantAudioSettings(), + wake_word_phrase=None, + ) + await satellite.handle_audio(b"before") + await satellite.handle_audio(b"") + await satellite.handle_audio(b"after") + await satellite.handle_pipeline_stop(abort=False) + await pipeline_finished.wait() + + assert received_chunks == [b"before", b"after"] + + async def test_multichannel_audio_fallback_channel_0( hass: HomeAssistant, mock_client: APIClient, From d8b03067ca4a6aabb1267ac9f805531981cb2812 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 09:08:58 +0200 Subject: [PATCH 169/356] Convert the ZHA Inovelli LED effect when running the action (#184612) --- homeassistant/components/zha/device_action.py | 14 ++- tests/components/zha/test_device_action.py | 92 ++++++++++++++++++- 2 files changed, 100 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/zha/device_action.py b/homeassistant/components/zha/device_action.py index 3e4ad06081af..45c5f8876a76 100644 --- a/homeassistant/components/zha/device_action.py +++ b/homeassistant/components/zha/device_action.py @@ -37,7 +37,9 @@ INOVELLI_ALL_LED_EFFECT_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend( { probatio.Required(CONF_TYPE): INOVELLI_ALL_LED_EFFECT, probatio.Required(CONF_DOMAIN): DOMAIN, - probatio.Required("effect_type"): AllLEDEffectType.__getitem__, + probatio.Required("effect_type"): probatio.In( + AllLEDEffectType.__members__.keys() + ), probatio.Required("color"): probatio.All( probatio.Coerce(int), probatio.Range(0, 255) ), @@ -53,7 +55,9 @@ INOVELLI_ALL_LED_EFFECT_SCHEMA = cv.DEVICE_ACTION_BASE_SCHEMA.extend( INOVELLI_INDIVIDUAL_LED_EFFECT_SCHEMA = INOVELLI_ALL_LED_EFFECT_SCHEMA.extend( { probatio.Required(CONF_TYPE): INOVELLI_INDIVIDUAL_LED_EFFECT, - probatio.Required("effect_type"): SingleLEDEffectType.__getitem__, + probatio.Required("effect_type"): probatio.In( + SingleLEDEffectType.__members__.keys() + ), probatio.Required("led_number"): probatio.All( probatio.Coerce(int), probatio.Range(0, 6) ), @@ -221,7 +225,9 @@ async def _execute_inovelli_all_led_effect( async with convert_zha_error_to_ha_error(): await cluster.led_effect( - led_effect=config["effect_type"], + # The action isn't validated when ZHA wasn't loaded yet, so the + # effect type is converted here instead of in the schema + led_effect=AllLEDEffectType[config["effect_type"]], led_color=config["color"], led_level=config["level"], led_duration=config["duration"], @@ -237,7 +243,7 @@ async def _execute_inovelli_individual_led_effect( async with convert_zha_error_to_ha_error(): await cluster.individual_led_effect( - led_effect=config["effect_type"], + led_effect=SingleLEDEffectType[config["effect_type"]], led_color=config["color"], led_level=config["level"], led_duration=config["duration"], diff --git a/tests/components/zha/test_device_action.py b/tests/components/zha/test_device_action.py index 3309292f4280..fbe71d614d4b 100644 --- a/tests/components/zha/test_device_action.py +++ b/tests/components/zha/test_device_action.py @@ -1,10 +1,12 @@ """The test for ZHA device automation actions.""" from collections.abc import Callable, Coroutine -from unittest.mock import patch +from unittest.mock import AsyncMock, patch +import probatio import pytest from pytest_unordered import unordered +from zhaquirks.inovelli.types import AllLEDEffectType, SingleLEDEffectType from zigpy.device import Device from zigpy.profiles import zha from zigpy.zcl.clusters import general, security @@ -12,7 +14,7 @@ import zigpy.zcl.foundation as zcl_f from homeassistant.components import automation from homeassistant.components.device_automation import DeviceAutomationType -from homeassistant.components.zha import DOMAIN +from homeassistant.components.zha import DOMAIN, device_action from homeassistant.components.zha.helpers import get_zha_gateway from homeassistant.const import Platform from homeassistant.core import HomeAssistant @@ -223,6 +225,92 @@ async def test_action( assert calls[0].data["ieee"] == ieee_address +@pytest.mark.parametrize( + ("action_type", "extra_config", "cluster_method", "expected_effect"), + [ + pytest.param( + "issue_all_led_effect", + {}, + "led_effect", + AllLEDEffectType.Clear, + id="all_leds", + ), + pytest.param( + "issue_individual_led_effect", + {"led_number": 1}, + "individual_led_effect", + SingleLEDEffectType.Clear, + id="individual_led", + ), + ], +) +async def test_inovelli_led_effect_from_unvalidated_config( + hass: HomeAssistant, + action_type: str, + extra_config: dict[str, int], + cluster_method: str, + expected_effect: AllLEDEffectType | SingleLEDEffectType, +) -> None: + """Test the LED effect is sent as an effect type, even if ZHA didn't validate it. + + ZHA only validates the action when it is loaded, so the action can receive + the effect type as it was configured. + """ + cluster = AsyncMock() + config = { + "device_id": "device_id", + "domain": DOMAIN, + "type": action_type, + "effect_type": "Clear", + "color": 200, + "level": 100, + "duration": 255, + **extra_config, + } + + with patch( + "homeassistant.components.zha.device_action._find_inovelli_cluster", + return_value=cluster, + ): + await device_action.async_call_action_from_config(hass, config, {}, None) + + assert getattr(cluster, cluster_method).call_args.kwargs["led_effect"] is ( + expected_effect + ) + + +@pytest.mark.parametrize( + ("action_type", "extra_config"), + [ + pytest.param("issue_all_led_effect", {}, id="all_leds"), + pytest.param( + "issue_individual_led_effect", {"led_number": 1}, id="individual_led" + ), + ], +) +@pytest.mark.parametrize("effect_type", [77, "77", "Unknown"]) +async def test_inovelli_led_effect_rejects_unknown_effect( + hass: HomeAssistant, + action_type: str, + extra_config: dict[str, int], + effect_type: int | str, +) -> None: + """Test only known effect names pass validation, not raw effect codes.""" + config = { + "device_id": "device_id", + "domain": DOMAIN, + "type": action_type, + "effect_type": effect_type, + "color": 200, + "level": 100, + "duration": 255, + **extra_config, + } + + with pytest.raises(probatio.Invalid): + await device_action.async_validate_action_config(hass, config) + + async def test_client_unique_id_suffix_stripped( hass: HomeAssistant, setup_zha: Callable[..., Coroutine[None]], From 4b40a80fc363f01a6be12193db723e938e91b403 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 11:44:07 +0200 Subject: [PATCH 170/356] Use the local day of the last Habitica cron for the calendars (#184613) --- homeassistant/components/habitica/calendar.py | 5 +- .../habitica/snapshots/test_calendar.ambr | 70 ++----------------- tests/components/habitica/test_calendar.py | 34 ++++++++- 3 files changed, 42 insertions(+), 67 deletions(-) diff --git a/homeassistant/components/habitica/calendar.py b/homeassistant/components/habitica/calendar.py index 4efd3121e027..e2422f87a775 100644 --- a/homeassistant/components/habitica/calendar.py +++ b/homeassistant/components/habitica/calendar.py @@ -87,7 +87,10 @@ class HabiticaCalendarEntity(HabiticaBase, CalendarEntity): @property def start_of_today(self) -> datetime: """Habitica daystart.""" - return dt_util.start_of_local_day(self.coordinator.data.user.lastCron) + if (last_cron := self.coordinator.data.user.lastCron) is None: + return dt_util.start_of_local_day() + + return dt_util.start_of_local_day(dt_util.as_local(last_cron)) def get_recurrence_dates( self, recurrences: rrule, start_date: datetime, end_date: datetime | None = None diff --git a/tests/components/habitica/snapshots/test_calendar.ambr b/tests/components/habitica/snapshots/test_calendar.ambr index 0a6c9bf7f3db..5f59fd95121c 100644 --- a/tests/components/habitica/snapshots/test_calendar.ambr +++ b/tests/components/habitica/snapshots/test_calendar.ambr @@ -17,51 +17,6 @@ # --- # name: test_api_events[default date range-calendar.test_user_dailies] list([ - dict({ - 'description': 'Klicke um Deinen Terminplan festzulegen!', - 'end': dict({ - 'date': '2024-09-22', - }), - 'location': None, - 'recurrence_id': None, - 'rrule': 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR,SA,SU', - 'start': dict({ - 'date': '2024-09-21', - }), - 'status': None, - 'summary': '5 Minuten ruhig durchatmen', - 'uid': 'f2c85972-1a19-4426-bc6d-ce3337b9d99f', - }), - dict({ - 'description': 'Ein einstündiges Workout im Fitnessstudio absolvieren.', - 'end': dict({ - 'date': '2024-09-22', - }), - 'location': None, - 'recurrence_id': None, - 'rrule': 'FREQ=WEEKLY;BYDAY=WE,SA,SU', - 'start': dict({ - 'date': '2024-09-21', - }), - 'status': None, - 'summary': 'Fitnessstudio besuchen', - 'uid': '2c6d136c-a1c3-4bef-b7c4-fa980784b1e1', - }), - dict({ - 'description': 'Klicke um Änderungen zu machen!', - 'end': dict({ - 'date': '2024-09-23', - }), - 'location': None, - 'recurrence_id': None, - 'rrule': 'FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR,SA,SU', - 'start': dict({ - 'date': '2024-09-22', - }), - 'status': None, - 'summary': 'Zahnseide benutzen', - 'uid': '564b9ac9-c53d-4638-9e7f-1cd96fe19baa', - }), dict({ 'description': 'Klicke um Deinen Terminplan festzulegen!', 'end': dict({ @@ -666,21 +621,6 @@ # --- # name: test_api_events[default date range-calendar.test_user_daily_reminders] list([ - dict({ - 'description': 'Klicke um Deinen Terminplan festzulegen!', - 'end': dict({ - 'dateTime': '2024-09-21T21:00:00+02:00', - }), - 'location': None, - 'recurrence_id': None, - 'rrule': None, - 'start': dict({ - 'dateTime': '2024-09-21T20:00:00+02:00', - }), - 'status': None, - 'summary': '5 Minuten ruhig durchatmen', - 'uid': 'f2c85972-1a19-4426-bc6d-ce3337b9d99f_1491d640-6b21-4d0c-8940-0b7aa61c8836', - }), dict({ 'description': 'Klicke um Deinen Terminplan festzulegen!', 'end': dict({ @@ -1033,11 +973,11 @@ 'attributes': ReadOnlyDict({ : True, : 'Klicke um Deinen Terminplan festzulegen!', - : '2024-09-22 00:00:00', + : '2024-09-23 00:00:00', : 'test-user Dailies', : '', : '5 Minuten ruhig durchatmen', - : '2024-09-21 00:00:00', + : '2024-09-22 00:00:00', 'yesterdaily': False, }), 'context': , @@ -1045,7 +985,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'on', + 'state': 'off', }) # --- # name: test_calendar_platform[calendar.test_user_daily_reminders-entry] @@ -1090,11 +1030,11 @@ 'attributes': ReadOnlyDict({ : False, : 'Klicke um Deinen Terminplan festzulegen!', - : '2024-09-21 21:00:00', + : '2024-09-22 21:00:00', : 'test-user Daily reminders', : '', : '5 Minuten ruhig durchatmen', - : '2024-09-21 20:00:00', + : '2024-09-22 20:00:00', }), 'context': , 'entity_id': 'calendar.test_user_daily_reminders', diff --git a/tests/components/habitica/test_calendar.py b/tests/components/habitica/test_calendar.py index 228314eb2beb..0cca37d68dff 100644 --- a/tests/components/habitica/test_calendar.py +++ b/tests/components/habitica/test_calendar.py @@ -1,7 +1,8 @@ """Tests for the Habitica calendar platform.""" from collections.abc import Generator -from unittest.mock import patch +from datetime import UTC, datetime +from unittest.mock import AsyncMock, patch import pytest from syrupy.assertion import SnapshotAssertion @@ -92,3 +93,34 @@ async def test_api_events( ) assert await response.json() == snapshot + + +@pytest.mark.freeze_time("2024-09-25T10:00:00.000Z") +@pytest.mark.parametrize( + ("last_cron", "expected_start"), + [ + pytest.param( + # Already September 22 in Berlin, while still September 21 in UTC + datetime(2024, 9, 21, 22, 1, 55, tzinfo=UTC), + "2024-09-22 00:00:00", + id="local_day_of_last_cron", + ), + pytest.param(None, "2024-09-25 00:00:00", id="no_last_cron"), + ], +) +async def test_dailies_start_of_today( + hass: HomeAssistant, + config_entry: MockConfigEntry, + habitica: AsyncMock, + last_cron: datetime | None, + expected_start: str, +) -> None: + """Test the dailies start on the local day of the last cron, or today without one.""" + habitica.get_user.return_value.data.lastCron = last_cron + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("calendar.test_user_dailies")) + assert state.attributes["start_time"] == expected_start From f830e8ac1e997da4781dd8395a82aa37e9bc1170 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 08:34:16 +0200 Subject: [PATCH 171/356] Refresh motionEye after changing a switch (#184616) --- homeassistant/components/motioneye/switch.py | 1 + tests/components/motioneye/test_switch.py | 37 ++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/homeassistant/components/motioneye/switch.py b/homeassistant/components/motioneye/switch.py index 11bb8fd5ede0..fc13c96353fe 100644 --- a/homeassistant/components/motioneye/switch.py +++ b/homeassistant/components/motioneye/switch.py @@ -128,6 +128,7 @@ class MotionEyeSwitch(MotionEyeEntity, SwitchEntity): if camera: camera[self.entity_description.key] = value await self._client.async_set_camera(self._camera_id, camera) + await self.coordinator.async_refresh() @override async def async_turn_on(self, **kwargs: Any) -> None: diff --git a/tests/components/motioneye/test_switch.py b/tests/components/motioneye/test_switch.py index e810dc51be69..93ff757a257a 100644 --- a/tests/components/motioneye/test_switch.py +++ b/tests/components/motioneye/test_switch.py @@ -99,6 +99,43 @@ async def test_switch_turn_on_off( assert entity_state.state == "on" +async def test_switch_state_updates_right_after_toggling(hass: HomeAssistant) -> None: + """Test the switch shows the new state without waiting for the next poll.""" + client = create_mock_motioneye_client() + await setup_mock_motioneye_config_entry(hass, client=client) + + client.async_get_camera = AsyncMock(return_value=copy.deepcopy(TEST_CAMERA)) + + updated_camera = copy.deepcopy(TEST_CAMERA) + updated_camera[KEY_MOTION_DETECTION] = False + client.async_get_cameras = AsyncMock(return_value={"cameras": [updated_camera]}) + + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_OFF, + {ATTR_ENTITY_ID: TEST_SWITCH_MOTION_DETECTION_ENTITY_ID}, + blocking=True, + ) + + assert (entity_state := hass.states.get(TEST_SWITCH_MOTION_DETECTION_ENTITY_ID)) + assert entity_state.state == "off" + + # Toggle again right away, within the cooldown of a requested refresh + client.async_get_cameras = AsyncMock( + return_value={"cameras": [copy.deepcopy(TEST_CAMERA)]} + ) + + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: TEST_SWITCH_MOTION_DETECTION_ENTITY_ID}, + blocking=True, + ) + + assert (entity_state := hass.states.get(TEST_SWITCH_MOTION_DETECTION_ENTITY_ID)) + assert entity_state.state == "on" + + async def test_switch_state_update_from_coordinator( hass: HomeAssistant, freezer: FrozenDateTimeFactory ) -> None: From 469deaf80b1ac5f918e70d0dc7776c01322649c6 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 08:21:58 +0200 Subject: [PATCH 172/356] Raise a Home Assistant error when sending Tuya commands fails (#184621) --- homeassistant/components/tuya/entity.py | 18 +++++++-- homeassistant/components/tuya/strings.json | 6 +++ tests/components/tuya/test_switch.py | 47 ++++++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/tuya/entity.py b/homeassistant/components/tuya/entity.py index b1a092aae313..cb9f94e9150f 100644 --- a/homeassistant/components/tuya/entity.py +++ b/homeassistant/components/tuya/entity.py @@ -3,9 +3,12 @@ from dataclasses import dataclass from typing import Any, override +import requests from tuya_device_handlers.device_wrapper import DeviceWrapper from tuya_sharing import CustomerDevice, Manager +from tuya_sharing.exceptions import TuyaSDKException +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.dispatcher import async_dispatcher_connect from homeassistant.helpers.entity import Entity, EntityDescription @@ -95,9 +98,18 @@ class TuyaEntity(Entity): LOGGER.debug("Sending commands for device %s: %s", self.device.id, commands) if not commands: return - await self.hass.async_add_executor_job( - self.device_manager.send_commands, self.device.id, commands - ) + try: + await self.hass.async_add_executor_job( + self.device_manager.send_commands, self.device.id, commands + ) + except TuyaSDKException as err: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="command_rejected" + ) from err + except requests.RequestException as err: + raise HomeAssistantError( + translation_domain=DOMAIN, translation_key="send_command_failed" + ) from err def _read_wrapper[T](self, wrapper: DeviceWrapper[T] | None) -> T | None: """Read the wrapper device status.""" diff --git a/homeassistant/components/tuya/strings.json b/homeassistant/components/tuya/strings.json index 5dc61aa1c3d2..5f043efb9bd0 100644 --- a/homeassistant/components/tuya/strings.json +++ b/homeassistant/components/tuya/strings.json @@ -1298,6 +1298,9 @@ "action_dpcode_not_found": { "message": "Unable to process action as the device does not provide a corresponding function code (expected one of {expected} in {available})." }, + "command_rejected": { + "message": "The Tuya cloud rejected the command." + }, "device_not_found": { "message": "Feeder with ID {device_id} could not be found." }, @@ -1312,6 +1315,9 @@ }, "invalid_meal_plan_data": { "message": "Unable to parse meal plan data." + }, + "send_command_failed": { + "message": "Failed to send the command to the Tuya cloud." } }, "selector": { diff --git a/tests/components/tuya/test_switch.py b/tests/components/tuya/test_switch.py index 6efd1d4423ed..c3ce9f40ecda 100644 --- a/tests/components/tuya/test_switch.py +++ b/tests/components/tuya/test_switch.py @@ -1,12 +1,15 @@ """Test Tuya switch platform.""" +import re from typing import Any from unittest.mock import patch from freezegun.api import FrozenDateTimeFactory import pytest +import requests from syrupy.assertion import SnapshotAssertion from tuya_sharing import CustomerDevice, Manager +from tuya_sharing.exceptions import ApiRequestException from homeassistant.components.switch import ( DOMAIN as SWITCH_DOMAIN, @@ -15,6 +18,7 @@ from homeassistant.components.switch import ( ) from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from . import TuyaNotificationHelper, check_selective_state_update, initialize_entry @@ -136,6 +140,49 @@ async def test_action( ) +@pytest.mark.usefixtures("no_quirk") +@pytest.mark.parametrize("mock_device_code", ["cz_PGEkBctAbtzKOZng"]) +@pytest.mark.parametrize( + ("side_effect", "expected_message"), + [ + pytest.param( + ApiRequestException(error_code="-9999999", error_message="sign invalid"), + "The Tuya cloud rejected the command", + id="rejected", + ), + pytest.param( + requests.exceptions.ConnectionError, + "Failed to send the command to the Tuya cloud", + id="connection_error", + ), + pytest.param( + requests.exceptions.Timeout, + "Failed to send the command to the Tuya cloud", + id="timeout", + ), + ], +) +async def test_action_error( + hass: HomeAssistant, + mock_manager: Manager, + mock_config_entry: MockConfigEntry, + mock_device: CustomerDevice, + side_effect: Exception, + expected_message: str, +) -> None: + """Test errors while sending a command are raised as Home Assistant errors.""" + await initialize_entry(hass, mock_manager, mock_config_entry, mock_device) + mock_manager.send_commands.side_effect = side_effect + + with pytest.raises(HomeAssistantError, match=re.escape(expected_message)): + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.din_socket"}, + blocking=True, + ) + + @pytest.mark.parametrize( "mock_device_code", ["cz_PGEkBctAbtzKOZng"], From b64f01ade9ec2ec27706a6ab10e5148a49302648 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 08:01:20 +0200 Subject: [PATCH 173/356] Default the LaMetric message icon like notify does (#184624) --- homeassistant/components/lametric/services.py | 2 +- tests/components/lametric/test_services.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/lametric/services.py b/homeassistant/components/lametric/services.py index 1c10a58e00b1..40646c73ce64 100644 --- a/homeassistant/components/lametric/services.py +++ b/homeassistant/components/lametric/services.py @@ -90,7 +90,7 @@ def async_setup_services(hass: HomeAssistant) -> None: call, [ Simple( - icon=call.data.get(CONF_ICON), + icon=call.data.get(CONF_ICON, "a7956"), text=call.data[CONF_MESSAGE], ) ], diff --git a/tests/components/lametric/test_services.py b/tests/components/lametric/test_services.py index b9b5c4c8b3ad..7797461fb7b7 100644 --- a/tests/components/lametric/test_services.py +++ b/tests/components/lametric/test_services.py @@ -155,7 +155,7 @@ async def test_service_message( assert len(notification.model.frames) == 1 frame = notification.model.frames[0] assert type(frame) is Simple - assert frame.icon is None + assert frame.icon == "a7956" assert frame.text == "Hi!" await hass.services.async_call( From 5e731d0f2334eaf8e2889646375ef565c02558a0 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 11:50:48 +0200 Subject: [PATCH 174/356] Keep updating collection helper entities after an entity ID change (#184631) --- homeassistant/helpers/collection.py | 14 +++++++++- tests/helpers/test_collection.py | 43 +++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/collection.py b/homeassistant/helpers/collection.py index 07d089b11592..4e985f6349cc 100644 --- a/homeassistant/helpers/collection.py +++ b/homeassistant/helpers/collection.py @@ -489,8 +489,20 @@ class _CollectionLifeCycle[_EntityT: Entity = Entity]: # the entity registry event handled by Entity._async_registry_updated entities.pop(item_id, None) + def _get_entity(self, item_id: str) -> CollectionEntity | None: + """Return the live entity for an item.""" + # Changing the entity ID removes and re-adds the entity, which drops it + # from self.entities, so look it up through the registry first + if entity_id := self.ent_reg.async_get_entity_id( + self.domain, self.platform, item_id + ): + entity = self.entity_component.get_entity(entity_id) + return entity if isinstance(entity, CollectionEntity) else None + + return self.entities.get(item_id) + async def _update_entity(self, change_set: CollectionChange) -> None: - if entity := self.entities.get(change_set.item_id): + if entity := self._get_entity(change_set.item_id): if change_set.item_hash: self.ent_reg.async_update_entity_options( entity.entity_id, "collection", {"hash": change_set.item_hash} diff --git a/tests/helpers/test_collection.py b/tests/helpers/test_collection.py index 9d78b5202051..afc8f16ead9a 100644 --- a/tests/helpers/test_collection.py +++ b/tests/helpers/test_collection.py @@ -373,6 +373,49 @@ async def test_attach_entity_component_collection(hass: HomeAssistant) -> None: assert hass.states.get("test.mock_1") is None +async def test_entity_component_collection_update_after_entity_id_change( + hass: HomeAssistant, entity_registry: er.EntityRegistry +) -> None: + """Test updates still reach the entity after its entity ID changed.""" + ent_comp = entity_component.EntityComponent(_LOGGER, "test", hass) + await ent_comp.async_setup({}) + coll = MockObservableCollection(None) + collection.sync_entity_lifecycle(hass, "test", "test", ent_comp, coll, MockEntity) + + await coll.notify_changes( + [ + collection.CollectionChange( + collection.CHANGE_ADDED, + "mock_id", + {"id": "mock_id", "state": "initial", "name": "Mock 1"}, + ) + ], + ) + + entity_registry.async_update_entity("test.mock_1", new_entity_id="test.renamed") + await hass.async_block_till_done() + assert hass.states.get("test.renamed").state == "initial" + + await coll.notify_changes( + [ + collection.CollectionChange( + collection.CHANGE_UPDATED, + "mock_id", + {"id": "mock_id", "state": "second", "name": "Mock 1 updated"}, + ) + ], + ) + + assert hass.states.get("test.renamed").name == "Mock 1 updated" + assert hass.states.get("test.renamed").state == "second" + + await coll.notify_changes( + [collection.CollectionChange(collection.CHANGE_REMOVED, "mock_id", None)], + ) + + assert hass.states.get("test.renamed") is None + + async def test_entity_component_collection_abort( hass: HomeAssistant, entity_registry: er.EntityRegistry ) -> None: From 8ddbb13aa70536ec3f305ceb83cf69eff630bf78 Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Wed, 7 Oct 2026 18:20:09 +1000 Subject: [PATCH 175/356] Clear Teslemetry route entities when navigation ends (#184638) --- .../components/teslemetry/device_tracker.py | 4 +- homeassistant/components/teslemetry/sensor.py | 4 +- .../teslemetry/test_device_tracker.py | 53 ++++++++- tests/components/teslemetry/test_sensor.py | 102 +++++++++++++++++- 4 files changed, 157 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/teslemetry/device_tracker.py b/homeassistant/components/teslemetry/device_tracker.py index 97dcd8b1515d..dcc066d444e3 100644 --- a/homeassistant/components/teslemetry/device_tracker.py +++ b/homeassistant/components/teslemetry/device_tracker.py @@ -47,8 +47,8 @@ DESCRIPTIONS: tuple[TeslemetryDeviceTrackerEntityDescription, ...] = ( TeslemetryDeviceTrackerEntityDescription( key="route", polling_prefix="drive_state_active_route", - value_listener=lambda vehicle, callback: vehicle.listen_DestinationLocation( - callback + value_listener=lambda vehicle, callback: ( + vehicle.listen_ActiveRouteDestinationLocation(callback) ), streaming_firmware="2024.26", ), diff --git a/homeassistant/components/teslemetry/sensor.py b/homeassistant/components/teslemetry/sensor.py index a58ce014e519..5a5e8ab964ba 100644 --- a/homeassistant/components/teslemetry/sensor.py +++ b/homeassistant/components/teslemetry/sensor.py @@ -567,7 +567,7 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryVehicleSensorEntityDescription, ...] = ( key="drive_state_active_route_traffic_minutes_delay", polling=True, streaming_listener=lambda vehicle, callback: ( - vehicle.listen_RouteTrafficMinutesDelay(callback) + vehicle.listen_ActiveRouteTrafficMinutesDelay(callback) ), state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=UnitOfTime.MINUTES, @@ -578,7 +578,7 @@ VEHICLE_DESCRIPTIONS: tuple[TeslemetryVehicleSensorEntityDescription, ...] = ( key="drive_state_active_route_energy_at_arrival", polling=True, streaming_listener=lambda vehicle, callback: ( - vehicle.listen_ExpectedEnergyPercentAtTripArrival(callback) + vehicle.listen_ActiveRouteExpectedEnergyPercentAtTripArrival(callback) ), state_class=SensorStateClass.MEASUREMENT, native_unit_of_measurement=PERCENTAGE, diff --git a/tests/components/teslemetry/test_device_tracker.py b/tests/components/teslemetry/test_device_tracker.py index c9e40028e1c3..50b28c979612 100644 --- a/tests/components/teslemetry/test_device_tracker.py +++ b/tests/components/teslemetry/test_device_tracker.py @@ -6,7 +6,7 @@ import pytest from syrupy.assertion import SnapshotAssertion from teslemetry_stream.const import Signal -from homeassistant.const import Platform +from homeassistant.const import ATTR_LATITUDE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -81,6 +81,7 @@ async def test_device_tracker_streaming( "latitude": 3.0, "longitude": 4.0, }, + Signal.MINUTES_TO_ARRIVAL: 12.5, Signal.ORIGIN_LOCATION: None, }, "createdAt": "2024-10-04T10:45:17.537Z", @@ -101,3 +102,53 @@ async def test_device_tracker_streaming( assert hass.states.get("device_tracker.test_location").state == "not_home" assert hass.states.get("device_tracker.test_route").state == "not_home" assert hass.states.get("device_tracker.test_origin").state == "unknown" + + +async def test_device_tracker_streaming_route_ends( + hass: HomeAssistant, + mock_add_listener: AsyncMock, +) -> None: + """Test the streaming route tracker clears when navigation ends.""" + await setup_platform(hass, [Platform.DEVICE_TRACKER]) + vin = VEHICLE_DATA_ALT["response"]["vin"] + + mock_add_listener.send( + { + "vin": vin, + "data": { + Signal.DESTINATION_LOCATION: { + "latitude": -27.824252, + "longitude": 153.328079, + }, + Signal.DESTINATION_NAME: "Home", + Signal.MINUTES_TO_ARRIVAL: 12.5, + Signal.MILES_TO_ARRIVAL: 6.2, + }, + "createdAt": "2026-09-28T08:40:00.000Z", + } + ) + await hass.async_block_till_done() + assert (state := hass.states.get("device_tracker.test_route")) + assert state.attributes[ATTR_LATITUDE] == -27.824252 + + # The car keeps reporting the last destination after arriving, but the + # route fields go null. + mock_add_listener.send( + { + "vin": vin, + "data": { + Signal.DESTINATION_LOCATION: { + "latitude": -27.824252, + "longitude": 153.328079, + }, + Signal.DESTINATION_NAME: None, + Signal.MINUTES_TO_ARRIVAL: None, + Signal.MILES_TO_ARRIVAL: None, + }, + "createdAt": "2026-09-28T08:59:11.879Z", + } + ) + await hass.async_block_till_done() + assert (state := hass.states.get("device_tracker.test_route")) + assert state.state == STATE_UNKNOWN + assert ATTR_LATITUDE not in state.attributes diff --git a/tests/components/teslemetry/test_sensor.py b/tests/components/teslemetry/test_sensor.py index 8598025bc470..65ed23deab23 100644 --- a/tests/components/teslemetry/test_sensor.py +++ b/tests/components/teslemetry/test_sensor.py @@ -19,6 +19,7 @@ from homeassistant.components.teslemetry.coordinator import VEHICLE_INTERVAL from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, + EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STATE_UNKNOWN, EntityCategory, @@ -39,7 +40,7 @@ from .const import ( VEHICLE_DATA_ALT, ) -from tests.common import async_fire_time_changed +from tests.common import async_capture_events, async_fire_time_changed # VIN used across the Teslemetry test fixtures. VEHICLE_VIN = "LRW3F7EK4NC700000" @@ -442,6 +443,105 @@ async def test_sensors_streaming_unit_conversion( assert float(state.state) == pytest.approx(expected_state) +@pytest.mark.parametrize( + ("updates", "expected_delay", "expected_energy"), + [ + pytest.param( + [ + { + Signal.MINUTES_TO_ARRIVAL: 12.5, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 3, + Signal.EXPECTED_ENERGY_PERCENT_AT_TRIP_ARRIVAL: 62, + }, + # The car keeps reporting the last trip's arrival energy and + # traffic delay after arriving, but MinutesToArrival goes null. + { + Signal.MINUTES_TO_ARRIVAL: None, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 0, + Signal.EXPECTED_ENERGY_PERCENT_AT_TRIP_ARRIVAL: 62, + }, + ], + ["3", STATE_UNKNOWN], + ["62", STATE_UNKNOWN], + id="route_ends", + ), + pytest.param( + [ + { + Signal.MINUTES_TO_ARRIVAL: 12.5, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 3, + }, + { + Signal.MINUTES_TO_ARRIVAL: None, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 0, + }, + { + Signal.MINUTES_TO_ARRIVAL: 30.0, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 5, + }, + ], + ["3", STATE_UNKNOWN, "5"], + [], + id="route_restarts", + ), + pytest.param( + [ + { + Signal.MINUTES_TO_ARRIVAL: 12.5, + Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 3, + }, + {Signal.MINUTES_TO_ARRIVAL: None}, + {Signal.MINUTES_TO_ARRIVAL: 20.0}, + ], + ["3", STATE_UNKNOWN, "3"], + [], + id="route_restarts_with_unchanged_value", + ), + pytest.param( + [ + {Signal.ROUTE_TRAFFIC_MINUTES_DELAY: 3}, + {Signal.MINUTES_TO_ARRIVAL: 12.5}, + ], + ["3"], + [], + id="waits_for_minutes_to_arrival", + ), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_sensors_streaming_active_route( + hass: HomeAssistant, + mock_add_listener: AsyncMock, + updates: list[dict[Signal, float | None]], + expected_delay: list[str], + expected_energy: list[str], +) -> None: + """Test the streaming active route sensors only report during navigation.""" + await setup_platform(hass, [Platform.SENSOR]) + events = async_capture_events(hass, EVENT_STATE_CHANGED) + + for data in updates: + mock_add_listener.send( + { + "vin": VEHICLE_DATA_ALT["response"]["vin"], + "data": data, + "createdAt": "2026-09-28T08:40:00.000Z", + } + ) + await hass.async_block_till_done() + + assert [ + event.data["new_state"].state + for event in events + if event.data["entity_id"] == "sensor.test_traffic_delay" + ] == expected_delay + assert [ + event.data["new_state"].state + for event in events + if event.data["entity_id"] == "sensor.test_state_of_charge_at_arrival" + ] == expected_energy + + @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_sensors_streaming_tpms_none_clears_state( hass: HomeAssistant, From e89491db029ed005d2d85a07d209e2ac2c51bf35 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 09:20:43 +0200 Subject: [PATCH 176/356] Turn off timed out Tractive LED and buzzer switches (#184644) --- homeassistant/components/tractive/__init__.py | 9 ++++ tests/components/tractive/test_switch.py | 45 +++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/homeassistant/components/tractive/__init__.py b/homeassistant/components/tractive/__init__.py index 63594c86ed64..54711cec8ba1 100644 --- a/homeassistant/components/tractive/__init__.py +++ b/homeassistant/components/tractive/__init__.py @@ -24,7 +24,9 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.dispatcher import async_dispatcher_send from .const import ( + ATTR_BUZZER, ATTR_DAILY_GOAL, + ATTR_LED, ATTR_MINUTES_ACTIVE, ATTR_MINUTES_DAY_SLEEP, ATTR_MINUTES_NIGHT_SLEEP, @@ -323,6 +325,13 @@ class TractiveClient: for switch, key in SWITCH_KEY_MAP.items(): if switch_data := event.get(key): payload[switch] = switch_data["active"] + # A timed out LED or buzzer is still reported as active, with + # no time remaining + if ( + switch in (ATTR_BUZZER, ATTR_LED) + and switch_data.get("remaining") == 0 + ): + payload[switch] = False if hardware := event.get("hardware", {}): payload[ATTR_POWER_SAVING] = ( hardware.get("power_saving_zone_id") is not None diff --git a/tests/components/tractive/test_switch.py b/tests/components/tractive/test_switch.py index eb34dcf7e8b2..a98fd85c7d4c 100644 --- a/tests/components/tractive/test_switch.py +++ b/tests/components/tractive/test_switch.py @@ -81,6 +81,51 @@ async def test_switch_on( assert state.state == STATE_ON +@pytest.mark.parametrize( + ("entity_id", "event_key"), + [ + pytest.param("switch.tracker_device_id_123_led", "led_control", id="led"), + pytest.param( + "switch.tracker_device_id_123_buzzer", "buzzer_control", id="buzzer" + ), + ], +) +async def test_timed_switch_off_when_expired( + hass: HomeAssistant, + mock_tractive_client: AsyncMock, + mock_config_entry: MockConfigEntry, + entity_id: str, + event_key: str, +) -> None: + """Test a timed switch turns off once its time ran out.""" + await init_integration(hass, mock_config_entry) + + mock_tractive_client.send_switch_event( + mock_config_entry, + { + "tracker_id": "device_id_123", + event_key: {"active": True, "timeout": 900, "remaining": 896}, + }, + ) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_ON + + # The API keeps reporting the control as active after it timed out + mock_tractive_client.send_switch_event( + mock_config_entry, + { + "tracker_id": "device_id_123", + event_key: {"active": True, "timeout": 900, "remaining": 0}, + }, + ) + await hass.async_block_till_done() + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_OFF + + async def test_switch_off( hass: HomeAssistant, mock_tractive_client: AsyncMock, From 2917c56e831a1518a0928d1185fb9aa1ee2d2f61 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Wed, 7 Oct 2026 10:21:06 +0200 Subject: [PATCH 177/356] Handle stream errors while waiting for UniFi Protect playback (#184650) --- .../components/unifiprotect/media_player.py | 11 ++-- .../unifiprotect/test_media_player.py | 52 +++++++++++++++++++ 2 files changed, 56 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/unifiprotect/media_player.py b/homeassistant/components/unifiprotect/media_player.py index bd948534fbc9..18fff59ee92e 100644 --- a/homeassistant/components/unifiprotect/media_player.py +++ b/homeassistant/components/unifiprotect/media_player.py @@ -146,19 +146,16 @@ class ProtectMediaPlayer(ProtectDeviceEntity, MediaPlayerEntity): await self.async_media_stop() try: await self.device.play_audio(media_id, blocking=False) + self._async_updated_event(self.device) + await self.device.wait_until_audio_completes() except StreamError as err: _LOGGER.debug("Error playing audio: %s", err) raise HomeAssistantError( translation_domain=DOMAIN, translation_key="stream_error", ) from err - - # update state after starting player - self._async_updated_event(self.device) - # wait until player finishes to update state again - await self.device.wait_until_audio_completes() - - self._async_updated_event(self.device) + finally: + self._async_updated_event(self.device) @override async def async_browse_media( diff --git a/tests/components/unifiprotect/test_media_player.py b/tests/components/unifiprotect/test_media_player.py index b9dee4dc2d7c..3698f52a5544 100644 --- a/tests/components/unifiprotect/test_media_player.py +++ b/tests/components/unifiprotect/test_media_player.py @@ -1,5 +1,6 @@ """Test the UniFi Protect media_player platform.""" +import logging from unittest.mock import AsyncMock, Mock, patch import pytest @@ -293,3 +294,54 @@ async def test_media_player_play_error( assert mock_play.called assert not mock_wait.called + + +async def test_media_player_play_wait_error( + hass: HomeAssistant, + ufp: MockUFPFixture, + doorbell: Camera, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a stream error while waiting for playback raises and resets the state.""" + + await init_entry(hass, ufp, [doorbell]) + assert_entity_counts(hass, Platform.MEDIA_PLAYER, 1, 1) + + doorbell.talkback_stream = Mock(is_running=True) + + async def _wait_fails() -> None: + assert ( + hass.states.get("media_player.test_camera_speaker").state == STATE_PLAYING + ) + doorbell.talkback_stream.is_running = False + raise StreamError("Audio streaming failed") + + with ( + patch_ufp_method(doorbell, "stop_audio", new_callable=AsyncMock), + patch_ufp_method(doorbell, "play_audio", new_callable=AsyncMock), + patch_ufp_method( + doorbell, + "wait_until_audio_completes", + new_callable=AsyncMock, + side_effect=_wait_fails, + ), + pytest.raises(HomeAssistantError) as exc_info, + ): + await hass.services.async_call( + "media_player", + "play_media", + { + ATTR_ENTITY_ID: "media_player.test_camera_speaker", + "media_content_id": "http://example.com/test.mp3", + "media_content_type": "music", + }, + blocking=True, + ) + + assert exc_info.value.translation_key == "stream_error" + assert ( + "homeassistant.components.unifiprotect.media_player", + logging.DEBUG, + "Error playing audio: Audio streaming failed", + ) in caplog.record_tuples + assert hass.states.get("media_player.test_camera_speaker").state == STATE_IDLE From 677416a5eec0208f1ca3d6981fa48a50ba55dbd0 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Wed, 7 Oct 2026 11:08:15 +0200 Subject: [PATCH 178/356] Bump uiprotect to 23.0.1 (#184655) --- homeassistant/components/unifiprotect/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/unifiprotect/manifest.json b/homeassistant/components/unifiprotect/manifest.json index 3a94273a8243..84563dc93a94 100644 --- a/homeassistant/components/unifiprotect/manifest.json +++ b/homeassistant/components/unifiprotect/manifest.json @@ -9,5 +9,5 @@ "iot_class": "local_push", "loggers": ["uiprotect"], "quality_scale": "platinum", - "requirements": ["uiprotect==23.0.0"] + "requirements": ["uiprotect==23.0.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 57076f7274ad..07da574c8857 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3326,7 +3326,7 @@ uasiren==0.0.1 uhooapi==1.2.8 # homeassistant.components.unifiprotect -uiprotect==23.0.0 +uiprotect==23.0.1 # homeassistant.components.landisgyr_heat_meter ultraheat-api==0.6.1 From 75849002f8d9ee4c13f05e1883a4bbea4495b63e Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Wed, 7 Oct 2026 12:49:02 +0200 Subject: [PATCH 179/356] Add repair flow for Renault Kamereon account changes (#184661) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/renault/__init__.py | 48 ++++- .../components/renault/renault_hub.py | 22 ++- homeassistant/components/renault/repairs.py | 111 ++++++++++++ homeassistant/components/renault/strings.json | 27 +++ tests/components/renault/conftest.py | 22 +++ tests/components/renault/const.py | 6 + tests/components/renault/test_init.py | 87 ++++++++- tests/components/renault/test_repairs.py | 166 ++++++++++++++++++ 8 files changed, 482 insertions(+), 7 deletions(-) create mode 100644 homeassistant/components/renault/repairs.py create mode 100644 tests/components/renault/test_repairs.py diff --git a/homeassistant/components/renault/__init__.py b/homeassistant/components/renault/__init__.py index 34c7ca49e9be..04d006a441d1 100644 --- a/homeassistant/components/renault/__init__.py +++ b/homeassistant/components/renault/__init__.py @@ -3,11 +3,20 @@ import aiohttp from renault_api.exceptions import NotAuthenticatedException from renault_api.gigya.exceptions import GigyaException +from renault_api.kamereon.exceptions import ForbiddenException from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady -from homeassistant.helpers import config_validation as cv, device_registry as dr +from homeassistant.exceptions import ( + ConfigEntryAuthFailed, + ConfigEntryError, + ConfigEntryNotReady, +) +from homeassistant.helpers import ( + config_validation as cv, + device_registry as dr, + issue_registry as ir, +) from homeassistant.helpers.typing import ConfigType from .const import DOMAIN, PLATFORMS, RenaultConfigurationKeys @@ -18,6 +27,11 @@ CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) type RenaultConfigEntry = ConfigEntry[RenaultHub] +def _account_not_found_issue_id(entry_id: str) -> str: + """Return the issue id for a Kamereon account that no longer exists.""" + return f"account_not_found_{entry_id}" + + async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Renault component.""" async_setup_services(hass) @@ -33,9 +47,30 @@ async def async_setup_entry( await renault_hub.async_initialise(config_entry) except NotAuthenticatedException as exc: raise ConfigEntryAuthFailed from exc + except ForbiddenException as exc: + account_id = config_entry.data[RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID] + if account_id not in await renault_hub.get_all_account_ids(): + ir.async_create_issue( + hass, + DOMAIN, + _account_not_found_issue_id(config_entry.entry_id), + is_fixable=True, + severity=ir.IssueSeverity.ERROR, + translation_key="account_not_found", + translation_placeholders={"account_id": account_id}, + data={"entry_id": config_entry.entry_id}, + ) + raise ConfigEntryError( + translation_domain=DOMAIN, + translation_key="account_forbidden", + translation_placeholders={"account_id": account_id}, + ) from exc except (aiohttp.ClientError, GigyaException) as exc: raise ConfigEntryNotReady from exc + ir.async_delete_issue( + hass, DOMAIN, _account_not_found_issue_id(config_entry.entry_id) + ) config_entry.runtime_data = renault_hub await hass.config_entries.async_forward_entry_setups(config_entry, PLATFORMS) @@ -50,6 +85,15 @@ async def async_unload_entry( return await hass.config_entries.async_unload_platforms(config_entry, PLATFORMS) +async def async_remove_entry( + hass: HomeAssistant, config_entry: RenaultConfigEntry +) -> None: + """Remove the repair issue of a removed config entry.""" + ir.async_delete_issue( + hass, DOMAIN, _account_not_found_issue_id(config_entry.entry_id) + ) + + async def async_remove_config_entry_device( hass: HomeAssistant, config_entry: RenaultConfigEntry, diff --git a/homeassistant/components/renault/renault_hub.py b/homeassistant/components/renault/renault_hub.py index d9beb1d5301e..8a9b56201485 100644 --- a/homeassistant/components/renault/renault_hub.py +++ b/homeassistant/components/renault/renault_hub.py @@ -99,9 +99,8 @@ class RenaultHub: return True return False - async def async_initialise(self, config_entry: RenaultConfigEntry) -> None: - """Set up proxy.""" - # Reuse the stored login token, or fall back to a password login. + async def async_login(self, config_entry: RenaultConfigEntry) -> None: + """Log in with the stored login token, or fall back to the password.""" if login_token := config_entry.data.get(RenaultConfigurationKeys.LOGIN_TOKEN): self._client.session.set_login_token(login_token) elif await self.attempt_login( @@ -119,6 +118,10 @@ class RenaultHub: else: raise NotAuthenticatedException + async def async_initialise(self, config_entry: RenaultConfigEntry) -> None: + """Set up proxy.""" + await self.async_login(config_entry) + account_id: str = config_entry.data[ RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID ] @@ -210,6 +213,19 @@ class RenaultHub: accounts.append(account.account_id) return accounts + async def get_all_account_ids(self) -> list[str]: + """Get all Kamereon account ids, including those without vehicles.""" + return [account.account_id for account in await self._client.get_api_accounts()] + + async def get_account_ids_for_vins(self, vins: set[str]) -> list[str]: + """Get Kamereon account ids linked to any of the given vehicles.""" + accounts = [] + for account in await self._client.get_api_accounts(): + vehicle_links = await _get_filtered_vehicles(account) + if any(link.vin in vins for link in vehicle_links): + accounts.append(account.account_id) + return accounts + @property def vehicles(self) -> dict[str, RenaultVehicleProxy]: """Get list of vehicles.""" diff --git a/homeassistant/components/renault/repairs.py b/homeassistant/components/renault/repairs.py new file mode 100644 index 000000000000..3915a2c23c53 --- /dev/null +++ b/homeassistant/components/renault/repairs.py @@ -0,0 +1,111 @@ +"""Repairs for the Renault integration.""" + +from typing import TYPE_CHECKING, Any + +import aiohttp +import probatio +from renault_api.exceptions import NotAuthenticatedException +from renault_api.gigya.exceptions import GigyaException +from renault_api.kamereon.exceptions import KamereonResponseException + +from homeassistant.components.repairs import RepairsFlow, RepairsFlowResult +from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr + +from .const import DOMAIN, RenaultConfigurationKeys +from .renault_hub import RenaultHub + +if TYPE_CHECKING: + from . import RenaultConfigEntry + + +class AccountNotFoundRepairFlow(RepairsFlow): + """Move a config entry to the new Kamereon account of its vehicles.""" + + def __init__(self, entry: RenaultConfigEntry) -> None: + """Initialize the repair flow.""" + self._entry = entry + + async def async_step_init( + self, user_input: dict[str, Any] | None = None + ) -> RepairsFlowResult: + """Handle the first step of the repair flow.""" + return await self.async_step_account() + + async def async_step_account( + self, user_input: dict[str, Any] | None = None + ) -> RepairsFlowResult: + """Select the new Kamereon account.""" + old_account_id = self._entry.data[RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID] + if user_input is not None: + new_account_id = user_input[RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID] + self.hass.config_entries.async_update_entry( + self._entry, + data={ + **self._entry.data, + RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID: new_account_id, + }, + unique_id=new_account_id, + # The entry title defaults to the account id. + title=new_account_id + if self._entry.title == old_account_id + else self._entry.title, + ) + self.hass.config_entries.async_schedule_reload(self._entry.entry_id) + return self.async_create_entry(data={}) + + device_registry = dr.async_get(self.hass) + vins = { + identifier[1] + for device in dr.async_entries_for_config_entry( + device_registry, self._entry.entry_id + ) + for identifier in device.identifiers + if identifier[0] == DOMAIN + } + hub = RenaultHub(self.hass, self._entry.data[RenaultConfigurationKeys.LOCALE]) + try: + await hub.async_login(self._entry) + account_ids = await hub.get_account_ids_for_vins(vins) + except NotAuthenticatedException: + self._entry.async_start_reauth(self.hass) + return self.async_abort(reason="reauth_required") + except aiohttp.ClientError, GigyaException, KamereonResponseException: + return self.async_abort(reason="cannot_connect") + + configured_account_ids = { + entry.unique_id for entry in self.hass.config_entries.async_entries(DOMAIN) + } + candidates = [ + account_id + for account_id in account_ids + if account_id not in configured_account_ids + ] + if not candidates: + return self.async_abort( + reason="no_new_account", + description_placeholders={"account_id": old_account_id}, + ) + + return self.async_show_form( + step_id="account", + data_schema=probatio.Schema( + { + probatio.Required( + RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID, + default=candidates[0], + ): probatio.In(candidates) + } + ), + description_placeholders={"account_id": old_account_id}, + ) + + +async def async_create_fix_flow( + hass: HomeAssistant, issue_id: str, data: dict[str, Any] | None +) -> RepairsFlow: + """Create the repair flow for a Kamereon account that no longer exists.""" + assert data + return AccountNotFoundRepairFlow( + hass.config_entries.async_get_known_entry(data["entry_id"]) + ) diff --git a/homeassistant/components/renault/strings.json b/homeassistant/components/renault/strings.json index a44daa145880..45ab0601ae4f 100644 --- a/homeassistant/components/renault/strings.json +++ b/homeassistant/components/renault/strings.json @@ -210,6 +210,9 @@ } }, "exceptions": { + "account_forbidden": { + "message": "Access to Kamereon account {account_id} was denied by the Renault servers" + }, "battery_soc_unavailable": { "message": "Battery state of charge data is currently unavailable" }, @@ -220,6 +223,30 @@ "message": "An unknown error occurred while communicating with the Renault servers: {error}" } }, + "issues": { + "account_not_found": { + "fix_flow": { + "abort": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "no_new_account": "No other Kamereon account linked to your vehicles was found. If you already added your vehicles again under a new Renault entry, delete the entry for account {account_id}.", + "reauth_required": "Your Renault login is no longer valid. Re-authenticate the Renault integration, then open this repair again." + }, + "step": { + "account": { + "data": { + "kamereon_account_id": "[%key:component::renault::config::step::kamereon::data::kamereon_account_id%]" + }, + "data_description": { + "kamereon_account_id": "The new Kamereon account ID linked to your vehicles" + }, + "description": "Renault no longer lists the Kamereon account {account_id}, so Home Assistant can't load your vehicles. Renault may have moved your vehicles to a new account.\n\nSelect the new account to keep using your existing devices and entities. The integration is reloaded once you submit.", + "title": "Select the new Kamereon account" + } + } + }, + "title": "Renault account {account_id} no longer exists" + } + }, "services": { "ac_cancel": { "description": "Cancels A/C on vehicle.", diff --git a/tests/components/renault/conftest.py b/tests/components/renault/conftest.py index 99ec1d57c40b..2fcd78a78a4f 100644 --- a/tests/components/renault/conftest.py +++ b/tests/components/renault/conftest.py @@ -63,6 +63,28 @@ async def patch_renault_account(hass: HomeAssistant) -> AsyncGenerator[RenaultAc yield renault_account +@pytest.fixture(name="account_ids") +def get_account_ids() -> list[str]: + """Kamereon account ids returned by the Renault servers.""" + return [MOCK_ACCOUNT_ID] + + +@pytest.fixture(name="patch_get_api_accounts") +def patch_get_api_accounts( + hass: HomeAssistant, account_ids: list[str] +) -> Generator[None]: + """Mock the list of Kamereon accounts.""" + websession = aiohttp_client.async_get_clientsession(hass) + with patch( + "renault_api.renault_client.RenaultClient.get_api_accounts", + return_value=[ + RenaultAccount(account_id, websession=websession) + for account_id in account_ids + ], + ): + yield + + @pytest.fixture(name="patch_get_vehicles") def patch_get_vehicles(vehicle_type: str) -> Generator[None]: """Mock fixtures.""" diff --git a/tests/components/renault/const.py b/tests/components/renault/const.py index 35f6daf504cb..db970e3a7365 100644 --- a/tests/components/renault/const.py +++ b/tests/components/renault/const.py @@ -1,8 +1,14 @@ """Constants for the Renault integration tests.""" +from renault_api.kamereon.exceptions import ForbiddenException + from homeassistant.components.renault.const import RenaultConfigurationKeys MOCK_ACCOUNT_ID = "account_id_1" +OTHER_ACCOUNT_ID = "account_id_2" +FORBIDDEN_EXCEPTION = ForbiddenException( + "err.func.wired.forbidden", "The access is forbidden" +) MOCK_LOGIN_TOKEN = "sample-login-token" # Mock config data to be used across multiple tests diff --git a/tests/components/renault/test_init.py b/tests/components/renault/test_init.py index c8eb572e3135..7846d154297f 100644 --- a/tests/components/renault/test_init.py +++ b/tests/components/renault/test_init.py @@ -18,10 +18,15 @@ from homeassistant.config_entries import ( ConfigEntryState, ) 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.setup import async_setup_component -from .const import MOCK_ACCOUNT_ID, MOCK_LOGIN_TOKEN +from .const import ( + FORBIDDEN_EXCEPTION, + MOCK_ACCOUNT_ID, + MOCK_LOGIN_TOKEN, + OTHER_ACCOUNT_ID, +) from tests.common import MockConfigEntry from tests.typing import WebSocketGenerator @@ -197,6 +202,84 @@ async def test_setup_entry_kamereon_exception( assert config_entry.state is ConfigEntryState.SETUP_RETRY +@pytest.mark.usefixtures("patch_renault_account", "patch_get_api_accounts") +@pytest.mark.parametrize( + ("account_ids", "expected_issues"), + [ + pytest.param([MOCK_ACCOUNT_ID], set(), id="account_listed"), + pytest.param( + [OTHER_ACCOUNT_ID], + {(DOMAIN, "account_not_found_123456")}, + id="account_not_listed", + ), + ], +) +async def test_setup_entry_forbidden( + hass: HomeAssistant, + config_entry: ConfigEntry, + issue_registry: ir.IssueRegistry, + expected_issues: set[tuple[str, str]], +) -> None: + """Test a forbidden Kamereon account fails setup without retrying.""" + with patch( + "renault_api.renault_account.RenaultAccount.get_vehicles", + side_effect=FORBIDDEN_EXCEPTION, + ): + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.SETUP_ERROR + assert set(issue_registry.issues) == expected_issues + + +@pytest.mark.usefixtures( + "patch_renault_account", "patch_get_api_accounts", "patch_get_vehicles" +) +@pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True) +@pytest.mark.parametrize("account_ids", [[OTHER_ACCOUNT_ID]]) +async def test_account_not_found_issue_deleted_on_setup( + hass: HomeAssistant, + config_entry: ConfigEntry, + issue_registry: ir.IssueRegistry, +) -> None: + """Test the issue is deleted once the account loads again.""" + with patch( + "renault_api.renault_account.RenaultAccount.get_vehicles", + side_effect=FORBIDDEN_EXCEPTION, + ): + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert len(issue_registry.issues) == 1 + + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.LOADED + assert len(issue_registry.issues) == 0 + + +@pytest.mark.usefixtures("patch_renault_account", "patch_get_api_accounts") +@pytest.mark.parametrize("account_ids", [[OTHER_ACCOUNT_ID]]) +async def test_account_not_found_issue_deleted_on_removal( + hass: HomeAssistant, + config_entry: ConfigEntry, + issue_registry: ir.IssueRegistry, +) -> None: + """Test the issue is deleted when the config entry is removed.""" + with patch( + "renault_api.renault_account.RenaultAccount.get_vehicles", + side_effect=FORBIDDEN_EXCEPTION, + ): + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + assert len(issue_registry.issues) == 1 + + await hass.config_entries.async_remove(config_entry.entry_id) + await hass.async_block_till_done() + + assert len(issue_registry.issues) == 0 + + @pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") @pytest.mark.parametrize("vehicle_type", ["missing_details"], indirect=True) async def test_setup_entry_missing_vehicle_details( diff --git a/tests/components/renault/test_repairs.py b/tests/components/renault/test_repairs.py new file mode 100644 index 000000000000..f8dfefcfe67e --- /dev/null +++ b/tests/components/renault/test_repairs.py @@ -0,0 +1,166 @@ +"""Tests for Renault repairs.""" + +from collections.abc import Generator +from unittest.mock import patch + +import aiohttp +import pytest +from renault_api.exceptions import NotAuthenticatedException + +from homeassistant.components.renault.const import DOMAIN, RenaultConfigurationKeys +from homeassistant.config_entries import ( + SOURCE_REAUTH, + SOURCE_USER, + ConfigEntry, + ConfigEntryState, +) +from homeassistant.core import HomeAssistant +from homeassistant.data_entry_flow import FlowResultType +from homeassistant.helpers import issue_registry as ir +from homeassistant.setup import async_setup_component + +from .const import FORBIDDEN_EXCEPTION, MOCK_ACCOUNT_ID, MOCK_CONFIG, OTHER_ACCOUNT_ID + +from tests.common import MockConfigEntry +from tests.components.repairs import process_repair_fix_flow, start_repair_fix_flow +from tests.typing import ClientSessionGenerator + +ISSUE_ID = "account_not_found_123456" + +pytestmark = [ + pytest.mark.usefixtures( + "patch_renault_account", "patch_get_api_accounts", "patch_get_vehicles" + ), + pytest.mark.parametrize("vehicle_type", ["zoe_40"], indirect=True), + pytest.mark.parametrize("account_ids", [[OTHER_ACCOUNT_ID]]), +] + + +@pytest.fixture(autouse=True) +def override_platforms() -> Generator[None]: + """Override PLATFORMS.""" + with patch("homeassistant.components.renault.PLATFORMS", []): + yield + + +async def _setup_with_account_not_found( + hass: HomeAssistant, config_entry: ConfigEntry +) -> None: + """Load the entry, then fail setup because its account no longer exists.""" + assert await async_setup_component(hass, "repairs", {}) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + with patch( + "renault_api.renault_account.RenaultAccount.get_vehicles", + side_effect=FORBIDDEN_EXCEPTION, + ): + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done() + assert config_entry.state is ConfigEntryState.SETUP_ERROR + + +@pytest.mark.parametrize( + ("title", "expected_title"), + [ + pytest.param(MOCK_ACCOUNT_ID, OTHER_ACCOUNT_ID, id="default_title"), + pytest.param("My car", "My car", id="custom_title"), + ], +) +async def test_account_not_found_repair( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + issue_registry: ir.IssueRegistry, + config_entry: ConfigEntry, + title: str, + expected_title: str, +) -> None: + """Test moving the entry to the new account of its vehicles.""" + hass.config_entries.async_update_entry(config_entry, title=title) + await _setup_with_account_not_found(hass, config_entry) + + client = await hass_client() + result = await start_repair_fix_flow(client, DOMAIN, ISSUE_ID) + assert result["type"] == FlowResultType.FORM + assert result["step_id"] == "account" + + result = await process_repair_fix_flow( + client, + result["flow_id"], + json={RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID: OTHER_ACCOUNT_ID}, + ) + assert result["type"] == FlowResultType.CREATE_ENTRY + await hass.async_block_till_done() + + assert config_entry.state is ConfigEntryState.LOADED + assert config_entry.unique_id == OTHER_ACCOUNT_ID + assert config_entry.title == expected_title + assert ( + config_entry.data[RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID] + == OTHER_ACCOUNT_ID + ) + assert len(issue_registry.issues) == 0 + + +async def test_account_not_found_repair_already_configured( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + config_entry: ConfigEntry, +) -> None: + """Test the repair aborts when the new account already has an entry.""" + MockConfigEntry( + domain=DOMAIN, + source=SOURCE_USER, + data={ + **MOCK_CONFIG, + RenaultConfigurationKeys.KAMEREON_ACCOUNT_ID: OTHER_ACCOUNT_ID, + }, + unique_id=OTHER_ACCOUNT_ID, + ).add_to_hass(hass) + await _setup_with_account_not_found(hass, config_entry) + + client = await hass_client() + result = await start_repair_fix_flow(client, DOMAIN, ISSUE_ID) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == "no_new_account" + + +@pytest.mark.parametrize( + ("side_effect", "reason", "reauth_flows"), + [ + pytest.param( + aiohttp.ClientConnectionError, "cannot_connect", 0, id="cannot_connect" + ), + pytest.param( + NotAuthenticatedException("Authentication expired."), + "reauth_required", + 1, + id="reauth_required", + ), + ], +) +async def test_account_not_found_repair_login_error( + hass: HomeAssistant, + hass_client: ClientSessionGenerator, + config_entry: ConfigEntry, + side_effect: Exception | type[Exception], + reason: str, + reauth_flows: int, +) -> None: + """Test the repair aborts when the Renault servers can't be used.""" + await _setup_with_account_not_found(hass, config_entry) + + client = await hass_client() + with patch( + "renault_api.renault_client.RenaultClient.get_api_accounts", + side_effect=side_effect, + ): + result = await start_repair_fix_flow(client, DOMAIN, ISSUE_ID) + assert result["type"] == FlowResultType.ABORT + assert result["reason"] == reason + + await hass.async_block_till_done() + assert ( + len(list(config_entry.async_get_active_flows(hass, {SOURCE_REAUTH}))) + == reauth_flows + ) From fb8f6ad9cb1d7499d03ac6310b9859b8f7b555a9 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Wed, 7 Oct 2026 11:52:00 +0200 Subject: [PATCH 180/356] Update frontend to 20260930.2 (#184662) --- homeassistant/components/frontend/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- pylint/plugins/pylint_home_assistant/generated/mdi_icons.py | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 53b71f2c8c34..035d6074311d 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -22,5 +22,5 @@ "integration_type": "system", "preview_features": { "winter_mode": {} }, "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20260930.1"] + "requirements": ["home-assistant-frontend==20260930.2"] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 817486d0ebec..ad9d1fdc3c99 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -40,7 +40,7 @@ habluetooth==7.1.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-frontend==20260930.1 +home-assistant-frontend==20260930.2 home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 diff --git a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py index 5925990b61f8..90b2a92bdada 100644 --- a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py +++ b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py @@ -5,7 +5,7 @@ To update, run python3 -m script.hassfest from typing import Final -FRONTEND_VERSION: Final[str] = "20260930.1" +FRONTEND_VERSION: Final[str] = "20260930.2" MDI_ICONS: Final[set[str]] = { "ab-testing", diff --git a/requirements_all.txt b/requirements_all.txt index 07da574c8857..fa113ae32e7c 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1312,7 +1312,7 @@ hole==0.9.2 holidays==0.106 # homeassistant.components.frontend -home-assistant-frontend==20260930.1 +home-assistant-frontend==20260930.2 # homeassistant.components.conversation home-assistant-intents==2026.10.6 From b5e92b1fd3c47c89441635440a60802d850885b5 Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Wed, 7 Oct 2026 12:00:19 +0200 Subject: [PATCH 181/356] Bump my-pv to 0.0.12 (#184670) --- homeassistant/components/my_pv/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/my_pv/manifest.json b/homeassistant/components/my_pv/manifest.json index c2900328f9ac..e4d9b11bce15 100644 --- a/homeassistant/components/my_pv/manifest.json +++ b/homeassistant/components/my_pv/manifest.json @@ -16,6 +16,6 @@ "iot_class": "local_polling", "loggers": ["my_pv"], "quality_scale": "bronze", - "requirements": ["my-pv==0.0.11"], + "requirements": ["my-pv==0.0.12"], "zeroconf": ["_mypv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index fa113ae32e7c..e4e98e441005 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1686,7 +1686,7 @@ mutesync==0.0.1 mvg==1.6.0 # homeassistant.components.my_pv -my-pv==0.0.11 +my-pv==0.0.12 # homeassistant.components.myuplink myuplink==0.7.0 From fb649569d3136043796837d694b9de4e9b5b7fdc Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 12:44:24 +0200 Subject: [PATCH 182/356] Fix Hue setup failing when devices share a Zigbee MAC (#184672) --- homeassistant/components/hue/v2/device.py | 31 +++++- tests/components/hue/test_bridge.py | 114 +++++++++++++++++++++- 2 files changed, 140 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/hue/v2/device.py b/homeassistant/components/hue/v2/device.py index fb476759a5b8..dc6f3b08a84d 100644 --- a/homeassistant/components/hue/v2/device.py +++ b/homeassistant/components/hue/v2/device.py @@ -35,6 +35,9 @@ async def async_setup_devices(bridge: HueBridge): api: HueBridgeV2 = bridge.api # to satisfy typing dev_reg = dr.async_get(hass) dev_controller = api.devices + # Multi-channel Zigbee devices show up as several Hue devices sharing one MAC, + # while a connection must be unique within the config entry. + mac_owners: dict[str, str] = {} @callback def add_device(hue_resource: Device | Room | Zone | ServiceGroup) -> dr.DeviceEntry: @@ -80,13 +83,20 @@ async def async_setup_devices(bridge: HueBridge): ) zigbee = dev_controller.get_zigbee_connectivity(hue_resource.id) if zigbee and zigbee.mac_address: - params[ATTR_CONNECTIONS] = {(dr.CONNECTION_NETWORK_MAC, zigbee.mac_address)} + mac_owner = mac_owners.setdefault(zigbee.mac_address, hue_resource.id) + if mac_owner == hue_resource.id: + params[ATTR_CONNECTIONS] = { + (dr.CONNECTION_NETWORK_MAC, zigbee.mac_address) + } return dev_reg.async_get_or_create(config_entry_id=entry.entry_id, **params) @callback def remove_device(hue_device_id: str) -> None: """Remove device from registry.""" + for mac, owner in list(mac_owners.items()): + if owner == hue_device_id: + del mac_owners[mac] if device := dev_reg.async_get_device_by_identifier( (DOMAIN, hue_device_id), entry.entry_id ): @@ -104,10 +114,23 @@ async def async_setup_devices(bridge: HueBridge): # updates to existing device will also be handled by this call add_device(hue_resource) + def registration_order(hue_device: Device) -> tuple[bool, bool]: + """Sort the bridge first, then devices already in the registry. + + A new device claiming a MAC that a known device holds would be merged + into that device by the registry. + """ + is_bridge = hue_device.id == api.config.bridge_device.id + is_known = ( + dev_reg.async_get_device_by_identifier( + (DOMAIN, hue_device.id), entry.entry_id + ) + is not None + ) + return (not is_bridge, not is_known) + # create/update all current devices found in controllers - # sort the devices to ensure bridges are added first - hue_devices = list(dev_controller) - hue_devices.sort(key=lambda dev: dev.id != api.config.bridge_device.id) + hue_devices = sorted(dev_controller, key=registration_order) known_devices = [add_device(hue_device) for hue_device in hue_devices] known_devices += [add_device(hue_room) for hue_room in api.groups.room] known_devices += [add_device(hue_zone) for hue_zone in api.groups.zone] diff --git a/tests/components/hue/test_bridge.py b/tests/components/hue/test_bridge.py index 1310d3354423..5725b06ed890 100644 --- a/tests/components/hue/test_bridge.py +++ b/tests/components/hue/test_bridge.py @@ -15,12 +15,14 @@ from homeassistant.components.hue.const import ( CONF_ALLOW_UNREACHABLE, DOMAIN, ) +from homeassistant.components.hue.v2.device import async_setup_devices from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import device_registry as dr from homeassistant.util.json import JsonArrayType -from .conftest import setup_platform +from .conftest import create_config_entry, replace_resources, setup_platform +from .const import FAKE_DEVICE, FAKE_ZIGBEE_CONNECTIVITY from .test_light_v1 import LIGHT_RESPONSE from tests.common import MockConfigEntry, async_capture_events @@ -147,6 +149,116 @@ async def test_bridge_device_v2( assert len(create_events) == 1 +# Two lights in the v2 fixture; the first one's MAC is shared in the tests below +SHARED_MAC_DEVICE_ID = "0b216218-d811-4c95-8c55-bbcda50f9d50" +SECOND_DEVICE_ID = "b9e76da7-ac22-476a-986d-e466e62e962f" +SHARED_MAC = "00:17:88:01:09:aa:bb:65" + + +@pytest.mark.parametrize( + ("registered_before", "mac_owner_id", "other_device_id"), + [ + pytest.param({}, SHARED_MAC_DEVICE_ID, SECOND_DEVICE_ID, id="fresh_install"), + pytest.param( + {SHARED_MAC_DEVICE_ID: False, SECOND_DEVICE_ID: False}, + SHARED_MAC_DEVICE_ID, + SECOND_DEVICE_ID, + id="devices_already_registered", + ), + pytest.param( + {SECOND_DEVICE_ID: True}, + SECOND_DEVICE_ID, + SHARED_MAC_DEVICE_ID, + id="new_device_listed_before_registered_mac_holder", + ), + ], +) +async def test_devices_sharing_a_mac_v2( + hass: HomeAssistant, + mock_bridge_v2: Mock, + v2_resources_test_data: JsonArrayType, + device_registry: dr.DeviceRegistry, + registered_before: dict[str, bool], + mac_owner_id: str, + other_device_id: str, +) -> None: + """Test setting up Hue devices that share one Zigbee MAC. + + Multi-channel controllers (like GLEDOPTO or Dresden FLS-PP3) show up as + several Hue devices with the same MAC address. + """ + await mock_bridge_v2.api.load_test_data( + replace_resources( + v2_resources_test_data, + [ + { + "id": "717afeb6-b1ce-426e-96de-48e8fe037fb0", + "id_v1": "/lights/16", + "mac_address": SHARED_MAC, + "owner": {"rid": SECOND_DEVICE_ID, "rtype": "device"}, + "status": "connected", + "type": "zigbee_connectivity", + } + ], + ) + ) + config_entry = create_config_entry(api_version=2) + config_entry.add_to_hass(hass) + mock_bridge_v2.config_entry = config_entry + for hue_device_id, holds_mac in registered_before.items(): + device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + identifiers={(DOMAIN, hue_device_id)}, + connections={(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} + if holds_mac + else set(), + ) + + await async_setup_devices(mock_bridge_v2) + + mac_owner = device_registry.async_get_device_by_identifier( + (DOMAIN, mac_owner_id), config_entry.entry_id + ) + other_device = device_registry.async_get_device_by_identifier( + (DOMAIN, other_device_id), config_entry.entry_id + ) + assert mac_owner is not None + assert other_device is not None + assert mac_owner.id != other_device.id + assert mac_owner.connections == {(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} + assert other_device.connections == set() + + +async def test_device_sharing_a_mac_added_v2( + hass: HomeAssistant, + mock_bridge_v2: Mock, + v2_resources_test_data: JsonArrayType, + device_registry: dr.DeviceRegistry, +) -> None: + """Test a device added at runtime that shares a MAC with a known device.""" + await mock_bridge_v2.api.load_test_data(v2_resources_test_data) + await setup_platform(hass, mock_bridge_v2, []) + + mock_bridge_v2.api.emit_event( + "add", {**FAKE_ZIGBEE_CONNECTIVITY, "mac_address": SHARED_MAC} + ) + mock_bridge_v2.api.emit_event("add", FAKE_DEVICE) + await hass.async_block_till_done() + + entry_id = mock_bridge_v2.config_entry.entry_id + first_device = device_registry.async_get_device_by_identifier( + (DOMAIN, SHARED_MAC_DEVICE_ID), entry_id + ) + added_device = device_registry.async_get_device_by_identifier( + (DOMAIN, FAKE_DEVICE["id"]), entry_id + ) + assert first_device is not None + assert added_device is not None + assert first_device.id != added_device.id + assert first_device.connections == {(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} + assert added_device.connections == set() + + async def test_bridge_setup_v2(hass: HomeAssistant, mock_api_v2: Mock) -> None: """Test a successful setup for V2 bridge.""" config_entry = MockConfigEntry( From 9eb3d53ae4ebd2e0041dc2e4b891894da6a8fd1b Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Wed, 7 Oct 2026 12:28:41 +0200 Subject: [PATCH 183/356] Bump zinvolt to 1.0.1 (#184673) --- homeassistant/components/zinvolt/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/zinvolt/manifest.json b/homeassistant/components/zinvolt/manifest.json index 0157193ba02b..a81346ad7cf4 100644 --- a/homeassistant/components/zinvolt/manifest.json +++ b/homeassistant/components/zinvolt/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["zinvolt"], "quality_scale": "bronze", - "requirements": ["zinvolt==1.0.0"] + "requirements": ["zinvolt==1.0.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index e4e98e441005..11fa29e19004 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3547,7 +3547,7 @@ zhong-hong-hvac==1.0.21 ziggo-mediabox-xl==1.1.0 # homeassistant.components.zinvolt -zinvolt==1.0.0 +zinvolt==1.0.1 # homeassistant.components.zoneminder zm-py==0.5.4 From 6aca6d6455ba0363a9f5e895dbfcaca74df753a2 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 12:54:34 +0200 Subject: [PATCH 184/356] Close the WiZ bulb when a different device is found at its IP (#184674) --- homeassistant/components/wiz/__init__.py | 1 + tests/components/wiz/test_init.py | 2 ++ 2 files changed, 3 insertions(+) diff --git a/homeassistant/components/wiz/__init__.py b/homeassistant/components/wiz/__init__.py index 1bc3f1ea6a3a..12c71e392767 100644 --- a/homeassistant/components/wiz/__init__.py +++ b/homeassistant/components/wiz/__init__.py @@ -75,6 +75,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: WizConfigEntry) -> bool: # and another WiZ device has taken the IP. Avoid setting up # since its the wrong device. As soon as the device comes back # online the ip will get updated and setup will proceed. + await bulb.async_close() raise ConfigEntryNotReady( f"Found bulb {bulb.mac} at {ip_address}, expected {entry.unique_id}" ) diff --git a/tests/components/wiz/test_init.py b/tests/components/wiz/test_init.py index 34dd75a0de79..7fcc22e0f07d 100644 --- a/tests/components/wiz/test_init.py +++ b/tests/components/wiz/test_init.py @@ -74,6 +74,8 @@ async def test_wrong_device_now_has_our_ip(hass: HomeAssistant) -> None: bulb.mac = "dddddddddddd" _, entry = await async_setup_integration(hass, wizlight=bulb) assert entry.state is ConfigEntryState.SETUP_RETRY + # Each retry creates a new bulb, so the socket of this one must not leak + bulb.async_close.assert_called_once() with _patch_wizlight(): await hass.async_block_till_done(wait_background_tasks=True) From 7736342bfc4aabe2fc6df0a9e6ee5bbe4f7f1019 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 12:53:36 +0200 Subject: [PATCH 185/356] Use the same MAC address in the ONVIF config flow as the device (#184675) --- homeassistant/components/onvif/config_flow.py | 11 +--- homeassistant/components/onvif/device.py | 18 ++++-- tests/components/onvif/test_config_flow.py | 61 +++++++++++++++++++ 3 files changed, 78 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/onvif/config_flow.py b/homeassistant/components/onvif/config_flow.py index 1a021761f2c2..622e195dd18d 100644 --- a/homeassistant/components/onvif/config_flow.py +++ b/homeassistant/components/onvif/config_flow.py @@ -51,7 +51,7 @@ from .const import ( GET_CAPABILITIES_EXCEPTIONS, LOGGER, ) -from .device import get_device +from .device import get_device, get_mac_address CONF_MANUAL_INPUT = "Manually configure ONVIF device" @@ -120,7 +120,7 @@ class OnvifFlowHandler(ConfigFlow, domain=DOMAIN): def __init__(self) -> None: """Initialize the ONVIF config flow.""" - self.device_id = None + self.device_id: str | None = None self.devices: list[dict[str, Any]] = [] self.onvif_config: dict[str, Any] = {} @@ -329,12 +329,7 @@ class OnvifFlowHandler(ConfigFlow, domain=DOMAIN): if not self.device_id: try: network_interfaces = await device_mgmt.GetNetworkInterfaces() - interface = next( - filter(lambda interface: interface.Enabled, network_interfaces), - None, - ) - if interface: - self.device_id = interface.Info.HwAddress + self.device_id = get_mac_address(network_interfaces) except Fault as fault: if "not implemented" not in fault.message: raise diff --git a/homeassistant/components/onvif/device.py b/homeassistant/components/onvif/device.py index 0f802e222d85..ac0555818672 100644 --- a/homeassistant/components/onvif/device.py +++ b/homeassistant/components/onvif/device.py @@ -344,13 +344,10 @@ class ONVIFDevice: firmware_version = device_info.FirmwareVersion serial_number = device_info.SerialNumber - # Grab the last MAC address for backwards compatibility mac = None try: network_interfaces = await device_mgmt.GetNetworkInterfaces() - for interface in network_interfaces: - if interface.Enabled: - mac = interface.Info.HwAddress + mac = get_mac_address(network_interfaces) except Fault as fault: if "not implemented" not in fault.message: raise @@ -702,3 +699,16 @@ def get_device( f"{os.path.dirname(onvif.__file__)}/wsdl/", no_cache=True, ) + + +def get_mac_address(network_interfaces: list[Any]) -> str | None: + """Get the MAC address of the last enabled network interface. + + Existing entries and entities are keyed on the last one. Some cameras also + list a dummy interface first that has the same MAC address on every unit. + """ + mac = None + for interface in network_interfaces: + if interface.Enabled: + mac = interface.Info.HwAddress + return mac diff --git a/tests/components/onvif/test_config_flow.py b/tests/components/onvif/test_config_flow.py index 54d17eba5059..0343eff0be10 100644 --- a/tests/components/onvif/test_config_flow.py +++ b/tests/components/onvif/test_config_flow.py @@ -368,6 +368,67 @@ async def test_flow_manual_entry(hass: HomeAssistant) -> None: } +async def test_flow_manual_entry_multiple_interfaces(hass: HomeAssistant) -> None: + """Test the unique ID comes from the last enabled network interface. + + Some Dahua based cameras (like Imou) report a dummy eth0 that has the same + MAC address on every unit, next to the interface they actually use. + """ + shared_mac = "00:30:1b:ba:02:db" + own_mac = "a8:31:62:73:43:60" + # Another camera of the same kind, configured with the shared MAC + MockConfigEntry(domain=DOMAIN, unique_id=shared_mac).add_to_hass(hass) + + dummy_interface = MagicMock(Enabled=True) + dummy_interface.Info.HwAddress = shared_mac + wifi_interface = MagicMock(Enabled=True) + wifi_interface.Info.HwAddress = own_mac + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with ( + patch( + "homeassistant.components.onvif.config_flow.get_device" + ) as mock_onvif_camera, + patch( + "homeassistant.components.onvif.config_flow.WSDiscovery" + ) as mock_discovery, + patch("homeassistant.components.onvif.ONVIFDevice") as mock_device, + ): + setup_mock_onvif_camera(mock_onvif_camera) + devicemgmt = mock_onvif_camera.create_devicemgmt_service.return_value + devicemgmt.GetNetworkInterfaces = AsyncMock( + return_value=[dummy_interface, wifi_interface] + ) + mock_discovery.return_value = [] + setup_mock_device(mock_device) + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={"auto": False}, + ) + + with patch( + "homeassistant.components.onvif.async_setup_entry", return_value=True + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + config_flow.CONF_NAME: NAME, + config_flow.CONF_HOST: HOST, + config_flow.CONF_PORT: PORT, + config_flow.CONF_USERNAME: USERNAME, + config_flow.CONF_PASSWORD: PASSWORD, + }, + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == own_mac + + async def test_flow_manual_entry_no_profiles(hass: HomeAssistant) -> None: """Test that config flow when no profiles are returned.""" result = await hass.config_entries.flow.async_init( From fde91e4c79ab103679e7711890f4986d35062e41 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 13:05:12 +0200 Subject: [PATCH 186/356] Only offer discovered Denon devices that serve the receiver API (#184679) --- .../components/denonavr/config_flow.py | 23 +++++++++----- tests/components/denonavr/test_config_flow.py | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/denonavr/config_flow.py b/homeassistant/components/denonavr/config_flow.py index 0c0de9f9f491..90986587e50f 100644 --- a/homeassistant/components/denonavr/config_flow.py +++ b/homeassistant/components/denonavr/config_flow.py @@ -181,10 +181,8 @@ class DenonAvrFlowHandler(ConfigFlow, domain=DOMAIN): self._set_confirm_only() return self.async_show_form(step_id="confirm") - async def async_step_connect( - self, user_input: dict[str, Any] | None = None - ) -> ConfigFlowResult: - """Connect to the receiver.""" + async def _async_connect_receiver(self) -> denonavr.DenonAVR | None: + """Connect to the receiver, return None if that fails.""" assert self.host connect_denonavr = ConnectDenonAVR( self.host, @@ -200,11 +198,17 @@ class DenonAvrFlowHandler(ConfigFlow, domain=DOMAIN): try: success = await connect_denonavr.async_connect_receiver() except AvrNetworkError, AvrTimoutError: - success = False + return None if not success: + return None + return connect_denonavr.receiver + + async def async_step_connect( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Connect to the receiver.""" + if (receiver := await self._async_connect_receiver()) is None: return self.async_abort(reason="cannot_connect") - receiver = connect_denonavr.receiver - assert receiver if not self.serial_number: self.serial_number = receiver.serial_number @@ -272,6 +276,11 @@ class DenonAvrFlowHandler(ConfigFlow, domain=DOMAIN): await self.async_set_unique_id(unique_id) self._abort_if_unique_id_configured({CONF_HOST: self.host}) + # HEOS-only devices (like the Denon Home speakers) are discovered as well, + # but don't serve the receiver API, so they could never be set up + if await self._async_connect_receiver() is None: + return self.async_abort(reason="cannot_connect") + self.context.update( { "title_placeholders": { diff --git a/tests/components/denonavr/test_config_flow.py b/tests/components/denonavr/test_config_flow.py index 92fe381ac4da..939433841e15 100644 --- a/tests/components/denonavr/test_config_flow.py +++ b/tests/components/denonavr/test_config_flow.py @@ -2,6 +2,7 @@ from unittest.mock import patch +from denonavr.exceptions import AvrNetworkError import pytest from homeassistant import config_entries @@ -396,6 +397,35 @@ async def test_config_flow_ssdp_missing_info(hass: HomeAssistant) -> None: assert result["reason"] == "not_denonavr_missing" +async def test_config_flow_ssdp_no_receiver_api(hass: HomeAssistant) -> None: + """Failed flow initialized by ssdp discovery. + + HEOS-only devices (like a Denon Home speaker) are discovered, but don't + serve the receiver API. + """ + with patch( + "homeassistant.components.denonavr.receiver.DenonAVR.async_setup", + side_effect=AvrNetworkError("NetworkError", "async_setup"), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_SSDP}, + data=SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location=TEST_SSDP_LOCATION, + upnp={ + ATTR_UPNP_MANUFACTURER: TEST_MANUFACTURER, + ATTR_UPNP_MODEL_NAME: "Denon Home 150", + ATTR_UPNP_SERIAL: TEST_SERIALNUMBER, + }, + ), + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "cannot_connect" + + async def test_config_flow_ssdp_ignored_model(hass: HomeAssistant) -> None: """Failed flow initialized by ssdp discovery. From 26e6afd9a7a58edc6013ffe740665b847dbc6ca3 Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Wed, 7 Oct 2026 12:51:57 +0200 Subject: [PATCH 187/356] Avoid using zigbee macs as network macs in hue (#175083) Co-authored-by: Claude Sonnet 5.5 --- homeassistant/components/hue/__init__.py | 30 +++++++++++++++- homeassistant/components/hue/config_flow.py | 1 + homeassistant/components/hue/v2/device.py | 4 +-- tests/components/hue/conftest.py | 1 + tests/components/hue/test_bridge.py | 10 +++--- tests/components/hue/test_init.py | 40 +++++++++++++++++++-- tests/components/hue/test_migration.py | 39 ++++++++++++++++++++ 7 files changed, 113 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/hue/__init__.py b/homeassistant/components/hue/__init__.py index 3e2cfeaaef7e..a840ced7d57c 100644 --- a/homeassistant/components/hue/__init__.py +++ b/homeassistant/components/hue/__init__.py @@ -3,7 +3,7 @@ from aiohue.util import normalize_bridge_id from homeassistant.config_entries import SOURCE_IGNORE -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.helpers import config_validation as cv, device_registry as dr from homeassistant.helpers.typing import ConfigType @@ -23,6 +23,34 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: return True +async def async_migrate_entry(hass: HomeAssistant, entry: HueConfigEntry) -> bool: + """Migrate old entry.""" + if entry.minor_version < 2: + _migrate_zigbee_connections(hass, entry) + hass.config_entries.async_update_entry(entry, minor_version=2) + + return True + + +@callback +def _migrate_zigbee_connections(hass: HomeAssistant, entry: HueConfigEntry) -> None: + """Migrate zigbee macs that were incorrectly stored as network macs.""" + dev_reg = dr.async_get(hass) + for device in dr.async_entries_for_config_entry(dev_reg, entry.entry_id): + # Zigbee macs have 8 octets, network macs have 6. + zigbee_connections = { + (conn_type, value) + for conn_type, value in device.connections + if conn_type == dr.CONNECTION_NETWORK_MAC and value.count(":") == 7 + } + if not zigbee_connections: + continue + new_connections = (device.connections - zigbee_connections) | { + (dr.CONNECTION_ZIGBEE, value) for _, value in zigbee_connections + } + dev_reg.async_update_device(device.id, new_connections=new_connections) + + async def async_setup_entry(hass: HomeAssistant, entry: HueConfigEntry) -> bool: """Set up a bridge from a config entry.""" # check (and run) migrations if needed diff --git a/homeassistant/components/hue/config_flow.py b/homeassistant/components/hue/config_flow.py index 3a77cf6b7833..cf4097e9d0b7 100644 --- a/homeassistant/components/hue/config_flow.py +++ b/homeassistant/components/hue/config_flow.py @@ -48,6 +48,7 @@ class HueFlowHandler(ConfigFlow, domain=DOMAIN): """Handle a Hue config flow.""" VERSION = 1 + MINOR_VERSION = 2 @staticmethod @callback diff --git a/homeassistant/components/hue/v2/device.py b/homeassistant/components/hue/v2/device.py index dc6f3b08a84d..c81a02c362b2 100644 --- a/homeassistant/components/hue/v2/device.py +++ b/homeassistant/components/hue/v2/device.py @@ -85,9 +85,7 @@ async def async_setup_devices(bridge: HueBridge): if zigbee and zigbee.mac_address: mac_owner = mac_owners.setdefault(zigbee.mac_address, hue_resource.id) if mac_owner == hue_resource.id: - params[ATTR_CONNECTIONS] = { - (dr.CONNECTION_NETWORK_MAC, zigbee.mac_address) - } + params[ATTR_CONNECTIONS] = {(dr.CONNECTION_ZIGBEE, zigbee.mac_address)} return dev_reg.async_get_or_create(config_entry_id=entry.entry_id, **params) diff --git a/tests/components/hue/conftest.py b/tests/components/hue/conftest.py index 2f16d88580c2..6eaf568b79fb 100644 --- a/tests/components/hue/conftest.py +++ b/tests/components/hue/conftest.py @@ -241,6 +241,7 @@ def create_config_entry( domain=hue.DOMAIN, title=f"Mock bridge {api_version}", data={"host": host, "api_version": api_version, "api_key": ""}, + minor_version=2, ) diff --git a/tests/components/hue/test_bridge.py b/tests/components/hue/test_bridge.py index 5725b06ed890..60a44a60d1d9 100644 --- a/tests/components/hue/test_bridge.py +++ b/tests/components/hue/test_bridge.py @@ -136,7 +136,7 @@ async def test_bridge_device_v2( # async_setup_devices) and the network MAC connection (merged in by # _async_register_bridge_device) assert bridge_device.connections == { - (dr.CONNECTION_NETWORK_MAC, "00:17:88:01:aa:bb:fd:c7"), + (dr.CONNECTION_ZIGBEE, "00:17:88:01:aa:bb:fd:c7"), (dr.CONNECTION_NETWORK_MAC, mock_bridge_v2.api.config.mac_address), } # The bridge device is registered exactly once @@ -209,9 +209,7 @@ async def test_devices_sharing_a_mac_v2( device_registry.async_get_or_create( config_entry_id=config_entry.entry_id, identifiers={(DOMAIN, hue_device_id)}, - connections={(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} - if holds_mac - else set(), + connections={(dr.CONNECTION_ZIGBEE, SHARED_MAC)} if holds_mac else set(), ) await async_setup_devices(mock_bridge_v2) @@ -225,7 +223,7 @@ async def test_devices_sharing_a_mac_v2( assert mac_owner is not None assert other_device is not None assert mac_owner.id != other_device.id - assert mac_owner.connections == {(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} + assert mac_owner.connections == {(dr.CONNECTION_ZIGBEE, SHARED_MAC)} assert other_device.connections == set() @@ -255,7 +253,7 @@ async def test_device_sharing_a_mac_added_v2( assert first_device is not None assert added_device is not None assert first_device.id != added_device.id - assert first_device.connections == {(dr.CONNECTION_NETWORK_MAC, SHARED_MAC)} + assert first_device.connections == {(dr.CONNECTION_ZIGBEE, SHARED_MAC)} assert added_device.connections == set() diff --git a/tests/components/hue/test_init.py b/tests/components/hue/test_init.py index f573711616e3..fcd19a0d0335 100644 --- a/tests/components/hue/test_init.py +++ b/tests/components/hue/test_init.py @@ -8,11 +8,20 @@ import pytest from homeassistant import config_entries from homeassistant.components import hue from homeassistant.components.hue import DOMAIN +from homeassistant.const import Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import device_registry as dr from homeassistant.setup import async_setup_component +from homeassistant.util.json import JsonArrayType + +from .conftest import setup_platform from tests.common import MockConfigEntry, async_get_persistent_notifications +# The `Wall switch with 2 controls` device and its zigbee mac +WALL_SWITCH_ID = "3ff06175-29e8-44a8-8fe7-af591b0025da" +WALL_SWITCH_ZIGBEE_MAC = "00:17:88:01:0b:aa:bb:99" + @pytest.fixture def mock_bridge_setup(): @@ -49,7 +58,9 @@ async def test_setup_with_no_config(hass: HomeAssistant) -> None: async def test_unload_entry(hass: HomeAssistant, mock_bridge_setup) -> None: """Test being able to unload an entry.""" entry = MockConfigEntry( - domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2} + domain=hue.DOMAIN, + data={"host": "0.0.0.0", "api_version": 2}, + minor_version=2, ) entry.add_to_hass(hass) @@ -70,7 +81,9 @@ async def test_unload_entry(hass: HomeAssistant, mock_bridge_setup) -> None: async def test_setting_unique_id(hass: HomeAssistant, mock_bridge_setup) -> None: """Test we set unique ID if not set yet.""" entry = MockConfigEntry( - domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2} + domain=hue.DOMAIN, + data={"host": "0.0.0.0", "api_version": 2}, + minor_version=2, ) entry.add_to_hass(hass) assert await async_setup_component(hass, hue.DOMAIN, {}) is True @@ -85,6 +98,7 @@ async def test_fixing_unique_id_no_other( domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2}, unique_id="invalid-id", + minor_version=2, ) entry.add_to_hass(hass) assert await async_setup_component(hass, hue.DOMAIN, {}) is True @@ -100,11 +114,13 @@ async def test_fixing_unique_id_other_ignored( data={"host": "0.0.0.0", "api_version": 2}, unique_id="mock-id", source=config_entries.SOURCE_IGNORE, + minor_version=2, ).add_to_hass(hass) entry = MockConfigEntry( domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2}, unique_id="invalid-id", + minor_version=2, ) entry.add_to_hass(hass) assert await async_setup_component(hass, hue.DOMAIN, {}) is True @@ -121,12 +137,14 @@ async def test_fixing_unique_id_other_correct( domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2}, unique_id="mock-id", + minor_version=2, ) correct_entry.add_to_hass(hass) entry = MockConfigEntry( domain=hue.DOMAIN, data={"host": "0.0.0.0", "api_version": 2}, unique_id="invalid-id", + minor_version=2, ) entry.add_to_hass(hass) assert await async_setup_component(hass, hue.DOMAIN, {}) is True @@ -170,3 +188,21 @@ async def test_security_vuln_check(hass: HomeAssistant) -> None: notifications = async_get_persistent_notifications(hass) assert "hue_hub_firmware" in notifications assert "CVE-2020-6007" in notifications["hue_hub_firmware"]["message"] + + +async def test_zigbee_connection( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + mock_bridge_v2: Mock, + v2_resources_test_data: JsonArrayType, +) -> None: + """Test that the zigbee mac is added as a zigbee connection.""" + await mock_bridge_v2.api.load_test_data(v2_resources_test_data) + await setup_platform(hass, mock_bridge_v2, Platform.LIGHT) + + device = device_registry.async_get_device_by_identifier( + identifier=(hue.DOMAIN, WALL_SWITCH_ID), + config_entry_id=mock_bridge_v2.config_entry.entry_id, + ) + assert device is not None + assert device.connections == {(dr.CONNECTION_ZIGBEE, WALL_SWITCH_ZIGBEE_MAC)} diff --git a/tests/components/hue/test_migration.py b/tests/components/hue/test_migration.py index 995e8ed6f208..4f88555fb09e 100644 --- a/tests/components/hue/test_migration.py +++ b/tests/components/hue/test_migration.py @@ -7,6 +7,8 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.util.json import JsonArrayType +from .conftest import setup_bridge + from tests.common import MockConfigEntry @@ -229,3 +231,40 @@ async def test_group_entity_migration_with_v2_group_id( migrated_entity = entity_registry.async_get("light.hue_migrated_grouped_light") assert migrated_entity is not None assert migrated_entity.unique_id == "e937f8db-2f0e-49a0-936e-027e60e15b34" + + +async def test_zigbee_connection_migration( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + mock_bridge_v2: Mock, + v2_resources_test_data: JsonArrayType, +) -> None: + """Test that a zigbee mac stored as a network mac is migrated.""" + config_entry = MockConfigEntry( + domain=hue.DOMAIN, + data={"host": "mock-host", "api_version": 2, "api_key": ""}, + minor_version=1, + ) + config_entry.add_to_hass(hass) + + zigbee_mac = "00:17:88:01:0b:aa:bb:99" + network_mac = "aa:bb:cc:dd:ee:ff" + zigbee_device = device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + identifiers={(hue.DOMAIN, "3ff06175-29e8-44a8-8fe7-af591b0025da")}, + connections={ + (dr.CONNECTION_NETWORK_MAC, zigbee_mac), + (dr.CONNECTION_NETWORK_MAC, network_mac), + }, + ) + + await mock_bridge_v2.api.load_test_data(v2_resources_test_data) + await setup_bridge(hass, mock_bridge_v2, config_entry) + + migrated_device = device_registry.async_get(zigbee_device.id) + assert migrated_device is not None + assert migrated_device.connections == { + (dr.CONNECTION_ZIGBEE, zigbee_mac), + (dr.CONNECTION_NETWORK_MAC, network_mac), + } + assert config_entry.minor_version == 2 From 578734fa82a9b134fb4a33550f70e4192f392db4 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 11:31:11 +0000 Subject: [PATCH 188/356] Bump version to 2026.10.0b5 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 1131f0c76ff7..e50268dc0aee 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b4" +PATCH_VERSION: Final = "0b5" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 8e7e96a2db4d..6b2d5e641f4d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b4" +version = "2026.10.0b5" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 665c1080be84fe91c0a8c15b2ad5db4c56a836a0 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 15:02:48 +0200 Subject: [PATCH 189/356] Fix telegram_bot test patching httpx2 on the rc branch (#184711) --- tests/components/telegram_bot/test_telegram_bot.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/components/telegram_bot/test_telegram_bot.py b/tests/components/telegram_bot/test_telegram_bot.py index b7c3ba3ba2ec..d33cd7ac8993 100644 --- a/tests/components/telegram_bot/test_telegram_bot.py +++ b/tests/components/telegram_bot/test_telegram_bot.py @@ -2744,7 +2744,7 @@ async def test_send_media_group_caption_parse_mode( with ( patch( - "homeassistant.components.telegram_bot.bot.httpx2.AsyncClient.get" + "homeassistant.components.telegram_bot.bot.httpx.AsyncClient.get" ) as mock_get, patch( "homeassistant.components.telegram_bot.bot.Bot.send_media_group", From 312b368de22a32fbbf3f2d9847b903aebc11fb14 Mon Sep 17 00:00:00 2001 From: AlCalzone Date: Wed, 7 Oct 2026 14:09:03 +0200 Subject: [PATCH 190/356] Fix managed app configuration resetting existing options (#182441) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../components/hassio/addon_manager.py | 7 +- tests/components/hassio/test_addon_manager.py | 65 +++++++++++++++++++ tests/components/zwave_js/test_init.py | 25 ++++++- 3 files changed, 91 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/hassio/addon_manager.py b/homeassistant/components/hassio/addon_manager.py index dd4fe89669e3..2b6207fe5ff7 100644 --- a/homeassistant/components/hassio/addon_manager.py +++ b/homeassistant/components/hassio/addon_manager.py @@ -274,14 +274,15 @@ class AddonManager: self, addon_config: dict[str, Any], ) -> None: - """Configure the manager add-on, if needed.""" + """Update the managed add-on options, preserving unspecified options.""" addon_info = await self.async_get_addon_info() if addon_info.state is AddonState.NOT_INSTALLED: raise AddonError(f"{self.addon_name} app is not installed") - if addon_config != addon_info.options: - await self.async_set_addon_options(addon_config) + new_addon_config = addon_info.options | addon_config + if new_addon_config != addon_info.options: + await self.async_set_addon_options(new_addon_config) @callback def async_schedule_install_addon(self, catch_error: bool = False) -> asyncio.Task: diff --git a/tests/components/hassio/test_addon_manager.py b/tests/components/hassio/test_addon_manager.py index 5e3a998f0048..84dfcc0093f9 100644 --- a/tests/components/hassio/test_addon_manager.py +++ b/tests/components/hassio/test_addon_manager.py @@ -1,6 +1,7 @@ """Test the addon manager.""" import asyncio +from typing import Any from unittest.mock import AsyncMock, call from uuid import uuid4 @@ -194,6 +195,70 @@ async def test_set_addon_options( ) +@pytest.mark.usefixtures("addon_installed") +@pytest.mark.parametrize( + "addon_config", + [ + pytest.param({"new_key": "new"}, id="add-option"), + pytest.param({"test_key": "updated"}, id="update-option"), + ], +) +async def test_configure_addon_preserves_options( + addon_manager: AddonManager, + addon_options: dict[str, Any], + set_addon_options: AsyncMock, + addon_config: dict[str, str], +) -> None: + """Test configuring an add-on preserves all options outside the update.""" + existing_options = { + "test_key": "test", + "log_level": "debug", + "log_to_file": True, + "user_option": {"enabled": False, "values": [1, "two", None]}, + } + addon_options.update(existing_options) + expected_options = existing_options | addon_config + + await addon_manager.async_configure_addon(addon_config) + + set_addon_options.assert_awaited_once_with( + "test_addon", AddonsOptions(config=expected_options) + ) + assert addon_options == expected_options + assert addon_options["log_level"] == "debug" + assert addon_options["log_to_file"] is True + + +@pytest.mark.usefixtures("addon_installed") +@pytest.mark.parametrize( + "addon_config", + [ + pytest.param({}, id="empty-update"), + pytest.param({"test_key": "test"}, id="unchanged-option"), + ], +) +async def test_configure_addon_unchanged( + addon_manager: AddonManager, + addon_options: dict[str, Any], + set_addon_options: AsyncMock, + addon_config: dict[str, str], +) -> None: + """Test unchanged managed options do not trigger a write.""" + existing_options = { + "test_key": "test", + "log_level": "debug", + "log_to_file": True, + } + addon_options.update(existing_options) + + await addon_manager.async_configure_addon(addon_config) + + set_addon_options.assert_not_awaited() + assert addon_options == existing_options + assert addon_options["log_level"] == "debug" + assert addon_options["log_to_file"] is True + + async def test_set_addon_options_error( hass: HomeAssistant, addon_manager: AddonManager, set_addon_options: AsyncMock ) -> None: diff --git a/tests/components/zwave_js/test_init.py b/tests/components/zwave_js/test_init.py index d4cb60165c0d..0bd96f1220c7 100644 --- a/tests/components/zwave_js/test_init.py +++ b/tests/components/zwave_js/test_init.py @@ -1009,13 +1009,31 @@ async def test_null_name( @pytest.mark.usefixtures("addon_installed", "addon_info") +@pytest.mark.parametrize( + "existing_addon_options", + [ + pytest.param({}, id="unconfigured"), + pytest.param( + { + "device": "/old", + "log_level": "debug", + "log_to_file": True, + "rf_region": "Europe", + }, + id="user-configured", + ), + ], +) async def test_start_addon( hass: HomeAssistant, install_addon: AsyncMock, set_addon_options: AsyncMock, start_addon: AsyncMock, + addon_options: dict[str, Any], + existing_addon_options: dict[str, Any], ) -> None: - """Test start the Z-Wave JS add-on during entry setup.""" + """Test entry setup preserves user options when starting the Z-Wave JS add-on.""" + addon_options.update(existing_addon_options) device = "/test" s0_legacy_key = "s0_legacy" s2_access_control_key = "s2_access_control" @@ -1023,7 +1041,7 @@ async def test_start_addon( s2_unauthenticated_key = "s2_unauthenticated" lr_s2_access_control_key = "lr_s2_access_control" lr_s2_authenticated_key = "lr_s2_authenticated" - addon_options = { + expected_options = existing_addon_options | { "device": device, "s0_legacy_key": s0_legacy_key, "s2_access_control_key": s2_access_control_key, @@ -1055,8 +1073,9 @@ async def test_start_addon( assert install_addon.call_count == 0 assert set_addon_options.call_count == 1 assert set_addon_options.call_args == call( - "core_zwave_js", AddonsOptions(config=addon_options) + "core_zwave_js", AddonsOptions(config=expected_options) ) + assert addon_options == expected_options assert start_addon.call_count == 1 assert start_addon.call_args == call("core_zwave_js") From f0fc4f8c4d9d83cc87caca0b3c29d1348957d14e Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Fri, 2 Oct 2026 08:56:40 +0200 Subject: [PATCH 191/356] Add tempora to license exceptions (#183971) Co-authored-by: Claude Opus 5.5 --- script/licenses.py | 1 + 1 file changed, 1 insertion(+) diff --git a/script/licenses.py b/script/licenses.py index dbf5926f620c..6fbd90192a09 100644 --- a/script/licenses.py +++ b/script/licenses.py @@ -199,6 +199,7 @@ EXCEPTIONS = { "pysabnzbd", # https://github.com/jeradM/pysabnzbd/pull/6 "sharp_aquos_rc", # https://github.com/jmoore987/sharp_aquos_rc/pull/14 "tapsaff", # https://github.com/bazwilliams/python-taps-aff/pull/5 + "tempora", # https://github.com/jaraco/tempora/issues/61 "ujson", # https://github.com/ultrajson/ultrajson/blob/main/LICENSE.txt } From ec27d9b3709587fc1231040b1e778ce06117822c Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Sun, 4 Oct 2026 23:10:48 +1000 Subject: [PATCH 192/356] Use a radio list for the Teslemetry local vehicle subentry (#184171) --- .../components/teslemetry/config_flow.py | 18 +----------------- .../components/teslemetry/test_config_flow.py | 3 +++ 2 files changed, 4 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/teslemetry/config_flow.py b/homeassistant/components/teslemetry/config_flow.py index 36ead311071f..f557a7ce50be 100644 --- a/homeassistant/components/teslemetry/config_flow.py +++ b/homeassistant/components/teslemetry/config_flow.py @@ -64,12 +64,6 @@ from homeassistant.const import CONF_ADDRESS, CONF_HOST, CONF_PASSWORD from homeassistant.core import callback from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers.aiohttp_client import async_get_clientsession -from homeassistant.helpers.selector import ( - SelectOptionDict, - SelectSelector, - SelectSelectorConfig, - SelectSelectorMode, -) from . import _BLE_KEY_ERRORS, TeslemetryConfigEntry from .const import ( @@ -288,17 +282,7 @@ class VehicleSubentryFlowHandler(ConfigSubentryFlow): return self.async_show_form( step_id="user", data_schema=probatio.Schema( - { - probatio.Required(CONF_VIN): SelectSelector( - SelectSelectorConfig( - options=[ - SelectOptionDict(value=vin, label=name) - for vin, name in choices.items() - ], - mode=SelectSelectorMode.DROPDOWN, - ) - ) - } + {probatio.Required(CONF_VIN): probatio.In(choices)} ), ) diff --git a/tests/components/teslemetry/test_config_flow.py b/tests/components/teslemetry/test_config_flow.py index 8cfd227e7077..f5c3b4920092 100644 --- a/tests/components/teslemetry/test_config_flow.py +++ b/tests/components/teslemetry/test_config_flow.py @@ -1812,6 +1812,9 @@ async def test_subentry_add_flow_keeps_device_on_parent( ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" + schema = result["data_schema"].schema + assert next(iter(schema)) == CONF_VIN + assert schema[CONF_VIN].container == {VIN: "Test"} # async_schedule_reload is left unpatched so the real reload runs here with the # committed BLE address; keep the setup-time Bluetooth mocks active so it neither From c4b0c6d3f77b96ab8dff3df1fd1490793963ecf7 Mon Sep 17 00:00:00 2001 From: jameson_uk <1040621+jamesonuk@users.noreply.github.com> Date: Wed, 7 Oct 2026 13:58:23 +0100 Subject: [PATCH 193/356] bump alexa_devices to 16.3.2 (#184703) --- homeassistant/components/alexa_devices/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/alexa_devices/manifest.json b/homeassistant/components/alexa_devices/manifest.json index 3e0efbc31e5e..f653fa1623c9 100644 --- a/homeassistant/components/alexa_devices/manifest.json +++ b/homeassistant/components/alexa_devices/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aioamazondevices"], "quality_scale": "platinum", - "requirements": ["aioamazondevices==16.3.1"] + "requirements": ["aioamazondevices==16.3.2"] } diff --git a/requirements_all.txt b/requirements_all.txt index 11fa29e19004..91e64c84696d 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -190,7 +190,7 @@ aioairzone-cloud==0.7.2 aioairzone==1.0.5 # homeassistant.components.alexa_devices -aioamazondevices==16.3.1 +aioamazondevices==16.3.2 # homeassistant.components.ambient_network # homeassistant.components.ambient_station From 8f25f388b1f7118f01d2b33e7cbb6e6bd0cfd56a Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 13:52:15 +0000 Subject: [PATCH 194/356] Bump version to 2026.10.0b6 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index e50268dc0aee..b61eab623503 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b5" +PATCH_VERSION: Final = "0b6" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 6b2d5e641f4d..9a45e6b0f8e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b5" +version = "2026.10.0b6" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 4e50be504f18adc9c4970db2c392cda3b61d6422 Mon Sep 17 00:00:00 2001 From: Michael Rademaker Date: Wed, 7 Oct 2026 16:09:31 +0200 Subject: [PATCH 195/356] Fix EARN-E P1 listener stopping while another entry sets up (#182289) Co-authored-by: David-Wu1119 <133224895+David-Wu1119@users.noreply.github.com> Co-authored-by: Claude Opus 5 --- .../components/earn_e_p1/__init__.py | 58 +++++------ .../components/earn_e_p1/config_flow.py | 12 +-- homeassistant/components/earn_e_p1/const.py | 8 ++ homeassistant/components/earn_e_p1/models.py | 17 ++++ tests/components/earn_e_p1/conftest.py | 15 +++ tests/components/earn_e_p1/test_init.py | 98 ++++++++++++++++++- 6 files changed, 172 insertions(+), 36 deletions(-) create mode 100644 homeassistant/components/earn_e_p1/models.py diff --git a/homeassistant/components/earn_e_p1/__init__.py b/homeassistant/components/earn_e_p1/__init__.py index 2b4e9ce1b075..561c428188c9 100644 --- a/homeassistant/components/earn_e_p1/__init__.py +++ b/homeassistant/components/earn_e_p1/__init__.py @@ -1,15 +1,15 @@ """The EARN-E P1 Meter integration.""" -# pylint: disable=home-assistant-use-runtime-data # Uses legacy hass.data[DOMAIN] pattern from earn_e_p1 import DEFAULT_PORT, EarnEP1Listener -from homeassistant.config_entries import ConfigEntry, ConfigEntryState +from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_MAC, Platform from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady -from .const import CONF_SERIAL, DOMAIN +from .const import CONF_SERIAL, EARN_E_P1_DATA from .coordinator import EarnEP1Coordinator +from .models import EarnEP1Data PLATFORMS: list[Platform] = [Platform.SENSOR] @@ -22,20 +22,35 @@ async def async_setup_entry(hass: HomeAssistant, entry: EarnEP1ConfigEntry) -> b serial = entry.data[CONF_SERIAL] mac = entry.data.get(CONF_MAC) - # Get or create shared listener - if DOMAIN not in hass.data: - listener = EarnEP1Listener() - try: - await listener.start() - except OSError as err: - raise ConfigEntryNotReady( - f"Cannot start UDP listener on port {DEFAULT_PORT}: {err}" - ) from err - hass.data[DOMAIN] = listener + data = hass.data.setdefault(EARN_E_P1_DATA, EarnEP1Data()) + async with data.lock: + if (listener := data.listener) is None: + listener = EarnEP1Listener() + try: + await listener.start() + except OSError as err: + raise ConfigEntryNotReady( + f"Cannot start UDP listener on port {DEFAULT_PORT}: {err}" + ) from err + data.listener = listener + + # Claim the listener under the lock, so that another entry unloading + # while this one sets up cannot stop it from under us. + data.entries.add(entry.entry_id) + + async def _release_listener() -> None: + """Stop the shared listener once the last entry has released it.""" + async with data.lock: + data.entries.discard(entry.entry_id) + if not data.entries: + data.listener = None + await listener.stop() + + entry.async_on_unload(_release_listener) - listener = hass.data[DOMAIN] coordinator = EarnEP1Coordinator(hass, entry, host, serial, listener, mac) coordinator.start() + entry.async_on_unload(coordinator.stop) entry.runtime_data = coordinator await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) @@ -44,17 +59,4 @@ async def async_setup_entry(hass: HomeAssistant, entry: EarnEP1ConfigEntry) -> b async def async_unload_entry(hass: HomeAssistant, entry: EarnEP1ConfigEntry) -> bool: """Unload a config entry.""" - unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) - if unload_ok: - entry.runtime_data.stop() - - # Stop shared listener if no other entries are loaded - other_loaded = any( - e.state is ConfigEntryState.LOADED and e.entry_id != entry.entry_id - for e in hass.config_entries.async_entries(DOMAIN) - ) - if not other_loaded: - await hass.data[DOMAIN].stop() - hass.data.pop(DOMAIN) - - return unload_ok + return await hass.config_entries.async_unload_platforms(entry, PLATFORMS) diff --git a/homeassistant/components/earn_e_p1/config_flow.py b/homeassistant/components/earn_e_p1/config_flow.py index 126c46d83682..7d872c7f2a27 100644 --- a/homeassistant/components/earn_e_p1/config_flow.py +++ b/homeassistant/components/earn_e_p1/config_flow.py @@ -3,7 +3,7 @@ import logging from typing import Any, override -from earn_e_p1 import EarnEP1Device, EarnEP1Listener, discover, validate +from earn_e_p1 import EarnEP1Device, discover, validate import probatio from homeassistant.config_entries import ConfigFlow, ConfigFlowResult @@ -11,7 +11,7 @@ from homeassistant.const import CONF_HOST, CONF_MAC from homeassistant.helpers.device_registry import format_mac from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo -from .const import CONF_SERIAL, DOMAIN +from .const import CONF_SERIAL, DOMAIN, EARN_E_P1_DATA _LOGGER = logging.getLogger(__name__) @@ -38,8 +38,8 @@ class EarnEP1ConfigFlow(ConfigFlow, domain=DOMAIN): async def _async_discover(self) -> EarnEP1Device | None: """Discover an EARN-E device on the network.""" - listener: EarnEP1Listener | None = self.hass.data.get(DOMAIN) - if listener is not None: + data = self.hass.data.get(EARN_E_P1_DATA) + if data is not None and (listener := data.listener) is not None: devices = await listener.discover(timeout=DISCOVERY_TIMEOUT) else: try: @@ -54,8 +54,8 @@ class EarnEP1ConfigFlow(ConfigFlow, domain=DOMAIN): Uses the shared listener if available, otherwise creates a temporary one. Returns the device if serial is found, None on timeout. """ - listener: EarnEP1Listener | None = self.hass.data.get(DOMAIN) - if listener is not None: + data = self.hass.data.get(EARN_E_P1_DATA) + if data is not None and (listener := data.listener) is not None: return await listener.validate(host, timeout=VALIDATION_TIMEOUT) return await validate(host, timeout=VALIDATION_TIMEOUT) diff --git a/homeassistant/components/earn_e_p1/const.py b/homeassistant/components/earn_e_p1/const.py index 9b9f4cbfbe61..64167a94fd44 100644 --- a/homeassistant/components/earn_e_p1/const.py +++ b/homeassistant/components/earn_e_p1/const.py @@ -1,4 +1,12 @@ """Constants for the EARN-E P1 Meter integration.""" +from homeassistant.util.hass_dict import HassKey + +from .models import EarnEP1Data + DOMAIN = "earn_e_p1" CONF_SERIAL = "serial" + +# One UDP listener receives packets from every meter, so it is shared between +# config entries and reused by the config flow for discovery and validation. +EARN_E_P1_DATA: HassKey[EarnEP1Data] = HassKey(DOMAIN) diff --git a/homeassistant/components/earn_e_p1/models.py b/homeassistant/components/earn_e_p1/models.py new file mode 100644 index 000000000000..e64d624cc576 --- /dev/null +++ b/homeassistant/components/earn_e_p1/models.py @@ -0,0 +1,17 @@ +"""Models for the EARN-E P1 Meter integration.""" + +import asyncio +from dataclasses import dataclass, field + +from earn_e_p1 import EarnEP1Listener + + +@dataclass +class EarnEP1Data: + """Shared UDP listener and the config entries currently using it.""" + + # Entries set up concurrently at startup, so creating and stopping the + # listener must not interleave or two of them race to bind the UDP port. + lock: asyncio.Lock = field(default_factory=asyncio.Lock) + listener: EarnEP1Listener | None = None + entries: set[str] = field(default_factory=set) diff --git a/tests/components/earn_e_p1/conftest.py b/tests/components/earn_e_p1/conftest.py index d0807c48ebff..891b6d34306d 100644 --- a/tests/components/earn_e_p1/conftest.py +++ b/tests/components/earn_e_p1/conftest.py @@ -15,8 +15,10 @@ from homeassistant.helpers.service_info.dhcp import DhcpServiceInfo from tests.common import MockConfigEntry MOCK_HOST = "192.168.1.100" +MOCK_HOST_2 = "192.168.1.101" MOCK_NEW_HOST = "192.168.1.200" MOCK_SERIAL = "E0012345678901234" +MOCK_SERIAL_2 = "E0012345678905678" MOCK_MAC = "aabbcc112233" # Devices announce themselves as "Energiemonitor-<4 hex>"; DHCP lowercases it. MOCK_HOSTNAME = "energiemonitor-d674" @@ -98,6 +100,19 @@ def mock_config_entry( return entry +@pytest.fixture +def mock_config_entry_2(hass: HomeAssistant) -> MockConfigEntry: + """Create a mock config entry for a second meter.""" + entry = MockConfigEntry( + domain=DOMAIN, + title=f"EARN-E P1 ({MOCK_HOST_2})", + data={CONF_HOST: MOCK_HOST_2, CONF_SERIAL: MOCK_SERIAL_2}, + unique_id=MOCK_SERIAL_2, + ) + entry.add_to_hass(hass) + return entry + + @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock]: """Patch async_setup_entry to avoid real setup in config flow tests.""" diff --git a/tests/components/earn_e_p1/test_init.py b/tests/components/earn_e_p1/test_init.py index f0d3c0a2e63d..132c7cc9ebb6 100644 --- a/tests/components/earn_e_p1/test_init.py +++ b/tests/components/earn_e_p1/test_init.py @@ -1,16 +1,25 @@ """Tests for the EARN-E P1 Meter integration setup.""" +import asyncio from unittest.mock import AsyncMock, MagicMock import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.config_entries import ConfigEntryState -from homeassistant.const import CONF_MAC +from homeassistant.const import CONF_HOST, CONF_MAC from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr -from .conftest import DOMAIN, MOCK_MAC, MOCK_SERIAL, trigger_callback +from .conftest import ( + CONF_SERIAL, + DOMAIN, + MOCK_HOST_2, + MOCK_MAC, + MOCK_SERIAL, + MOCK_SERIAL_2, + trigger_callback, +) from tests.common import MockConfigEntry @@ -56,6 +65,91 @@ async def test_unload_entry( mock_listener.stop.assert_awaited() +async def test_unload_entry_keeps_listener_for_remaining_entry( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_config_entry_2: MockConfigEntry, + mock_listener: MagicMock, +) -> None: + """Test the shared listener survives until the last entry is unloaded.""" + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_config_entry_2.state is ConfigEntryState.LOADED + mock_listener.start.assert_awaited_once() + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_listener.stop.assert_not_awaited() + + await hass.config_entries.async_unload(mock_config_entry_2.entry_id) + await hass.async_block_till_done() + + mock_listener.stop.assert_awaited_once() + + +async def test_unload_entry_keeps_listener_while_other_entry_sets_up( + hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_listener: MagicMock +) -> None: + """Test unloading an entry leaves a listener another setup already claimed.""" + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + second_entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_HOST: MOCK_HOST_2, CONF_SERIAL: MOCK_SERIAL_2}, + unique_id=MOCK_SERIAL_2, + ) + second_entry.add_to_hass(hass) + + def unload_first_entry(*_: object) -> None: + """Unload the first entry while the second one is still setting up.""" + hass.async_create_task( + hass.config_entries.async_unload(mock_config_entry.entry_id) + ) + + # The coordinator registers with the listener right after claiming it. + mock_listener.register.side_effect = unload_first_entry + + await hass.config_entries.async_setup(second_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.NOT_LOADED + assert second_entry.state is ConfigEntryState.LOADED + mock_listener.stop.assert_not_awaited() + + +async def test_concurrent_setup_starts_listener_once( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_config_entry_2: MockConfigEntry, + mock_listener: MagicMock, +) -> None: + """Test entries setting up at the same time share a single listener.""" + starting = asyncio.Event() + resume = asyncio.Event() + + async def blocked_start() -> None: + starting.set() + await resume.wait() + + mock_listener.start.side_effect = blocked_start + + setup = hass.async_create_task( + hass.config_entries.async_setup(mock_config_entry.entry_id) + ) + await starting.wait() + resume.set() + await setup + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_config_entry_2.state is ConfigEntryState.LOADED + mock_listener.start.assert_awaited_once() + + async def test_device_info( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From cc1f505354dbed273e19ba9dffe7382f7e3baa5a Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Thu, 8 Oct 2026 00:14:59 +1000 Subject: [PATCH 196/356] Fix Teslemetry HW4 mileage sensors not created for streaming vehicles (#184632) --- homeassistant/components/teslemetry/sensor.py | 12 ++++---- tests/components/teslemetry/test_sensor.py | 29 +++++++++++-------- 2 files changed, 24 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/teslemetry/sensor.py b/homeassistant/components/teslemetry/sensor.py index 5a5e8ab964ba..21f5a6449f3c 100644 --- a/homeassistant/components/teslemetry/sensor.py +++ b/homeassistant/components/teslemetry/sensor.py @@ -1666,8 +1666,14 @@ async def async_setup_entry( """Set up the Teslemetry sensor platform from a config entry.""" location_scope = Scope.VEHICLE_LOCATION in entry.runtime_data.scopes + # Streaming vehicles are never polled, so their vehicle_config comes from metadata + vehicles_metadata = entry.runtime_data.metadata_coordinator.data["vehicles"] entities: list[SensorEntity] = [] for vehicle in entry.runtime_data.vehicles: + hw4 = ( + vehicles_metadata[vehicle.vin].get("config", {}).get("driver_assist") + == DRIVER_ASSIST_HW4 + ) for description in VEHICLE_DESCRIPTIONS: if description.requires_location_scope and not location_scope: continue @@ -1675,11 +1681,7 @@ async def async_setup_entry( not vehicle.poll and description.streaming_listener and firmware_at_least(vehicle.firmware, description.streaming_firmware) - and ( - not description.requires_hw4 - or vehicle.coordinator.data.get("vehicle_config_driver_assist") - == DRIVER_ASSIST_HW4 - ) + and (not description.requires_hw4 or hw4) ): entities.append(TeslemetryStreamSensorEntity(vehicle, description)) elif description.polling and vehicle.poll is not False: diff --git a/tests/components/teslemetry/test_sensor.py b/tests/components/teslemetry/test_sensor.py index 65ed23deab23..e01dc3c41377 100644 --- a/tests/components/teslemetry/test_sensor.py +++ b/tests/components/teslemetry/test_sensor.py @@ -66,11 +66,11 @@ TPMS_NO_WARNINGS = { } -def _products_with_driver_assist(driver_assist: str) -> dict: - """Return a products response with the vehicle's driver-assist capability set.""" - products = deepcopy(PRODUCTS) - products["response"][0]["vehicle_config"]["driver_assist"] = driver_assist - return products +def _metadata_with_driver_assist(driver_assist: str | None) -> dict: + """Return a metadata response with the vehicle's driver-assist hardware set.""" + metadata = deepcopy(METADATA) + metadata["vehicles"][VEHICLE_VIN]["config"]["driver_assist"] = driver_assist + return metadata def _live_status(**overrides: object) -> dict: @@ -193,7 +193,7 @@ async def test_sensors_streaming( entity_registry: er.EntityRegistry, freezer: FrozenDateTimeFactory, mock_vehicle_data: AsyncMock, - mock_products: AsyncMock, + mock_metadata: AsyncMock, mock_add_listener: AsyncMock, ) -> None: """Tests that the sensor entities with streaming are correct.""" @@ -201,7 +201,7 @@ async def test_sensors_streaming( freezer.move_to("2024-01-01 00:00:00+00:00") # miles_since_reset and self_driving_miles_since_reset are HW4-only fields. - mock_products.return_value = _products_with_driver_assist("TeslaAP4") + mock_metadata.return_value = _metadata_with_driver_assist("TeslaAP4") entry = await setup_platform(hass, [Platform.SENSOR]) @@ -315,14 +315,14 @@ async def test_sensors_streaming( async def test_new_streaming_sensors_disabled_by_default( hass: HomeAssistant, entity_registry: er.EntityRegistry, - mock_products: AsyncMock, + mock_metadata: AsyncMock, mock_add_listener: AsyncMock, entity_id: str, ) -> None: """Test the new firmware-2025.44 streaming sensors are disabled-by-default diagnostics.""" # miles_since_reset and self_driving_miles_since_reset are HW4-only fields. - mock_products.return_value = _products_with_driver_assist("TeslaAP4") + mock_metadata.return_value = _metadata_with_driver_assist("TeslaAP4") await setup_platform(hass, [Platform.SENSOR]) @@ -345,12 +345,14 @@ async def test_new_streaming_sensors_disabled_by_default( [ ("2025.44.25.5", "TeslaAP4", True), ("2025.44.25.5", "TeslaAP3", False), + ("2025.44.25.5", None, False), ("2025.44.25.4", "TeslaAP4", False), ("2025.44.25.4", "TeslaAP3", False), ], ids=[ "hw4_at_threshold", "hw3_at_threshold", + "unknown_at_threshold", "hw4_below_threshold", "hw3_below_threshold", ], @@ -363,16 +365,19 @@ async def test_hw4_mileage_sensors_gating( mock_add_listener: AsyncMock, entity_id: str, firmware: str, - driver_assist: str, + driver_assist: str | None, expected: bool, ) -> None: """Test HW4 mileage sensors need both AP4 hardware and qualifying firmware.""" - metadata = deepcopy(METADATA) + metadata = _metadata_with_driver_assist(driver_assist) metadata["vehicles"][VEHICLE_VIN]["firmware"] = firmware mock_metadata.return_value = metadata - mock_products.return_value = _products_with_driver_assist(driver_assist) + # A streaming vehicle is never polled, so vehicle_config is only in metadata. + products = deepcopy(PRODUCTS) + del products["response"][0]["vehicle_config"] + mock_products.return_value = products await setup_platform(hass, [Platform.SENSOR]) From 89197a1dd046910fffb36c8e099d0421b7cc8fa9 Mon Sep 17 00:00:00 2001 From: Maciej Bieniek Date: Wed, 7 Oct 2026 16:04:12 +0200 Subject: [PATCH 197/356] Abort the config flow if the Shelly device is not supported (#184668) Co-authored-by: Shay Levy --- .../components/shelly/config_flow.py | 32 ++++ homeassistant/components/shelly/strings.json | 1 + homeassistant/components/shelly/utils.py | 28 +++ tests/components/shelly/test_config_flow.py | 165 +++++++++++++++++- 4 files changed, 221 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/shelly/config_flow.py b/homeassistant/components/shelly/config_flow.py index ed3cf83cc50c..5eceab035605 100644 --- a/homeassistant/components/shelly/config_flow.py +++ b/homeassistant/components/shelly/config_flow.py @@ -91,12 +91,14 @@ from .utils import ( get_block_device_sleep_period, get_coap_context, get_device_entry_gen, + get_device_from_manufacturer_data, get_http_port, get_info_auth, get_info_gen, get_model_name, get_rpc_device_wakeup_period, get_ws_context, + is_device_supported, mac_address_from_name, ) @@ -441,6 +443,12 @@ class ShellyConfigFlow(ConfigFlow, domain=DOMAIN): await self.async_set_unique_id(self.info[CONF_MAC], raise_on_progress=False) self._abort_if_unique_id_configured({CONF_HOST: host}) + if not is_device_supported(self.info): + return self.async_abort( + reason="unsupported_device", + description_placeholders={"model": get_model_name(self.info)}, + ) + self.host = host self.port = port self.verify_ssl = verify_ssl @@ -504,6 +512,15 @@ class ShellyConfigFlow(ConfigFlow, domain=DOMAIN): self.device_name = device_data.name await self.async_set_unique_id(device_data.mac, raise_on_progress=False) self._abort_if_unique_id_configured() + if ( + device := get_device_from_manufacturer_data( + device_data.discovery_info.manufacturer_data + ) + ) and not device.supported: + return self.async_abort( + reason="unsupported_device", + description_placeholders={"model": device.name}, + ) self.context.update( { "title_placeholders": {"name": self.device_name}, @@ -769,6 +786,15 @@ class ShellyConfigFlow(ConfigFlow, domain=DOMAIN): # Check if already configured - abort if device is already set up await self.async_set_unique_id(mac) self._abort_if_unique_id_configured() + if ( + device := get_device_from_manufacturer_data( + discovery_info.manufacturer_data + ) + ) and not device.supported: + return self.async_abort( + reason="unsupported_device", + description_placeholders={"model": device.name}, + ) # Store BLE device and name for WiFi provisioning self.ble_device = async_ble_device_from_address( @@ -1184,6 +1210,12 @@ class ShellyConfigFlow(ConfigFlow, domain=DOMAIN): mac = self.info[CONF_MAC] await self._async_handle_zeroconf_mac_discovery(mac, host, port) + if not is_device_supported(self.info): + return self.async_abort( + reason="unsupported_device", + description_placeholders={"model": get_model_name(self.info)}, + ) + self.host = host self.port = port self.verify_ssl = verify_ssl diff --git a/homeassistant/components/shelly/strings.json b/homeassistant/components/shelly/strings.json index 8bff186c92f4..bbbd64108bd0 100644 --- a/homeassistant/components/shelly/strings.json +++ b/homeassistant/components/shelly/strings.json @@ -14,6 +14,7 @@ "no_wifi_networks": "No Wi-Fi networks found during scan.", "reauth_unsuccessful": "Re-authentication was unsuccessful, please remove the integration and set it up again.", "unknown": "[%key:common::config_flow::error::unknown%]", + "unsupported_device": "{model} is not supported by the Shelly integration because it uses an incompatible protocol.", "wifi_provisioned": "Wi-Fi credentials for {ssid} have been provisioned to {name}. The device is connecting to Wi-Fi and will complete setup automatically." }, "error": { diff --git a/homeassistant/components/shelly/utils.py b/homeassistant/components/shelly/utils.py index 385c2ab80b04..31ecdf4ffef1 100644 --- a/homeassistant/components/shelly/utils.py +++ b/homeassistant/components/shelly/utils.py @@ -5,6 +5,8 @@ from ipaddress import IPv4Address, IPv6Address, ip_address from typing import TYPE_CHECKING, Any, cast from aiohttp.web import Request, WebSocketResponse +from aioshelly.ble import get_device_from_model_id +from aioshelly.ble.manufacturer_data import parse_shelly_manufacturer_data from aioshelly.block_device import COAP, Block, BlockDevice from aioshelly.const import ( BLOCK_GENERATIONS, @@ -12,6 +14,7 @@ from aioshelly.const import ( BLU_TRV_MODEL_NAME, DEFAULT_COAP_PORT, DEFAULT_HTTP_PORT, + DEVICES, MODEL_1L, MODEL_DIMMER, MODEL_DIMMER_2, @@ -20,6 +23,7 @@ from aioshelly.const import ( MODEL_NAMES, MODEL_PLUG, RPC_GENERATIONS, + ShellyDevice, ) from aioshelly.rpc_device import RpcDevice, WsServer from yarl import URL @@ -321,6 +325,30 @@ def get_model_name(info: dict[str, Any]) -> str: return cast(str, MODEL_NAMES.get(info["type"], info["type"])) +def is_device_supported(info: dict[str, Any]) -> bool: + """Return True if the device model is supported.""" + if get_info_gen(info) in RPC_GENERATIONS: + # Devices with firmware not fully provisioned + model = info.get(CONF_MODEL, "") + else: + model = info["type"] + if (device := DEVICES.get(model)) is None: + return True + + return device.supported + + +def get_device_from_manufacturer_data( + manufacturer_data: dict[int, bytes], +) -> ShellyDevice | None: + """Return the Shelly device matching the advertised BLE model ID.""" + parsed = parse_shelly_manufacturer_data(manufacturer_data) + if not parsed or not isinstance(model_id := parsed.get("model_id"), int): + return None + + return get_device_from_model_id(model_id) + + def get_shelly_model_name( model: str, sleep_period: int, diff --git a/tests/components/shelly/test_config_flow.py b/tests/components/shelly/test_config_flow.py index 6ef54abdc831..9dcc3670a2b4 100644 --- a/tests/components/shelly/test_config_flow.py +++ b/tests/components/shelly/test_config_flow.py @@ -11,6 +11,8 @@ from aioshelly.const import ( DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT, MODEL_1, + MODEL_4PRO, + MODEL_AZ_HT, MODEL_PLUS_2PM, ) from aioshelly.exceptions import ( @@ -132,6 +134,12 @@ BLE_MANUFACTURER_DATA_WITH_MAC_UNKNOWN_MODEL = { # Flags (0x01, 0x05, 0x00), Model (0x0b, 0x99, 0x99) - # unknown model ID, MAC (0x0a, 0x70, 0xd6, 0xc2, 0x97, 0xba, 0xcc) +BLE_MANUFACTURER_DATA_UNSUPPORTED_MODEL = { + 0x0BA9: bytes.fromhex("0105000b16180a70d6c297bacc") +} +# Flags (0x01, 0x05, 0x00), Model (0x0b, 0x16, 0x18) - Shelly AZ H&T (0x1816), +# unsupported model, MAC (0x0a, 0x70, 0xd6, 0xc2, 0x97, 0xba, 0xcc) + BLE_MANUFACTURER_DATA_FOR_CLEAR_TEST = { 0x0BA9: bytes.fromhex("0105000b30100a00eeddccbbaa") } @@ -259,6 +267,26 @@ BLE_DISCOVERY_INFO_MAC_UNKNOWN_MODEL = BluetoothServiceInfoBleak( tx_power=-127, ) +BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL = BluetoothServiceInfoBleak( + name="CC:BA:97:C2:D6:72", # BLE address as name (newer devices) + address="CC:BA:97:C2:D6:72", # BLE address may differ from device MAC + rssi=-32, + manufacturer_data=BLE_MANUFACTURER_DATA_UNSUPPORTED_MODEL, + service_uuids=[], + service_data={}, + source="local", + device=generate_ble_device( + address="CC:BA:97:C2:D6:72", + name="CC:BA:97:C2:D6:72", + ), + advertisement=generate_advertisement_data( + manufacturer_data=BLE_MANUFACTURER_DATA_UNSUPPORTED_MODEL, + ), + time=0, + connectable=True, + tx_power=-127, +) + BLE_DISCOVERY_INFO_NO_DEVICE = BluetoothServiceInfoBleak( name="ShellyPlus2PM-C049EF8873E8", address="00:00:00:00:00:00", # Invalid address that won't be found @@ -1023,7 +1051,7 @@ async def test_form_errors_test_connection( with ( patch( "homeassistant.components.shelly.config_flow.get_info", - return_value={"mac": "test-mac", "auth": False}, + return_value={"mac": "test-mac", "type": MODEL_1, "auth": False}, ), patch( "aioshelly.block_device.BlockDevice.create", new=AsyncMock(side_effect=exc) @@ -1039,7 +1067,7 @@ async def test_form_errors_test_connection( with patch( "homeassistant.components.shelly.config_flow.get_info", - return_value={"mac": "test-mac", "auth": False}, + return_value={"mac": "test-mac", "type": MODEL_1, "auth": False}, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], @@ -1737,7 +1765,7 @@ async def test_user_flow_zeroconf_device_requires_auth( "homeassistant.components.shelly.config_flow.get_info", return_value={ "mac": "AABBCCDDEEFF", - "model": MODEL_1, + "type": MODEL_1, "auth": True, # Requires auth "gen": 1, }, @@ -1757,7 +1785,7 @@ async def test_user_flow_zeroconf_device_requires_auth( "homeassistant.components.shelly.config_flow.get_info", return_value={ "mac": "AABBCCDDEEFF", - "model": MODEL_1, + "type": MODEL_1, "auth": False, # Auth passed with credentials "gen": 1, "port": 80, @@ -2218,7 +2246,7 @@ async def test_form_auth_errors_test_connection_gen1( with patch( "homeassistant.components.shelly.config_flow.get_info", - return_value={"mac": "test-mac", "auth": True}, + return_value={"mac": "test-mac", "type": MODEL_1, "auth": True}, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], @@ -5777,3 +5805,130 @@ async def test_bluetooth_provision_ble_reconnect_fails_during_ip_fetch( # Abort flow to reach terminal state hass.config_entries.flow.async_abort(result["flow_id"]) await hass.async_block_till_done(wait_background_tasks=True) + + +@pytest.mark.parametrize( + ("get_info", "model_name"), + [ + ( + {"mac": "test-mac", "model": MODEL_AZ_HT, "auth": False, "gen": 3}, + "Shelly AZ H&T", + ), + ( + {"mac": "test-mac", "type": MODEL_4PRO, "auth": False, "gen": 1}, + "Shelly 4Pro", + ), + ], +) +async def test_form_unsupported_device( + hass: HomeAssistant, get_info: dict[str, Any], model_name: str +) -> None: + """Test user flow aborts for a device model not supported by aioshelly.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + with patch( + "homeassistant.components.shelly.config_flow.get_info", + return_value=get_info, + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_HOST: "1.1.1.1", CONF_PORT: DEFAULT_HTTP_PORT}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + assert result["description_placeholders"] == {"model": model_name} + + +async def test_zeroconf_unsupported_device(hass: HomeAssistant) -> None: + """Test zeroconf discovery aborts for a device model not supported by aioshelly.""" + with patch( + "homeassistant.components.shelly.config_flow.get_info", + return_value={ + "mac": "test-mac", + "model": MODEL_AZ_HT, + "auth": False, + "gen": 3, + }, + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=DISCOVERY_INFO, + context={"source": config_entries.SOURCE_ZEROCONF}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + assert result["description_placeholders"] == {"model": "Shelly AZ H&T"} + + +@pytest.mark.usefixtures("mock_zeroconf") +async def test_bluetooth_discovery_unsupported_device(hass: HomeAssistant) -> None: + """Test bluetooth discovery aborts before provisioning for unsupported model.""" + await _async_inject_ble_discovery(hass, BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL, + context={"source": config_entries.SOURCE_BLUETOOTH}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + assert result["description_placeholders"] == {"model": "Shelly AZ H&T"} + + +@pytest.mark.usefixtures("mock_zeroconf") +async def test_bluetooth_discovery_unsupported_device_already_configured( + hass: HomeAssistant, +) -> None: + """Test already configured check runs before the unsupported model check.""" + await _async_inject_ble_discovery(hass, BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL) + + entry = MockConfigEntry( + domain=DOMAIN, + unique_id="CCBA97C2D670", # MAC from manufacturer data + data={ + CONF_HOST: "1.1.1.1", + CONF_MODEL: MODEL_AZ_HT, + CONF_SLEEP_PERIOD: 0, + CONF_GEN: 3, + }, + ) + entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, + data=BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL, + context={"source": config_entries.SOURCE_BLUETOOTH}, + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +async def test_user_flow_select_ble_unsupported_device( + hass: HomeAssistant, + mock_discovery: AsyncMock, +) -> None: + """Test selecting an unsupported BLE device aborts before provisioning.""" + mock_discovery.return_value = [] + await _async_inject_ble_discovery(hass, BLE_DISCOVERY_INFO_UNSUPPORTED_MODEL) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "user" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + {CONF_DEVICE: "CCBA97C2D670"}, # MAC from manufacturer data + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unsupported_device" + assert result["description_placeholders"] == {"model": "Shelly AZ H&T"} From a3e0ce8dfc719519ba1245cd84435cf833181194 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Wed, 7 Oct 2026 15:20:32 +0100 Subject: [PATCH 198/356] Revert PR 183342 (#184717) --- .../components/utility_meter/diagnostics.py | 28 +++++++++++-------- homeassistant/helpers/restore_state.py | 6 ---- .../snapshots/test_diagnostics.ambr | 6 ++-- tests/helpers/test_restore_state.py | 2 -- 4 files changed, 18 insertions(+), 24 deletions(-) diff --git a/homeassistant/components/utility_meter/diagnostics.py b/homeassistant/components/utility_meter/diagnostics.py index af1a17f62623..5163de2c883e 100644 --- a/homeassistant/components/utility_meter/diagnostics.py +++ b/homeassistant/components/utility_meter/diagnostics.py @@ -13,18 +13,22 @@ async def async_get_config_entry_diagnostics( ) -> dict[str, Any]: """Return diagnostics for a config entry.""" - tariff_sensors = [ - { - "name": sensor.name, - "entity_id": sensor.entity_id, - "extra_attributes": sensor.extra_state_attributes, - "last_sensor_data": sensor.extra_restore_state_data.as_dict(), - "period": sensor._period, # noqa: SLF001 - "cron": sensor._cron_pattern, # noqa: SLF001 - "source": sensor._sensor_source_id, # noqa: SLF001 - } - for sensor in hass.data[DATA_UTILITY][entry.entry_id][DATA_TARIFF_SENSORS] - ] + tariff_sensors = [] + + for sensor in hass.data[DATA_UTILITY][entry.entry_id][DATA_TARIFF_SENSORS]: + restored_last_extra_data = await sensor.async_get_last_extra_data() + + tariff_sensors.append( + { + "name": sensor.name, + "entity_id": sensor.entity_id, + "extra_attributes": sensor.extra_state_attributes, + "last_sensor_data": restored_last_extra_data, + "period": sensor._period, # noqa: SLF001 + "cron": sensor._cron_pattern, # noqa: SLF001 + "source": sensor._sensor_source_id, # noqa: SLF001 + } + ) return { "config_entry": entry, diff --git a/homeassistant/helpers/restore_state.py b/homeassistant/helpers/restore_state.py index 8697ed1900e4..814b3328975a 100644 --- a/homeassistant/helpers/restore_state.py +++ b/homeassistant/helpers/restore_state.py @@ -169,8 +169,6 @@ class RestoreStateData: This includes the states of all registered entities, as well as the stored states from the previous run, which have not been created as entities on this run, and have not expired. - - Stored states that will not be saved are dropped from memory too. """ now = dt_util.utcnow() all_states = self.hass.states.async_all() @@ -201,7 +199,6 @@ class RestoreStateData: ) ) expiration_time = now - STATE_EXPIRATION - last_states: dict[str, StoredState] = {} for entity_id, stored_state in self.last_states.items(): # Don't save old states that have entities in the current run @@ -215,9 +212,6 @@ class RestoreStateData: continue stored_states.append(stored_state) - last_states[entity_id] = stored_state - - self.last_states = last_states return stored_states diff --git a/tests/components/utility_meter/snapshots/test_diagnostics.ambr b/tests/components/utility_meter/snapshots/test_diagnostics.ambr index 59a4736e038a..024fd1aaa7b7 100644 --- a/tests/components/utility_meter/snapshots/test_diagnostics.ambr +++ b/tests/components/utility_meter/snapshots/test_diagnostics.ambr @@ -44,10 +44,9 @@ 'tariff': 'tariff0', }), 'last_sensor_data': dict({ - 'input_device_class': 'None', 'last_period': '0', 'last_reset': '2024-04-05T00:00:00+00:00', - 'last_valid_state': None, + 'last_valid_state': 3, 'native_unit_of_measurement': 'kWh', 'native_value': dict({ '__type': "", @@ -71,10 +70,9 @@ 'tariff': 'tariff1', }), 'last_sensor_data': dict({ - 'input_device_class': 'None', 'last_period': '0', 'last_reset': '2024-04-05T00:00:00+00:00', - 'last_valid_state': None, + 'last_valid_state': 7, 'native_unit_of_measurement': 'kWh', 'native_value': dict({ '__type': "", diff --git a/tests/helpers/test_restore_state.py b/tests/helpers/test_restore_state.py index 69de9a395124..d7dca037249c 100644 --- a/tests/helpers/test_restore_state.py +++ b/tests/helpers/test_restore_state.py @@ -321,8 +321,6 @@ async def test_dump_data(hass: HomeAssistant) -> None: assert state1["state"]["state"] == "off" assert state2["state"]["entity_id"] == "input_boolean.b5" assert state2["state"]["state"] == "off" - # States that are not written anymore are dropped from memory as well - assert list(data.last_states) == ["input_boolean.b3", "input_boolean.b5"] # Test that removed entities are not persisted await entity.async_remove() From 276922cfc37651b125d2c76f6c19f4ac6d4d990f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 15:06:07 +0000 Subject: [PATCH 199/356] Bump version to 2026.10.0b7 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index b61eab623503..f80b5cdd7397 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b6" +PATCH_VERSION: Final = "0b7" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 9a45e6b0f8e7..3d6ae3e41391 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b6" +version = "2026.10.0b7" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From dbd9f9c04b64ba62fc06faa9f40aa8b6bad880ce Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Wed, 7 Oct 2026 16:16:25 +0000 Subject: [PATCH 200/356] Bump version to 2026.10.0 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index f80b5cdd7397..85c9b6f0590f 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0b7" +PATCH_VERSION: Final = "0" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 3d6ae3e41391..2a591cd98bc3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0b7" +version = "2026.10.0" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 2e3ff9f8ac5d96ca9455ad5418692592f004e188 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ludovic=20BOU=C3=89?= Date: Wed, 7 Oct 2026 17:05:10 +0200 Subject: [PATCH 201/356] Split Matter TemperatureOffset range by Thermostat ClusterRevision (#180517) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Ludovic BOUÉ <938089+lboue@users.noreply.github.com> Co-authored-by: Claude Sonnet 5 --- homeassistant/components/matter/const.py | 1 + homeassistant/components/matter/discovery.py | 33 +++++- homeassistant/components/matter/models.py | 8 ++ homeassistant/components/matter/number.py | 68 ++++++++++-- .../matter/snapshots/test_number.ambr | 16 +-- tests/components/matter/test_discovery.py | 103 ++++++++++++++++++ tests/components/matter/test_number.py | 33 ++++++ 7 files changed, 243 insertions(+), 19 deletions(-) create mode 100644 tests/components/matter/test_discovery.py diff --git a/homeassistant/components/matter/const.py b/homeassistant/components/matter/const.py index 939011281d1b..f188bab2ab8a 100644 --- a/homeassistant/components/matter/const.py +++ b/homeassistant/components/matter/const.py @@ -18,6 +18,7 @@ ID_TYPE_DEVICE_ID = "deviceid" ID_TYPE_SERIAL = "serial" FEATUREMAP_ATTRIBUTE_ID = 65532 +CLUSTER_REVISION_ATTRIBUTE_ID = 65533 # --- Lock domain constants --- diff --git a/homeassistant/components/matter/discovery.py b/homeassistant/components/matter/discovery.py index 498b54ef7cd6..f6821c058a17 100644 --- a/homeassistant/components/matter/discovery.py +++ b/homeassistant/components/matter/discovery.py @@ -11,7 +11,7 @@ from homeassistant.core import callback from .binary_sensor import DISCOVERY_SCHEMAS as BINARY_SENSOR_SCHEMAS from .button import DISCOVERY_SCHEMAS as BUTTON_SCHEMAS from .climate import DISCOVERY_SCHEMAS as CLIMATE_SENSOR_SCHEMAS -from .const import FEATUREMAP_ATTRIBUTE_ID +from .const import CLUSTER_REVISION_ATTRIBUTE_ID, FEATUREMAP_ATTRIBUTE_ID from .cover import DISCOVERY_SCHEMAS as COVER_SCHEMAS from .event import DISCOVERY_SCHEMAS as EVENT_SCHEMAS from .fan import DISCOVERY_SCHEMAS as FAN_SCHEMAS @@ -57,6 +57,33 @@ def iter_schemas() -> Generator[MatterDiscoverySchema]: yield from platform_schemas +def _matches_cluster_revision( + endpoint: MatterEndpoint, + primary_attribute: type[ClusterAttributeDescriptor], + schema: MatterDiscoverySchema, +) -> bool: + """Return whether the endpoint's ClusterRevision matches the schema.""" + if schema.cluster_revision_min is None and schema.cluster_revision_max is None: + return True + raw_cluster_revision = endpoint.get_attribute_value( + primary_attribute.cluster_id, CLUSTER_REVISION_ATTRIBUTE_ID + ) + if raw_cluster_revision in (None, NullValue, 0): + # ClusterRevision starts at 1 (Matter spec 7.13.1); 0 means the + # attribute could not be read, so do not filter out the schema + return True + cluster_revision_value = int(raw_cluster_revision) + if ( + schema.cluster_revision_min is not None + and cluster_revision_value < schema.cluster_revision_min + ) or ( + schema.cluster_revision_max is not None + and cluster_revision_value > schema.cluster_revision_max + ): + return False + return True + + @callback def async_discover_entities( endpoint: MatterEndpoint, @@ -145,6 +172,10 @@ def async_discover_entities( ): continue + # check for required cluster revision range + if not _matches_cluster_revision(endpoint, primary_attribute, schema): + continue + # BEGIN checks on actual attribute values # these are the least likely to be used and least # efficient, so they are checked last diff --git a/homeassistant/components/matter/models.py b/homeassistant/components/matter/models.py index df30a636bae0..92762f47e0e3 100644 --- a/homeassistant/components/matter/models.py +++ b/homeassistant/components/matter/models.py @@ -125,6 +125,14 @@ class MatterDiscoverySchema: # for example for the DoorSensor on a DoorLock Cluster featuremap_contains: int | None = None + # [optional] the primary attribute's cluster ClusterRevision + # must be at least this value (inclusive) + cluster_revision_min: int | None = None + + # [optional] the primary attribute's cluster ClusterRevision + # must be at most this value (inclusive) + cluster_revision_max: int | None = None + # [optional] bool to specify if this primary value may be discovered # by multiple platforms allow_multi: bool = False diff --git a/homeassistant/components/matter/number.py b/homeassistant/components/matter/number.py index a837a4dc39c6..e89b4c851f45 100644 --- a/homeassistant/components/matter/number.py +++ b/homeassistant/components/matter/number.py @@ -30,6 +30,12 @@ from .entity import MatterEntity, MatterEntityDescription from .helpers import MatterConfigEntry from .models import MatterDiscoverySchema +# Thermostat ClusterRevision (Matter spec 7.13.1) at which the +# LocalTemperatureCalibration range was extended from ±2.5°C to the full +# int8 storage range of ±12.7°C (Matter 1.4, see connectedhomeip +# data_model/1.4/clusters/Thermostat.xml vs. data_model/1.3/clusters/Thermostat.xml) +THERMOSTAT_EXTENDED_CALIBRATION_REVISION = 7 + async def async_setup_entry( hass: HomeAssistant, @@ -308,8 +314,31 @@ DISCOVERY_SCHEMAS = [ ), featuremap_contains=(clusters.Thermostat.Bitmaps.Feature.kSetback), ), - # Eve temperature offset; shares the bounds of the generic schema below - # and will be merged into it under that schema's unique ID (follow-up PR) + # Eve temperature offset; identical to the generic schema below (will be + # merged into it in a follow-up PR). See that schema for the range rationale. + MatterDiscoverySchema( + platform=Platform.NUMBER, + entity_description=MatterNumberEntityDescription( + key="EveTemperatureOffset", + device_class=NumberDeviceClass.TEMPERATURE_DELTA, + entity_category=EntityCategory.CONFIG, + translation_key="temperature_offset", + native_max_value=2.5, + native_min_value=-2.5, + native_step=0.1, + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + device_to_ha=lambda x: None if x is None else x / 10, + ha_to_device=lambda x: round(x * 10), + mode=NumberMode.BOX, + ), + entity_class=MatterNumber, + required_attributes=( + clusters.Thermostat.Attributes.LocalTemperatureCalibration, + ), + vendor_id=(4874,), # Eve Systems + cluster_revision_max=THERMOSTAT_EXTENDED_CALIBRATION_REVISION - 1, + ), + # Eve temperature offset, extended range (Matter 1.4+) MatterDiscoverySchema( platform=Platform.NUMBER, entity_description=MatterNumberEntityDescription( @@ -317,10 +346,6 @@ DISCOVERY_SCHEMAS = [ device_class=NumberDeviceClass.TEMPERATURE_DELTA, entity_category=EntityCategory.CONFIG, translation_key="temperature_offset", - # Matter 1.4 raises this to the SignedTemperature type's usable - # range (±127 in 0.1°C units; -128 is reserved). Matter 1.3 is - # limited to ±2.5°C; that will be enforced via cluster_revision - # filtering in a follow-up PR. native_max_value=12.7, native_min_value=-12.7, native_step=0.1, @@ -334,7 +359,33 @@ DISCOVERY_SCHEMAS = [ clusters.Thermostat.Attributes.LocalTemperatureCalibration, ), vendor_id=(4874,), # Eve Systems + cluster_revision_min=THERMOSTAT_EXTENDED_CALIBRATION_REVISION, ), + # Matter 1.3 and earlier (ClusterRevision <= 6) limit LocalTemperatureCalibration + # to ±2.5°C; this schema also matches when ClusterRevision is unreadable. + MatterDiscoverySchema( + platform=Platform.NUMBER, + entity_description=MatterNumberEntityDescription( + key="TemperatureOffset", + device_class=NumberDeviceClass.TEMPERATURE_DELTA, + entity_category=EntityCategory.CONFIG, + translation_key="temperature_offset", + native_max_value=2.5, + native_min_value=-2.5, + native_step=0.1, + native_unit_of_measurement=UnitOfTemperature.CELSIUS, + device_to_ha=lambda x: None if x is None else x / 10, + ha_to_device=lambda x: round(x * 10), + mode=NumberMode.BOX, + ), + entity_class=MatterNumber, + required_attributes=( + clusters.Thermostat.Attributes.LocalTemperatureCalibration, + ), + cluster_revision_max=THERMOSTAT_EXTENDED_CALIBRATION_REVISION - 1, + ), + # Temperature offset, extended range (Matter 1.4+): SignedTemperature's + # usable range, ±127 in 0.1°C units (-128 is reserved). MatterDiscoverySchema( platform=Platform.NUMBER, entity_description=MatterNumberEntityDescription( @@ -342,10 +393,6 @@ DISCOVERY_SCHEMAS = [ device_class=NumberDeviceClass.TEMPERATURE_DELTA, entity_category=EntityCategory.CONFIG, translation_key="temperature_offset", - # Matter 1.4 raises this to the SignedTemperature type's usable - # range (±127 in 0.1°C units; -128 is reserved). Matter 1.3 is - # limited to ±2.5°C; that will be enforced via cluster_revision - # filtering in a follow-up PR. native_max_value=12.7, native_min_value=-12.7, native_step=0.1, @@ -358,6 +405,7 @@ DISCOVERY_SCHEMAS = [ required_attributes=( clusters.Thermostat.Attributes.LocalTemperatureCalibration, ), + cluster_revision_min=THERMOSTAT_EXTENDED_CALIBRATION_REVISION, ), MatterDiscoverySchema( platform=Platform.NUMBER, diff --git a/tests/components/matter/snapshots/test_number.ambr b/tests/components/matter/snapshots/test_number.ambr index 4ec1b71199a3..c6a895d4e2b5 100644 --- a/tests/components/matter/snapshots/test_number.ambr +++ b/tests/components/matter/snapshots/test_number.ambr @@ -422,8 +422,8 @@ ]), 'area_id': None, 'capabilities': dict({ - : 12.7, - : -12.7, + : 2.5, + : -2.5, : , : 0.1, }), @@ -462,8 +462,8 @@ 'attributes': ReadOnlyDict({ : 'temperature_delta', : 'Floor Heating Thermostat Temperature offset', - : 12.7, - : -12.7, + : 2.5, + : -2.5, : , : 0.1, : , @@ -720,8 +720,8 @@ ]), 'area_id': None, 'capabilities': dict({ - : 12.7, - : -12.7, + : 2.5, + : -2.5, : , : 0.1, }), @@ -760,8 +760,8 @@ 'attributes': ReadOnlyDict({ : 'temperature_delta', : 'Eve Thermo 20EBP1701 Temperature offset', - : 12.7, - : -12.7, + : 2.5, + : -2.5, : , : 0.1, : , diff --git a/tests/components/matter/test_discovery.py b/tests/components/matter/test_discovery.py new file mode 100644 index 000000000000..1538bc21cdd0 --- /dev/null +++ b/tests/components/matter/test_discovery.py @@ -0,0 +1,103 @@ +"""Test Matter discovery helpers.""" + +from unittest.mock import MagicMock + +from chip.clusters import Objects as clusters +from chip.clusters.ClusterObjects import ClusterAttributeDescriptor, NullValue +import pytest + +from homeassistant.components.matter import discovery +from homeassistant.components.matter.discovery import ( + _matches_cluster_revision, + async_discover_entities, +) +from homeassistant.components.matter.models import MatterDiscoverySchema +from homeassistant.const import Platform + +from .common import create_node_from_fixture + + +def _make_schema( + cluster_revision_min: int | None, cluster_revision_max: int | None +) -> MatterDiscoverySchema: + """Return a minimal MatterDiscoverySchema for cluster_revision filtering tests.""" + return MatterDiscoverySchema( + platform=Platform.SENSOR, + entity_description=MagicMock(), + entity_class=MagicMock(), + required_attributes=( + clusters.Thermostat.Attributes.LocalTemperatureCalibration, + ), + cluster_revision_min=cluster_revision_min, + cluster_revision_max=cluster_revision_max, + ) + + +@pytest.mark.parametrize( + ( + "cluster_revision_min", + "cluster_revision_max", + "raw_cluster_revision", + "expected", + "expected_call_count", + ), + [ + pytest.param(None, None, 5, True, 0, id="no bounds"), + pytest.param(7, None, 6, False, 1, id="min unmet"), + pytest.param(7, None, 7, True, 1, id="min met"), + pytest.param(None, 6, 7, False, 1, id="max exceeded"), + pytest.param(None, 6, 6, True, 1, id="max met"), + pytest.param(2, 6, 1, False, 1, id="below range"), + pytest.param(2, 6, 7, False, 1, id="above range"), + pytest.param(2, 6, 4, True, 1, id="within range"), + pytest.param(7, None, None, True, 1, id="unreadable revision (None)"), + pytest.param(7, None, NullValue, True, 1, id="unreadable revision (NullValue)"), + pytest.param( + 7, + None, + 0, + True, + 1, + id="unreadable revision (0, unpopulated uint16 default)", + ), + ], +) +def test_matches_cluster_revision( + cluster_revision_min: int | None, + cluster_revision_max: int | None, + raw_cluster_revision: int | None, + expected: bool, + expected_call_count: int, +) -> None: + """Test _matches_cluster_revision matches schema bounds against ClusterRevision.""" + endpoint = MagicMock() + endpoint.get_attribute_value.return_value = raw_cluster_revision + schema = _make_schema(cluster_revision_min, cluster_revision_max) + primary_attribute: type[ClusterAttributeDescriptor] = schema.required_attributes[0] + + assert _matches_cluster_revision(endpoint, primary_attribute, schema) is expected + assert endpoint.get_attribute_value.call_count == expected_call_count + + +@pytest.mark.parametrize( + ("cluster_revision", "expected_discovered"), + [ + pytest.param(6, True, id="within range"), + pytest.param(7, False, id="above range"), + pytest.param(0, True, id="unreadable revision (0)"), + ], +) +def test_async_discover_entities_filters_by_cluster_revision( + monkeypatch: pytest.MonkeyPatch, + cluster_revision: int, + expected_discovered: bool, +) -> None: + """Test async_discover_entities honors cluster_revision_min/cluster_revision_max.""" + schema = _make_schema(cluster_revision_min=None, cluster_revision_max=6) + monkeypatch.setattr(discovery, "DISCOVERY_SCHEMAS", {Platform.SENSOR: [schema]}) + node = create_node_from_fixture( + "mock_thermostat", override_attributes={"1/513/65533": cluster_revision} + ) + endpoint = node.endpoints[1] + + assert bool(list(async_discover_entities(endpoint))) is expected_discovered diff --git a/tests/components/matter/test_number.py b/tests/components/matter/test_number.py index 73c20c017d02..bb3bc1d078b5 100644 --- a/tests/components/matter/test_number.py +++ b/tests/components/matter/test_number.py @@ -376,6 +376,39 @@ async def test_thermostat_temperature_offset( ) +@pytest.mark.parametrize( + ("node_fixture", "entity_id", "expected_min", "expected_max"), + [ + pytest.param( + "aqara_thermostat_w500", + "number.floor_heating_thermostat_temperature_offset", + -2.5, + 2.5, + id="cluster_revision_6_legacy_range", + ), + pytest.param( + "mock_thermostat", + "number.mock_thermostat_temperature_offset", + -12.7, + 12.7, + id="cluster_revision_9_extended_range", + ), + ], +) +@pytest.mark.usefixtures("matter_node") +async def test_thermostat_temperature_offset_cluster_revision_range( + hass: HomeAssistant, + entity_id: str, + expected_min: float, + expected_max: float, +) -> None: + """Test TemperatureOffset bounds depend on the Thermostat ClusterRevision.""" + state = hass.states.get(entity_id) + assert state + assert state.attributes["min"] == expected_min + assert state.attributes["max"] == expected_max + + @pytest.mark.parametrize("node_fixture", ["aqara_multi_state_p100"]) async def test_boolean_state_configuration_current_sensitivity_level( hass: HomeAssistant, From ed74a0ce5654e3a44230710bad9474ad3d41c1ae Mon Sep 17 00:00:00 2001 From: Kevin Stillhammer Date: Wed, 7 Oct 2026 12:37:57 +0200 Subject: [PATCH 202/356] Bump pywaze to 1.2.4 (#184663) --- homeassistant/components/waze_travel_time/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/waze_travel_time/manifest.json b/homeassistant/components/waze_travel_time/manifest.json index d677c06512a9..c24d2d57642c 100644 --- a/homeassistant/components/waze_travel_time/manifest.json +++ b/homeassistant/components/waze_travel_time/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["pywaze", "homeassistant.helpers.location"], - "requirements": ["pywaze==1.2.3"] + "requirements": ["pywaze==1.2.4"] } diff --git a/requirements_all.txt b/requirements_all.txt index 91e64c84696d..f8edf12c8784 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2887,7 +2887,7 @@ pyvlx==0.2.36 pyvolumio==0.1.5 # homeassistant.components.waze_travel_time -pywaze==1.2.3 +pywaze==1.2.4 # homeassistant.components.weatherflow pyweatherflowudp==1.6.3 From a733b78b05730fc2873898eb72c7dfd8ac37b46a Mon Sep 17 00:00:00 2001 From: Federico Zivolo <5382443+FezVrasta@users.noreply.github.com> Date: Thu, 8 Oct 2026 17:37:46 +0200 Subject: [PATCH 203/356] Bump pyicloud to 2.7.0 (#184728) --- homeassistant/components/icloud/coordinator.py | 15 ++++++++------- homeassistant/components/icloud/manifest.json | 2 +- requirements_all.txt | 2 +- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/icloud/coordinator.py b/homeassistant/components/icloud/coordinator.py index 18055beeed23..fce8d91bb7bc 100644 --- a/homeassistant/components/icloud/coordinator.py +++ b/homeassistant/components/icloud/coordinator.py @@ -217,8 +217,9 @@ REMINDERS_ERRORS = ( # Cloud Storage key. Such a reminder has no readable title and no notes, and # `update()` rewrites TitleDocument and NotesDocument unconditionally, so # writing one back would replace the real title with this placeholder and blank -# the notes. They are left out of the to-do lists entirely until the library -# requests Protected Cloud Storage access. +# the notes. pyicloud requests that key before every Reminders access, so this +# should not happen anymore, but any such reminder is still left out of the +# to-do lists rather than risk overwriting it. UNDECODED_TITLE = "Error Decoding Title" # Reminders are fetched one list at a time, so keep the per-list page bounded. @@ -314,9 +315,10 @@ class IcloudRemindersCoordinator(DataUpdateCoordinator[dict[str, IcloudReminderL """Warn once if reminders had to be left out because of encryption. With Advanced Data Protection enabled, CloudKit only returns readable - content to a session holding a Protected Cloud Storage key, which - pyicloud does not yet request. Those reminders are skipped rather than - shown as placeholders, so say once why a list looks short. + content to a session holding a Protected Cloud Storage key. pyicloud + requests one, but if a reminder still comes back undecoded it is + skipped rather than shown as a placeholder, so say once why a list + looks short. """ if self._warned_undecoded or not self._skipped_undecoded: return @@ -324,8 +326,7 @@ class IcloudRemindersCoordinator(DataUpdateCoordinator[dict[str, IcloudReminderL self._warned_undecoded = True _LOGGER.warning( "Some reminders could not be decrypted and have been left out of " - "the to-do lists. This account uses Advanced Data Protection, " - "which Home Assistant cannot read Reminders from yet" + "the to-do lists" ) diff --git a/homeassistant/components/icloud/manifest.json b/homeassistant/components/icloud/manifest.json index a7a0f91b6614..f9bc4456ed69 100644 --- a/homeassistant/components/icloud/manifest.json +++ b/homeassistant/components/icloud/manifest.json @@ -8,5 +8,5 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["keyrings.alt", "pyicloud"], - "requirements": ["pyicloud==2.6.5"] + "requirements": ["pyicloud==2.7.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index f8edf12c8784..7dd166b52927 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2301,7 +2301,7 @@ pyhomeworks==1.1.2 pyialarm==2.2.0 # homeassistant.components.icloud -pyicloud==2.6.5 +pyicloud==2.7.0 # homeassistant.components.imou pyimouapi==1.4.0 From e4a638715e90f1fc61fc07e425e46c9d2a855ee4 Mon Sep 17 00:00:00 2001 From: Simone Chemelli Date: Fri, 9 Oct 2026 15:08:23 +0200 Subject: [PATCH 204/356] Retry failed Analytics insights refresh (#184731) --- .../analytics_insights/coordinator.py | 58 ++++++++++++---- .../analytics_insights/test_sensor.py | 67 +++++++++++++++++-- 2 files changed, 107 insertions(+), 18 deletions(-) diff --git a/homeassistant/components/analytics_insights/coordinator.py b/homeassistant/components/analytics_insights/coordinator.py index 5a7955760d8d..9f2165d5f693 100644 --- a/homeassistant/components/analytics_insights/coordinator.py +++ b/homeassistant/components/analytics_insights/coordinator.py @@ -1,13 +1,15 @@ """DataUpdateCoordinator for the Homeassistant Analytics integration.""" +from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import timedelta -from typing import TYPE_CHECKING, override +from typing import TYPE_CHECKING, Any, cast, override from python_homeassistant_analytics import ( CustomIntegration, HomeassistantAnalyticsClient, HomeassistantAnalyticsConnectionError, + HomeassistantAnalyticsError, HomeassistantAnalyticsNotModifiedError, ) from python_homeassistant_analytics.models import Addon @@ -26,6 +28,8 @@ from .const import ( if TYPE_CHECKING: from . import AnalyticsInsightsConfigEntry +RETRY_AFTER = timedelta(minutes=15) + @dataclass(frozen=True) class AnalyticsData: @@ -65,21 +69,49 @@ class HomeassistantAnalyticsDataUpdateCoordinator(DataUpdateCoordinator[Analytic self._tracked_custom_integrations = self.config_entry.options[ CONF_TRACKED_CUSTOM_INTEGRATIONS ] + # The client keeps one ETag per endpoint, so a 304 only means that + # endpoint is unchanged: keep each last response to fall back on. + self._responses: dict[str, Any] = {} + + async def _async_fetch[_T]( + self, endpoint: str, fetch: Callable[[], Awaitable[_T]] + ) -> _T: + """Fetch one endpoint, falling back to its last response on 304.""" + try: + result = await fetch() + except HomeassistantAnalyticsNotModifiedError as err: + if endpoint in self._responses: + return cast(_T, self._responses[endpoint]) + raise UpdateFailed( + f"Homeassistant Analytics returned 304 for {endpoint} without " + "previous data", + retry_after=RETRY_AFTER.total_seconds(), + ) from err + except HomeassistantAnalyticsConnectionError as err: + raise UpdateFailed( + f"Could not reach Homeassistant Analytics while fetching {endpoint}: " + f"{err}", + retry_after=RETRY_AFTER.total_seconds(), + ) from err + except HomeassistantAnalyticsError as err: + raise UpdateFailed( + f"Unexpected response from Homeassistant Analytics for {endpoint}", + retry_after=RETRY_AFTER.total_seconds(), + ) from err + self._responses[endpoint] = result + return result @override async def _async_update_data(self) -> AnalyticsData: - try: - apps_data = ( - await self._client.get_addons() - ) # Still add method name. Needs library update - data = await self._client.get_current_analytics() - custom_data = await self._client.get_custom_integrations() - except HomeassistantAnalyticsConnectionError as err: - raise UpdateFailed( - "Error communicating with Homeassistant Analytics" - ) from err - except HomeassistantAnalyticsNotModifiedError: - return self.data + apps_data = await self._async_fetch( + "addons.json", self._client.get_addons + ) # Still add method name. Needs library update + data = await self._async_fetch( + "current_data.json", self._client.get_current_analytics + ) + custom_data = await self._async_fetch( + "custom_integrations.json", self._client.get_custom_integrations + ) apps = {app: get_app_value(apps_data, app) for app in self._tracked_apps} core_integrations = { integration: data.integrations.get(integration, 0) diff --git a/tests/components/analytics_insights/test_sensor.py b/tests/components/analytics_insights/test_sensor.py index ce41afeb2726..b17a36259070 100644 --- a/tests/components/analytics_insights/test_sensor.py +++ b/tests/components/analytics_insights/test_sensor.py @@ -1,5 +1,6 @@ """Test the Home Assistant analytics sensor module.""" +from dataclasses import replace from datetime import timedelta from unittest.mock import AsyncMock, patch @@ -7,10 +8,13 @@ from freezegun.api import FrozenDateTimeFactory import pytest from python_homeassistant_analytics import ( HomeassistantAnalyticsConnectionError, + HomeassistantAnalyticsError, HomeassistantAnalyticsNotModifiedError, ) from syrupy.assertion import SnapshotAssertion +from homeassistant.components.analytics_insights.coordinator import RETRY_AFTER +from homeassistant.config_entries import ConfigEntryState from homeassistant.const import STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -39,18 +43,26 @@ async def test_all_entities( ) -async def test_connection_error( +@pytest.mark.parametrize( + "exception", + [ + pytest.param(HomeassistantAnalyticsConnectionError(), id="connection"), + pytest.param( + HomeassistantAnalyticsError("Unexpected response"), id="bad_response" + ), + ], +) +async def test_update_error_recovers( hass: HomeAssistant, mock_analytics_client: AsyncMock, mock_config_entry: MockConfigEntry, freezer: FrozenDateTimeFactory, + exception: HomeassistantAnalyticsError, ) -> None: - """Test connection error.""" + """Test entities go unavailable on error and recover after the retry delay.""" await setup_integration(hass, mock_config_entry) - mock_analytics_client.get_current_analytics.side_effect = ( - HomeassistantAnalyticsConnectionError() - ) + mock_analytics_client.get_current_analytics.side_effect = exception freezer.tick(delta=timedelta(hours=12)) async_fire_time_changed(hass) await hass.async_block_till_done() @@ -60,6 +72,13 @@ async def test_connection_error( == STATE_UNAVAILABLE ) + mock_analytics_client.get_current_analytics.side_effect = None + freezer.tick(delta=RETRY_AFTER) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass.states.get("sensor.homeassistant_analytics_spotify").state == "24388" + async def test_data_not_modified( hass: HomeAssistant, @@ -80,3 +99,41 @@ async def test_data_not_modified( mock_analytics_client.get_current_analytics.assert_called() assert hass.states.get("sensor.homeassistant_analytics_spotify").state == "24388" + + +async def test_data_not_modified_uses_other_endpoints( + hass: HomeAssistant, + mock_analytics_client: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a 304 on one endpoint does not discard fresh data from the others.""" + await setup_integration(hass, mock_config_entry) + + current = mock_analytics_client.get_current_analytics.return_value + mock_analytics_client.get_addons.side_effect = ( + HomeassistantAnalyticsNotModifiedError + ) + mock_analytics_client.get_current_analytics.return_value = replace( + current, integrations={**current.integrations, "spotify": 1} + ) + freezer.tick(delta=timedelta(hours=12)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert hass.states.get("sensor.homeassistant_analytics_core_samba").state == "76357" + assert hass.states.get("sensor.homeassistant_analytics_spotify").state == "1" + + +async def test_data_not_modified_without_previous_data( + hass: HomeAssistant, + mock_analytics_client: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a 304 with no earlier response to fall back on retries setup.""" + mock_analytics_client.get_addons.side_effect = ( + HomeassistantAnalyticsNotModifiedError + ) + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY From a43b098debbd13c359bed6d8b818ea1adc5e7120 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 8 Oct 2026 15:17:37 +0200 Subject: [PATCH 205/356] Fix WLED color modes not following a changed LED setup (#184778) --- homeassistant/components/wled/coordinator.py | 113 ++++++++++++- tests/components/wled/test_coordinator.py | 46 +++++- tests/components/wled/test_light.py | 159 +++++++++++++++++++ tests/components/wled/test_update.py | 6 +- 4 files changed, 312 insertions(+), 12 deletions(-) diff --git a/homeassistant/components/wled/coordinator.py b/homeassistant/components/wled/coordinator.py index b988287d2b40..98a589d4005e 100644 --- a/homeassistant/components/wled/coordinator.py +++ b/homeassistant/components/wled/coordinator.py @@ -1,10 +1,11 @@ """DataUpdateCoordinator for WLED.""" -from typing import TYPE_CHECKING, override +from typing import TYPE_CHECKING, Any, override from wled import ( WLED, Device as WLEDDevice, + LightCapability, Releases, WLEDConnectionClosedError, WLEDError, @@ -43,6 +44,39 @@ def normalize_mac_address(mac: str) -> str: return mac.lower().replace(":", "").replace(".", "").replace("-", "").strip() +def _led_setup(device: WLEDDevice) -> tuple[Any, ...] | None: + """Return what of the LED setup the color modes depend on, if known.""" + if (led_config := device.led_config) is None: + return None + + return ( + led_config.cct_from_rgb, + tuple( + ( + output.start, + output.length, + output.has_rgb, + output.has_white, + output.has_cct, + ) + for output in led_config.outputs + ), + ) + + +def _segment_outputs( + device: WLEDDevice, segment_id: int +) -> frozenset[tuple[bool, bool, bool]] | None: + """Return the kinds of LED outputs a segment is on, if known.""" + if device.led_config is None: + return None + + return frozenset( + (output.has_rgb, output.has_white, output.has_cct) + for output in device.segment_led_outputs(segment_id) + ) + + class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): """Class to manage fetching WLED data from single endpoint.""" @@ -62,6 +96,13 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): self.wled = WLED(entry.data[CONF_HOST], session=async_get_clientsession(hass)) self.unsub: CALLBACK_TYPE | None = None + # What the entities were set up from. The library updates the device + # object in place, so this keeps copies to compare new data against. + self._repo: str | None = None + self._led_setup: tuple[Any, ...] | None = None + self._light_capabilities: dict[int, LightCapability | None] = {} + self._segment_outputs: dict[int, frozenset[tuple[bool, bool, bool]]] = {} + if TYPE_CHECKING: assert entry.unique_id self.config_mac_address = normalize_mac_address(entry.unique_id) @@ -74,6 +115,64 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): update_interval=SCAN_INTERVAL, ) + def _remember_setup(self, device: WLEDDevice) -> None: + """Remember what the entities are set up from.""" + self._repo = device.info.repo + + # An LED setup that isn't known right now, like when fetching it + # failed, keeps the last known one; it would reload twice for nothing. + if (led_setup := _led_setup(device)) is not None: + self._led_setup = led_setup + + # Segments that disappear keep their entity, so keep theirs as well. + for segment_id, segment in device.state.segments.items(): + self._light_capabilities[segment_id] = segment.light_capabilities + if (outputs := _segment_outputs(device, segment_id)) is not None: + self._segment_outputs[segment_id] = outputs + + def _setup_changed(self, device: WLEDDevice) -> bool: + """Return whether the device changed in a way the entities can't follow.""" + # Firmware from another repository changes which updates can be offered, + # like after flashing a fork. + if device.info.repo != self._repo: + return True + + for segment_id, segment in device.state.segments.items(): + # A segment can do other colors, like after changing the LED type. + if ( + segment_id in self._light_capabilities + and self._light_capabilities[segment_id] != segment.light_capabilities + ): + return True + + # A segment moved onto other kinds of LEDs, like from an RGBCCT + # output onto an RGBW one, while it reports the same capabilities. + outputs = _segment_outputs(device, segment_id) + if ( + outputs is not None + and segment_id in self._segment_outputs + and outputs != self._segment_outputs[segment_id] + ): + return True + + led_setup = _led_setup(device) + return led_setup is not None and led_setup != self._led_setup + + @callback + def _async_reload_on_setup_change(self, device: WLEDDevice) -> None: + """Set the integration up again when the device changed its setup.""" + if self._setup_changed(device): + self.hass.config_entries.async_schedule_reload(self.config_entry.entry_id) + + # Remembering it reloads only once, while more updates come in. + self._remember_setup(device) + + @callback + def _async_handle_websocket_update(self, device: WLEDDevice) -> None: + """Handle an update the device pushed over the WebSocket.""" + self._async_reload_on_setup_change(device) + self.async_set_updated_data(device) + @property def has_main_light(self) -> bool: """Return if the coordinated device has a main light.""" @@ -107,7 +206,7 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): # Stop polling as long as we have a websocket. WS will push # updates to us self.update_interval = None - await self.wled.listen(callback=self.async_set_updated_data) + await self.wled.listen(callback=self._async_handle_websocket_update) except WLEDConnectionClosedError as err: self.last_update_success = False self.logger.info(err) @@ -173,10 +272,12 @@ class WLEDDataUpdateCoordinator(DataUpdateCoordinator[WLEDDevice]): }, ) - # Firmware from another repository changes which updates can be offered, - # like after flashing a fork; set the integration up again for it. - if self.data is not None and device.info.repo != self.data.info.repo: - self.hass.config_entries.async_schedule_reload(self.config_entry.entry_id) + # The first data is what the entities are set up from. + previous: WLEDDevice | None = self.data + if previous is None: + self._remember_setup(device) + else: + self._async_reload_on_setup_change(device) # If the device supports a WebSocket, try activating it. if ( diff --git a/tests/components/wled/test_coordinator.py b/tests/components/wled/test_coordinator.py index 4e703dd1565d..2017dd32eb4e 100644 --- a/tests/components/wled/test_coordinator.py +++ b/tests/components/wled/test_coordinator.py @@ -3,7 +3,7 @@ import asyncio from collections.abc import Callable from copy import deepcopy -from unittest.mock import MagicMock +from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest @@ -15,7 +15,7 @@ from wled import ( WLEDUnsupportedVersionError, ) -from homeassistant.components.wled.const import SCAN_INTERVAL +from homeassistant.components.wled.const import DOMAIN, SCAN_INTERVAL from homeassistant.config_entries import ConfigEntryState from homeassistant.const import ( EVENT_HOMEASSISTANT_STOP, @@ -25,7 +25,11 @@ from homeassistant.const import ( ) from homeassistant.core import HomeAssistant -from tests.common import MockConfigEntry, async_fire_time_changed +from tests.common import ( + MockConfigEntry, + async_fire_time_changed, + async_load_json_object_fixture, +) async def test_not_supporting_websocket( @@ -282,3 +286,39 @@ async def test_fail_when_unsupported_version( in mock_config_entry.reason ) assert "0.14.0-b1" in mock_config_entry.reason + + +@pytest.mark.parametrize("device_fixture", ["rgb_websocket"]) +async def test_websocket_update_with_other_led_setup( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_wled: MagicMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Ensure an LED setup change pushed over the WebSocket sets up again.""" + connection_connected = asyncio.Future() + connection_finished = asyncio.Future() + push: Callable[[WLEDDevice], None] | None = None + + async def connect(callback: Callable[[WLEDDevice], None]): + nonlocal push + push = callback + connection_connected.set_result(None) + await connection_finished + + mock_wled.listen.side_effect = connect + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await connection_connected + assert push is not None + + # The segment is now on an RGBW output; the library updates in place. + data = await async_load_json_object_fixture(hass, "rgb_websocket.json", DOMAIN) + data["info"]["leds"]["seglc"] = [3] + device = mock_wled.update.return_value + device.update_from_dict(data) + with patch.object(hass.config_entries, "async_schedule_reload") as reload: + push(device) + + reload.assert_called_once_with(init_integration.entry_id) + connection_finished.set_result(None) diff --git a/tests/components/wled/test_light.py b/tests/components/wled/test_light.py index f2233565241f..f99ffd179052 100644 --- a/tests/components/wled/test_light.py +++ b/tests/components/wled/test_light.py @@ -1,6 +1,7 @@ """Tests for the WLED light platform.""" from collections.abc import Generator +from copy import deepcopy from typing import Any from unittest.mock import MagicMock, patch @@ -735,3 +736,161 @@ async def test_no_rgbww_light( ColorMode.RGBW, ] assert state.attributes[ATTR_COLOR_MODE] == ColorMode.RGBW + + +async def _async_refresh_with( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, + light_capabilities: int, + led_config: dict[str, Any] | None, +) -> None: + """Let the device answer with another LED setup on the next update.""" + data = await async_load_json_object_fixture(hass, "cct.json", DOMAIN) + data["info"]["leds"]["seglc"] = [light_capabilities] + data["state"]["seg"][0]["col"] = [[255, 0, 0, 255], [0, 0, 0, 0], [0, 0, 0, 0]] + # The library has no LED setup when fetching it failed. + data["cfg"] = {"hw": {"led": led_config}} if led_config is not None else None + + # The library updates the device object in place, like the real one does. + mock_wled.update.return_value.update_from_dict(data) + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_modes_follow_led_type_change( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the color modes follow a change of the LED type.""" + sk6812 = {"cct": True, "ins": [{"start": 0, "len": 178, "type": 30}]} + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], sk6812 + ) + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + await _async_refresh_with(hass, mock_wled, mock_config_entry, 7, WS2805) + + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBWW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_modes_follow_light_capabilities_change( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the color modes follow a change of a segment's capabilities.""" + await _async_load_segment(hass, mock_wled, mock_config_entry, 1, [255, 0, 0]) + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.RGB] + + await _async_refresh_with(hass, mock_wled, mock_config_entry, 7, None) + + assert (state := hass.states.get("light.wled_cct_light")) + assert state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ + ColorMode.COLOR_TEMP, + ColorMode.RGBW, + ] + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_modes_kept_when_led_setup_not_known( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test an LED setup that can't be fetched for a moment changes nothing.""" + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], WS2805 + ) + + with patch.object(hass.config_entries, "async_schedule_reload") as reload: + await _async_refresh_with(hass, mock_wled, mock_config_entry, 7, None) + + reload.assert_not_called() + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBWW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_modes_once_led_setup_is_known( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test an LED setup not known at setup is picked up once it is.""" + await _async_load_segment(hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255]) + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + await _async_refresh_with(hass, mock_wled, mock_config_entry, 7, WS2805) + + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBWW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + +async def test_color_modes_follow_segment_coming_back( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a segment that comes back with other capabilities sets up again.""" + data = await async_load_json_object_fixture(hass, "rgb.json", DOMAIN) + device = mock_wled.update.return_value + + # The second segment is removed, its entity stays. + removed = deepcopy(data) + removed["state"]["seg"] = removed["state"]["seg"][:1] + removed["info"]["leds"]["seglc"] = [1] + device.update_from_dict(removed) + await mock_config_entry.runtime_data.async_refresh() + await hass.async_block_till_done() + + # It comes back on an RGBW output. + data["info"]["leds"]["seglc"] = [1, 3] + device.update_from_dict(data) + with patch.object(hass.config_entries, "async_schedule_reload") as reload: + await mock_config_entry.runtime_data.async_refresh() + + reload.assert_called_once_with(mock_config_entry.entry_id) + + +@pytest.mark.parametrize("device_fixture", ["cct"]) +async def test_color_modes_follow_segment_moving_to_other_leds( + hass: HomeAssistant, + mock_wled: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a segment growing onto other kinds of LEDs sets up again.""" + led_config = { + "cb": 30, + "ins": [ + {"start": 0, "len": 89, "type": 32}, + {"start": 89, "len": 89, "type": 30}, + ], + } + await _async_load_segment( + hass, mock_wled, mock_config_entry, 7, [255, 0, 0, 255], led_config + ) + device = mock_wled.update.return_value + device.state.segments[0].stop = 89 + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("light.wled_cct_light")) + assert ColorMode.RGBWW in state.attributes[ATTR_SUPPORTED_COLOR_MODES] + + # The segment now covers the RGBW output too, same capabilities. + data = await async_load_json_object_fixture(hass, "cct.json", DOMAIN) + data["info"]["leds"]["seglc"] = [7] + data["state"]["seg"][0]["stop"] = 178 + device.update_from_dict(data) + with patch.object(hass.config_entries, "async_schedule_reload") as reload: + await mock_config_entry.runtime_data.async_refresh() + + reload.assert_called_once_with(mock_config_entry.entry_id) diff --git a/tests/components/wled/test_update.py b/tests/components/wled/test_update.py index 2c7eb3a79c2e..38a141758f6a 100644 --- a/tests/components/wled/test_update.py +++ b/tests/components/wled/test_update.py @@ -6,7 +6,7 @@ from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion -from wled import Device as WLEDDevice, Releases, WLEDError, WLEDUpgradeError +from wled import Releases, WLEDError, WLEDUpgradeError from homeassistant.components.homeassistant import ( DOMAIN as HOME_ASSISTANT_DOMAIN, @@ -341,10 +341,10 @@ async def test_update_follows_firmware_repository_change( assert (state := hass.states.get("update.wled_rgb_light_firmware")) assert "github.com/wled/WLED/" in state.attributes[ATTR_RELEASE_URL] - # A new device object, as the device answers after being flashed. + # The library updates the device object in place, like the real one does. data = await async_load_json_object_fixture(hass, "rgb.json", DOMAIN) data["info"]["repo"] = "MoonModules/WLED-MM" - mock_wled.update.return_value = WLEDDevice.from_dict(data) + mock_wled.update.return_value.update_from_dict(data) await mock_config_entry.runtime_data.async_refresh() await hass.async_block_till_done() From 86475520ae29d916ce16bf659e051d43825edad0 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 8 Oct 2026 07:03:38 +0200 Subject: [PATCH 206/356] Bump dwdwfsapi to 1.1.0 (#184784) --- homeassistant/components/dwd_weather_warnings/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/dwd_weather_warnings/manifest.json b/homeassistant/components/dwd_weather_warnings/manifest.json index c43f4e1b5be7..7aa0abe46824 100644 --- a/homeassistant/components/dwd_weather_warnings/manifest.json +++ b/homeassistant/components/dwd_weather_warnings/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "loggers": ["dwdwfsapi"], - "requirements": ["dwdwfsapi==1.0.7"] + "requirements": ["dwdwfsapi==1.1.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 7dd166b52927..47eecd51b382 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -884,7 +884,7 @@ dropmqttapi==1.0.3 dsmr-parser==1.11.1 # homeassistant.components.dwd_weather_warnings -dwdwfsapi==1.0.7 +dwdwfsapi==1.1.0 # homeassistant.components.dynalite dynalite-devices==0.1.47 From 1017a2249d45b33e9fb195d1908d102bfc12da4d Mon Sep 17 00:00:00 2001 From: TengfeiLi <115617397+tengfeili-qingping@users.noreply.github.com> Date: Thu, 8 Oct 2026 14:33:48 +0800 Subject: [PATCH 207/356] =?UTF-8?q?Add=20description=20for=20the=20device?= =?UTF-8?q?=20selection=20field=20in=20the=20Qingping=20config=E2=80=A6=20?= =?UTF-8?q?(#184797)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Claude Code --- homeassistant/components/qingping/strings.json | 3 +++ 1 file changed, 3 insertions(+) diff --git a/homeassistant/components/qingping/strings.json b/homeassistant/components/qingping/strings.json index 3257ad384c3d..5d18bfce1381 100644 --- a/homeassistant/components/qingping/strings.json +++ b/homeassistant/components/qingping/strings.json @@ -14,6 +14,9 @@ "data": { "address": "[%key:common::config_flow::data::device%]" }, + "data_description": { + "address": "Select the Qingping device you want to set up" + }, "description": "[%key:component::bluetooth::config::step::user::description%]" } } From 1c3b5b5ac3d4af4e8f1d29a466988962d0b44c8a Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 8 Oct 2026 11:57:29 +0200 Subject: [PATCH 208/356] Send a result for the ZHA reconfigure websocket subscription (#184812) --- homeassistant/components/zha/websocket_api.py | 1 + tests/components/zha/test_websocket_api.py | 8 ++++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/zha/websocket_api.py b/homeassistant/components/zha/websocket_api.py index 5acedbe2c251..fa4f84c4d7c1 100644 --- a/homeassistant/components/zha/websocket_api.py +++ b/homeassistant/components/zha/websocket_api.py @@ -514,6 +514,7 @@ async def websocket_reconfigure_node( remove_dispatcher_function() connection.subscriptions[msg["id"]] = async_cleanup + connection.send_result(msg[ID]) _LOGGER.debug("Re-interview node with ieee_address: %s", ieee) hass.async_create_task(zha_gateway.async_reinterview_device(ieee)) diff --git a/tests/components/zha/test_websocket_api.py b/tests/components/zha/test_websocket_api.py index b9fe88821172..71d9948e467c 100644 --- a/tests/components/zha/test_websocket_api.py +++ b/tests/components/zha/test_websocket_api.py @@ -1280,7 +1280,7 @@ async def test_websocket_reconfigure( messages = [] - while len(messages) != 3: + while len(messages) != 4: msg = await zha_client.receive_json() if msg[ID] == 6: @@ -1289,8 +1289,12 @@ async def test_websocket_reconfigure( # Ensure the gateway re-interview was triggered with the correct IEEE assert reinterview_mock.mock_calls == [call(zha_device_proxy.device.ieee)] + # Ensure the subscription is confirmed, so the frontend can unsubscribe + assert messages[0]["type"] == "result" + assert messages[0]["success"] + # Ensure the frontend receives progress events - assert {m["event"]["type"] for m in messages} == { + assert {m["event"]["type"] for m in messages[1:]} == { "zha_channel_configure_reporting", "zha_channel_bind", "zha_channel_cfg_done", From 2c109064adb77c2920d66b232d2ef91ae193ad98 Mon Sep 17 00:00:00 2001 From: tronikos Date: Thu, 8 Oct 2026 00:15:11 -0700 Subject: [PATCH 209/356] Bump solaredge-web to 0.5.0 (#184821) --- homeassistant/components/solaredge/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/solaredge/manifest.json b/homeassistant/components/solaredge/manifest.json index e1d91c12141e..d1df8c2a2b84 100644 --- a/homeassistant/components/solaredge/manifest.json +++ b/homeassistant/components/solaredge/manifest.json @@ -14,5 +14,5 @@ "integration_type": "device", "iot_class": "cloud_polling", "loggers": ["aiosolaredge", "solaredge_web"], - "requirements": ["aiosolaredge==1.0.2", "solaredge-web==0.4.0"] + "requirements": ["aiosolaredge==1.0.2", "solaredge-web==0.5.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 47eecd51b382..6fa610c38ebf 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3120,7 +3120,7 @@ soco==0.31.2 sofar-modbus==0.17.0 # homeassistant.components.solaredge -solaredge-web==0.4.0 +solaredge-web==0.5.0 # homeassistant.components.solaredge_modbus solaredged==0.5.0 From 8c8df6fc3a1d2f594ec6d9da36bbbe517e4f30ef Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 07:09:22 +0200 Subject: [PATCH 210/356] Keep a missing meter history from blocking Peblar setup (#184824) --- homeassistant/components/peblar/__init__.py | 6 +- homeassistant/components/peblar/event.py | 22 ++++- tests/components/peblar/test_event.py | 91 ++++++++++++++++++++- 3 files changed, 114 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/peblar/__init__.py b/homeassistant/components/peblar/__init__.py index ee4ccf598fd8..cf58e7f7e878 100644 --- a/homeassistant/components/peblar/__init__.py +++ b/homeassistant/components/peblar/__init__.py @@ -92,9 +92,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: PeblarConfigEntry) -> bo meter_coordinator.async_config_entry_first_refresh(), user_configuration_coordinator.async_config_entry_first_refresh(), version_coordinator.async_config_entry_first_refresh(), - authorization_coordinator.async_config_entry_first_refresh(), ) + # Reading back who was shown in is an extra the rest does not depend on, + # and the endpoint it needs is missing on older firmware. Asking for it + # above would take the whole integration down over a single entity. + await authorization_coordinator.async_refresh() + # Store the runtime data entry.runtime_data = PeblarRuntimeData( authorization_coordinator=authorization_coordinator, diff --git a/homeassistant/components/peblar/event.py b/homeassistant/components/peblar/event.py index 6df24dedbd03..692c6d4eb0ae 100644 --- a/homeassistant/components/peblar/event.py +++ b/homeassistant/components/peblar/event.py @@ -58,12 +58,28 @@ class PeblarAuthorizationEventEntity( was watching, and dating it now would put the wrong time on it. """ + _has_bearings: bool = False _session_number: int | None = None @override async def async_added_to_hass(self) -> None: - """Take note of the session already running, without reporting it.""" + """Take note of where the charger is, without reporting it.""" await super().async_added_to_hass() + self._take_bearings() + + @callback + def _take_bearings(self) -> None: + """Note the session the charger is on, and report nothing for it. + + A read that only lands after this entity started says nothing about + when its session began, so the first one to come back is a starting + point rather than news. Reading nothing is different: the charger + answered and had nothing to report, and whatever comes next is new. + """ + if not self.coordinator.last_update_success: + return + + self._has_bearings = True if (authorization := self.coordinator.data) is not None: self._session_number = authorization.session_number @@ -72,7 +88,9 @@ class PeblarAuthorizationEventEntity( def _handle_coordinator_update(self) -> None: """Report a session that was not there the last time we looked.""" authorization = self.coordinator.data - if ( + if not self._has_bearings: + self._take_bearings() + elif ( authorization is not None and authorization.session_number != self._session_number ): diff --git a/tests/components/peblar/test_event.py b/tests/components/peblar/test_event.py index d274afdb1366..f472ea144e78 100644 --- a/tests/components/peblar/test_event.py +++ b/tests/components/peblar/test_event.py @@ -4,11 +4,12 @@ from datetime import timedelta from unittest.mock import MagicMock from freezegun.api import FrozenDateTimeFactory -from peblar import PeblarMeterHistory +from peblar import PeblarError, PeblarMeterHistory import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.const import STATE_UNKNOWN, Platform +from homeassistant.config_entries import ConfigEntryState +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.util import dt as dt_util @@ -204,3 +205,89 @@ async def test_nothing_to_report( async def test_no_reader_no_entity(hass: HomeAssistant) -> None: """Test a charger without a reader shows nobody in.""" assert hass.states.get(ENTITY_ID) is None + + +async def test_a_charger_without_meter_history( + hass: HomeAssistant, + mock_peblar: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test a charger that cannot answer for its meter history still loads. + + Firmware older than the statistics endpoint answers it with a 404. + Reading back who was shown in is one entity, and it must not take the + rest of the integration down with it. The entity says it has nothing + rather than going missing: a read can fail for a moment too, and the + poll that follows is free to put it right. + """ + mock_peblar.meter_history.side_effect = PeblarError("Not Found") + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + state = hass.states.get(ENTITY_ID) + assert state + assert state.state == STATE_UNAVAILABLE + + +async def test_a_read_that_failed_once_recovers( + hass: HomeAssistant, + mock_peblar: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a read that failed at startup is not held against the entity. + + The charger answers three other coordinators right before this one, so + a failure here is usually the endpoint missing. It can just as well be + a moment of bad luck on the heaviest request of the lot, and the next + poll should be allowed to settle it. + + What that poll finds is the session already running, which says nothing + about when it began. It is taken as a starting point rather than + reported, the same as a session already running at startup. + """ + mock_peblar.meter_history.side_effect = PeblarError("Blip") + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + mock_peblar.meter_history.side_effect = None + await _async_poll(hass, freezer) + + assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN + + +async def test_a_new_session_after_a_failed_read_is_reported( + hass: HomeAssistant, + mock_peblar: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test taking bearings does not swallow the sessions that follow. + + The first read back only sets the starting point. A card shown after + that is news like any other. + """ + mock_peblar.meter_history.side_effect = PeblarError("Blip") + mock_config_entry.add_to_hass(hass) + + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_peblar.meter_history.side_effect = None + await _async_poll(hass, freezer) + + mock_peblar.meter_history.return_value = _history(99, "1D0A0B0C0D0E03") + await _async_poll(hass, freezer) + + state = hass.states.get(ENTITY_ID) + assert state + assert state.state != STATE_UNKNOWN + assert state.attributes["session_number"] == 99 + assert state.attributes["token"] == "Frenck" From 0f2d608d9832682afa9aeb0e0c9f03ff4c65f9b9 Mon Sep 17 00:00:00 2001 From: Maciej Bieniek Date: Thu, 8 Oct 2026 10:26:19 +0200 Subject: [PATCH 211/356] Fix `KeyError` in the Airly integration when the API payload contain no sensor data (#184828) --- homeassistant/components/airly/sensor.py | 43 ++++----- tests/components/airly/test_sensor.py | 111 ++++++++++++++++++++++- 2 files changed, 127 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/airly/sensor.py b/homeassistant/components/airly/sensor.py index 59da86bf6967..88b06a64acc1 100644 --- a/homeassistant/components/airly/sensor.py +++ b/homeassistant/components/airly/sensor.py @@ -61,6 +61,15 @@ class AirlySensorEntityDescription(SensorEntityDescription): attrs: Callable[[dict[str, Any]], dict[str, Any]] = lambda data: {} +def _pollutant_attrs(data: dict[str, Any], pollutant: str) -> dict[str, Any]: + """Return limit and percent attributes for a pollutant.""" + percent = data.get(f"{pollutant}_{SUFFIX_PERCENT}") + return { + ATTR_LIMIT: data.get(f"{pollutant}_{SUFFIX_LIMIT}"), + ATTR_PERCENT: None if percent is None else round(percent), + } + + SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( AirlySensorEntityDescription( key=ATTR_API_CAQI, @@ -86,10 +95,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_PM25}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_PM25}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_PM25), ), AirlySensorEntityDescription( key=ATTR_API_PM10, @@ -97,10 +103,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_PM10}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_PM10}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_PM10), ), AirlySensorEntityDescription( key=ATTR_API_HUMIDITY, @@ -129,10 +132,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_CO}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_CO}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_CO), ), AirlySensorEntityDescription( key=ATTR_API_NO2, @@ -140,10 +140,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_NO2}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_NO2}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_NO2), ), AirlySensorEntityDescription( key=ATTR_API_SO2, @@ -151,10 +148,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_SO2}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_SO2}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_SO2), ), AirlySensorEntityDescription( key=ATTR_API_O3, @@ -162,10 +156,7 @@ SENSOR_TYPES: tuple[AirlySensorEntityDescription, ...] = ( native_unit_of_measurement=UnitOfDensity.MICROGRAMS_PER_CUBIC_METER, state_class=SensorStateClass.MEASUREMENT, suggested_display_precision=0, - attrs=lambda data: { - ATTR_LIMIT: data[f"{ATTR_API_O3}_{SUFFIX_LIMIT}"], - ATTR_PERCENT: round(data[f"{ATTR_API_O3}_{SUFFIX_PERCENT}"]), - }, + attrs=lambda data: _pollutant_attrs(data, ATTR_API_O3), ), ) @@ -186,7 +177,7 @@ async def async_setup_entry( for description in SENSOR_TYPES # When we use the nearest method, we are not sure # which sensors are available - if coordinator.data.get(description.key) + if coordinator.data.get(description.key) is not None ), False, ) @@ -227,7 +218,7 @@ class AirlySensor(CoordinatorEntity[AirlyDataUpdateCoordinator], SensorEntity): @override def _handle_coordinator_update(self) -> None: """Handle updated data from the coordinator.""" - self._attr_native_value = self.coordinator.data[self.entity_description.key] + self._attr_native_value = self.coordinator.data.get(self.entity_description.key) self._attr_extra_state_attributes = self.entity_description.attrs( self.coordinator.data ) diff --git a/tests/components/airly/test_sensor.py b/tests/components/airly/test_sensor.py index c211625dd926..e0a1b4f0a613 100644 --- a/tests/components/airly/test_sensor.py +++ b/tests/components/airly/test_sensor.py @@ -6,6 +6,8 @@ from http import HTTPStatus from unittest.mock import MagicMock, patch from airly.exceptions import AirlyError +from airly.measurements import Measurement +from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion @@ -13,7 +15,12 @@ from homeassistant.components.homeassistant import ( DOMAIN as HOMEASSISTANT_DOMAIN, SERVICE_UPDATE_ENTITY, ) -from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform +from homeassistant.const import ( + ATTR_ENTITY_ID, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + Platform, +) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.setup import async_setup_component @@ -115,3 +122,105 @@ async def test_manual_update_entity( ) assert measurements.update.call_count == call_count + 1 + + +@pytest.mark.parametrize( + ("entity_id", "key", "value"), + [ + ("sensor.home_temperature", "TEMPERATURE", "14.37"), + ("sensor.home_pm2_5", "PM25", "4.37"), + ], +) +async def test_missing_measurement( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_airly_client: MagicMock, + mock_airly_measurements: Measurement, + freezer: FrozenDateTimeFactory, + caplog: pytest.LogCaptureFixture, + entity_id: str, + key: str, + value: str, +) -> None: + """Test the entity state is unknown when the API omits its measurement.""" + await init_integration(hass, mock_config_entry) + + measurements = mock_airly_client.create_measurements_session_point.return_value + measurements.current = Measurement( + { + **mock_airly_measurements, + "values": [ + item + for item in mock_airly_measurements["values"] + if item["name"] != key + ], + } + ) + freezer.tick(timedelta(minutes=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get(entity_id) + assert state + assert state.state == STATE_UNKNOWN + assert "Unexpected error updating listener" not in caplog.text + + measurements.current = mock_airly_measurements + freezer.tick(timedelta(minutes=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get(entity_id) + assert state + assert state.state == value + + +async def test_zero_value_creates_entity( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_airly_client: MagicMock, + mock_airly_measurements: Measurement, +) -> None: + """Test an entity is created for a measurement with a value of zero.""" + measurements = mock_airly_client.create_measurements_session_point.return_value + measurements.current = Measurement( + {**mock_airly_measurements, "values": [{"name": "SO2", "value": 0}]} + ) + + await init_integration(hass, mock_config_entry) + + state = hass.states.get("sensor.home_sulphur_dioxide") + assert state + assert state.state == "0" + + +async def test_missing_standard( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_airly_client: MagicMock, + mock_airly_measurements: Measurement, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the entity keeps its value when the API omits the pollutant standard.""" + await init_integration(hass, mock_config_entry) + + measurements = mock_airly_client.create_measurements_session_point.return_value + measurements.current = Measurement( + { + **mock_airly_measurements, + "standards": [ + item + for item in mock_airly_measurements["standards"] + if item["pollutant"] != "PM25" + ], + } + ) + freezer.tick(timedelta(minutes=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + state = hass.states.get("sensor.home_pm2_5") + assert state + assert state.state == "4.37" + assert state.attributes["limit"] is None + assert state.attributes["percent"] is None From caf1e53f1e1a1758a86d979a09755a1559d91112 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Thu, 8 Oct 2026 17:44:28 +0200 Subject: [PATCH 212/356] Restore unverified TLS for stream sources and add a verify_ssl option (#184877) Co-authored-by: Robert Resch --- homeassistant/components/stream/__init__.py | 13 +++++- tests/components/stream/test_init.py | 52 ++++++++++++++++++++- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/stream/__init__.py b/homeassistant/components/stream/__init__.py index 5c858324c2ee..8999301384ff 100644 --- a/homeassistant/components/stream/__init__.py +++ b/homeassistant/components/stream/__init__.py @@ -28,7 +28,11 @@ from typing import TYPE_CHECKING, Any, Final, cast import probatio from yarl import URL -from homeassistant.const import EVENT_HOMEASSISTANT_STOP, EVENT_LOGGING_CHANGED +from homeassistant.const import ( + CONF_VERIFY_SSL, + EVENT_HOMEASSISTANT_STOP, + EVENT_LOGGING_CHANGED, +) from homeassistant.core import Event, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_validation as cv @@ -150,12 +154,16 @@ def _convert_stream_options( raise HomeAssistantError("Stream integration is not set up.") stream_settings = copy.copy(hass.data[DOMAIN][ATTR_SETTINGS]) - pyav_options: dict[str, str] = {} try: STREAM_OPTIONS_SCHEMA(stream_options) except probatio.Invalid as exc: raise HomeAssistantError(f"Invalid stream options: {exc}") from exc + # FFmpeg 9 verifies TLS peers by default; cameras use self-signed certificates + pyav_options: dict[str, str] = { + "tls_verify": "1" if stream_options.get(CONF_VERIFY_SSL) else "0" + } + if extra_wait_time := stream_options.get(CONF_EXTRA_PART_WAIT_TIME): stream_settings.hls_part_timeout += extra_wait_time if rtsp_transport := stream_options.get(CONF_RTSP_TRANSPORT): @@ -630,5 +638,6 @@ STREAM_OPTIONS_SCHEMA: Final = probatio.Schema( probatio.Optional(CONF_RTSP_TRANSPORT): probatio.In(RTSP_TRANSPORTS), probatio.Optional(CONF_USE_WALLCLOCK_AS_TIMESTAMPS): bool, probatio.Optional(CONF_EXTRA_PART_WAIT_TIME): cv.positive_float, + probatio.Optional(CONF_VERIFY_SSL): bool, } ) diff --git a/tests/components/stream/test_init.py b/tests/components/stream/test_init.py index 28552c87ffad..2ed1b413d248 100644 --- a/tests/components/stream/test_init.py +++ b/tests/components/stream/test_init.py @@ -16,7 +16,7 @@ from homeassistant.components.stream import ( create_stream, ) from homeassistant.components.stream.const import ATTR_PREFER_TCP, DOMAIN -from homeassistant.const import EVENT_LOGGING_CHANGED +from homeassistant.const import CONF_VERIFY_SSL, EVENT_LOGGING_CHANGED from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component @@ -94,6 +94,7 @@ async def test_check_open_stream_params(hass: HomeAssistant) -> None: options = { "rtsp_flags": ATTR_PREFER_TCP, "stimeout": "5000000", + "tls_verify": "0", } open_mock.assert_called_once_with(source, options=options, timeout=SOURCE_TIMEOUT) container_mock.close.assert_called_once() @@ -149,7 +150,7 @@ async def test_try_open_stream_error( [ ( {}, - {"rtsp_flags": "prefer_tcp", "stimeout": "5000000"}, + {"rtsp_flags": "prefer_tcp", "stimeout": "5000000", "tls_verify": "0"}, ), ( {"rtsp_transport": "udp"}, @@ -157,6 +158,7 @@ async def test_try_open_stream_error( "rtsp_flags": "prefer_tcp", "rtsp_transport": "udp", "stimeout": "5000000", + "tls_verify": "0", }, ), ( @@ -164,6 +166,7 @@ async def test_try_open_stream_error( { "rtsp_flags": "prefer_tcp", "stimeout": "5000000", + "tls_verify": "0", "use_wallclock_as_timestamps": "1", }, ), @@ -187,3 +190,48 @@ async def test_convert_stream_options( source, options=expected_pyav_options, timeout=SOURCE_TIMEOUT ) container_mock.close.assert_called_once() + + +@pytest.mark.parametrize( + "source", + [ + pytest.param("rtsps://foobar", id="rtsps"), + pytest.param("https://foobar", id="https"), + # an http source can redirect to https + pytest.param("http://foobar", id="http"), + ], +) +async def test_tls_verify_disabled(hass: HomeAssistant, source: str) -> None: + """Test TLS certificate verification is disabled for non-RTSP sources.""" + await async_setup_component(hass, DOMAIN, {"stream": {}}) + + with patch("av.open") as open_mock: + await async_check_stream_client_error(hass, source) + + open_mock.assert_called_once_with( + source, options={"tls_verify": "0"}, timeout=SOURCE_TIMEOUT + ) + + +@pytest.mark.parametrize( + ("verify_ssl", "tls_verify"), + [ + pytest.param(True, "1", id="enabled"), + pytest.param(False, "0", id="disabled"), + ], +) +async def test_verify_ssl_option( + hass: HomeAssistant, verify_ssl: bool, tls_verify: str +) -> None: + """Test the verify_ssl stream option controls TLS certificate verification.""" + await async_setup_component(hass, DOMAIN, {"stream": {}}) + source = "rtsps://foobar" + + with patch("av.open") as open_mock: + await async_check_stream_client_error( + hass, source, {CONF_VERIFY_SSL: verify_ssl} + ) + + open_mock.assert_called_once_with( + source, options={"tls_verify": tls_verify}, timeout=SOURCE_TIMEOUT + ) From 54a2ffda7ad28f72286744b9b34a1ecfe643686e Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Thu, 8 Oct 2026 13:35:27 +0200 Subject: [PATCH 213/356] Fix FRITZ!SmartHome SSDP discovery with hostname presentation URL (#184896) Co-authored-by: Claude Opus 5.5 --- .../components/fritzbox/config_flow.py | 36 ++++++++++-------- tests/components/fritzbox/test_config_flow.py | 37 +++++++++++++++++++ 2 files changed, 58 insertions(+), 15 deletions(-) diff --git a/homeassistant/components/fritzbox/config_flow.py b/homeassistant/components/fritzbox/config_flow.py index 4f545bce03f8..f20f8febedc9 100644 --- a/homeassistant/components/fritzbox/config_flow.py +++ b/homeassistant/components/fritzbox/config_flow.py @@ -2,7 +2,7 @@ from collections.abc import Mapping import ipaddress -from typing import TYPE_CHECKING, Any, Self, override +from typing import Any, Self, override import probatio from pyfritzhome import Fritzhome, LoginError @@ -60,6 +60,15 @@ RESULT_NOT_SUPPORTED = "not_supported" RESULT_SUCCESS = "success" +def _is_ipv6_link_local(host: str) -> bool: + """Return True if host is an IPv6 link-local address.""" + try: + ip = ipaddress.ip_address(host) + except ValueError: + return False + return ip.version == 6 and ip.is_link_local + + class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): """Handle a AVM FRITZ!SmartHome config flow.""" @@ -157,22 +166,19 @@ class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): self, discovery_info: SsdpServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by discovery.""" - if upnp_repr_udl := discovery_info.upnp.get(ATTR_UPNP_PRESENTATION_URL): - self._url = upnp_repr_udl + assert isinstance(discovery_info.ssdp_location, str) + host = URL(discovery_info.ssdp_location).host + assert isinstance(host, str) + + # presentationURL may be relative according to the UPnP spec + presentation_url = discovery_info.upnp.get(ATTR_UPNP_PRESENTATION_URL) + if presentation_url and (presentation_host := URL(presentation_url).host): + self._url = presentation_url else: - assert isinstance(discovery_info.ssdp_location, str) - host = URL(discovery_info.ssdp_location).host - assert isinstance(host, str) - self._url = f"http://{host}" - representation_url = URL(self._url) + presentation_host = host + self._url = str(URL.build(scheme="http", host=host)) - if TYPE_CHECKING: - assert isinstance(representation_url.host, str) - - if ( - ipaddress.ip_address(representation_url.host).version == 6 - and ipaddress.ip_address(representation_url.host).is_link_local - ): + if _is_ipv6_link_local(host) or _is_ipv6_link_local(presentation_host): return self.async_abort(reason="ignore_ip6_link_local") if uuid := discovery_info.upnp.get(ATTR_UPNP_UDN): diff --git a/tests/components/fritzbox/test_config_flow.py b/tests/components/fritzbox/test_config_flow.py index 7703fc5c477a..6b70a0724670 100644 --- a/tests/components/fritzbox/test_config_flow.py +++ b/tests/components/fritzbox/test_config_flow.py @@ -68,6 +68,36 @@ MOCK_SSDP_DATA = { ATTR_UPNP_PRESENTATION_URL: "http://[1234::1]", }, ), + "ip4_hostname": SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location="http://10.0.0.1:49000/fboxdesc.xml", + upnp={ + ATTR_UPNP_FRIENDLY_NAME: CONF_FAKE_NAME, + ATTR_UPNP_UDN: "uuid:only-a-test", + ATTR_UPNP_PRESENTATION_URL: "http://fritz.repeater", + }, + ), + "ip4_relative_presentation_url": SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location="http://10.0.0.1:49000/fboxdesc.xml", + upnp={ + ATTR_UPNP_FRIENDLY_NAME: CONF_FAKE_NAME, + ATTR_UPNP_UDN: "uuid:only-a-test", + ATTR_UPNP_PRESENTATION_URL: "/", + }, + ), + "ip6_invalid_hostname": SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location="http://[fe80::1%1]:49000/fboxdesc.xml", + upnp={ + ATTR_UPNP_FRIENDLY_NAME: CONF_FAKE_NAME, + ATTR_UPNP_UDN: "uuid:only-a-test", + ATTR_UPNP_PRESENTATION_URL: "http://fritz.repeater", + }, + ), "ip6_invalid": SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", @@ -332,8 +362,15 @@ async def test_reconfigure_failed(hass: HomeAssistant, fritz: Mock) -> None: [ (MOCK_SSDP_DATA["ip4_valid"], "http://10.0.0.1", FlowResultType.FORM), (MOCK_SSDP_DATA["ip4_ssdp_fallback"], "http://10.0.0.1", FlowResultType.FORM), + (MOCK_SSDP_DATA["ip4_hostname"], "http://fritz.repeater", FlowResultType.FORM), + ( + MOCK_SSDP_DATA["ip4_relative_presentation_url"], + "http://10.0.0.1", + FlowResultType.FORM, + ), (MOCK_SSDP_DATA["ip6_valid"], "http://[1234::1]", FlowResultType.FORM), (MOCK_SSDP_DATA["ip6_invalid"], None, FlowResultType.ABORT), + (MOCK_SSDP_DATA["ip6_invalid_hostname"], None, FlowResultType.ABORT), ], ) async def test_ssdp( From 8fa174989cb0c26d02276337c7cdf1519f48032b Mon Sep 17 00:00:00 2001 From: Thomas <10558666+mosandlt@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:08:29 +0200 Subject: [PATCH 214/356] Only create Bosch SHC child lock switch when ChildProtection exists (#184908) Co-authored-by: Claude Sonnet 5.5 --- homeassistant/components/bosch_shc/switch.py | 1 + tests/components/bosch_shc/conftest.py | 4 ++++ tests/components/bosch_shc/test_switch.py | 23 ++++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/homeassistant/components/bosch_shc/switch.py b/homeassistant/components/bosch_shc/switch.py index c59e13dbdf29..5d6392ba15ff 100644 --- a/homeassistant/components/bosch_shc/switch.py +++ b/homeassistant/components/bosch_shc/switch.py @@ -405,6 +405,7 @@ async def async_setup_entry( *session.device_helper.micromodule_dimmers, *session.device_helper.light_switches_bsm, ) + if "ChildProtection" in switch.device_service_ids ) presence_simulation_system = session.device_helper.presence_simulation_system diff --git a/tests/components/bosch_shc/conftest.py b/tests/components/bosch_shc/conftest.py index c2d5771f49fc..ebd804ded5a2 100644 --- a/tests/components/bosch_shc/conftest.py +++ b/tests/components/bosch_shc/conftest.py @@ -392,6 +392,7 @@ def micromodule_relay_device( device_id: str = "hdm:ZigBee:relay1", name: str = "Relay", child_lock: bool = False, + has_child_protection: bool = True, supports_switch_configuration: bool = False, swap_inputs: bool = False, swap_outputs: bool = False, @@ -410,6 +411,7 @@ def micromodule_relay_device( device.deleted = False device.status = "AVAILABLE" device.child_lock = child_lock + device.device_service_ids = {"ChildProtection"} if has_child_protection else set() device.supports_switch_configuration = supports_switch_configuration device.swap_inputs = swap_inputs device.swap_outputs = swap_outputs @@ -426,6 +428,7 @@ def light_switch_bsm_device( device_id: str = "hdm:ZigBee:lightswitch1", name: str = "Light switch", child_lock: bool = False, + has_child_protection: bool = True, ) -> SHCLightSwitchBSM: """Build a minimal device double for the light_switches_bsm bucket. @@ -444,6 +447,7 @@ def light_switch_bsm_device( device.status = "AVAILABLE" device.switchstate = PowerSwitchService.State.OFF device.child_lock = child_lock + device.device_service_ids = {"ChildProtection"} if has_child_protection else set() return device diff --git a/tests/components/bosch_shc/test_switch.py b/tests/components/bosch_shc/test_switch.py index c9facef23119..7464ca24a1a7 100644 --- a/tests/components/bosch_shc/test_switch.py +++ b/tests/components/bosch_shc/test_switch.py @@ -198,6 +198,29 @@ async def test_light_switch_bsm_child_lock_unique_id( assert lightswitch_entry.unique_id != child_lock_entry.unique_id +@pytest.mark.parametrize( + "device_buckets", + [ + { + "light_switches_bsm": [ + light_switch_bsm_device(child_lock=False, has_child_protection=False) + ] + } + ], + indirect=True, +) +@pytest.mark.usefixtures("mock_session") +async def test_no_child_lock_without_child_protection_service( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """No child-lock switch is created for a device lacking ChildProtection.""" + await setup_integration(hass, mock_config_entry) + + assert hass.states.get("switch.light_switch") is not None + assert hass.states.get("switch.light_switch_child_lock") is None + + @pytest.mark.parametrize( "device_buckets", [{"presence_simulation_system": presence_simulation_system_device(enabled=False)}], From d1b1da87aa233e3c303c5a1b83c2a676dc7f3f2a Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:57:44 +0200 Subject: [PATCH 215/356] Skip TLS verification for UniFi Protect RTSPS streams (#184930) Co-authored-by: Robert Resch --- homeassistant/components/unifiprotect/camera.py | 3 +++ tests/components/unifiprotect/test_camera.py | 11 ++++++++++- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/unifiprotect/camera.py b/homeassistant/components/unifiprotect/camera.py index eb657ec601bd..b0a8226e6d1d 100644 --- a/homeassistant/components/unifiprotect/camera.py +++ b/homeassistant/components/unifiprotect/camera.py @@ -17,6 +17,7 @@ from uiprotect.data import ( from uiprotect.data.public_devices import PublicCamera from homeassistant.components.camera import Camera, CameraEntityFeature +from homeassistant.const import CONF_VERIFY_SSL from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_platform, issue_registry as ir @@ -271,6 +272,8 @@ class ProtectCamera(ProtectDeviceEntity, Camera): self._attr_name = get_camera_base_name(quality) # only the default (first active) quality channel is enabled by default self._attr_entity_registry_enabled_default = is_default + # RTSPS uses a self-signed certificate on the console IP + self.stream_options[CONF_VERIFY_SSL] = False # Set the stream source before finishing the init # because async_added_to_hass is too late and camera # integration uses async_internal_added_to_hass to access diff --git a/tests/components/unifiprotect/test_camera.py b/tests/components/unifiprotect/test_camera.py index d52561aaa2b2..9070d324fb08 100644 --- a/tests/components/unifiprotect/test_camera.py +++ b/tests/components/unifiprotect/test_camera.py @@ -22,11 +22,17 @@ from homeassistant.components.camera import ( CameraEntityFeature, async_get_image, async_get_stream_source, + get_camera_from_entity_id, ) from homeassistant.components.unifiprotect.const import CONF_DISABLE_RTSP, DOMAIN from homeassistant.components.unifiprotect.utils import get_camera_base_name from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState -from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform +from homeassistant.const import ( + ATTR_ENTITY_ID, + CONF_VERIFY_SSL, + STATE_UNAVAILABLE, + Platform, +) from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import ( @@ -93,6 +99,9 @@ async def test_basic_setup( await async_get_stream_source(hass, high_id) == camera_all.channels[0].rtsps_no_srtp_url ) + assert get_camera_from_entity_id(hass, high_id).stream_options == { + CONF_VERIFY_SSL: False + } # medium starts disabled; once enabled it streams from the public API medium_id = _assert_entity(hass, camera_all, 1, enabled=False) From c87a26bad628ba8df5971e48520ddd8a79b52283 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Fri, 9 Oct 2026 07:10:44 +0200 Subject: [PATCH 216/356] Return same images as you see on the immich server, even the edited ones (#184955) Co-authored-by: Copilot --- homeassistant/components/immich/manifest.json | 2 +- homeassistant/components/immich/media_source.py | 4 +++- requirements_all.txt | 2 +- tests/components/immich/test_media_source.py | 3 +++ 4 files changed, 8 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/immich/manifest.json b/homeassistant/components/immich/manifest.json index 457580168624..5a4db13fefbb 100644 --- a/homeassistant/components/immich/manifest.json +++ b/homeassistant/components/immich/manifest.json @@ -9,5 +9,5 @@ "iot_class": "local_polling", "loggers": ["aioimmich"], "quality_scale": "platinum", - "requirements": ["aioimmich==0.17.0"] + "requirements": ["aioimmich==0.18.0"] } diff --git a/homeassistant/components/immich/media_source.py b/homeassistant/components/immich/media_source.py index 506ef41cf2d6..0c1f22b91d13 100644 --- a/homeassistant/components/immich/media_source.py +++ b/homeassistant/components/immich/media_source.py @@ -527,7 +527,9 @@ class ImmichMediaView(HomeAssistantView): if size == "person": image = await immich_api.people.async_get_person_thumbnail(asset_id) else: - image = await immich_api.assets.async_view_asset(asset_id, size) + image = await immich_api.assets.async_view_asset( + asset_id, size, edited=True + ) except ImmichError as exc: raise HTTPNotFound from exc return Response(body=image, content_type=f"{mime_type_base}/{mime_type_format}") diff --git a/requirements_all.txt b/requirements_all.txt index 6fa610c38ebf..de643d75aff4 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -309,7 +309,7 @@ aiohue==4.9.0 aioimaplib==2.0.1 # homeassistant.components.immich -aioimmich==0.17.0 +aioimmich==0.18.0 # homeassistant.components.indi_allsky aioindiallsky==0.1.3 diff --git a/tests/components/immich/test_media_source.py b/tests/components/immich/test_media_source.py index 6107e826c349..7735c2db67b1 100644 --- a/tests/components/immich/test_media_source.py +++ b/tests/components/immich/test_media_source.py @@ -640,6 +640,9 @@ async def test_media_view( "2e94c203-50aa-4ad2-8e29-56dd74e0eff4/thumbnail/image/jpeg", ) assert isinstance(result, web.Response) + mock_immich.assets.async_view_asset.assert_awaited_with( + "2e94c203-50aa-4ad2-8e29-56dd74e0eff4", "thumbnail", edited=True + ) with patch.object(tempfile, "tempdir", tmp_path): result = await view.get( request, From 3a0121eabed5c917f13ff825434d9c5be19e6114 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:09:32 +0200 Subject: [PATCH 217/356] Don't report 0 for missing FRITZ!SmartHome powermeter values (#184968) Co-authored-by: Claude --- homeassistant/components/fritzbox/sensor.py | 36 ++++++++++++++++--- tests/components/fritzbox/test_sensor.py | 40 +++++++++++++++++++++ 2 files changed, 72 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/fritzbox/sensor.py b/homeassistant/components/fritzbox/sensor.py index abae490d7f07..191bbbeb139e 100644 --- a/homeassistant/components/fritzbox/sensor.py +++ b/homeassistant/components/fritzbox/sensor.py @@ -110,6 +110,34 @@ def value_nextchange_time(device: FritzhomeDevice) -> datetime | None: return None +def value_power(device: FritzhomeDevice) -> float | None: + """Return native value for power consumption sensor.""" + if not isinstance(device.power, int | float): + return None + return round(device.power / 1000, 3) + + +def value_voltage(device: FritzhomeDevice) -> float | None: + """Return native value for voltage sensor.""" + if not isinstance(device.voltage, int | float): + return None + return round(device.voltage / 1000, 2) + + +def value_current(device: FritzhomeDevice) -> float | None: + """Return native value for electric current sensor.""" + if not isinstance(device.current, int | float): + return None + return round(device.current / 1000, 3) + + +def value_total_energy(device: FritzhomeDevice) -> float | None: + """Return native value for total energy sensor.""" + if not isinstance(device.energy, int | float): + return None + return device.energy / 1000 + + SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = ( FritzSensorEntityDescription( key="temperature", @@ -143,7 +171,7 @@ SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = ( device_class=SensorDeviceClass.POWER, state_class=SensorStateClass.MEASUREMENT, suitable=lambda device: device.has_powermeter, - native_value=lambda device: round((device.power or 0.0) / 1000, 3), + native_value=value_power, ), FritzSensorEntityDescription( key="voltage", @@ -151,7 +179,7 @@ SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = ( device_class=SensorDeviceClass.VOLTAGE, state_class=SensorStateClass.MEASUREMENT, suitable=lambda device: device.has_powermeter, - native_value=lambda device: round((device.voltage or 0.0) / 1000, 2), + native_value=value_voltage, ), FritzSensorEntityDescription( key="electric_current", @@ -159,7 +187,7 @@ SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = ( device_class=SensorDeviceClass.CURRENT, state_class=SensorStateClass.MEASUREMENT, suitable=lambda device: device.has_powermeter, - native_value=lambda device: round((device.current or 0.0) / 1000, 3), + native_value=value_current, ), FritzSensorEntityDescription( key="total_energy", @@ -167,7 +195,7 @@ SENSOR_TYPES: Final[tuple[FritzSensorEntityDescription, ...]] = ( device_class=SensorDeviceClass.ENERGY, state_class=SensorStateClass.TOTAL_INCREASING, suitable=lambda device: device.has_powermeter, - native_value=lambda device: (device.energy or 0.0) / 1000, + native_value=value_total_energy, ), # Thermostat Sensors FritzSensorEntityDescription( diff --git a/tests/components/fritzbox/test_sensor.py b/tests/components/fritzbox/test_sensor.py index 067d733118c0..92390a510988 100644 --- a/tests/components/fritzbox/test_sensor.py +++ b/tests/components/fritzbox/test_sensor.py @@ -171,3 +171,43 @@ async def test_next_change_sensors( state = hass.states.get(f"{base_name}_current_scheduled_preset") assert state assert state.state == expected_states[3] + + +@pytest.mark.parametrize( + ("attribute", "value", "entity_id", "expected_state"), + [ + pytest.param( + "power", None, f"{ENTITY_ID}_power", STATE_UNKNOWN, id="power_missing" + ), + pytest.param("power", 0, f"{ENTITY_ID}_power", "0.0", id="power_zero"), + pytest.param( + "voltage", None, f"{ENTITY_ID}_voltage", STATE_UNKNOWN, id="voltage_missing" + ), + pytest.param( + "current", None, f"{ENTITY_ID}_current", STATE_UNKNOWN, id="current_missing" + ), + pytest.param( + "energy", None, f"{ENTITY_ID}_energy", STATE_UNKNOWN, id="energy_missing" + ), + pytest.param("energy", 0, f"{ENTITY_ID}_energy", "0.0", id="energy_zero"), + ], +) +async def test_powermeter_missing_values( + hass: HomeAssistant, + fritz: Mock, + attribute: str, + value: int | None, + entity_id: str, + expected_state: str, +) -> None: + """Test powermeter sensors do not report 0 for missing values.""" + device = FritzDeviceSwitchMock() + setattr(device, attribute, value) + + await setup_config_entry( + hass, MOCK_CONFIG[DOMAIN][CONF_DEVICES][0], ENTITY_ID, device, fritz + ) + + state = hass.states.get(entity_id) + assert state + assert state.state == expected_state From ae86a06f8ededddb32c0b7497b4d0ebca80761dd Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Thu, 8 Oct 2026 21:54:31 +0200 Subject: [PATCH 218/356] Reload Immich integration when the server version changes (#184978) Co-authored-by: Claude Opus 5.5 --- .../components/immich/coordinator.py | 12 +++++ tests/components/immich/test_init.py | 47 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 tests/components/immich/test_init.py diff --git a/homeassistant/components/immich/coordinator.py b/homeassistant/components/immich/coordinator.py index 265fe0d21c4a..0c77af815396 100644 --- a/homeassistant/components/immich/coordinator.py +++ b/homeassistant/components/immich/coordinator.py @@ -126,6 +126,18 @@ class ImmichDataUpdateCoordinator(DataUpdateCoordinator[ImmichData]): translation_placeholders={"error": str(err)}, ) from err + if ( + self.data is not None + and self.data.server_about.version != server_about.version + ): + # The API client adapts to the server version during setup + _LOGGER.info( + "Immich server version changed from %s to %s, reloading integration", + self.data.server_about.version, + server_about.version, + ) + self.hass.config_entries.async_schedule_reload(self.config_entry.entry_id) + return ImmichData( server_about, server_storage, server_usage, server_version_check ) diff --git a/tests/components/immich/test_init.py b/tests/components/immich/test_init.py new file mode 100644 index 000000000000..7c6bc9ee5457 --- /dev/null +++ b/tests/components/immich/test_init.py @@ -0,0 +1,47 @@ +"""Test the Immich integration setup.""" + +from dataclasses import replace +from datetime import timedelta +from unittest.mock import Mock + +from freezegun.api import FrozenDateTimeFactory +import pytest + +from homeassistant.config_entries import ConfigEntryState +from homeassistant.core import HomeAssistant + +from . import setup_integration + +from tests.common import MockConfigEntry, async_fire_time_changed + + +@pytest.mark.parametrize( + ("new_version", "setup_calls"), + [ + pytest.param("v1.134.0", 1, id="unchanged"), + pytest.param("v3.1.0", 2, id="changed"), + ], +) +async def test_reload_on_server_version_change( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_immich: Mock, + mock_config_entry: MockConfigEntry, + new_version: str, + setup_calls: int, +) -> None: + """Test the integration reloads only when the server version changes.""" + await setup_integration(hass, mock_config_entry) + assert mock_immich.async_setup.call_count == 1 + + server_about = mock_immich.server.async_get_about_info.return_value + mock_immich.server.async_get_about_info.return_value = replace( + server_about, version=new_version + ) + + freezer.tick(timedelta(seconds=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert mock_immich.async_setup.call_count == setup_calls From 1aba15b81fe87328cf821e393dd8c9e1d3704cc1 Mon Sep 17 00:00:00 2001 From: Thomas55555 <59625598+Thomas55555@users.noreply.github.com> Date: Fri, 9 Oct 2026 09:08:14 +0200 Subject: [PATCH 219/356] Set state to unknown in Husqvarna Automower error sensor, when error is unknown (#185087) --- .../components/husqvarna_automower/sensor.py | 15 +++++++++++++-- .../snapshots/test_sensor.ambr | 4 ++++ .../components/husqvarna_automower/test_sensor.py | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/husqvarna_automower/sensor.py b/homeassistant/components/husqvarna_automower/sensor.py index 8371fd669e56..a806063494a4 100644 --- a/homeassistant/components/husqvarna_automower/sensor.py +++ b/homeassistant/components/husqvarna_automower/sensor.py @@ -16,6 +16,7 @@ from aioautomower.model import ( WorkArea, WorkAreaType, ) +from aioautomower.model.model_mower import UNKNOWN_ERROR from homeassistant.components.sensor import ( SensorDeviceClass, @@ -23,7 +24,13 @@ from homeassistant.components.sensor import ( SensorEntityDescription, SensorStateClass, ) -from homeassistant.const import PERCENTAGE, EntityCategory, UnitOfLength, UnitOfTime +from homeassistant.const import ( + PERCENTAGE, + STATE_UNKNOWN, + EntityCategory, + UnitOfLength, + UnitOfTime, +) from homeassistant.core import HomeAssistant, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType @@ -44,7 +51,9 @@ PARALLEL_UPDATES = 0 ATTR_WORK_AREA_ID_ASSIGNMENT = "work_area_id_assignment" ERROR_KEY_LIST = sorted( - set(ERROR_KEYS) | {state.lower() for state in ERROR_STATES} | {"no_error"} + set(ERROR_KEYS) + | {state.lower() for state in ERROR_STATES} + | {"no_error", STATE_UNKNOWN} ) INACTIVE_REASONS: list = [ @@ -135,6 +144,8 @@ def _get_current_work_area_dict(data: MowerAttributes) -> Mapping[str, Any]: @callback def _get_error_string(data: MowerAttributes) -> str: """Return the error key, if not provided the mower state or `no error`.""" + if data.mower.error_key == UNKNOWN_ERROR: + return STATE_UNKNOWN if data.mower.error_key is not None: return data.mower.error_key if data.mower.state in ERROR_STATES: diff --git a/tests/components/husqvarna_automower/snapshots/test_sensor.ambr b/tests/components/husqvarna_automower/snapshots/test_sensor.ambr index 4794fc646fcc..10022a734804 100644 --- a/tests/components/husqvarna_automower/snapshots/test_sensor.ambr +++ b/tests/components/husqvarna_automower/snapshots/test_sensor.ambr @@ -321,6 +321,7 @@ 'ultrasonic_sensor_4_defect', 'unexpected_cutting_height_adj', 'unexpected_error', + 'unknown', 'upside_down', 'vision_system_error', 'vision_system_malfunction', @@ -522,6 +523,7 @@ 'ultrasonic_sensor_4_defect', 'unexpected_cutting_height_adj', 'unexpected_error', + 'unknown', 'upside_down', 'vision_system_error', 'vision_system_malfunction', @@ -1848,6 +1850,7 @@ 'ultrasonic_sensor_4_defect', 'unexpected_cutting_height_adj', 'unexpected_error', + 'unknown', 'upside_down', 'vision_system_error', 'vision_system_malfunction', @@ -2049,6 +2052,7 @@ 'ultrasonic_sensor_4_defect', 'unexpected_cutting_height_adj', 'unexpected_error', + 'unknown', 'upside_down', 'vision_system_error', 'vision_system_malfunction', diff --git a/tests/components/husqvarna_automower/test_sensor.py b/tests/components/husqvarna_automower/test_sensor.py index 80c5f75b298c..79e8c288a9f0 100644 --- a/tests/components/husqvarna_automower/test_sensor.py +++ b/tests/components/husqvarna_automower/test_sensor.py @@ -13,6 +13,7 @@ from aioautomower.model import ( WorkArea, WorkAreaType, ) +from aioautomower.model.model_mower import UNKNOWN_ERROR from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion @@ -290,6 +291,7 @@ async def test_error_sensor( (MowerStates.ERROR, None, MowerStates.ERROR.lower()), (MowerStates.ERROR_AT_POWER_UP, None, MowerStates.ERROR_AT_POWER_UP.lower()), (MowerStates.FATAL_ERROR, None, MowerStates.FATAL_ERROR.lower()), + (MowerStates.ERROR, UNKNOWN_ERROR, STATE_UNKNOWN), ): values[TEST_MOWER_ID].mower.state = state values[TEST_MOWER_ID].mower.error_key = error_key @@ -298,6 +300,7 @@ async def test_error_sensor( async_fire_time_changed(hass) await hass.async_block_till_done() state = hass.states.get("sensor.garden_test_mower_1_error") + assert state is not None assert state.state == expected_state From 98ea78d3e2cf0e00e340cc8e7bbeafd050496dbd Mon Sep 17 00:00:00 2001 From: Marcus Ahlberg Date: Fri, 9 Oct 2026 17:08:31 +0200 Subject: [PATCH 220/356] Seed deCONZ group color modes from unreachable lights too (#185117) --- homeassistant/components/deconz/light.py | 3 +- tests/components/deconz/test_light.py | 54 ++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/deconz/light.py b/homeassistant/components/deconz/light.py index 6092f7ec95ae..e9c3ac3a6e53 100644 --- a/homeassistant/components/deconz/light.py +++ b/homeassistant/components/deconz/light.py @@ -173,8 +173,9 @@ async def async_setup_entry( lights = [ light for light_id in group.lights - if (light := hub.api.lights.lights.get(light_id)) and light.reachable + if (light := hub.api.lights.lights.get(light_id)) ] + lights.sort(key=lambda light: light.reachable) update_color_state(group, lights, True) async_add_entities([DeconzGroup(group, hub)]) diff --git a/tests/components/deconz/test_light.py b/tests/components/deconz/test_light.py index e7935ebff930..9bac39770349 100644 --- a/tests/components/deconz/test_light.py +++ b/tests/components/deconz/test_light.py @@ -1302,3 +1302,57 @@ async def test_verify_group_color_mode_fallback( group_state = hass.states.get("light.opbergruimte") assert group_state.state == STATE_ON assert group_state.attributes[ATTR_COLOR_MODE] is ColorMode.BRIGHTNESS + + +@pytest.mark.parametrize( + "group_payload", + [ + { + "1": { + "id": "Group1", + "name": "Group", + "type": "LightGroup", + "state": {"all_on": False, "any_on": True}, + "action": {}, + "scenes": [], + "lights": ["1", "2"], + }, + } + ], +) +@pytest.mark.parametrize( + "light_payload", + [ + { + "1": { + "ctmax": 454, + "ctmin": 155, + "name": "Tunable light", + "state": { + "on": True, + "bri": 100, + "colormode": "ct", + "ct": 2500, + "reachable": False, + }, + "type": "Color temperature light", + "uniqueid": "00:00:00:00:00:00:00:01-00", + }, + "2": { + "name": "Dimmable light", + "state": {"on": True, "bri": 255, "reachable": True}, + "type": "Dimmable light", + "uniqueid": "00:00:00:00:00:00:00:02-00", + }, + } + ], +) +@pytest.mark.usefixtures("config_entry_setup") +async def test_group_color_modes_include_unreachable_lights( + hass: HomeAssistant, +) -> None: + """Test that a light unreachable during setup still contributes its color modes.""" + group_state = hass.states.get("light.group") + assert group_state.attributes[ATTR_SUPPORTED_COLOR_MODES] == [ColorMode.COLOR_TEMP] + assert group_state.attributes[ATTR_COLOR_MODE] == ColorMode.COLOR_TEMP + assert group_state.attributes[ATTR_BRIGHTNESS] == 255 From 2d066142cf2ad971f3b43ad0e9a4eea4203c9239 Mon Sep 17 00:00:00 2001 From: TheJulianJES Date: Fri, 9 Oct 2026 07:09:53 +0200 Subject: [PATCH 221/356] Bump ZHA to 2.3.1 (#185156) --- homeassistant/components/zha/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/zha/manifest.json b/homeassistant/components/zha/manifest.json index 09500c594ea0..83ac5c29036c 100644 --- a/homeassistant/components/zha/manifest.json +++ b/homeassistant/components/zha/manifest.json @@ -23,7 +23,7 @@ "universal_silabs_flasher", "serialx" ], - "requirements": ["zha==2.3.0", "zha-quirks==2.3.0"], + "requirements": ["zha==2.3.1", "zha-quirks==2.3.0"], "usb": [ { "description": "*2652*", diff --git a/requirements_all.txt b/requirements_all.txt index de643d75aff4..51a1aafd70f9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3538,7 +3538,7 @@ zeversolar==0.3.2 zha-quirks==2.3.0 # homeassistant.components.zha -zha==2.3.0 +zha==2.3.1 # homeassistant.components.zhong_hong zhong-hong-hvac==1.0.21 From 4fe3fbd2f6a4fb93e75d152667187a23e0f3f4ee Mon Sep 17 00:00:00 2001 From: Kevin-Tamayose <125572668+Kevin-Tamayose@users.noreply.github.com> Date: Fri, 9 Oct 2026 03:40:08 -0300 Subject: [PATCH 222/356] Fix storing traces for automations without an ID (#185161) --- homeassistant/components/automation/trace.py | 3 +- tests/components/trace/test_websocket_api.py | 31 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/automation/trace.py b/homeassistant/components/automation/trace.py index c440624b7f68..8e42028047fe 100644 --- a/homeassistant/components/automation/trace.py +++ b/homeassistant/components/automation/trace.py @@ -64,7 +64,8 @@ def trace_automation( trace = AutomationTrace( automation_id, config, blueprint_inputs, context, not_triggered=not_triggered ) - async_store_trace(hass, trace, trace_config[CONF_STORED_TRACES]) + if automation_id: + async_store_trace(hass, trace, trace_config[CONF_STORED_TRACES]) try: yield trace diff --git a/tests/components/trace/test_websocket_api.py b/tests/components/trace/test_websocket_api.py index a39110b016ac..de2c9f72f5ed 100644 --- a/tests/components/trace/test_websocket_api.py +++ b/tests/components/trace/test_websocket_api.py @@ -1665,6 +1665,37 @@ async def test_trace_blueprint_automation( assert trace.get("trigger", UNDEFINED) == "event 'blueprint_event'" +async def test_automation_without_id_does_not_store_trace( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, +) -> None: + """Automations without an id do not create an invalid trace.""" + await _setup_automation_or_script( + hass, + "automation", + [ + { + "triggers": { + "platform": "event", + "event_type": "test_event", + }, + "actions": {"event": "automation_ran"}, + } + ], + ) + + hass.bus.async_fire("test_event") + await hass.async_block_till_done() + + client = await hass_ws_client() + await client.send_json({"id": 1, "type": "trace/list", "domain": "automation"}) + response = await client.receive_json() + + assert response["success"] + assert response["result"] == [] + assert "automation.None" not in hass.data[DATA_TRACE] + + class _DiagnosticActionTrace(ActionTrace): """Automation-domain trace used to exercise not-triggered serialization.""" From c09fe1db115f7a6fb8146aea4f97b9c6ae52b64b Mon Sep 17 00:00:00 2001 From: tronikos Date: Fri, 9 Oct 2026 06:09:04 -0700 Subject: [PATCH 223/356] Tag TTS audio carrying an empty ID3 tag (#185193) --- homeassistant/components/tts/__init__.py | 4 +++- tests/components/tts/test_init.py | 23 +++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/tts/__init__.py b/homeassistant/components/tts/__init__.py index 4dff1e456f0f..3013715cd391 100644 --- a/homeassistant/components/tts/__init__.py +++ b/homeassistant/components/tts/__init__.py @@ -1211,7 +1211,9 @@ class SpeechManager: try: tts_file = mutagen.File(data_bytes) if tts_file is not None: - if not tts_file.tags: + # An ID3 tag with no frames is falsy but present, and adding + # another one raises. + if tts_file.tags is None: tts_file.add_tags() tts_file.tags.add(TPE1(encoding=Encoding.UTF8, text=artist)) # type: ignore[no-untyped-call] tts_file.tags.add(TALB(encoding=Encoding.UTF8, text=album)) # type: ignore[no-untyped-call] diff --git a/tests/components/tts/test_init.py b/tests/components/tts/test_init.py index 32f665268bb5..b82d3f02b5c7 100644 --- a/tests/components/tts/test_init.py +++ b/tests/components/tts/test_init.py @@ -2440,6 +2440,29 @@ def test_write_tags_adds_tag_to_untagged_audio() -> None: assert tags["TIT2"].text == ["There is someone at the door."] +def test_write_tags_fills_empty_id3_tag() -> None: + """Test audio arriving with an ID3 tag holding no frames gets the frames.""" + data = b"ID3\x04\x00\x00\x00\x00\x00\x00" + load_fixture_bytes( + "untagged.mp3", DOMAIN + ) + assert not mutagen.File(io.BytesIO(data)).tags + + tagged = ORIG_WRITE_TAGS( + "42f18378fd4393d18c8dd11d03fa9563c1e54491_en-us_-_test.mp3", + data, + "Test", + "There is someone at the door.", + "en", + None, + ) + + assert tagged.count(b"ID3") == 1 + tags = mutagen.File(io.BytesIO(tagged)).tags + assert tags["TPE1"].text == ["en"] + assert tags["TALB"].text == ["Test"] + assert tags["TIT2"].text == ["There is someone at the door."] + + def test_write_tags_overwrites_id3v1_metadata() -> None: """Test audio arriving with only an ID3v1 trailer gets the frames rewritten.""" data = load_fixture_bytes("id3v1.mp3", DOMAIN) From 7980a686317823f80b544b5a0ff5b00631a8444f Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 12:16:13 +0200 Subject: [PATCH 224/356] Fix Tradfri color bulbs losing HS color mode (#185197) --- homeassistant/components/tradfri/light.py | 15 ++++++---- .../tradfri/fixtures/bulb_cws_color_temp.json | 29 +++++++++++++++++++ tests/components/tradfri/test_light.py | 24 +++++++++++++++ 3 files changed, 63 insertions(+), 5 deletions(-) create mode 100644 tests/components/tradfri/fixtures/bulb_cws_color_temp.json diff --git a/homeassistant/components/tradfri/light.py b/homeassistant/components/tradfri/light.py index f95b7aa75b4c..42a3f530f87b 100644 --- a/homeassistant/components/tradfri/light.py +++ b/homeassistant/components/tradfri/light.py @@ -73,7 +73,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): # Calculate supported color modes modes: set[ColorMode] = {ColorMode.ONOFF} - if self._device_data.supports_hsb_xy_color: + if self._supports_hs_color: modes.add(ColorMode.HS) if self._device_data.supports_color_temp: modes.add(ColorMode.COLOR_TEMP) @@ -90,6 +90,12 @@ class TradfriLight(TradfriBaseEntity, LightEntity): self._device_control.max_mireds ) + @property + def _supports_hs_color(self) -> bool: + """Return if the light supports setting a hue and saturation.""" + # supports_hsb_xy_color is False for color bulbs that also report mireds + return self._device_data.raw.color_hue is not None + @override def _refresh(self) -> None: """Refresh the device.""" @@ -178,7 +184,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): dimmer_command = self._device_control.set_state(True) color_command = None - if ATTR_HS_COLOR in kwargs and self._device_data.supports_hsb_xy_color: + if ATTR_HS_COLOR in kwargs and self._supports_hs_color: hue = int(kwargs[ATTR_HS_COLOR][0] * (self._device_control.max_hue / 360)) sat = int( kwargs[ATTR_HS_COLOR][1] * (self._device_control.max_saturation / 100) @@ -190,8 +196,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): temp_command = None if ATTR_COLOR_TEMP_KELVIN in kwargs and ( - self._device_data.supports_color_temp - or self._device_data.supports_hsb_xy_color + self._device_data.supports_color_temp or self._supports_hs_color ): temp_k = kwargs[ATTR_COLOR_TEMP_KELVIN] # White Spectrum bulb @@ -207,7 +212,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): transition_time = None # Color bulb (CWS) # color_temp needs to be set with hue/saturation - elif self._device_data.supports_hsb_xy_color: + elif self._supports_hs_color: hs_color = color_util.color_temperature_to_hs(temp_k) hue = int(hs_color[0] * (self._device_control.max_hue / 360)) sat = int(hs_color[1] * (self._device_control.max_saturation / 100)) diff --git a/tests/components/tradfri/fixtures/bulb_cws_color_temp.json b/tests/components/tradfri/fixtures/bulb_cws_color_temp.json new file mode 100644 index 000000000000..95faab65f3df --- /dev/null +++ b/tests/components/tradfri/fixtures/bulb_cws_color_temp.json @@ -0,0 +1,29 @@ +{ + "3": { + "0": "IKEA of Sweden", + "1": "TRADFRI bulb GU10 CWS 345lm", + "2": "", + "3": "1.3.002", + "6": 1 + }, + "3311": [ + { + "5706": "f1e0b5", + "5707": 5427, + "5708": 42596, + "5709": 30015, + "5710": 26870, + "5711": 370, + "5850": 1, + "5851": 250, + "9003": 0 + } + ], + "5750": 2, + "9001": "Test CWS color temp", + "9002": 1509924799, + "9003": 65542, + "9019": 1, + "9020": 1510011206, + "9054": 0 +} diff --git a/tests/components/tradfri/test_light.py b/tests/components/tradfri/test_light.py index 43f3b436f5e1..6e7e81f3d1f2 100644 --- a/tests/components/tradfri/test_light.py +++ b/tests/components/tradfri/test_light.py @@ -50,6 +50,12 @@ def bulb_cws() -> str: return load_fixture("bulb_cws.json", DOMAIN) +@pytest.fixture(scope="module") +def bulb_cws_color_temp() -> str: + """Return a color bulb that also reports a color temperature.""" + return load_fixture("bulb_cws_color_temp.json", DOMAIN) + + @pytest.mark.parametrize( ("device", "entity_id", "state_attributes"), [ @@ -84,6 +90,16 @@ def bulb_cws() -> str: ATTR_COLOR_MODE: ColorMode.HS, }, ), + ( + "bulb_cws_color_temp", + "light.test_cws_color_temp", + { + ATTR_BRIGHTNESS: 250, + ATTR_HS_COLOR: (29.812, 65.252), + ATTR_SUPPORTED_COLOR_MODES: [ColorMode.COLOR_TEMP, ColorMode.HS], + ATTR_COLOR_MODE: ColorMode.HS, + }, + ), ], indirect=["device"], ) @@ -190,6 +206,13 @@ async def test_light_available( {"hs_color": [300, 100]}, {"hs_color": [300, 100]}, ), + # hs_color on a color bulb that also reports a color temperature + ( + "bulb_cws_color_temp", + "light.test_cws_color_temp", + {"hs_color": [300, 100]}, + {"hs_color": [300, 100]}, + ), # ct + brightness ( "bulb_ws", @@ -229,6 +252,7 @@ async def test_light_available( "color_temp_kelvin > 4000", "color_temp_kelvin < 2202", "hs_color", + "hs_color (color bulb with color temp)", "ct + brightness", "ct + brightness (no temp support)", "ct + brightness (no temp or color support)", From 167458760e1ab29b0529ee57e050edea2e2854dc Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 10:32:12 +0200 Subject: [PATCH 225/356] Fix false shell template repair for static command_line commands (#185203) --- .../components/command_line/utils.py | 7 +++ tests/components/command_line/test_sensor.py | 48 +++++++++++++++++-- 2 files changed, 52 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/command_line/utils.py b/homeassistant/components/command_line/utils.py index 46186db36cb4..f683791ed959 100644 --- a/homeassistant/components/command_line/utils.py +++ b/homeassistant/components/command_line/utils.py @@ -243,6 +243,13 @@ def render_template_args( prog, args = command.split(" ", 1) args_compiled = Template(args, hass) + if args_compiled.is_static: + # Rendering would still strip a trailing newline (from a YAML block + # scalar), making a plain command look like a substituted template. + issue_id = build_shell_template_issue_id(platform, name) + _update_issue(hass, issue_id, prog, platform, name, create=False) + LOGGER.debug("Running command: %s", command) + return command try: # parse_result=False keeps the output a string; the args are executed as a diff --git a/tests/components/command_line/test_sensor.py b/tests/components/command_line/test_sensor.py index 66a1197e2f0f..e97e8ad66547 100644 --- a/tests/components/command_line/test_sensor.py +++ b/tests/components/command_line/test_sensor.py @@ -1127,6 +1127,40 @@ async def test_template_with_shell_features_uses_shell_and_creates_issue( } +async def test_static_command_with_shell_features_no_issue( + hass: HomeAssistant, + issue_registry: ir.IssueRegistry, +) -> None: + """Commands without a template keep the shell path and create no repair issue.""" + # A folded YAML block scalar (command: >) leaves a trailing newline, + # which rendering would strip. + command = "echo 'ROC temperature 42' | awk '/ROC temperature/ {print $NF}'\n" + await setup.async_setup_component( + hass, + DOMAIN, + {"command_line": [{"sensor": {"name": "Test", "command": command}}]}, + ) + await hass.async_block_till_done() + + with mock_asyncio_subprocess_run(b"42\n") as mock_shell: + async_fire_time_changed( + hass, + dt_util.utcnow() + timedelta(minutes=1), + ) + await hass.async_block_till_done(wait_background_tasks=True) + + mock_shell.assert_called_once_with( + command, + stdin=None, + stdout=-1, + close_fds=False, + ) + assert not any( + issue.translation_key == "shell_command_template_deprecation" + for issue in issue_registry.issues.values() + ) + + async def test_template_shell_feature_issue_cleared_when_metachar_gone( hass: HomeAssistant, issue_registry: ir.IssueRegistry, @@ -1345,18 +1379,26 @@ async def test_template_quoted_executable_uses_exec( ) +@pytest.mark.parametrize( + "edited_command", + [ + pytest.param("echo {{ 'clean' }}", id="template_without_shell_features"), + pytest.param("echo clean | cat", id="no_template"), + ], +) async def test_template_issue_id_stable_across_command_edits( hass: HomeAssistant, issue_registry: ir.IssueRegistry, + edited_command: str, ) -> None: - """Editing the command to remove shell features clears the original issue.""" + """Editing the command to remove templated shell features clears the original issue.""" # A shell feature creates the issue for this entity. render_template_args(hass, "echo {{ 'a|b' }}", "sensor", "Test") assert [iid for (dom, iid) in issue_registry.issues if dom == DOMAIN] - # The same entity with an edited, safe command clears it; a command-derived + # The same entity with an edited command clears it; a command-derived # id would instead leave the original issue behind. - render_template_args(hass, "echo {{ 'clean' }}", "sensor", "Test") + render_template_args(hass, edited_command, "sensor", "Test") assert not [iid for (dom, iid) in issue_registry.issues if dom == DOMAIN] From 1cd7db86f573274cce508d21321165f8fbd7bd7c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 10:22:45 +0200 Subject: [PATCH 226/356] Constrain graphql-core below 3.3 (#185206) --- homeassistant/package_constraints.txt | 5 +++++ script/gen_requirements_all.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index ad9d1fdc3c99..d2beab74e0ad 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -258,6 +258,11 @@ auth0-python<5.0 backoff==2.2.1 python-backoff<2.4.0 +# graphql-core 3.3 removed graphql_input_types, which apischema 0.19.0 +# (used by pydrawise) still imports +# https://github.com/home-assistant/core/issues/184918 +graphql-core<3.3 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained diff --git a/script/gen_requirements_all.py b/script/gen_requirements_all.py index 17f1079840ff..ac259c588e83 100755 --- a/script/gen_requirements_all.py +++ b/script/gen_requirements_all.py @@ -242,6 +242,11 @@ auth0-python<5.0 backoff==2.2.1 python-backoff<2.4.0 +# graphql-core 3.3 removed graphql_input_types, which apischema 0.19.0 +# (used by pydrawise) still imports +# https://github.com/home-assistant/core/issues/184918 +graphql-core<3.3 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained From adacbcdbdc1ab64327916affdef9340612de17a7 Mon Sep 17 00:00:00 2001 From: Jonathan Date: Fri, 9 Oct 2026 09:55:50 +0200 Subject: [PATCH 227/356] Do not link a trace that is not stored as a child (#185207) --- homeassistant/components/trace/models.py | 3 +- tests/components/trace/test_websocket_api.py | 52 +++++++++++++++++++- 2 files changed, 53 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/trace/models.py b/homeassistant/components/trace/models.py index 89b2d2d3ddd6..d3a42ede803d 100644 --- a/homeassistant/components/trace/models.py +++ b/homeassistant/components/trace/models.py @@ -93,7 +93,8 @@ class ActionTrace(BaseTrace): self.key = f"{self._domain}.{item_id}" self._dict: dict[str, Any] | None = None self._short_dict: dict[str, Any] | None = None - if trace_id_get(): + # An automation without an id stores no trace, so there is nothing to link + if item_id and trace_id_get(): trace_set_child_id(self.key, self.run_id) trace_id_set((self.key, self.run_id)) diff --git a/tests/components/trace/test_websocket_api.py b/tests/components/trace/test_websocket_api.py index de2c9f72f5ed..2b8ef93dfa4e 100644 --- a/tests/components/trace/test_websocket_api.py +++ b/tests/components/trace/test_websocket_api.py @@ -19,7 +19,7 @@ from homeassistant.helpers.typing import UNDEFINED from homeassistant.setup import async_setup_component from homeassistant.util.uuid import random_uuid_hex -from tests.common import async_load_json_object_fixture +from tests.common import async_capture_events, async_load_json_object_fixture from tests.typing import WebSocketGenerator @@ -1696,6 +1696,56 @@ async def test_automation_without_id_does_not_store_trace( assert "automation.None" not in hass.data[DATA_TRACE] +async def test_automation_without_id_is_not_linked_as_child( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, +) -> None: + """A step that triggers an automation without an id does not link to it.""" + await _setup_automation_or_script( + hass, + "automation", + [ + { + "id": "sun", + "triggers": {"platform": "event", "event_type": "test_event"}, + "actions": { + "action": "automation.trigger", + "target": {"entity_id": "automation.no_id"}, + }, + }, + { + "alias": "No id", + "triggers": {"platform": "event", "event_type": "never_fired"}, + "actions": {"event": "automation_ran"}, + }, + ], + ) + events = async_capture_events(hass, "automation_ran") + + hass.bus.async_fire("test_event") + await hass.async_block_till_done() + assert len(events) == 1 + + client = await hass_ws_client() + await client.send_json({"id": 1, "type": "trace/list", "domain": "automation"}) + response = await client.receive_json() + assert response["success"] + sun_run_id = _find_run_id(response["result"], "automation", "sun") + + await client.send_json( + { + "id": 2, + "type": "trace/get", + "domain": "automation", + "item_id": "sun", + "run_id": sun_run_id, + } + ) + response = await client.receive_json() + assert response["success"] + assert "child_id" not in response["result"]["trace"]["action/0"][0] + + class _DiagnosticActionTrace(ActionTrace): """Automation-domain trace used to exercise not-triggered serialization.""" From d133a48433cc1ef52fddafba6ef8be75656bf615 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 11:36:36 +0200 Subject: [PATCH 228/356] Fix Hue light crash when the bridge reports no color temperature (#185218) --- homeassistant/components/hue/v2/light.py | 2 +- tests/components/hue/test_light_v2.py | 25 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/hue/v2/light.py b/homeassistant/components/hue/v2/light.py index 8b025dad5351..2f1c1987b7b8 100644 --- a/homeassistant/components/hue/v2/light.py +++ b/homeassistant/components/hue/v2/light.py @@ -175,7 +175,7 @@ class HueLight(HueBaseEntity, LightEntity): @override def color_temp_kelvin(self) -> int | None: """Return the color temperature value in Kelvin.""" - if color_temp := self.resource.color_temperature: + if (color_temp := self.resource.color_temperature) and color_temp.mirek: return color_util.color_temperature_mired_to_kelvin(color_temp.mirek) # return a fallback value to prevent issues with mired->kelvin conversions return FALLBACK_KELVIN diff --git a/tests/components/hue/test_light_v2.py b/tests/components/hue/test_light_v2.py index dac308cb9788..702138d98c9d 100644 --- a/tests/components/hue/test_light_v2.py +++ b/tests/components/hue/test_light_v2.py @@ -1072,3 +1072,28 @@ async def test_light_with_zero_mirek( # Should fall back to defaults instead of crashing assert test_light.attributes["max_color_temp_kelvin"] == 6535 assert test_light.attributes["min_color_temp_kelvin"] == 2000 + + +async def test_light_with_null_mirek( + hass: HomeAssistant, mock_bridge_v2: Mock, v2_resources_test_data: JsonArrayType +) -> None: + """Test a color temperature only light doesn't crash without a mirek value.""" + for resource in v2_resources_test_data: + if resource["id"] == "3a6710fa-4474-4eba-b533-5e6e72968feb": + resource["on"]["on"] = True + resource["color_temperature"]["mirek"] = None + resource["color_temperature"]["mirek_valid"] = False + break + + await mock_bridge_v2.api.load_test_data(v2_resources_test_data) + + await setup_platform(hass, mock_bridge_v2, Platform.LIGHT) + + test_light = hass.states.get( + "light.test_room_hue_light_with_color_temperature_only" + ) + assert test_light is not None + assert test_light.state == "on" + assert test_light.attributes["color_mode"] == ColorMode.COLOR_TEMP + # Falls back instead of converting the missing mirek value + assert test_light.attributes["color_temp_kelvin"] == 5800 From 462d2e09670d7ba0a9f1fed3a5147ab38a61f04c Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 11:09:36 +0200 Subject: [PATCH 229/356] Fix generic thermostat rechecking too late after a minimum cycle or cooldown (#185221) --- .../components/generic_thermostat/climate.py | 4 +- .../generic_thermostat/test_climate.py | 68 +++++++++++++++++++ 2 files changed, 70 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/generic_thermostat/climate.py b/homeassistant/components/generic_thermostat/climate.py index 084a68a21529..9bef4da189f6 100644 --- a/homeassistant/components/generic_thermostat/climate.py +++ b/homeassistant/components/generic_thermostat/climate.py @@ -621,7 +621,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity): ) self._check_callback = async_call_later( self.hass, - now - self._last_toggled_time + self.min_cycle_duration, + self._last_toggled_time + self.min_cycle_duration - now, self._async_timer_control_heating, ) elif called_by_timer: @@ -643,7 +643,7 @@ class GenericThermostat(ClimateEntity, RestoreEntity): ) self._check_callback = async_call_later( self.hass, - now - self._last_toggled_time + self.cycle_cooldown, + self._last_toggled_time + self.cycle_cooldown - now, self._async_timer_control_heating, ) elif called_by_timer: diff --git a/tests/components/generic_thermostat/test_climate.py b/tests/components/generic_thermostat/test_climate.py index 356d3770b086..03667408e3a9 100644 --- a/tests/components/generic_thermostat/test_climate.py +++ b/tests/components/generic_thermostat/test_climate.py @@ -1404,6 +1404,74 @@ async def test_cycle_cooldown_schedules_restart_after_cooldown( assert calls[0].service == SERVICE_TURN_ON +@pytest.mark.parametrize( + ( + "min_cycle_duration", + "cycle_cooldown", + "initial_switch_state", + "sensor_temperature", + "expected_service", + ), + [ + pytest.param(10, 0, True, 30, SERVICE_TURN_OFF, id="min_cycle_duration"), + pytest.param(0, 10, False, 20, SERVICE_TURN_ON, id="cycle_cooldown"), + ], +) +async def test_recheck_scheduled_for_remaining_time( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + min_cycle_duration: int, + cycle_cooldown: int, + initial_switch_state: bool, + sensor_temperature: float, + expected_service: str, +) -> None: + """Test the recheck fires when the remaining cycle time is up.""" + hass.config.temperature_unit = UnitOfTemperature.CELSIUS + now = dt_util.utcnow() + freezer.move_to(now) + + assert await async_setup_component( + hass, + CLIMATE_DOMAIN, + { + "climate": { + "platform": "generic_thermostat", + "name": "test", + "cold_tolerance": 0.3, + "hot_tolerance": 0.3, + "target_temp": 25, + "heater": ENT_SWITCH, + "target_sensor": ENT_SENSOR, + "min_cycle_duration": datetime.timedelta(minutes=min_cycle_duration), + "cycle_cooldown": datetime.timedelta(minutes=cycle_cooldown), + "initial_hvac_mode": HVACMode.HEAT, + } + }, + ) + await hass.async_block_till_done() + + calls = _setup_switch(hass, initial_switch_state) + await hass.async_block_till_done() + thermostats = hass.data[entity_platform.DATA_DOMAIN_PLATFORM_ENTITIES][ + (CLIMATE_DOMAIN, "generic_thermostat") + ] + thermostats[ENTITY]._last_toggled_time = now + + # The reading arrives halfway, so the switch has to wait 5 more minutes + freezer.move_to(now + datetime.timedelta(minutes=5)) + _setup_sensor(hass, sensor_temperature) + await hass.async_block_till_done() + assert len(calls) == 0 + + freezer.move_to(now + datetime.timedelta(minutes=10)) + async_fire_time_changed(hass, now + datetime.timedelta(minutes=10)) + await hass.async_block_till_done() + + assert len(calls) == 1 + assert calls[0].service == expected_service + + @pytest.fixture async def setup_comp_9(hass: HomeAssistant) -> None: """Initialize components.""" From 43fbf7db7ba6ea8585fdceddb34b062d8b1cdb25 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 13:02:33 +0200 Subject: [PATCH 230/356] Fix Signal Messenger notify failing to load when the REST API is down at startup (#185225) --- .../components/signal_messenger/notify.py | 24 ++++++++++---- tests/components/signal_messenger/conftest.py | 8 +++-- .../signal_messenger/test_notify.py | 33 +++++++++++++++++++ 3 files changed, 56 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/signal_messenger/notify.py b/homeassistant/components/signal_messenger/notify.py index 0b14458c9dc8..37f0cafcc9da 100644 --- a/homeassistant/components/signal_messenger/notify.py +++ b/homeassistant/components/signal_messenger/notify.py @@ -84,9 +84,7 @@ def get_service( recp_nrs = config[CONF_RECP_NR] signal_cli_rest_api_url = config[CONF_SIGNAL_CLI_REST_API] - signal_cli_rest_api = SignalCliRestApi(signal_cli_rest_api_url, sender_nr) - - return SignalNotificationService(hass, recp_nrs, signal_cli_rest_api) + return SignalNotificationService(hass, recp_nrs, signal_cli_rest_api_url, sender_nr) class SignalNotificationService(BaseNotificationService): @@ -96,13 +94,27 @@ class SignalNotificationService(BaseNotificationService): self, hass: HomeAssistant, recp_nrs: list[str], - signal_cli_rest_api: SignalCliRestApi, + signal_cli_rest_api_url: str, + sender_nr: str, ) -> None: """Initialize the service.""" self._hass = hass self._recp_nrs = recp_nrs - self._signal_cli_rest_api = signal_cli_rest_api + self._signal_cli_rest_api_url = signal_cli_rest_api_url + self._sender_nr = sender_nr + self._signal_cli_rest_api: SignalCliRestApi | None = None + + @property + def signal_cli_rest_api(self) -> SignalCliRestApi: + """Return the REST API client, creating it on first use.""" + # Creating the client queries the REST API, which may not be up yet + # when Home Assistant starts. + if self._signal_cli_rest_api is None: + self._signal_cli_rest_api = SignalCliRestApi( + self._signal_cli_rest_api_url, self._sender_nr + ) + return self._signal_cli_rest_api @override def send_message(self, message: str = "", **kwargs: Any) -> None: @@ -125,7 +137,7 @@ class SignalNotificationService(BaseNotificationService): data, CONF_MAX_ALLOWED_DOWNLOAD_SIZE_BYTES, self._hass ) try: - self._signal_cli_rest_api.send_message( + self.signal_cli_rest_api.send_message( message, recipients, notify_self=True, diff --git a/tests/components/signal_messenger/conftest.py b/tests/components/signal_messenger/conftest.py index db6af1b0dda6..f2ad6d551466 100644 --- a/tests/components/signal_messenger/conftest.py +++ b/tests/components/signal_messenger/conftest.py @@ -1,5 +1,6 @@ """Signal notification test helpers.""" +from collections.abc import Generator from http import HTTPStatus from unittest.mock import patch @@ -20,14 +21,15 @@ URL_ATTACHMENT = f"{SIGNAL_BASE_URL}/image.jpg" @pytest.fixture -def signal_notification_service(hass: HomeAssistant) -> SignalNotificationService: +def signal_notification_service( + hass: HomeAssistant, +) -> Generator[SignalNotificationService]: """Set up signal notification service.""" hass.config.allowlist_external_urls.add(URL_ATTACHMENT) recipients = ["+435565656565"] number = "+43443434343" with patch.object(SignalCliRestApi, "mode", return_value="normal"): - client = SignalCliRestApi(SIGNAL_BASE_URL, number) - return SignalNotificationService(hass, recipients, client) + yield SignalNotificationService(hass, recipients, SIGNAL_BASE_URL, number) @pytest.fixture diff --git a/tests/components/signal_messenger/test_notify.py b/tests/components/signal_messenger/test_notify.py index 2c081233cbfd..ecf932d42f3d 100644 --- a/tests/components/signal_messenger/test_notify.py +++ b/tests/components/signal_messenger/test_notify.py @@ -10,6 +10,7 @@ from unittest.mock import patch import probatio from pysignalclirestapi.api import SignalCliRestApiError import pytest +import requests from requests_mock.mocker import Mocker from homeassistant.components.notify import DOMAIN as NOTIFY_DOMAIN @@ -50,6 +51,38 @@ async def test_signal_messenger_init(hass: HomeAssistant) -> None: assert hass.services.has_service(NOTIFY_DOMAIN, "test") +async def test_signal_messenger_init_api_unavailable( + hass: HomeAssistant, + requests_mock: Mocker, + signal_requests_mock_factory: Mocker, +) -> None: + """Test that the service loads and sends once the REST API is available.""" + requests_mock.get( + f"{SIGNAL_BASE_URL}/v1/about", exc=requests.exceptions.ConnectionError + ) + config = { + NOTIFY_DOMAIN: { + "name": "test", + "platform": "signal_messenger", + "url": SIGNAL_BASE_URL, + "number": NUMBER_FROM, + "recipients": NUMBERS_TO, + } + } + + assert await async_setup_component(hass, NOTIFY_DOMAIN, config) + await hass.async_block_till_done() + + assert hass.services.has_service(NOTIFY_DOMAIN, "test") + + signal_requests_mock = signal_requests_mock_factory() + await hass.services.async_call( + NOTIFY_DOMAIN, "test", {"message": MESSAGE}, blocking=True + ) + + assert_sending_requests(signal_requests_mock) + + def test_send_message( signal_notification_service: SignalNotificationService, signal_requests_mock_factory: Mocker, From 9cc7d6de47673646380d2b9fb1f4afb8595746c8 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 10:50:00 +0200 Subject: [PATCH 231/356] Don't create Nibe number entities for date coils (#185229) --- .../components/nibe_heatpump/number.py | 2 +- tests/components/nibe_heatpump/test_number.py | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/nibe_heatpump/number.py b/homeassistant/components/nibe_heatpump/number.py index 04d90175ced1..ffd3081d05af 100644 --- a/homeassistant/components/nibe_heatpump/number.py +++ b/homeassistant/components/nibe_heatpump/number.py @@ -25,7 +25,7 @@ async def async_setup_entry( async_add_entities( Number(coordinator, coil) for coil in coordinator.coils - if coil.is_writable and not coil.mappings + if coil.is_writable and not coil.mappings and not coil.is_date ) diff --git a/tests/components/nibe_heatpump/test_number.py b/tests/components/nibe_heatpump/test_number.py index 2881ac62a331..652c82a022ca 100644 --- a/tests/components/nibe_heatpump/test_number.py +++ b/tests/components/nibe_heatpump/test_number.py @@ -1,5 +1,6 @@ """Test the Nibe Heat Pump number entities.""" +from datetime import date from typing import Any from unittest.mock import AsyncMock, patch @@ -65,6 +66,29 @@ async def test_update( assert state == snapshot +@pytest.mark.parametrize( + ("address", "entity_id"), + [ + (48044, "number.holiday_start_date_48044"), + (48045, "number.holiday_end_date_48045"), + ], +) +@pytest.mark.usefixtures("entity_registry_enabled_by_default") +async def test_date_coils_not_created( + hass: HomeAssistant, + address: int, + entity_id: str, + coils: dict[int, Any], +) -> None: + """Test writable date coils do not become number entities.""" + coils[address] = date(2025, 6, 28) + + await async_add_model(hass, Model.F1255) + + await hass.async_block_till_done() + assert hass.states.get(entity_id) is None + + @pytest.mark.parametrize( ("model", "address", "entity_id", "value"), [ From 77d9076f97e278bc3e026ac5374cab672167f716 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 12:23:56 +0200 Subject: [PATCH 232/356] Round LG Infrared target temperature instead of truncating it (#185231) --- .../components/lg_infrared/climate.py | 2 +- tests/components/lg_infrared/test_climate.py | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/lg_infrared/climate.py b/homeassistant/components/lg_infrared/climate.py index 12f5d772de48..9a3fdf13b28c 100644 --- a/homeassistant/components/lg_infrared/climate.py +++ b/homeassistant/components/lg_infrared/climate.py @@ -236,7 +236,7 @@ class LgAcClimateEntity( @override async def async_set_temperature(self, **kwargs: Any) -> None: """Set the target temperature, switching the HVAC mode when one is given.""" - temp = int(kwargs[ATTR_TEMPERATURE]) + temp = round(kwargs[ATTR_TEMPERATURE]) hvac_mode: HVACMode | None = kwargs.get(ATTR_HVAC_MODE) if hvac_mode is not None: self._valid_mode_or_raise("hvac", hvac_mode, self.hvac_modes) diff --git a/tests/components/lg_infrared/test_climate.py b/tests/components/lg_infrared/test_climate.py index fa49d3cda3f8..ffa37f869e9f 100644 --- a/tests/components/lg_infrared/test_climate.py +++ b/tests/components/lg_infrared/test_climate.py @@ -45,6 +45,7 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant, State from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers import entity_registry as er +from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM from tests.common import MockConfigEntry, mock_restore_cache, snapshot_platform from tests.components.common import assert_availability_follows_source_entity @@ -293,6 +294,44 @@ async def test_set_temperature_sends_command_when_active( assert float(state.attributes["temperature"]) == 26.0 +@pytest.mark.parametrize( + ("fahrenheit", "celsius"), + [(61, 16), (62, 17), (63, 17), (64, 18)], +) +@pytest.mark.usefixtures("init_integration") +async def test_set_temperature_fahrenheit_rounds( + hass: HomeAssistant, + mock_infrared_emitter_entity: MockInfraredEmitterEntity, + fahrenheit: int, + celsius: int, +) -> None: + """Test a Fahrenheit target is rounded to the nearest Celsius degree.""" + hass.config.units = US_CUSTOMARY_SYSTEM + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_HVAC_MODE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, "hvac_mode": HVACMode.COOL}, + blocking=True, + ) + mock_infrared_emitter_entity.send_command_calls.clear() + + await hass.services.async_call( + CLIMATE_DOMAIN, + SERVICE_SET_TEMPERATURE, + {ATTR_ENTITY_ID: _CLIMATE_ENTITY_ID, ATTR_TEMPERATURE: fahrenheit}, + blocking=True, + ) + + assert len(mock_infrared_emitter_entity.send_command_calls) == 1 + timings = mock_infrared_emitter_entity.send_command_calls[0].get_raw_timings() + assert ( + timings + == LgAcCommand( + mode=LgAcMode.COOL, temperature=celsius, fan=LgAcFanSpeed.AUTO + ).get_raw_timings() + ) + + @pytest.mark.usefixtures("init_integration") async def test_set_temperature_no_command_when_off( hass: HomeAssistant, From e91af22fa148db229de84fa9a751f0d708ef7261 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 15:55:51 +0200 Subject: [PATCH 233/356] Log in to OmniLogic again after a failed update (#185250) --- .../components/omnilogic/coordinator.py | 3 + .../components/omnilogic/test_coordinator.py | 62 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 tests/components/omnilogic/test_coordinator.py diff --git a/homeassistant/components/omnilogic/coordinator.py b/homeassistant/components/omnilogic/coordinator.py index 6897e5718da4..a0f754e59466 100644 --- a/homeassistant/components/omnilogic/coordinator.py +++ b/homeassistant/components/omnilogic/coordinator.py @@ -49,6 +49,9 @@ class OmniLogicUpdateCoordinator(DataUpdateCoordinator[dict[tuple, dict[str, Any data = await self.api.get_telemetry_data() except OmniLogicException as error: + # The library only logs in again without a token, so drop a + # possibly rejected one to have the next update log in again. + self.api.token = None raise UpdateFailed(f"Error updating from OmniLogic: {error}") from error parsed_data = {} diff --git a/tests/components/omnilogic/test_coordinator.py b/tests/components/omnilogic/test_coordinator.py new file mode 100644 index 000000000000..20384ca305b1 --- /dev/null +++ b/tests/components/omnilogic/test_coordinator.py @@ -0,0 +1,62 @@ +"""Tests for the Omnilogic coordinator.""" + +from datetime import timedelta +from typing import Any +from unittest.mock import patch + +from freezegun.api import FrozenDateTimeFactory +from omnilogic import OmniLogic, OmniLogicException + +from homeassistant.components.omnilogic.const import DOMAIN, SCAN_INTERVAL +from homeassistant.const import CONF_PASSWORD, CONF_USERNAME +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry, async_fire_time_changed + + +async def _get_telemetry_data(api: OmniLogic) -> list[dict[str, Any]]: + """Behave like omnilogic: only log in again when there is no token.""" + if api.token is None: + api.token = "new-token" + if api.token == "rejected-token": + raise OmniLogicException("Error converting Hayward data to JSON.") + return [] + + +async def test_rejected_token_logs_in_again( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Test the next update logs in again after Hayward rejects the token.""" + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_USERNAME: "test-username", CONF_PASSWORD: "test-password"}, + ) + entry.add_to_hass(hass) + + with ( + patch.object(OmniLogic, "connect", return_value=True), + patch.object( + OmniLogic, + "get_telemetry_data", + autospec=True, + side_effect=_get_telemetry_data, + ), + ): + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + coordinator = entry.runtime_data + assert coordinator.last_update_success + # Empty telemetry creates no entities, and without a listener the + # coordinator does not poll. + coordinator.async_add_listener(lambda: None) + + coordinator.api.token = "rejected-token" + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert not coordinator.last_update_success + + freezer.tick(timedelta(seconds=SCAN_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert coordinator.last_update_success From ba9aadf1c0899c4e8adc40bf4122f52baf0f2879 Mon Sep 17 00:00:00 2001 From: tronikos Date: Fri, 9 Oct 2026 06:25:54 -0700 Subject: [PATCH 234/356] Remember silent SolarEdge Modbus blocks across setups (#185255) --- .../components/solaredge_modbus/__init__.py | 38 +++++- .../components/solaredge_modbus/const.py | 4 + .../solaredge_modbus/test_config_flow.py | 6 +- .../components/solaredge_modbus/test_init.py | 115 ++++++++++++++++++ 4 files changed, 156 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/solaredge_modbus/__init__.py b/homeassistant/components/solaredge_modbus/__init__.py index 004c9a35e19e..e7c93a33a3d5 100644 --- a/homeassistant/components/solaredge_modbus/__init__.py +++ b/homeassistant/components/solaredge_modbus/__init__.py @@ -32,6 +32,7 @@ from homeassistant.helpers.event import async_track_time_interval from .const import ( ATTACHMENT_SCAN_INTERVAL, + CONF_SILENT_BLOCKS, CONF_UNIT_ID, DISCOVERY_SUBSYSTEMS, DOMAIN, @@ -85,8 +86,14 @@ async def async_setup_entry( translation_placeholders={"error": str(err)}, ) from err + # Blocks that were still silent on the last attachment check are taken for + # absent, so setting up does not wait out a timeout for each. The first + # check after setup asks them for real again, which is where a block that + # has started answering is found. + known_silent = _known_silent_blocks(entry) + try: - solaredge = await SolarEdge.async_probe(unit) + solaredge = await SolarEdge.async_probe(unit, assume_absent=known_silent) except SolarEdgeConnectionError as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, @@ -158,12 +165,13 @@ async def async_setup_entry( attachments=_attachment_identities(solaredge), ) - if silent := solaredge.unresponsive_blocks & _probed_blocks(solaredge).keys(): + silent = solaredge.unresponsive_blocks & _probed_blocks(solaredge).keys() + if newly_silent := silent - known_silent: LOGGER.warning( "%s did not answer for %s while probing, so the entities those" - " would carry are missing; this is looked at again every %s minutes", + " would carry are missing; this is looked at again in %s minutes", entry.title, - " and ".join(sorted(silent)), + " and ".join(sorted(newly_silent)), int(ATTACHMENT_SCAN_INTERVAL.total_seconds() // 60), ) @@ -184,6 +192,15 @@ async def async_setup_entry( return True +def _known_silent_blocks(entry: SolarEdgeModbusConfigEntry) -> frozenset[str]: + """Return the blocks the last attachment check settled as silent. + + Blocks that finding hardware depends on are never settled, so one stored + by anything else is not taken for absent either. + """ + return frozenset(entry.data.get(CONF_SILENT_BLOCKS, ())) - DISCOVERY_SUBSYSTEMS + + def _attachment_identities(solaredge: SolarEdge) -> frozenset[str]: """Return what the meters and batteries attached right now are known by.""" return frozenset( @@ -252,9 +269,20 @@ async def _async_reload_when_attachments_change( # later removal until the entry loads again. Blocks that finding hardware # depends on are never settled: picking up what was wired in later is what # asking is for. - entry.runtime_data.settled_silent_blocks = ( + settled = ( probed.unresponsive_blocks & solaredge.unresponsive_blocks ) - DISCOVERY_SUBSYSTEMS + entry.runtime_data.settled_silent_blocks = settled + + # Kept with the entry for the next setup, before a reload below can start + # one: a block that answered here must not be taken for absent by it. Only + # blocks whose return this check reloads for are kept: any other block that + # started answering later would stay unseen until something else reloaded. + kept = settled & _probed_blocks(probed).keys() + if kept != _known_silent_blocks(entry): + hass.config_entries.async_update_entry( + entry, data={**entry.data, CONF_SILENT_BLOCKS: sorted(kept)} + ) known = _probed_blocks(solaredge) for name, found in _probed_blocks(probed).items(): diff --git a/homeassistant/components/solaredge_modbus/const.py b/homeassistant/components/solaredge_modbus/const.py index 0a1d45670766..6e18ebca4e98 100644 --- a/homeassistant/components/solaredge_modbus/const.py +++ b/homeassistant/components/solaredge_modbus/const.py @@ -10,6 +10,10 @@ LOGGER = logging.getLogger(__package__) CONF_BAUDRATE: Final = "baudrate" CONF_UNIT_ID: Final = "unit_id" +# Blocks the inverter stayed silent about on the last attachment check, kept +# with the entry so that setting it up again does not wait out their timeouts. +CONF_SILENT_BLOCKS: Final = "silent_blocks" + TYPE_SERIAL: Final = "serial" TYPE_TCP: Final = "tcp" diff --git a/tests/components/solaredge_modbus/test_config_flow.py b/tests/components/solaredge_modbus/test_config_flow.py index bfeac3975480..8e079d1d166a 100644 --- a/tests/components/solaredge_modbus/test_config_flow.py +++ b/tests/components/solaredge_modbus/test_config_flow.py @@ -447,10 +447,12 @@ async def test_reconfigure_flow_new_line_settings_while_retrying( states: list[ConfigEntryState] = [] probe = SolarEdge.async_probe - async def probe_watching_the_entry(unit: ModbusUnit) -> SolarEdge: + async def probe_watching_the_entry( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: """Record whether the entry could still be reaching for the bus.""" states.append(entry.state) - return await probe(unit) + return await probe(unit, assume_absent=assume_absent) result = await entry.start_reconfigure_flow(hass) with patch.object(SolarEdge, "async_probe", probe_watching_the_entry): diff --git a/tests/components/solaredge_modbus/test_init.py b/tests/components/solaredge_modbus/test_init.py index 7ad80076d77d..890b8d37853e 100644 --- a/tests/components/solaredge_modbus/test_init.py +++ b/tests/components/solaredge_modbus/test_init.py @@ -21,6 +21,7 @@ from homeassistant.components.select import ( ) from homeassistant.components.solaredge_modbus.const import ( ATTACHMENT_SCAN_INTERVAL, + CONF_SILENT_BLOCKS, DOMAIN, SCAN_INTERVAL, SETTINGS_SCAN_INTERVAL, @@ -43,6 +44,8 @@ from .conftest import ( BATTERY_SERIAL_NUMBERS, METER_SERIAL_NUMBER, SERIAL_NUMBER, + STORAGE_CAPACITY_BASE, + add_storage_capacity, async_seed_unit, tcp_data, ) @@ -1161,3 +1164,115 @@ async def test_a_block_discovery_depends_on_keeps_being_asked( await hass.async_block_till_done() assert subsystem not in asked[1], "a block discovery depends on was settled" + + +async def test_a_settled_block_is_not_waited_for_on_the_next_setup( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, + caplog: pytest.LogCaptureFixture, +) -> None: + """A block settled as silent is taken for absent when the entry loads again. + + Each one would otherwise cost a full timeout every time the entry is set + up, which on a slow link is most of the time that takes. + """ + mock_modbus_unit.fail_read(POWER_CONTROL_REGISTER, ModbusTimeoutError("timed out")) + await _setup(hass, mock_config_entry) + await _tick_attachment_check(hass, freezer) + + assert mock_config_entry.data[CONF_SILENT_BLOCKS] == ["power_control"] + + asked: list[frozenset[str]] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + asked.append(assume_absent) + return await probe(unit, assume_absent=assume_absent) + + caplog.clear() + with patch.object(SolarEdge, "async_probe", recording_probe): + await hass.config_entries.async_reload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.LOADED + assert asked == [frozenset({"power_control"})] + assert "power_control" not in caplog.text, "a known silence is not news" + + +async def test_a_settled_block_that_answers_again_is_picked_up( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_modbus_unit: MockModbusUnit, +) -> None: + """The first check after setup still asks a settled block for real. + + The entry reloads to add what it found, so the block must be forgotten as + silent first, or that setup would take it for absent all over again. + """ + entry = MockConfigEntry( + domain=DOMAIN, + title="SolarEdge SE10000H", + unique_id=SERIAL_NUMBER, + data={**tcp_data(), CONF_SILENT_BLOCKS: ["power_control"]}, + ) + await _setup(hass, entry) + + assert hass.states.get(ACTIVE_POWER_LIMIT_ENTITY) is None + + await _tick_attachment_check(hass, freezer) + + assert hass.states.get(ACTIVE_POWER_LIMIT_ENTITY) is not None + assert entry.data[CONF_SILENT_BLOCKS] == [] + + +@pytest.mark.parametrize("subsystem", ["batteries", "meters", "mmppt"]) +async def test_a_stored_discovery_block_is_still_asked_at_setup( + hass: HomeAssistant, + mock_modbus_unit: MockModbusUnit, + subsystem: str, +) -> None: + """A block that finding hardware depends on is asked whatever was stored.""" + entry = MockConfigEntry( + domain=DOMAIN, + title="SolarEdge SE10000H", + unique_id=SERIAL_NUMBER, + data={**tcp_data(), CONF_SILENT_BLOCKS: [subsystem, "power_control"]}, + ) + asked: list[frozenset[str]] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + asked.append(assume_absent) + return await probe(unit, assume_absent=assume_absent) + + with patch.object(SolarEdge, "async_probe", recording_probe): + await _setup(hass, entry) + + assert asked == [frozenset({"power_control"})] + + +async def test_only_a_block_a_check_reloads_for_is_kept( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, +) -> None: + """A silent block is only skipped at setup if the check can bring it back. + + The check reloads when a control block starts answering. A silent model + chain, which is where storage capacity is found, does not get that reload, + so taking it for absent at setup would hide it until something else did. + """ + add_storage_capacity(mock_modbus_unit, state_of_charge=5960) + mock_modbus_unit.fail_read(POWER_CONTROL_REGISTER, ModbusTimeoutError("timed out")) + mock_modbus_unit.fail_read(STORAGE_CAPACITY_BASE, ModbusTimeoutError("timed out")) + await _setup(hass, mock_config_entry) + await _tick_attachment_check(hass, freezer) + + assert mock_config_entry.data[CONF_SILENT_BLOCKS] == ["power_control"] From 32cd3da42e4e9d1ac249b83737384fa9d5fa8dc6 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Fri, 9 Oct 2026 13:03:57 +0200 Subject: [PATCH 235/356] Update frontend to 20260930.3 (#185285) --- homeassistant/components/frontend/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- pylint/plugins/pylint_home_assistant/generated/mdi_icons.py | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 035d6074311d..75c866a736ac 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -22,5 +22,5 @@ "integration_type": "system", "preview_features": { "winter_mode": {} }, "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20260930.2"] + "requirements": ["home-assistant-frontend==20260930.3"] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index d2beab74e0ad..2c44ba8fcffe 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -40,7 +40,7 @@ habluetooth==7.1.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-frontend==20260930.2 +home-assistant-frontend==20260930.3 home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 diff --git a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py index 90b2a92bdada..a78564d99a7e 100644 --- a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py +++ b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py @@ -5,7 +5,7 @@ To update, run python3 -m script.hassfest from typing import Final -FRONTEND_VERSION: Final[str] = "20260930.2" +FRONTEND_VERSION: Final[str] = "20260930.3" MDI_ICONS: Final[set[str]] = { "ab-testing", diff --git a/requirements_all.txt b/requirements_all.txt index 51a1aafd70f9..67a3773284b0 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1312,7 +1312,7 @@ hole==0.9.2 holidays==0.106 # homeassistant.components.frontend -home-assistant-frontend==20260930.2 +home-assistant-frontend==20260930.3 # homeassistant.components.conversation home-assistant-intents==2026.10.6 From bc476b9034d169616b10825ce161389c461629fc Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 13:03:24 +0200 Subject: [PATCH 236/356] Bump wled to 1.1.1 (#185344) --- homeassistant/components/wled/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/wled/manifest.json b/homeassistant/components/wled/manifest.json index a59f54c62161..d61e5f711df8 100644 --- a/homeassistant/components/wled/manifest.json +++ b/homeassistant/components/wled/manifest.json @@ -7,6 +7,6 @@ "integration_type": "device", "iot_class": "local_push", "quality_scale": "platinum", - "requirements": ["wled==1.1.0"], + "requirements": ["wled==1.1.1"], "zeroconf": ["_wled._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 67a3773284b0..2066a7564499 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3457,7 +3457,7 @@ wiim==0.1.7 wirelesstagpy==0.8.1 # homeassistant.components.wled -wled==1.1.0 +wled==1.1.1 # homeassistant.components.wolflink wolf-comm==0.0.52 From b5b782a917be649b5d88ad2c489914ea6f1b153a Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 17:05:41 +0200 Subject: [PATCH 237/356] Keep deprecated device config entry attributes working in templates (#185361) --- .../helpers/template/extensions/devices.py | 50 ++++++++- .../template/extensions/test_devices.py | 103 +++++++++++++++++- 2 files changed, 150 insertions(+), 3 deletions(-) diff --git a/homeassistant/helpers/template/extensions/devices.py b/homeassistant/helpers/template/extensions/devices.py index 8d79983628dd..a10a33746371 100644 --- a/homeassistant/helpers/template/extensions/devices.py +++ b/homeassistant/helpers/template/extensions/devices.py @@ -1,7 +1,8 @@ """Device functions for Home Assistant templates.""" -from collections.abc import Iterable +from collections.abc import Callable, Iterable from itertools import chain +import logging from typing import TYPE_CHECKING, Any import probatio @@ -12,12 +13,38 @@ from homeassistant.helpers import ( device_registry as dr, entity_registry as er, ) +from homeassistant.util.hass_dict import HassKey from .base import BaseTemplateExtension, TemplateFunction if TYPE_CHECKING: from homeassistant.helpers.template import TemplateEnvironment +_LOGGER = logging.getLogger(__name__) + +# Shared by all template environments, a template entity with a custom log +# function gets a fresh environment (and extension) of its own. +_WARNED_DEPRECATED_ATTRS: HassKey[set[str]] = HassKey( + "template_device_attr_warned_deprecated" +) + +# Deprecated device attributes, resolved from config_entry_id and +# config_subentry_id, so reading them in a template does not raise. +_DEPRECATED_DEVICE_ATTRS: dict[str, tuple[str, Callable[[dr.BaseDeviceEntry], Any]]] = { + "config_entries": ( + "'config_entry_id'", + lambda device: {device.config_entry_id}, + ), + "config_entries_subentries": ( + "'config_entry_id' and 'config_subentry_id'", + lambda device: {device.config_entry_id: {device.config_subentry_id}}, + ), + "primary_config_entry": ( + "'config_entry_id'", + lambda device: device.config_entry_id, + ), +} + class DeviceExtension(BaseTemplateExtension): """Extension for device-related template functions.""" @@ -127,7 +154,26 @@ class DeviceExtension(BaseTemplateExtension): device = device_reg.async_get(_device_id) elif "." not in device_or_entity_id: device = device_reg.async_get(device_or_entity_id) - if device is None or not hasattr(device, attr_name): + if device is None: + return None + + if not device.is_composite_device and ( + deprecated := _DEPRECATED_DEVICE_ATTRS.get(attr_name) + ): + replacement, resolve = deprecated + warned = self.hass.data.setdefault(_WARNED_DEPRECATED_ATTRS, set()) + if attr_name not in warned: + warned.add(attr_name) + _LOGGER.warning( + "A template reads device attribute '%s', which is deprecated " + "and will stop working in Home Assistant 2027.10; use %s " + "instead", + attr_name, + replacement, + ) + return resolve(device) + + if not hasattr(device, attr_name): return None return getattr(device, attr_name) diff --git a/tests/helpers/template/extensions/test_devices.py b/tests/helpers/template/extensions/test_devices.py index c13c93ccb306..c8c3c5212a13 100644 --- a/tests/helpers/template/extensions/test_devices.py +++ b/tests/helpers/template/extensions/test_devices.py @@ -1,5 +1,9 @@ """Test device template functions.""" +from collections.abc import Callable +from typing import Any + +import attr import pytest from homeassistant.core import HomeAssistant @@ -7,7 +11,7 @@ from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.template import TemplateError from tests.common import MockConfigEntry -from tests.helpers.template.helpers import assert_result_info, render_to_info +from tests.helpers.template.helpers import assert_result_info, render, render_to_info async def test_device_entities( @@ -203,6 +207,103 @@ async def test_device_name( assert info.rate_limit is None +@pytest.mark.parametrize( + ("attr_name", "expected", "replacement"), + [ + pytest.param( + "config_entries", + lambda entry_id: {entry_id}, + "use 'config_entry_id' instead", + id="config_entries", + ), + pytest.param( + "config_entries_subentries", + lambda entry_id: {entry_id: {None}}, + "use 'config_entry_id' and 'config_subentry_id' instead", + id="config_entries_subentries", + ), + pytest.param( + "primary_config_entry", + lambda entry_id: entry_id, + "use 'config_entry_id' instead", + id="primary_config_entry", + ), + ], +) +async def test_device_attr_deprecated_config_entry_attributes( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + caplog: pytest.LogCaptureFixture, + attr_name: str, + expected: Callable[[str], Any], + replacement: str, +) -> None: + """Test deprecated config entry attributes keep working in templates.""" + config_entry = MockConfigEntry(domain="light") + config_entry.add_to_hass(hass) + device_entry = device_registry.async_get_or_create( + config_entry_id=config_entry.entry_id, + connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")}, + ) + + info = render_to_info( + hass, f"{{{{ device_attr('{device_entry.id}', '{attr_name}') }}}}" + ) + assert_result_info(info, expected(config_entry.entry_id)) + + info = render_to_info( + hass, + f"{{{{ is_device_attr('{device_entry.id}', '{attr_name}', None) }}}}", + ) + assert_result_info(info, False) + + # A custom log function renders in a fresh template environment + render( + hass, + f"{{{{ device_attr('{device_entry.id}', '{attr_name}') }}}}", + log_fn=lambda level, msg: None, + ) + + assert caplog.text.count(f"device attribute '{attr_name}'") == 1 + assert replacement in caplog.text + + +async def test_device_attr_deprecated_config_entry_attributes_composite( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test a pre-migration composite device id reports its merged config entries.""" + entry_1 = MockConfigEntry(domain="light") + entry_1.add_to_hass(hass) + entry_2 = MockConfigEntry(domain="light") + entry_2.add_to_hass(hass) + device_1 = device_registry.async_get_or_create( + config_entry_id=entry_1.entry_id, identifiers={("light", "1")} + ) + device_2 = device_registry.async_get_or_create( + config_entry_id=entry_2.entry_id, identifiers={("light", "2")} + ) + old_id = "composite00000000000000000000ab" + # Simulate a migration split: both devices carry the pre-migration composite id + device_registry._devices[device_1.id] = attr.evolve( + device_1, composite_device_id=old_id + ) + device_registry._devices[device_2.id] = attr.evolve( + device_2, composite_device_id=old_id + ) + + info = render_to_info(hass, f"{{{{ device_attr('{old_id}', 'config_entries') }}}}") + assert_result_info(info, {entry_1.entry_id, entry_2.entry_id}) + + info = render_to_info( + hass, f"{{{{ device_attr('{old_id}', 'config_entries_subentries') }}}}" + ) + assert_result_info(info, {entry_1.entry_id: {None}, entry_2.entry_id: {None}}) + + assert "is deprecated" not in caplog.text + + async def test_device_attr( hass: HomeAssistant, device_registry: dr.DeviceRegistry, From fc09721e99682835abe76b26117cfcab37143ba0 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Fri, 9 Oct 2026 08:36:43 -0400 Subject: [PATCH 238/356] Bump modbus-connection to 4.12.4 (#185419) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/modbus/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/modbus/manifest.json b/homeassistant/components/modbus/manifest.json index 7fafb06d158b..ff32ec53e174 100644 --- a/homeassistant/components/modbus/manifest.json +++ b/homeassistant/components/modbus/manifest.json @@ -7,7 +7,7 @@ "loggers": ["pymodbus"], "requirements": [ "pymodbus==3.13.1", - "modbus-connection[tmodbus]==4.12.3", + "modbus-connection[tmodbus]==4.12.4", "tmodbus==0.6.2" ] } diff --git a/requirements_all.txt b/requirements_all.txt index 2066a7564499..499db67496f1 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1641,7 +1641,7 @@ mitsubishi-comfort==0.6.0 moat-ble==0.1.1 # homeassistant.components.modbus -modbus-connection[tmodbus]==4.12.3 +modbus-connection[tmodbus]==4.12.4 # homeassistant.components.moehlenhoff_alpha2 moehlenhoff-alpha2==1.4.0 From 279eaa75baffafb473aebbbf615947bf5b97d4a2 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 16:05:48 +0200 Subject: [PATCH 239/356] Fix WLED adding Wi-Fi sensors to wired devices (#185425) --- homeassistant/components/wled/sensor.py | 10 ++++++ tests/components/wled/test_sensor.py | 44 +++++++++++++++---------- 2 files changed, 36 insertions(+), 18 deletions(-) diff --git a/homeassistant/components/wled/sensor.py b/homeassistant/components/wled/sensor.py index d36a0989a12f..a675d1e88448 100644 --- a/homeassistant/components/wled/sensor.py +++ b/homeassistant/components/wled/sensor.py @@ -42,6 +42,12 @@ class WLEDSensorEntityDescription(SensorEntityDescription): value_fn: Callable[[WLEDDevice], datetime | StateType] +def _connected_over_wifi(device: WLEDDevice) -> bool: + """Return whether the device is connected over Wi-Fi, not wired.""" + # Without a Wi-Fi connection, the library reports no signal strength. + return device.info.wifi is not None and device.info.wifi.rssi is not None + + SENSORS: tuple[WLEDSensorEntityDescription, ...] = ( WLEDSensorEntityDescription( key="estimated_current", @@ -91,6 +97,7 @@ SENSORS: tuple[WLEDSensorEntityDescription, ...] = ( WLEDSensorEntityDescription( key="wifi_signal", translation_key="wifi_signal", + exists_fn=_connected_over_wifi, native_unit_of_measurement=PERCENTAGE, state_class=SensorStateClass.MEASUREMENT, entity_category=EntityCategory.DIAGNOSTIC, @@ -100,6 +107,7 @@ SENSORS: tuple[WLEDSensorEntityDescription, ...] = ( WLEDSensorEntityDescription( key="wifi_rssi", translation_key="wifi_rssi", + exists_fn=_connected_over_wifi, native_unit_of_measurement=SIGNAL_STRENGTH_DECIBELS_MILLIWATT, device_class=SensorDeviceClass.SIGNAL_STRENGTH, state_class=SensorStateClass.MEASUREMENT, @@ -110,6 +118,7 @@ SENSORS: tuple[WLEDSensorEntityDescription, ...] = ( WLEDSensorEntityDescription( key="wifi_channel", translation_key="wifi_channel", + exists_fn=_connected_over_wifi, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.info.wifi.channel if device.info.wifi else None, @@ -117,6 +126,7 @@ SENSORS: tuple[WLEDSensorEntityDescription, ...] = ( WLEDSensorEntityDescription( key="wifi_bssid", translation_key="wifi_bssid", + exists_fn=_connected_over_wifi, entity_category=EntityCategory.DIAGNOSTIC, entity_registry_enabled_default=False, value_fn=lambda device: device.info.wifi.bssid if device.info.wifi else None, diff --git a/tests/components/wled/test_sensor.py b/tests/components/wled/test_sensor.py index 4b9f088bd7b5..bd7ff767f9f2 100644 --- a/tests/components/wled/test_sensor.py +++ b/tests/components/wled/test_sensor.py @@ -6,9 +6,10 @@ from unittest.mock import MagicMock, patch from freezegun.api import FrozenDateTimeFactory import pytest from syrupy.assertion import SnapshotAssertion +from wled import Wifi from homeassistant.components.wled.const import SCAN_INTERVAL -from homeassistant.const import STATE_UNKNOWN, Platform +from homeassistant.const import Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -58,34 +59,41 @@ async def test_disabled_by_default_sensors( assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION -@pytest.mark.parametrize( - "key", - [ - "bssid", - "channel", - "rssi", - "signal", - ], -) @pytest.mark.usefixtures("entity_registry_enabled_by_default") -async def test_no_wifi_support( +async def test_no_wifi_sensors_when_wired( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_wled: MagicMock, - key: str, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, ) -> None: - """Test missing Wi-Fi information from WLED device.""" - # Remove Wi-Fi info + """Test the Wi-Fi sensors are only added once the device uses Wi-Fi.""" + # A wired device reports no signal strength. device = mock_wled.update.return_value - device.info.wifi = None + wifi = device.info.wifi + device.info.wifi = Wifi.from_dict({"bssid": "00:00:00:00:00:00", "rssi": 0}) - # Setup mock_config_entry.add_to_hass(hass) await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() - assert (state := hass.states.get(f"sensor.wled_rgb_light_wi_fi_{key}")) - assert state.state == STATE_UNKNOWN + for key in ("bssid", "channel", "rssi", "signal"): + assert hass.states.get(f"sensor.wled_rgb_light_wi_fi_{key}") is None + + # The device is connected over Wi-Fi now. + device.info.wifi = wifi + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + for key in ("bssid", "channel", "rssi", "signal"): + assert hass.states.get(f"sensor.wled_rgb_light_wi_fi_{key}") + + # Later updates don't add them again. + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + assert "does not generate unique IDs" not in caplog.text async def test_no_current_measurement( From 7cef3c867a2b69f01d96a6fc95f88e828f8b3218 Mon Sep 17 00:00:00 2001 From: Thomas55555 <59625598+Thomas55555@users.noreply.github.com> Date: Fri, 9 Oct 2026 17:11:46 +0200 Subject: [PATCH 240/356] Add new error codes to Husqvarna Automower (#185477) --- .../components/husqvarna_automower/const.py | 4 ++++ .../components/husqvarna_automower/strings.json | 8 ++++++++ .../snapshots/test_event.ambr | 8 ++++++++ .../snapshots/test_sensor.ambr | 16 ++++++++++++++++ 4 files changed, 36 insertions(+) diff --git a/homeassistant/components/husqvarna_automower/const.py b/homeassistant/components/husqvarna_automower/const.py index 6e22504ae7b0..d430cffadc54 100644 --- a/homeassistant/components/husqvarna_automower/const.py +++ b/homeassistant/components/husqvarna_automower/const.py @@ -34,6 +34,8 @@ ERROR_KEYS = [ "bluetooth_communication_with_charging_station_failed", "bluetooth_settings_changed", "boundary_wire_problem", + "camera_lens_blocked", + "camera_lens_wet", "can_error", "cellular_settings_changed", "charging_aborted", @@ -120,6 +122,7 @@ ERROR_KEYS = [ "no_power_in_charging_station", "no_response_from_charger", "outside_working_area", + "partly_uncut_area", "pin_code_changed", "poor_signal_quality", "poor_vision_performance", @@ -132,6 +135,7 @@ ERROR_KEYS = [ "sim_card_locked", "sim_card_not_found", "sim_card_requires_pin", + "sitemap_changed", "slipped_mower_has_slipped_situation_not_solved_with_moving_pattern", "slope_too_steep", "sms_could_not_be_sent", diff --git a/homeassistant/components/husqvarna_automower/strings.json b/homeassistant/components/husqvarna_automower/strings.json index 3052d4321657..d204a7f2322b 100644 --- a/homeassistant/components/husqvarna_automower/strings.json +++ b/homeassistant/components/husqvarna_automower/strings.json @@ -70,6 +70,8 @@ "bluetooth_communication_with_charging_station_failed": "[%key:component::husqvarna_automower::entity::sensor::error::state::bluetooth_communication_with_charging_station_failed%]", "bluetooth_settings_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::bluetooth_settings_changed%]", "boundary_wire_problem": "[%key:component::husqvarna_automower::entity::sensor::error::state::boundary_wire_problem%]", + "camera_lens_blocked": "[%key:component::husqvarna_automower::entity::sensor::error::state::camera_lens_wet%]", + "camera_lens_wet": "[%key:component::husqvarna_automower::entity::sensor::error::state::camera_lens_wet%]", "can_error": "[%key:component::husqvarna_automower::entity::sensor::error::state::can_error%]", "cellular_settings_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::cellular_settings_changed%]", "charging_aborted": "[%key:component::husqvarna_automower::entity::sensor::error::state::charging_aborted%]", @@ -161,6 +163,7 @@ "no_response_from_charger": "[%key:component::husqvarna_automower::entity::sensor::error::state::no_response_from_charger%]", "off": "[%key:common::state::off%]", "outside_working_area": "[%key:component::husqvarna_automower::entity::sensor::error::state::outside_working_area%]", + "partly_uncut_area": "[%key:component::husqvarna_automower::entity::sensor::error::state::partly_uncut_area%]", "pin_code_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::pin_code_changed%]", "poor_signal_quality": "[%key:component::husqvarna_automower::entity::sensor::error::state::poor_signal_quality%]", "poor_vision_performance": "[%key:component::husqvarna_automower::entity::sensor::error::state::poor_vision_performance%]", @@ -173,6 +176,7 @@ "sim_card_locked": "[%key:component::husqvarna_automower::entity::sensor::error::state::sim_card_locked%]", "sim_card_not_found": "[%key:component::husqvarna_automower::entity::sensor::error::state::sim_card_not_found%]", "sim_card_requires_pin": "[%key:component::husqvarna_automower::entity::sensor::error::state::sim_card_requires_pin%]", + "sitemap_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::sitemap_changed%]", "slipped_mower_has_slipped_situation_not_solved_with_moving_pattern": "[%key:component::husqvarna_automower::entity::sensor::error::state::slipped_mower_has_slipped_situation_not_solved_with_moving_pattern%]", "slope_too_steep": "[%key:component::husqvarna_automower::entity::sensor::error::state::slope_too_steep%]", "sms_could_not_be_sent": "[%key:component::husqvarna_automower::entity::sensor::error::state::sms_could_not_be_sent%]", @@ -282,6 +286,8 @@ "bluetooth_communication_with_charging_station_failed": "Bluetooth communication with charging station failed", "bluetooth_settings_changed": "Bluetooth settings changed", "boundary_wire_problem": "Boundary wire problem", + "camera_lens_blocked": "Camera lens blocked", + "camera_lens_wet": "Camera lens wet", "can_error": "CAN error", "cellular_settings_changed": "Cellular settings changed", "charging_aborted": "Charging aborted", @@ -373,6 +379,7 @@ "no_response_from_charger": "No response from charger", "off": "[%key:common::state::off%]", "outside_working_area": "Outside working area", + "partly_uncut_area": "Partly uncut area", "pin_code_changed": "PIN code changed", "poor_signal_quality": "Poor signal quality", "poor_vision_performance": "Poor vision performance", @@ -385,6 +392,7 @@ "sim_card_locked": "SIM card locked", "sim_card_not_found": "SIM card not found", "sim_card_requires_pin": "SIM card requires PIN", + "sitemap_changed": "Sitemap changed", "slipped_mower_has_slipped_situation_not_solved_with_moving_pattern": "Slipped - Mower has Slipped. Situation not solved with moving pattern", "slope_too_steep": "Slope too steep", "sms_could_not_be_sent": "SMS could not be sent", diff --git a/tests/components/husqvarna_automower/snapshots/test_event.ambr b/tests/components/husqvarna_automower/snapshots/test_event.ambr index 3590edeb2bc3..0eb0e8ace6b6 100644 --- a/tests/components/husqvarna_automower/snapshots/test_event.ambr +++ b/tests/components/husqvarna_automower/snapshots/test_event.ambr @@ -23,6 +23,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -109,6 +111,7 @@ 'no_power_in_charging_station', 'no_response_from_charger', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -121,6 +124,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', @@ -217,6 +221,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -303,6 +309,7 @@ 'no_power_in_charging_station', 'no_response_from_charger', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -315,6 +322,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', diff --git a/tests/components/husqvarna_automower/snapshots/test_sensor.ambr b/tests/components/husqvarna_automower/snapshots/test_sensor.ambr index 10022a734804..a4c3e2d20e10 100644 --- a/tests/components/husqvarna_automower/snapshots/test_sensor.ambr +++ b/tests/components/husqvarna_automower/snapshots/test_sensor.ambr @@ -200,6 +200,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -291,6 +293,7 @@ 'no_response_from_charger', 'off', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -303,6 +306,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', @@ -402,6 +406,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -493,6 +499,7 @@ 'no_response_from_charger', 'off', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -505,6 +512,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', @@ -1729,6 +1737,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -1820,6 +1830,7 @@ 'no_response_from_charger', 'off', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -1832,6 +1843,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', @@ -1931,6 +1943,8 @@ 'bluetooth_communication_with_charging_station_failed', 'bluetooth_settings_changed', 'boundary_wire_problem', + 'camera_lens_blocked', + 'camera_lens_wet', 'can_error', 'cellular_settings_changed', 'charging_aborted', @@ -2022,6 +2036,7 @@ 'no_response_from_charger', 'off', 'outside_working_area', + 'partly_uncut_area', 'pin_code_changed', 'poor_signal_quality', 'poor_vision_performance', @@ -2034,6 +2049,7 @@ 'sim_card_locked', 'sim_card_not_found', 'sim_card_requires_pin', + 'sitemap_changed', 'slipped_mower_has_slipped_situation_not_solved_with_moving_pattern', 'slope_too_steep', 'sms_could_not_be_sent', From 3c64a1ed9e4997887a7fdb835eb08c9325879b8a Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:35:44 +0200 Subject: [PATCH 241/356] Fix Arve availability on failed updates (#185494) --- homeassistant/components/arve/entity.py | 2 +- tests/components/arve/test_sensor.py | 38 ++++++++++++++++++++++++- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/arve/entity.py b/homeassistant/components/arve/entity.py index 6d5d70dde692..a6af8de1ce64 100644 --- a/homeassistant/components/arve/entity.py +++ b/homeassistant/components/arve/entity.py @@ -44,7 +44,7 @@ class ArveDeviceEntity(CoordinatorEntity[ArveCoordinator]): @override def available(self) -> bool: """Check if device is available.""" - return super()._attr_available and ( + return super().available and ( self.device_serial_number in self.coordinator.data ) diff --git a/tests/components/arve/test_sensor.py b/tests/components/arve/test_sensor.py index 77711632c56a..41b10b80fe31 100644 --- a/tests/components/arve/test_sensor.py +++ b/tests/components/arve/test_sensor.py @@ -1,15 +1,19 @@ """Test for Arve sensors.""" +from datetime import timedelta from unittest.mock import MagicMock +from asyncarve import ArveConnectionError +from freezegun.api import FrozenDateTimeFactory from syrupy.assertion import SnapshotAssertion +from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from . import async_init_integration -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_fire_time_changed SENSORS = ( "air_quality_index", @@ -41,3 +45,35 @@ async def test_sensors( assert entry assert entry.device_id assert entry == snapshot(name=f"entry_{sensor}") + + +async def test_sensor_unavailable_on_update_failure( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_arve: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test the sensor becomes unavailable when the update fails.""" + entity_id = "sensor.test_sensor_temperature" + await async_init_integration(hass, mock_config_entry) + + assert (state := hass.states.get(entity_id)) + assert state.state == "26.02" + + mock_arve.get_devices.side_effect = ArveConnectionError + + freezer.tick(timedelta(seconds=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get(entity_id)) + assert state.state == STATE_UNAVAILABLE + + mock_arve.get_devices.side_effect = None + + freezer.tick(timedelta(seconds=60)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get(entity_id)) + assert state.state == "26.02" From 3644e39fcb3e490260147aac3a643675d4560c27 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:35:01 +0200 Subject: [PATCH 242/356] Fix EZVIZ availability on failed updates (#185497) --- homeassistant/components/ezviz/entity.py | 2 +- tests/components/ezviz/test_init.py | 40 +++++++++++++++++++++++- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/ezviz/entity.py b/homeassistant/components/ezviz/entity.py index 53ef875347c9..be9cbf659fd7 100644 --- a/homeassistant/components/ezviz/entity.py +++ b/homeassistant/components/ezviz/entity.py @@ -47,7 +47,7 @@ class EzvizEntity(CoordinatorEntity[EzvizDataUpdateCoordinator], Entity): @override def available(self) -> bool: """Return True if entity is available.""" - return self.data["status"] != 2 + return super().available and self.data["status"] != 2 class EzvizBaseEntity(Entity): diff --git a/tests/components/ezviz/test_init.py b/tests/components/ezviz/test_init.py index 856657f07ac9..9ff4337ddef1 100644 --- a/tests/components/ezviz/test_init.py +++ b/tests/components/ezviz/test_init.py @@ -4,11 +4,12 @@ from datetime import timedelta from unittest.mock import AsyncMock, Mock, patch from freezegun.api import FrozenDateTimeFactory +from pyezvizapi.exceptions import PyEzvizError import pytest from homeassistant.components import image from homeassistant.components.ezviz.const import ATTR_TYPE_CLOUD -from homeassistant.const import STATE_UNKNOWN +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -337,3 +338,40 @@ async def test_image_entity_keeps_last_alarm_pic_when_refresh_omits_it( state = hass.states.get("image.camera_1_last_motion_image") assert state is not None assert "last_alarm_pic" not in state.attributes + + +async def test_entity_unavailable_on_update_failure( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_ezviz_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test entities become unavailable when a coordinator update fails.""" + entity_id = "sensor.camera_1_battery" + mock_ezviz_client.load_cameras.return_value = { + "C123456789": _mock_camera_data(battery_level=85) + } + + await setup_integration(hass, mock_config_entry) + + state = hass.states.get(entity_id) + assert state is not None + assert state.state == "85" + + mock_ezviz_client.load_cameras.side_effect = PyEzvizError("Connection lost") + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + state = hass.states.get(entity_id) + assert state is not None + assert state.state == STATE_UNAVAILABLE + + mock_ezviz_client.load_cameras.side_effect = None + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + state = hass.states.get(entity_id) + assert state is not None + assert state.state == "85" From 7dcf2fe986a626e83df5787483da5f05dcfb32d7 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:34:21 +0200 Subject: [PATCH 243/356] Fix 17TRACK availability on failed updates (#185501) --- .../components/seventeentrack/sensor.py | 2 +- .../components/seventeentrack/test_sensor.py | 29 ++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/seventeentrack/sensor.py b/homeassistant/components/seventeentrack/sensor.py index b1411fcdc3af..6b6401752225 100644 --- a/homeassistant/components/seventeentrack/sensor.py +++ b/homeassistant/components/seventeentrack/sensor.py @@ -64,7 +64,7 @@ class SeventeenTrackSummarySensor(SeventeenTrackSensor): @override def available(self) -> bool: """Return whether the entity is available.""" - return self._status in self.coordinator.data.summary + return super().available and self._status in self.coordinator.data.summary @property @override diff --git a/tests/components/seventeentrack/test_sensor.py b/tests/components/seventeentrack/test_sensor.py index bac4691de3e1..d925e034d28b 100644 --- a/tests/components/seventeentrack/test_sensor.py +++ b/tests/components/seventeentrack/test_sensor.py @@ -2,15 +2,19 @@ from unittest.mock import AsyncMock +from freezegun.api import FrozenDateTimeFactory from pyseventeentrack.errors import SeventeenTrackError +from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant -from . import init_integration +from . import goto_future, init_integration from .conftest import DEFAULT_SUMMARY, get_package from tests.common import MockConfigEntry +IN_TRANSIT_ENTITY_ID = "sensor.17track_in_transit" + async def test_full_valid_config( hass: HomeAssistant, @@ -87,3 +91,26 @@ async def test_summary_error( assert ( hass.states.get("sensor.seventeentrack_packages_ready_to_be_picked_up") is None ) + + +async def test_summary_sensor_unavailable_on_failed_update( + hass: HomeAssistant, + mock_seventeentrack: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the summary sensors are unavailable while the update fails.""" + await init_integration(hass, mock_config_entry) + assert hass.states.get(IN_TRANSIT_ENTITY_ID).state == "0" + + mock_seventeentrack.return_value.profile.summary.side_effect = SeventeenTrackError( + "Error" + ) + await goto_future(hass, freezer) + + assert hass.states.get(IN_TRANSIT_ENTITY_ID).state == STATE_UNAVAILABLE + + mock_seventeentrack.return_value.profile.summary.side_effect = None + await goto_future(hass, freezer) + + assert hass.states.get(IN_TRANSIT_ENTITY_ID).state == "0" From 48d3ea055d0a6be889345378d0567cdfb6fbd00f Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:33:53 +0200 Subject: [PATCH 244/356] Fix Starlink availability on failed updates (#185502) --- homeassistant/components/starlink/time.py | 4 +- tests/components/starlink/test_time.py | 57 +++++++++++++++++++++++ 2 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 tests/components/starlink/test_time.py diff --git a/homeassistant/components/starlink/time.py b/homeassistant/components/starlink/time.py index ffeedb424083..4355b407e6e7 100644 --- a/homeassistant/components/starlink/time.py +++ b/homeassistant/components/starlink/time.py @@ -54,7 +54,9 @@ class StarlinkTimeEntity(StarlinkEntity, TimeEntity): @override def available(self) -> bool: """Return True if entity is available.""" - return self.entity_description.available_fn(self.coordinator.data) + return super().available and self.entity_description.available_fn( + self.coordinator.data + ) @override async def async_set_value(self, value: time) -> None: diff --git a/tests/components/starlink/test_time.py b/tests/components/starlink/test_time.py new file mode 100644 index 000000000000..9f37d66f84c3 --- /dev/null +++ b/tests/components/starlink/test_time.py @@ -0,0 +1,57 @@ +"""Tests Starlink time entities.""" + +from datetime import timedelta +from unittest.mock import patch + +from freezegun.api import FrozenDateTimeFactory +import pytest +from starlink_grpc import GrpcError + +from homeassistant.components.starlink.const import DOMAIN +from homeassistant.const import CONF_IP_ADDRESS, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant + +from .patchers import ( + HISTORY_STATS_SUCCESS_PATCHER, + LOCATION_DATA_SUCCESS_PATCHER, + STATUS_DATA_SUCCESS_PATCHER, +) + +from tests.common import MockConfigEntry, async_fire_time_changed + +ENTITY_ID = "time.starlink_sleep_start" +SLEEP_DATA_TARGET = "homeassistant.components.starlink.coordinator.get_sleep_config" + + +@pytest.mark.freeze_time("2026-06-01 12:00:00+00:00") +async def test_unavailable_on_update_failure( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Test the time entity is unavailable while the coordinator update fails.""" + entry = MockConfigEntry(domain=DOMAIN, data={CONF_IP_ADDRESS: "1.2.3.4:0000"}) + + with ( + LOCATION_DATA_SUCCESS_PATCHER, + STATUS_DATA_SUCCESS_PATCHER, + HISTORY_STATS_SUCCESS_PATCHER, + patch(SLEEP_DATA_TARGET, return_value=[0, 60, True]) as mock_sleep, + ): + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_ID).state == "17:00:00" + + mock_sleep.side_effect = GrpcError("error") + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + mock_sleep.side_effect = None + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == "17:00:00" From 1edc2a87b3c882e0b1e456d940266bdb9058da39 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:33:27 +0200 Subject: [PATCH 245/356] Fix Subaru availability on failed updates (#185503) --- .../components/subaru/device_tracker.py | 6 +-- .../components/subaru/test_device_tracker.py | 39 ++++++++++++++++++- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/subaru/device_tracker.py b/homeassistant/components/subaru/device_tracker.py index f31ac633893b..1cbc4e2e1310 100644 --- a/homeassistant/components/subaru/device_tracker.py +++ b/homeassistant/components/subaru/device_tracker.py @@ -65,8 +65,8 @@ class SubaruDeviceTracker(SubaruCoordinatorEntity, TrackerEntity): @property @override def available(self) -> bool: - """Return if available; not gated on last_update_success, only on the relevant status keys being present.""" - if not (vehicle_data := (self.coordinator.data or {}).get(self.vin)): + """Return if available and the location is known.""" + if not super().available: return False - status = vehicle_data.get(VEHICLE_STATUS) or {} + status = self.coordinator.data[self.vin].get(VEHICLE_STATUS) or {} return bool(status.keys() & {LATITUDE, LONGITUDE, TIMESTAMP}) diff --git a/tests/components/subaru/test_device_tracker.py b/tests/components/subaru/test_device_tracker.py index d4cb8e642f48..395f2af9b161 100644 --- a/tests/components/subaru/test_device_tracker.py +++ b/tests/components/subaru/test_device_tracker.py @@ -1,17 +1,29 @@ """Test Subaru device tracker.""" from copy import deepcopy +from datetime import timedelta from unittest.mock import patch +from freezegun.api import FrozenDateTimeFactory +import pytest +from subarulink import SubaruException from subarulink.const import LATITUDE, LONGITUDE, TIMESTAMP, VEHICLE_STATUS -from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE +from homeassistant.components.subaru.const import FETCH_INTERVAL +from homeassistant.const import ( + ATTR_LATITUDE, + ATTR_LONGITUDE, + STATE_NOT_HOME, + STATE_UNAVAILABLE, +) from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from .api_responses import EXPECTED_STATE_EV_IMPERIAL, VEHICLE_STATUS_EV from .conftest import MOCK_API_FETCH, MOCK_API_GET_DATA, advance_time_to_next_fetch +from tests.common import async_fire_time_changed + DEVICE_ID = "device_tracker.test_vehicle_2" @@ -56,3 +68,28 @@ async def test_device_tracker_missing_data(hass: HomeAssistant, ev_entry) -> Non actual = hass.states.get(DEVICE_ID) assert not actual.attributes.get(ATTR_LATITUDE) assert not actual.attributes.get(ATTR_LONGITUDE) + + +@pytest.mark.usefixtures("ev_entry") +async def test_device_tracker_unavailable_on_update_failure( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Test the device tracker is unavailable while the coordinator update fails.""" + assert hass.states.get(DEVICE_ID).state == STATE_NOT_HOME + + with patch(MOCK_API_FETCH, side_effect=SubaruException("error")): + freezer.tick(timedelta(seconds=FETCH_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(DEVICE_ID).state == STATE_UNAVAILABLE + + with ( + patch(MOCK_API_FETCH), + patch(MOCK_API_GET_DATA, return_value=VEHICLE_STATUS_EV), + ): + freezer.tick(timedelta(seconds=FETCH_INTERVAL)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(DEVICE_ID).state == STATE_NOT_HOME From 0927792c94703a7695012a918c8dcbf0e36224bb Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:33:07 +0200 Subject: [PATCH 246/356] Fix SUPLA availability on failed updates (#185504) --- CODEOWNERS | 1 + homeassistant/components/supla/entity.py | 2 +- tests/components/supla/__init__.py | 1 + tests/components/supla/test_switch.py | 64 ++++++++++++++++++++++++ 4 files changed, 67 insertions(+), 1 deletion(-) create mode 100644 tests/components/supla/__init__.py create mode 100644 tests/components/supla/test_switch.py diff --git a/CODEOWNERS b/CODEOWNERS index d2812c4f75a0..067c88d62962 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1825,6 +1825,7 @@ CLAUDE.md @home-assistant/core /homeassistant/components/sunsynk/ @jamesridgway /tests/components/sunsynk/ @jamesridgway /homeassistant/components/supla/ @mwegrzynek +/tests/components/supla/ @mwegrzynek /homeassistant/components/surepetcare/ @benleb @danielhiversen /tests/components/surepetcare/ @benleb @danielhiversen /homeassistant/components/swiss_hydrological_data/ @fabaff diff --git a/homeassistant/components/supla/entity.py b/homeassistant/components/supla/entity.py index 69be045529b3..20643d4d193c 100644 --- a/homeassistant/components/supla/entity.py +++ b/homeassistant/components/supla/entity.py @@ -43,7 +43,7 @@ class SuplaEntity(CoordinatorEntity[SuplaCoordinator]): @override def available(self) -> bool: """Return True if entity is available.""" - if self.channel_data is None: + if not super().available or self.channel_data is None: return False if (state := self.channel_data.get("state")) is None: return False diff --git a/tests/components/supla/__init__.py b/tests/components/supla/__init__.py new file mode 100644 index 000000000000..56c9f3f8a14d --- /dev/null +++ b/tests/components/supla/__init__.py @@ -0,0 +1 @@ +"""Tests for the SUPLA integration.""" diff --git a/tests/components/supla/test_switch.py b/tests/components/supla/test_switch.py new file mode 100644 index 000000000000..58ebc051a270 --- /dev/null +++ b/tests/components/supla/test_switch.py @@ -0,0 +1,64 @@ +"""Tests for the SUPLA switch platform.""" + +from datetime import timedelta +from unittest.mock import AsyncMock, patch + +from aiohttp import ClientError +from freezegun.api import FrozenDateTimeFactory + +from homeassistant.components.supla import DOMAIN +from homeassistant.const import CONF_ACCESS_TOKEN, STATE_ON, STATE_UNAVAILABLE +from homeassistant.core import HomeAssistant +from homeassistant.setup import async_setup_component + +from tests.common import async_fire_time_changed + +ENTITY_ID = "switch.living_room_light" +CHANNELS = [ + { + "id": 1, + "caption": "Living room light", + "channelNumber": 0, + "function": {"name": "LIGHTSWITCH"}, + "iodevice": {"gUIDString": "ABCDEF"}, + "state": {"connected": True, "on": True}, + } +] + + +async def test_unavailable_on_update_failure( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Test the switch is unavailable while the coordinator update fails.""" + with patch("homeassistant.components.supla.SuplaAPI") as mock_api_class: + api = mock_api_class.return_value + api.get_server_info = AsyncMock(return_value={"authenticated": True}) + api.get_channels = AsyncMock(return_value=CHANNELS) + assert await async_setup_component( + hass, + DOMAIN, + { + DOMAIN: { + "servers": [ + {"server": "svr1.supla.org", CONF_ACCESS_TOKEN: "token"} + ] + } + }, + ) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_ID).state == STATE_ON + + api.get_channels.side_effect = ClientError + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + api.get_channels.side_effect = None + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_ON From 64b3a4960e9b190a9e26591992708e2b81687300 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:32:35 +0200 Subject: [PATCH 247/356] Fix TOLO availability on failed updates (#185505) --- homeassistant/components/tolo/button.py | 3 +- tests/components/tolo/conftest.py | 31 +++++++++++++++ tests/components/tolo/test_button.py | 50 +++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 tests/components/tolo/conftest.py create mode 100644 tests/components/tolo/test_button.py diff --git a/homeassistant/components/tolo/button.py b/homeassistant/components/tolo/button.py index b263eabad31b..15e29cbf2a39 100644 --- a/homeassistant/components/tolo/button.py +++ b/homeassistant/components/tolo/button.py @@ -46,7 +46,8 @@ class ToloLampNextColorButton(ToloSaunaCoordinatorEntity, ButtonEntity): def available(self) -> bool: """Return if entity is available.""" return ( - self.coordinator.data.status.lamp_on + super().available + and self.coordinator.data.status.lamp_on and self.coordinator.data.settings.lamp_mode == LampMode.MANUAL ) diff --git a/tests/components/tolo/conftest.py b/tests/components/tolo/conftest.py new file mode 100644 index 000000000000..db4e522b4c8b --- /dev/null +++ b/tests/components/tolo/conftest.py @@ -0,0 +1,31 @@ +"""Fixtures for the TOLO Sauna tests.""" + +from collections.abc import Generator +from unittest.mock import MagicMock, patch + +import pytest +from tololib import LampMode + +from homeassistant.components.tolo.const import DOMAIN +from homeassistant.const import CONF_HOST + +from tests.common import MockConfigEntry + + +@pytest.fixture +def mock_config_entry() -> MockConfigEntry: + """Return a TOLO Sauna config entry.""" + return MockConfigEntry(domain=DOMAIN, data={CONF_HOST: "127.0.0.1"}) + + +@pytest.fixture +def mock_tolo_client() -> Generator[MagicMock]: + """Mock the TOLO client used by the coordinator.""" + with patch( + "homeassistant.components.tolo.coordinator.ToloClient", autospec=True + ) as client_class: + client = client_class.return_value + client.get_status.return_value = MagicMock(lamp_on=True) + client.get_status.return_value.model.name = "SAUNA" + client.get_settings.return_value = MagicMock(lamp_mode=LampMode.MANUAL) + yield client diff --git a/tests/components/tolo/test_button.py b/tests/components/tolo/test_button.py new file mode 100644 index 000000000000..cb8cf339a3a6 --- /dev/null +++ b/tests/components/tolo/test_button.py @@ -0,0 +1,50 @@ +"""Tests for the TOLO Sauna buttons.""" + +from collections.abc import Generator +from datetime import timedelta +from unittest.mock import MagicMock, patch + +from freezegun.api import FrozenDateTimeFactory +import pytest + +from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry, async_fire_time_changed + +ENTITY_ID = "button.tolo_sauna_next_color" + + +@pytest.fixture(autouse=True) +def button_platform_only() -> Generator[None]: + """Only set up the button platform.""" + with patch("homeassistant.components.tolo.PLATFORMS", [Platform.BUTTON]): + yield + + +async def test_button_unavailable_on_failed_update( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_tolo_client: MagicMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the button becomes unavailable when an update fails.""" + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN + + mock_tolo_client.get_status.side_effect = TimeoutError + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + mock_tolo_client.get_status.side_effect = None + freezer.tick(timedelta(seconds=5)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN From 7e8e133492d379091c0365a1bc560d42bc0e53c0 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:32:11 +0200 Subject: [PATCH 248/356] Fix Xbox availability on failed updates (#185506) --- homeassistant/components/xbox/entity.py | 5 +++- tests/components/xbox/test_media_player.py | 34 ++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/xbox/entity.py b/homeassistant/components/xbox/entity.py index 3ae6f95f78b6..f5c172828f81 100644 --- a/homeassistant/components/xbox/entity.py +++ b/homeassistant/components/xbox/entity.py @@ -153,7 +153,10 @@ class XboxConsoleBaseEntity(CoordinatorEntity[XboxConsoleStatusCoordinator]): @override def available(self) -> bool: """Return if entity is available.""" - return self.coordinator.data.get(self._console.id) is not None + return ( + super().available + and self.coordinator.data.get(self._console.id) is not None + ) @property @override diff --git a/tests/components/xbox/test_media_player.py b/tests/components/xbox/test_media_player.py index 4de5b061222e..f67bcb7ff56f 100644 --- a/tests/components/xbox/test_media_player.py +++ b/tests/components/xbox/test_media_player.py @@ -165,6 +165,40 @@ async def test_media_player_added_before_console_status( assert state.state != STATE_UNAVAILABLE +async def test_media_player_unavailable_on_failed_update( + hass: HomeAssistant, + config_entry: MockConfigEntry, + xbox_live_client: AsyncMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the media player becomes unavailable when a status update fails.""" + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("media_player.xonex")) is not None + assert state.state != STATE_UNAVAILABLE + + xbox_live_client.smartglass.get_console_status.side_effect = TimeoutException( + "timeout" + ) + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get("media_player.xonex")) is not None + assert state.state == STATE_UNAVAILABLE + + xbox_live_client.smartglass.get_console_status.side_effect = None + freezer.tick(timedelta(seconds=10)) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get("media_player.xonex")) is not None + assert state.state != STATE_UNAVAILABLE + + @pytest.mark.usefixtures("xbox_live_client") async def test_browse_media( hass: HomeAssistant, From f92afa5a353cf6ccef2f5568555293772c3c7d9c Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 9 Oct 2026 17:51:51 +0200 Subject: [PATCH 249/356] Fix Yardian availability on failed updates (#185507) --- homeassistant/components/yardian/switch.py | 4 ++- tests/components/yardian/test_switch.py | 37 +++++++++++++++++++++- 2 files changed, 39 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/yardian/switch.py b/homeassistant/components/yardian/switch.py index 540497431b6c..596e49003e7c 100644 --- a/homeassistant/components/yardian/switch.py +++ b/homeassistant/components/yardian/switch.py @@ -68,7 +68,9 @@ class YardianSwitch(YardianZoneEntity, SwitchEntity): @override def available(self) -> bool: """Return the switch is available or not.""" - return self.coordinator.data.zones[self._zone_id].is_enabled + return ( + super().available and self.coordinator.data.zones[self._zone_id].is_enabled + ) @override async def async_turn_on(self, **kwargs: Any) -> None: diff --git a/tests/components/yardian/test_switch.py b/tests/components/yardian/test_switch.py index f71d1b0d246a..bc240d34c7de 100644 --- a/tests/components/yardian/test_switch.py +++ b/tests/components/yardian/test_switch.py @@ -2,13 +2,19 @@ from unittest.mock import AsyncMock, patch +from freezegun.api import FrozenDateTimeFactory +import pytest +from pyyardian import NetworkException from syrupy.assertion import SnapshotAssertion from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN +from homeassistant.components.yardian.coordinator import SCAN_INTERVAL from homeassistant.const import ( ATTR_ENTITY_ID, SERVICE_TURN_OFF, SERVICE_TURN_ON, + STATE_ON, + STATE_UNAVAILABLE, Platform, ) from homeassistant.core import HomeAssistant @@ -16,7 +22,7 @@ from homeassistant.helpers import entity_registry as er from . import setup_integration -from tests.common import MockConfigEntry, snapshot_platform +from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform async def test_all_entities( @@ -69,3 +75,32 @@ async def test_turn_off_switch( blocking=True, ) mock_yardian_client.stop_zone.assert_called_once() + + +@pytest.mark.usefixtures("switch_platform_only") +async def test_switch_unavailable_on_failed_update( + hass: HomeAssistant, + mock_yardian_client: AsyncMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test a switch becomes unavailable when an update fails.""" + await setup_integration(hass, mock_config_entry) + + entity_id = "switch.zone_1" + + assert hass.states.get(entity_id).state == STATE_ON + + mock_yardian_client.fetch_device_state.side_effect = NetworkException + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(entity_id).state == STATE_UNAVAILABLE + + mock_yardian_client.fetch_device_state.side_effect = None + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(entity_id).state == STATE_ON From 2f7a4dc16bb8a811547377bdddef8440b8963102 Mon Sep 17 00:00:00 2001 From: tronikos Date: Fri, 9 Oct 2026 09:48:14 -0700 Subject: [PATCH 250/356] Give SolarEdge Modbus reads a 30 s timeout (#185518) --- .../components/solaredge_modbus/__init__.py | 4 +++ .../components/solaredge_modbus/const.py | 6 ++++ .../components/solaredge_modbus/test_init.py | 28 +++++++++++++++++++ 3 files changed, 38 insertions(+) diff --git a/homeassistant/components/solaredge_modbus/__init__.py b/homeassistant/components/solaredge_modbus/__init__.py index e7c93a33a3d5..73c33942f14c 100644 --- a/homeassistant/components/solaredge_modbus/__init__.py +++ b/homeassistant/components/solaredge_modbus/__init__.py @@ -37,6 +37,7 @@ from .const import ( DISCOVERY_SUBSYSTEMS, DOMAIN, LOGGER, + READ_TIMEOUT, SCAN_INTERVAL, SETTINGS_SCAN_INTERVAL, SUBSYSTEM_BATTERIES, @@ -106,6 +107,9 @@ async def async_setup_entry( translation_key="no_solaredge_device", ) from err + # Only now: the probe gives up on a silent block after the link's default. + unit.require_timeout(READ_TIMEOUT) + readings = SolarEdgeModbusDataUpdateCoordinator( hass, entry, diff --git a/homeassistant/components/solaredge_modbus/const.py b/homeassistant/components/solaredge_modbus/const.py index 6e18ebca4e98..11c87a188955 100644 --- a/homeassistant/components/solaredge_modbus/const.py +++ b/homeassistant/components/solaredge_modbus/const.py @@ -51,6 +51,12 @@ SUBSYSTEM_ADVANCED_POWER_CONTROL: Final = "advanced_power_control" SUBSYSTEM_POWER_CONTROL: Final = "power_control" SUBSYSTEM_SITE_CONTROL: Final = "site_control" +# How long a request may take once the inverter's blocks are known. Over Wi-Fi +# a SolarEdge inverter answers some requests well past the link's default 10 s, +# and one late answer fails the whole poll. Probing keeps the default: a block +# the inverter never answers costs a full timeout there. +READ_TIMEOUT: Final = 30 + # Local Modbus is cheap to read and PV production moves fast. SCAN_INTERVAL: Final = timedelta(seconds=10) diff --git a/tests/components/solaredge_modbus/test_init.py b/tests/components/solaredge_modbus/test_init.py index 890b8d37853e..eefd52da7ce8 100644 --- a/tests/components/solaredge_modbus/test_init.py +++ b/tests/components/solaredge_modbus/test_init.py @@ -23,6 +23,7 @@ from homeassistant.components.solaredge_modbus.const import ( ATTACHMENT_SCAN_INTERVAL, CONF_SILENT_BLOCKS, DOMAIN, + READ_TIMEOUT, SCAN_INTERVAL, SETTINGS_SCAN_INTERVAL, ) @@ -1276,3 +1277,30 @@ async def test_only_a_block_a_check_reloads_for_is_kept( await _tick_attachment_check(hass, freezer) assert mock_config_entry.data[CONF_SILENT_BLOCKS] == ["power_control"] + + +async def test_reads_wait_longer_than_the_probe( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_modbus_unit: MockModbusUnit, +) -> None: + """Polls get a longer timeout, the probe keeps the link's default. + + Over Wi-Fi some answers come late, and one late answer fails a whole poll. + The probe waits out a full timeout for every block the inverter never + answers, so raising it there would only make setting up slower. + """ + during_probe: list[float | None] = [] + probe = SolarEdge.async_probe + + async def recording_probe( + unit: ModbusUnit, *, assume_absent: frozenset[str] = frozenset() + ) -> SolarEdge: + during_probe.append(mock_modbus_unit.required_timeout) + return await probe(unit, assume_absent=assume_absent) + + with patch.object(SolarEdge, "async_probe", recording_probe): + await _setup(hass, mock_config_entry) + + assert during_probe == [None] + assert mock_modbus_unit.required_timeout == READ_TIMEOUT From 3a4e28d88d37d3d44c4ad640a1322f0bc2d7c084 Mon Sep 17 00:00:00 2001 From: Thomas55555 <59625598+Thomas55555@users.noreply.github.com> Date: Fri, 9 Oct 2026 20:35:43 +0200 Subject: [PATCH 251/356] Fix typo in Husqvarna Automower (#185532) --- homeassistant/components/husqvarna_automower/strings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/homeassistant/components/husqvarna_automower/strings.json b/homeassistant/components/husqvarna_automower/strings.json index d204a7f2322b..644e63bdb0f9 100644 --- a/homeassistant/components/husqvarna_automower/strings.json +++ b/homeassistant/components/husqvarna_automower/strings.json @@ -70,7 +70,7 @@ "bluetooth_communication_with_charging_station_failed": "[%key:component::husqvarna_automower::entity::sensor::error::state::bluetooth_communication_with_charging_station_failed%]", "bluetooth_settings_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::bluetooth_settings_changed%]", "boundary_wire_problem": "[%key:component::husqvarna_automower::entity::sensor::error::state::boundary_wire_problem%]", - "camera_lens_blocked": "[%key:component::husqvarna_automower::entity::sensor::error::state::camera_lens_wet%]", + "camera_lens_blocked": "[%key:component::husqvarna_automower::entity::sensor::error::state::camera_lens_blocked%]", "camera_lens_wet": "[%key:component::husqvarna_automower::entity::sensor::error::state::camera_lens_wet%]", "can_error": "[%key:component::husqvarna_automower::entity::sensor::error::state::can_error%]", "cellular_settings_changed": "[%key:component::husqvarna_automower::entity::sensor::error::state::cellular_settings_changed%]", From 77a58c97dbf7326f7600c03124e03d62447df6ca Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Fri, 9 Oct 2026 22:05:33 +0200 Subject: [PATCH 252/356] Revert "Resolve integration brand images before brand images" (#185535) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/brands/__init__.py | 15 +-- tests/components/brands/test_init.py | 123 +++----------------- 2 files changed, 21 insertions(+), 117 deletions(-) diff --git a/homeassistant/components/brands/__init__.py b/homeassistant/components/brands/__init__.py index 544c2440bf4e..f47587fd92e9 100644 --- a/homeassistant/components/brands/__init__.py +++ b/homeassistant/components/brands/__init__.py @@ -266,21 +266,10 @@ class BrandsIntegrationView(_BrandsBaseView): ) is not None: return response - # 2. Try the integration image. Direct paths are used instead of the - # "_/" namespace so real 404s can be cached as markers. - if ( - data := await self._get_image_data( - cdn_path=f"{domain}/{image}", - cache_subpath=f"integrations/{domain}/{image}", - ) - ) is not None: - return self._build_response(data) - - # 3. Fall back to the brand image, which is cached separately so the - # integration 404 marker is preserved. + # 2. Try cache / CDN (always use direct path for proper 404 caching) return await self._serve_from_cache_or_cdn( cdn_path=f"brands/{domain}/{image}", - cache_subpath=f"brands/{domain}/{image}", + cache_subpath=f"integrations/{domain}/{image}", fallback_placeholder=use_placeholder, ) diff --git a/tests/components/brands/test_init.py b/tests/components/brands/test_init.py index 6eb4ccebd7e1..613194ce626f 100644 --- a/tests/components/brands/test_init.py +++ b/tests/components/brands/test_init.py @@ -74,7 +74,7 @@ async def test_integration_view_serves_from_cdn( ) -> None: """Test serving an integration brand image from the CDN.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) @@ -86,68 +86,12 @@ async def test_integration_view_serves_from_cdn( assert await resp.read() == FAKE_PNG -async def test_integration_view_prefers_integration_over_brand( - hass: HomeAssistant, - hass_client: ClientSessionGenerator, - aioclient_mock: AiohttpClientMocker, -) -> None: - """Test that the integration image wins over a brand image of the same name.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/google/icon.png", - content=FAKE_PNG, - ) - aioclient_mock.get( - f"{BRANDS_CDN_URL}/brands/google/icon.png", - content=BRAND_PNG, - ) - - client = await hass_client() - resp = await client.get("/api/brands/integration/google/icon.png") - - assert resp.status == HTTPStatus.OK - assert await resp.read() == FAKE_PNG - assert aioclient_mock.call_count == 1 - - -async def test_integration_view_falls_back_to_brand( - hass: HomeAssistant, - hass_client: ClientSessionGenerator, - aioclient_mock: AiohttpClientMocker, -) -> None: - """Test that a brand-only domain is served from the brand namespace.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/apple/icon.png", - status=HTTPStatus.NOT_FOUND, - ) - aioclient_mock.get( - f"{BRANDS_CDN_URL}/brands/apple/icon.png", - content=BRAND_PNG, - ) - - client = await hass_client() - resp = await client.get("/api/brands/integration/apple/icon.png") - - assert resp.status == HTTPStatus.OK - assert await resp.read() == BRAND_PNG - assert aioclient_mock.call_count == 2 - - # The integration 404 marker and the brand image are cached separately - resp = await client.get("/api/brands/integration/apple/icon.png") - assert resp.status == HTTPStatus.OK - assert await resp.read() == BRAND_PNG - assert aioclient_mock.call_count == 2 - - async def test_integration_view_default_placeholder_fallback( hass: HomeAssistant, hass_client: ClientSessionGenerator, aioclient_mock: AiohttpClientMocker, ) -> None: """Test that CDN 404 serves placeholder by default.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/nonexistent/icon.png", - status=HTTPStatus.NOT_FOUND, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/nonexistent/icon.png", status=HTTPStatus.NOT_FOUND, @@ -170,10 +114,6 @@ async def test_integration_view_no_placeholder( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that CDN 404 returns 404 when placeholder=no is set.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/nonexistent/icon.png", - status=HTTPStatus.NOT_FOUND, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/nonexistent/icon.png", status=HTTPStatus.NOT_FOUND, @@ -248,7 +188,7 @@ async def test_integration_view_all_allowed_images( ] for image in allowed: aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/{image}", + f"{BRANDS_CDN_URL}/brands/hue/{image}", content=FAKE_PNG, ) @@ -264,10 +204,6 @@ async def test_integration_view_cdn_error_returns_none( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that CDN connection errors result in 404 with placeholder=no.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/broken/icon.png", - exc=ClientError(), - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/broken/icon.png", exc=ClientError(), @@ -285,10 +221,6 @@ async def test_integration_view_cdn_unexpected_status( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that unexpected CDN status codes result in 404 with placeholder=no.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/broken/icon.png", - status=HTTPStatus.INTERNAL_SERVER_ERROR, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/broken/icon.png", status=HTTPStatus.INTERNAL_SERVER_ERROR, @@ -312,7 +244,7 @@ async def test_disk_cache_hit( ) -> None: """Test that a second request is served from disk cache.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) @@ -336,10 +268,6 @@ async def test_disk_cache_404_marker( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that 404s are cached as empty files.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/nothing/icon.png", - status=HTTPStatus.NOT_FOUND, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/nothing/icon.png", status=HTTPStatus.NOT_FOUND, @@ -347,16 +275,15 @@ async def test_disk_cache_404_marker( client = await hass_client() - # First request: CDN returns 404 for both namespaces, each cached as an - # empty file + # First request: CDN returns 404, cached as empty file resp = await client.get("/api/brands/integration/nothing/icon.png?placeholder=no") assert resp.status == HTTPStatus.NOT_FOUND - assert aioclient_mock.call_count == 2 + assert aioclient_mock.call_count == 1 - # Second request: served from cached 404 markers + # Second request: served from cached 404 marker resp = await client.get("/api/brands/integration/nothing/icon.png?placeholder=no") assert resp.status == HTTPStatus.NOT_FOUND - assert aioclient_mock.call_count == 2 # No additional CDN call + assert aioclient_mock.call_count == 1 # No additional CDN call async def test_stale_cache_triggers_background_refresh( @@ -366,7 +293,7 @@ async def test_stale_cache_triggers_background_refresh( ) -> None: """Test that stale cache entries trigger background refresh.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) @@ -404,10 +331,6 @@ async def test_stale_cache_404_marker_with_placeholder( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that stale cached 404 serves placeholder by default.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/gone/icon.png", - status=HTTPStatus.NOT_FOUND, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/gone/icon.png", status=HTTPStatus.NOT_FOUND, @@ -422,7 +345,7 @@ async def test_stale_cache_404_marker_with_placeholder( # First request caches the 404 (with placeholder=no) resp = await client.get("/api/brands/integration/gone/icon.png?placeholder=no") assert resp.status == HTTPStatus.NOT_FOUND - assert aioclient_mock.call_count == 2 + assert aioclient_mock.call_count == 1 # Make the cache stale cache_path = ( @@ -444,10 +367,6 @@ async def test_stale_cache_404_marker_no_placeholder( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that stale cached 404 with placeholder=no returns 404.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/gone/icon.png", - status=HTTPStatus.NOT_FOUND, - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/gone/icon.png", status=HTTPStatus.NOT_FOUND, @@ -458,7 +377,7 @@ async def test_stale_cache_404_marker_no_placeholder( # First request caches the 404 resp = await client.get("/api/brands/integration/gone/icon.png?placeholder=no") assert resp.status == HTTPStatus.NOT_FOUND - assert aioclient_mock.call_count == 2 + assert aioclient_mock.call_count == 1 # Make the cache stale cache_path = ( @@ -472,9 +391,9 @@ async def test_stale_cache_404_marker_no_placeholder( resp = await client.get("/api/brands/integration/gone/icon.png?placeholder=no") assert resp.status == HTTPStatus.NOT_FOUND - # Background refresh should have been triggered for the stale marker + # Background refresh should have been triggered await hass.async_block_till_done() - assert aioclient_mock.call_count == 3 + assert aioclient_mock.call_count == 2 # ------------------------------------------------------------------ @@ -517,7 +436,7 @@ async def test_custom_integration_no_brand_falls_through( custom = _create_custom_integration(hass, "my_custom", has_branding=False) aioclient_mock.get( - f"{BRANDS_CDN_URL}/my_custom/icon.png", + f"{BRANDS_CDN_URL}/brands/my_custom/icon.png", content=FAKE_PNG, ) @@ -545,7 +464,7 @@ async def test_custom_integration_brand_missing_file_falls_through( brand_dir.mkdir(parents=True, exist_ok=True) aioclient_mock.get( - f"{BRANDS_CDN_URL}/my_custom/icon.png", + f"{BRANDS_CDN_URL}/brands/my_custom/icon.png", content=FAKE_PNG, ) @@ -570,7 +489,7 @@ async def test_custom_integration_takes_priority_over_cache( # Prime the CDN cache first aioclient_mock.get( - f"{BRANDS_CDN_URL}/my_custom/icon.png", + f"{BRANDS_CDN_URL}/brands/my_custom/icon.png", content=FAKE_PNG, ) @@ -754,7 +673,7 @@ async def test_custom_integration_no_fallback_match_falls_through_to_cdn( # brand dir exists but is empty - no icon.png either aioclient_mock.get( - f"{BRANDS_CDN_URL}/my_custom/icon.png", + f"{BRANDS_CDN_URL}/brands/my_custom/icon.png", content=FAKE_PNG, ) @@ -839,10 +758,6 @@ async def test_cdn_timeout_returns_404( aioclient_mock: AiohttpClientMocker, ) -> None: """Test that CDN timeout results in 404 with placeholder=no.""" - aioclient_mock.get( - f"{BRANDS_CDN_URL}/slow/icon.png", - exc=TimeoutError(), - ) aioclient_mock.get( f"{BRANDS_CDN_URL}/brands/slow/icon.png", exc=TimeoutError(), @@ -866,7 +781,7 @@ async def test_authenticated_request( ) -> None: """Test that authenticated requests succeed.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) @@ -883,7 +798,7 @@ async def test_token_query_param_authentication( ) -> None: """Test that a valid access token in query param authenticates.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) @@ -943,7 +858,7 @@ async def test_token_rotation( ) -> None: """Test that access tokens rotate over time.""" aioclient_mock.get( - f"{BRANDS_CDN_URL}/hue/icon.png", + f"{BRANDS_CDN_URL}/brands/hue/icon.png", content=FAKE_PNG, ) From e5c75b6a98a1f26acdee12347e9ea6f5ae03af33 Mon Sep 17 00:00:00 2001 From: Balloob Bot Date: Fri, 9 Oct 2026 16:00:14 -0400 Subject: [PATCH 253/356] Allow dynamic ports for registered loopback OAuth redirects (#185544) Co-authored-by: Paulus Schoutsen --- homeassistant/components/auth/indieauth.py | 63 +++++-- homeassistant/components/auth/login_flow.py | 9 +- tests/components/auth/test_indieauth.py | 190 ++++++++++++++++++++ tests/components/auth/test_init.py | 128 ++++++++++++- 4 files changed, 374 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/auth/indieauth.py b/homeassistant/components/auth/indieauth.py index e16e9eef8afe..3ceba6481bf3 100644 --- a/homeassistant/components/auth/indieauth.py +++ b/homeassistant/components/auth/indieauth.py @@ -21,9 +21,13 @@ MAX_FETCH_BYTES = 10240 async def verify_redirect_uri( - hass: HomeAssistant, client_id: str, redirect_uri: str + hass: HomeAssistant, + client_id: str, + redirect_uri: str, + *, + allow_loopback_port_change: bool = False, ) -> bool: - """Verify that the client and redirect uri match.""" + """Verify the redirect URI, allowing loopback port changes only with PKCE.""" try: client_id_parts = _parse_client_id(client_id) except ValueError: @@ -63,6 +67,16 @@ async def verify_redirect_uri( redirect_uris = await fetch_redirect_uris(hass, client_id) if redirect_uri in redirect_uris: return True + # RFC 8252 requires PKCE for native clients choosing a loopback callback port. + if ( + allow_loopback_port_change + and (loopback_uri := _without_loopback_port(redirect_uri)) is not None + and any( + _without_loopback_port(registered_uri) == loopback_uri + for registered_uri in redirect_uris + ) + ): + return True _LOGGER.debug( "redirect_uri %s is not among the advertised redirect uris %s for client_id %s", redirect_uri, @@ -72,6 +86,36 @@ async def verify_redirect_uri( return False +def _without_loopback_port(uri: str) -> str | None: + """Remove only the port from an HTTP loopback redirect URI.""" + try: + parts = urlparse(uri) + port = parts.port + except ValueError: + return None + + if ( + parts.scheme != "http" + or parts.hostname not in ("127.0.0.1", "::1", "localhost") + or parts.username is not None + or "#" in uri + or port == 0 + ): + return None + + # urlparse lowercases the scheme, but only the port may differ. + scheme = uri[: len(parts.scheme)] + prefix = f"{scheme}://{parts.netloc}" + if not uri.startswith(prefix): + return None + if port is None: + return uri + + # Preserve the original spelling, path and query, including an empty query. + host = parts.netloc.rsplit(":", 1)[0] + return f"{scheme}://{host}{uri[len(prefix) :]}" + + class LinkTagParser(HTMLParser): """Parser to find link tags.""" @@ -199,10 +243,7 @@ def _parse_link_tag_redirect_uris(url: str, body: bytes) -> list[str]: parser = LinkTagParser("redirect_uri") parser.feed(body.decode(errors="replace")) - # Authorization endpoints verifying that a redirect_uri is allowed for use - # by a client MUST look for an exact match of the given redirect_uri in the - # request against the list of redirect_uris discovered after resolving any - # relative URLs. + # Resolve relative URLs before comparing registered redirect URIs. return [urljoin(url, found) for found in parser.found] @@ -214,10 +255,9 @@ def _parse_metadata_document_redirect_uris( Per draft-ietf-oauth-client-id-metadata-document the document only counts when the client_id URL is https with a path and no fragment, the response was a direct 200 (not redirected), the document's client_id round-trips, - and every redirect_uris entry is an absolute, fragment-free URI matched - exactly. The url and its document are client-controlled and fetched - unauthenticated, so rejections log at DEBUG (higher levels would be a - log-flood vector). + and every redirect_uris entry is an absolute, fragment-free URI. The url + and its document are client-controlled and fetched unauthenticated, so + rejections log at DEBUG (higher levels would be a log-flood vector). """ # A body at the read cap may be truncated; a truncated prefix must not be # trusted even if it happens to be parseable. @@ -261,8 +301,7 @@ def _parse_metadata_document_redirect_uris( ) return [] - # redirect_uris entries are returned unmodified for RFC 6749 exact matching - # rather than resolving relative references. + # Return entries unmodified; redirect verification handles loopback ports. redirect_uris = document.get("redirect_uris") if not isinstance(redirect_uris, list) or not all( isinstance(redirect_uri, str) and _is_valid_metadata_redirect_uri(redirect_uri) diff --git a/homeassistant/components/auth/login_flow.py b/homeassistant/components/auth/login_flow.py index b5134ce5205c..3f82756e2f5b 100644 --- a/homeassistant/components/auth/login_flow.py +++ b/homeassistant/components/auth/login_flow.py @@ -308,13 +308,18 @@ class LoginFlowBaseView(HomeAssistantView): hass = request.app[KEY_HASS] + context = result["context"] if not await indieauth.verify_redirect_uri( - hass, client_id, result["context"]["redirect_uri"] + hass, + client_id, + context["redirect_uri"], + allow_loopback_port_change=bool(context.get("code_challenge")) + and context.get("code_challenge_method") == "S256", ): return self.json_message("Invalid redirect URI", HTTPStatus.FORBIDDEN) result.pop("data") - context = result.pop("context") + result.pop("context") result_obj = result.pop("result") diff --git a/tests/components/auth/test_indieauth.py b/tests/components/auth/test_indieauth.py index 653a6b60f3fd..104b8d126207 100644 --- a/tests/components/auth/test_indieauth.py +++ b/tests/components/auth/test_indieauth.py @@ -412,6 +412,196 @@ async def test_verify_redirect_uri_unparsable(hass: HomeAssistant) -> None: ) +@pytest.mark.parametrize( + ("client_id", "registered_uri", "redirect_uri"), + [ + pytest.param( + "https://chatgpt.com/oauth/codex/example/client.json", + "http://127.0.0.1/callback/example", + "http://127.0.0.1:37545/callback/example", + id="codex", + ), + pytest.param( + "https://claude.ai/oauth/claude-code-client-metadata", + "http://localhost/callback", + "http://localhost:59019/callback", + id="claude-code", + ), + pytest.param( + "https://example.com/client", + "http://[::1]/callback", + "http://[::1]:12345/callback", + id="ipv6", + ), + pytest.param( + "https://example.com/client", + "http://127.0.0.1:12345/callback?client=example", + "http://127.0.0.1:54321/callback?client=example", + id="registered-port-and-query", + ), + pytest.param( + "https://example.com/client", + "HTTP://localhost/callback", + "HTTP://localhost:12345/callback", + id="uppercase-scheme", + ), + pytest.param( + "https://example.com/client", + "HtTp://localhost:12345/callback", + "HtTp://localhost:54321/callback", + id="mixed-case-scheme", + ), + ], +) +async def test_verify_redirect_uri_metadata_loopback( + hass: HomeAssistant, + mock_session: AiohttpClientMocker, + client_id: str, + registered_uri: str, + redirect_uri: str, +) -> None: + """Allow native clients to choose the port of a registered loopback callback.""" + mock_session.get( + client_id, + json={"client_id": client_id, "redirect_uris": [registered_uri]}, + ) + + assert not await indieauth.verify_redirect_uri(hass, client_id, redirect_uri) + assert await indieauth.verify_redirect_uri( + hass, client_id, redirect_uri, allow_loopback_port_change=True + ) + + +@pytest.mark.parametrize( + ("registered_uri", "redirect_uri"), + [ + pytest.param( + "http://localhost/callback", "http://localhost:12345/other", id="path" + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/callback?other=1", + id="query", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/callback?", + id="empty-query", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/callback#", + id="fragment", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/call%62ack", + id="encoding", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/call\nback", + id="newline", + ), + pytest.param( + "http://localhost/callback", + " http://localhost:12345/callback", + id="leading-space", + ), + pytest.param( + "http://localhost/callback", + "http://local\nhost:12345/callback", + id="host-newline", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:12345/Callback", + id="path-case", + ), + pytest.param( + "http://localhost/callback", "https://localhost:12345/callback", id="scheme" + ), + pytest.param( + "http://localhost/callback", + "HTTP://localhost:12345/callback", + id="requested-scheme-case-differs", + ), + pytest.param( + "HTTP://localhost/callback", + "http://localhost:12345/callback", + id="registered-scheme-case-differs", + ), + pytest.param( + "http://localhost/callback", + "http://127.0.0.1:12345/callback", + id="different-loopback-host", + ), + pytest.param( + "http://localhost/callback", + "http://localhost.example.com:12345/callback", + id="hostname-suffix", + ), + pytest.param( + "http://localhost/callback", + "http://user@localhost:12345/callback", + id="userinfo", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:invalid/callback", + id="invalid-port", + ), + pytest.param( + "http://localhost/callback", + "http://localhost:65536/callback", + id="port-out-of-range", + ), + pytest.param( + "http://localhost/callback", "http://localhost:0/callback", id="zero-port" + ), + pytest.param( + "http://localhost/callback", "http://localhost:/callback", id="empty-port" + ), + pytest.param( + "https://localhost/callback", + "https://localhost:12345/callback", + id="https-loopback", + ), + pytest.param( + "http://192.168.1.1/callback", + "http://192.168.1.1:12345/callback", + id="private-ip", + ), + pytest.param( + "http://other.com/callback", + "http://other.com:12345/callback", + id="remote-host", + ), + pytest.param( + "http://[::1]/callback", + "http://[::2]:12345/callback", + id="non-loopback-ipv6", + ), + ], +) +async def test_verify_redirect_uri_metadata_loopback_rejected( + hass: HomeAssistant, + mock_session: AiohttpClientMocker, + registered_uri: str, + redirect_uri: str, +) -> None: + """Only the port of an HTTP loopback callback may differ.""" + client_id = "https://example.com/client" + mock_session.get( + client_id, + json={"client_id": client_id, "redirect_uris": [registered_uri]}, + ) + + assert not await indieauth.verify_redirect_uri( + hass, client_id, redirect_uri, allow_loopback_port_change=True + ) + + async def test_fetch_redirect_uris_metadata_document_invalid_utf8( hass: HomeAssistant, mock_session: AiohttpClientMocker ) -> None: diff --git a/tests/components/auth/test_init.py b/tests/components/auth/test_init.py index 142d7a57827e..66c434aef3c6 100644 --- a/tests/components/auth/test_init.py +++ b/tests/components/auth/test_init.py @@ -772,13 +772,16 @@ RFC7636_CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM" async def _async_login_for_code( - client: TestClient, code_challenge: str | None = None + client: TestClient, + code_challenge: str | None = None, + *, + redirect_uri: str = CLIENT_REDIRECT_URI, ) -> str: """Run the login flow and return the authorization code.""" payload: dict[str, Any] = { "client_id": CLIENT_ID, "handler": ["insecure_example", None], - "redirect_uri": CLIENT_REDIRECT_URI, + "redirect_uri": redirect_uri, } if code_challenge is not None: payload["code_challenge"] = code_challenge @@ -800,6 +803,127 @@ async def _async_login_for_code( return step["result"] +async def test_loopback_port_change_requires_pkce( + hass: HomeAssistant, aiohttp_client: ClientSessionGenerator +) -> None: + """Do not issue a code for a changed loopback port without stored PKCE.""" + client = await async_setup_auth(hass, aiohttp_client, setup_api=True) + resp = await client.post( + "/auth/login_flow", + json={ + "client_id": CLIENT_ID, + "handler": ["insecure_example", None], + "redirect_uri": "http://localhost:59019/callback", + }, + ) + assert resp.status == HTTPStatus.OK + step = await resp.json() + + with patch( + "homeassistant.components.auth.indieauth.fetch_redirect_uris", + return_value=["http://localhost/callback"], + ): + resp = await client.post( + f"/auth/login_flow/{step['flow_id']}", + json={ + "client_id": CLIENT_ID, + "username": "test-user", + "password": "test-pass", + }, + ) + + assert resp.status == HTTPStatus.FORBIDDEN + assert (await resp.json())["message"] == "Invalid redirect URI" + + +@pytest.mark.parametrize( + ("code_challenge", "registered_uri", "token_parameters"), + [ + pytest.param( + RFC7636_CHALLENGE, + "http://localhost/callback", + {"code_verifier": RFC7636_VERIFIER}, + id="changed-port-with-pkce", + ), + pytest.param( + None, + "http://localhost:59019/callback", + {}, + id="exact-match-without-pkce", + ), + ], +) +async def test_loopback_auth_code_success( + hass: HomeAssistant, + aiohttp_client: ClientSessionGenerator, + code_challenge: str | None, + registered_uri: str, + token_parameters: dict[str, str], +) -> None: + """Exchange a code for an allowed loopback callback.""" + client = await async_setup_auth(hass, aiohttp_client, setup_api=True) + with patch( + "homeassistant.components.auth.indieauth.fetch_redirect_uris", + return_value=[registered_uri], + ): + code = await _async_login_for_code( + client, code_challenge, redirect_uri="http://localhost:59019/callback" + ) + + resp = await client.post( + "/auth/token", + data={ + "client_id": CLIENT_ID, + "grant_type": "authorization_code", + "code": code, + **token_parameters, + }, + ) + assert resp.status == HTTPStatus.OK + tokens = await resp.json() + assert hass.auth.async_validate_access_token(tokens["access_token"]) is not None + + +@pytest.mark.parametrize( + ("token_parameters", "expected_error"), + [ + pytest.param({}, "invalid_request", id="missing-verifier"), + pytest.param( + {"code_verifier": "x" * 43}, "invalid_grant", id="incorrect-verifier" + ), + ], +) +async def test_loopback_auth_code_requires_verifier( + hass: HomeAssistant, + aiohttp_client: ClientSessionGenerator, + token_parameters: dict[str, str], + expected_error: str, +) -> None: + """An intercepted loopback code cannot be redeemed without its verifier.""" + client = await async_setup_auth(hass, aiohttp_client, setup_api=True) + with patch( + "homeassistant.components.auth.indieauth.fetch_redirect_uris", + return_value=["http://localhost/callback"], + ): + code = await _async_login_for_code( + client, + RFC7636_CHALLENGE, + redirect_uri="http://localhost:59019/callback", + ) + + resp = await client.post( + "/auth/token", + data={ + "client_id": CLIENT_ID, + "grant_type": "authorization_code", + "code": code, + **token_parameters, + }, + ) + assert resp.status == HTTPStatus.BAD_REQUEST + assert (await resp.json())["error"] == expected_error + + async def test_auth_code_pkce_success( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator ) -> None: From ed025f619d9e224b113dceefc589b2d48a596ab7 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 9 Oct 2026 20:51:41 +0000 Subject: [PATCH 254/356] Bump version to 2026.10.1 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 85c9b6f0590f..15550e2590fe 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "0" +PATCH_VERSION: Final = "1" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 2a591cd98bc3..f530c7d4333b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.0" +version = "2026.10.1" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 47320a10c2cfc44ca8f093b26fd50943260efb20 Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Sat, 10 Oct 2026 01:35:07 -0400 Subject: [PATCH 255/356] Fix Matter get_lock_users stopping on a null nextUserIndex (#182808) Co-authored-by: Claude Opus 5 (1M context) Co-authored-by: TheJulianJES --- .../components/matter/lock_helpers.py | 19 +- tests/components/matter/test_lock.py | 257 +++++++++++++----- 2 files changed, 200 insertions(+), 76 deletions(-) diff --git a/homeassistant/components/matter/lock_helpers.py b/homeassistant/components/matter/lock_helpers.py index 6b1d4cb5dbd3..88d567e84d0d 100644 --- a/homeassistant/components/matter/lock_helpers.py +++ b/homeassistant/components/matter/lock_helpers.py @@ -492,9 +492,13 @@ async def get_lock_users( users: list[LockUserData] = [] current_index = 1 + # nextUserIndex skips over unoccupied slots, but some locks always report it + # as null. A null only ends the walk once the lock has reported a forward + # index, which is what shows it implements the field at all; otherwise the + # whole table is walked. + reports_next_index = False - # Iterate through users using next_user_index for efficiency - while current_index is not None and current_index <= max_users: + while current_index <= max_users: get_user_response = await matter_client.send_device_command( node_id=node.node_id, endpoint_id=lock_endpoint.endpoint_id, @@ -507,11 +511,16 @@ async def get_lock_users( if user_data is not None: users.append(user_data) - # Move to next user index next_index = _get_attr(get_user_response, "nextUserIndex") - if next_index is None or next_index <= current_index: + if next_index is not None and next_index > current_index: + reports_next_index = True + current_index = next_index + elif next_index is None and reports_next_index: break - current_index = next_index + else: + # A null from a lock that has never reported a forward index, or an + # index that would not advance the walk. + current_index += 1 return GetLockUsersResult( max_users=max_users, diff --git a/tests/components/matter/test_lock.py b/tests/components/matter/test_lock.py index acad03608ac6..06117e1c5302 100644 --- a/tests/components/matter/test_lock.py +++ b/tests/components/matter/test_lock.py @@ -1,5 +1,6 @@ """Test Matter locks.""" +from collections.abc import Iterable from typing import Any from unittest.mock import AsyncMock, MagicMock, call @@ -45,6 +46,39 @@ _FEATURE_USR_RFID = _FEATURE_USR | _FEATURE_RFID # 258 _FEATURE_USR_PIN_RFID = _FEATURE_USR | _FEATURE_PIN | _FEATURE_RFID # 259 _FEATURE_USR_FINGER = _FEATURE_USR | _FEATURE_FINGER # 260 +# GetUser response for an index that holds no user +_EMPTY_USER_RESPONSE = { + "userIndex": None, + "userName": None, + "userUniqueID": None, + "userStatus": None, + "userType": None, + "credentialRule": None, + "credentials": None, + "nextUserIndex": None, +} + + +def _mock_get_user(matter_client: MagicMock, users: dict[int, dict[str, Any]]) -> None: + """Answer GetUser commands from a user table keyed by user index.""" + + async def send_device_command(**kwargs: Any) -> dict[str, Any]: + return users.get(kwargs["command"].userIndex, _EMPTY_USER_RESPONSE) + + matter_client.send_device_command = AsyncMock(side_effect=send_device_command) + + +def _get_user_calls(node_id: int, indexes: Iterable[int]) -> list[call]: + """Build the expected GetUser calls for the given user indexes.""" + return [ + call( + node_id=node_id, + endpoint_id=1, + command=clusters.DoorLock.Commands.GetUser(userIndex=index), + ) + for index in indexes + ] + @pytest.mark.usefixtures("matter_devices") async def test_locks( @@ -545,9 +579,10 @@ async def test_get_lock_users_service( matter_node: MatterNode, ) -> None: """Test get_lock_users entity service returns users.""" - matter_client.send_device_command = AsyncMock( - side_effect=[ - { + _mock_get_user( + matter_client, + { + 1: { "userIndex": 1, "userName": "Alice", "userUniqueID": None, @@ -556,8 +591,8 @@ async def test_get_lock_users_service( "credentialRule": 0, "credentials": None, "nextUserIndex": None, - }, - ] + } + }, ) result = await hass.services.async_call( @@ -568,12 +603,8 @@ async def test_get_lock_users_service( return_response=True, ) - # Verify GetUser command was sent - assert matter_client.send_device_command.call_count == 1 - assert matter_client.send_device_command.call_args == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=1), + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, range(1, 11) ) assert result["lock.mock_door_lock"] == { @@ -689,9 +720,10 @@ async def test_get_lock_users_iterates_with_next_index( matter_node: MatterNode, ) -> None: """Test get_lock_users uses nextUserIndex for efficient iteration.""" - matter_client.send_device_command = AsyncMock( - side_effect=[ - { # First user at index 1 + _mock_get_user( + matter_client, + { + 1: { "userIndex": 1, "userStatus": 1, "userName": "User 1", @@ -701,7 +733,7 @@ async def test_get_lock_users_iterates_with_next_index( "credentials": None, "nextUserIndex": 5, # Next user at index 5 }, - { # Second user at index 5 + 5: { "userIndex": 5, "userStatus": 1, "userName": "User 5", @@ -709,9 +741,9 @@ async def test_get_lock_users_iterates_with_next_index( "userType": 0, "credentialRule": 0, "credentials": None, - "nextUserIndex": None, # No more users + "nextUserIndex": None, }, - ] + }, ) result = await hass.services.async_call( @@ -722,17 +754,10 @@ async def test_get_lock_users_iterates_with_next_index( return_response=True, ) - assert matter_client.send_device_command.call_count == 2 - # Verify it jumped from index 1 to index 5 via nextUserIndex - assert matter_client.send_device_command.call_args_list[0] == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=1), - ) - assert matter_client.send_device_command.call_args_list[1] == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=5), + # Indexes 2 to 4 are skipped, and the null after index 5 ends the walk + # because this lock has shown it reports the field + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, [1, 5] ) entity_result = result["lock.mock_door_lock"] @@ -796,25 +821,26 @@ async def test_code_format_property_with_pin_required( @pytest.mark.parametrize("node_fixture", ["mock_door_lock"]) @pytest.mark.parametrize("attributes", [{"1/257/65532": _FEATURE_USR_PIN}]) -async def test_get_lock_users_next_user_index_loop_prevention( +async def test_get_lock_users_scans_when_next_user_index_is_null( hass: HomeAssistant, matter_client: MagicMock, matter_node: MatterNode, ) -> None: - """Test get_lock_users handles nextUserIndex <= current to prevent loops.""" - matter_client.send_device_command = AsyncMock( - side_effect=[ - { # User at index 1 - "userIndex": 1, - "userStatus": 1, - "userName": "User 1", + """Test get_lock_users scans the table when nextUserIndex is always null.""" + _mock_get_user( + matter_client, + { + 3: { + "userIndex": 3, + "userName": "Alice", "userUniqueID": None, + "userStatus": 1, "userType": 0, "credentialRule": 0, "credentials": None, - "nextUserIndex": 1, # Same as current - should break loop - }, - ] + "nextUserIndex": None, + } + }, ) result = await hass.services.async_call( @@ -825,18 +851,110 @@ async def test_get_lock_users_next_user_index_loop_prevention( return_response=True, ) - assert matter_client.send_device_command.call_count == 1 - assert matter_client.send_device_command.call_args == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=1), + # The whole table is walked, so the user past the empty first slot is found + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, range(1, 11) + ) + assert result["lock.mock_door_lock"] == { + "max_users": 10, + "users": [ + { + "user_index": 3, + "user_name": "Alice", + "user_unique_id": None, + "user_status": "occupied_enabled", + "user_type": "unrestricted_user", + "credential_rule": "single", + "credentials": [], + "creator_fabric_index": None, + "last_modified_fabric_index": None, + "next_user_index": None, + } + ], + } + + +@pytest.mark.parametrize("node_fixture", ["mock_door_lock"]) +@pytest.mark.parametrize("attributes", [{"1/257/65532": _FEATURE_USR_PIN}]) +async def test_get_lock_users_follows_next_index_from_an_empty_slot( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, +) -> None: + """Test get_lock_users jumps over an empty slot that reports a next index.""" + _mock_get_user( + matter_client, + { + 1: {**_EMPTY_USER_RESPONSE, "nextUserIndex": 3}, + 3: { + "userIndex": 3, + "userName": "Alice", + "userUniqueID": None, + "userStatus": 1, + "userType": 0, + "credentialRule": 0, + "credentials": None, + "nextUserIndex": None, + }, + }, + ) + + result = await hass.services.async_call( + DOMAIN, + "get_lock_users", + {ATTR_ENTITY_ID: "lock.mock_door_lock"}, + blocking=True, + return_response=True, + ) + + # The empty slot points past itself, so the table is not scanned + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, [1, 3] + ) + users = result["lock.mock_door_lock"]["users"] + assert [user["user_index"] for user in users] == [3] + + +@pytest.mark.parametrize("node_fixture", ["mock_door_lock"]) +@pytest.mark.parametrize("attributes", [{"1/257/65532": _FEATURE_USR_PIN}]) +async def test_get_lock_users_next_user_index_loop_prevention( + hass: HomeAssistant, + matter_client: MagicMock, + matter_node: MatterNode, +) -> None: + """Test get_lock_users handles nextUserIndex <= current to prevent loops.""" + _mock_get_user( + matter_client, + { + 1: { + "userIndex": 1, + "userStatus": 1, + "userName": "User 1", + "userUniqueID": None, + "userType": 0, + "credentialRule": 0, + "credentials": None, + "nextUserIndex": 1, # Same as current - must not be followed + } + }, + ) + + result = await hass.services.async_call( + DOMAIN, + "get_lock_users", + {ATTR_ENTITY_ID: "lock.mock_door_lock"}, + blocking=True, + return_response=True, + ) + + # The walk moves on instead of querying index 1 again + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, range(1, 11) ) assert result is not None - # Result is keyed by entity_id lock_users = result["lock.mock_door_lock"] assert len(lock_users["users"]) == 1 - # Should have stopped after first user due to nextUserIndex <= current @pytest.mark.parametrize("node_fixture", ["mock_door_lock"]) @@ -848,9 +966,10 @@ async def test_get_lock_users_with_credentials( ) -> None: """Test get_lock_users returns credential info for users.""" pin_cred_type = clusters.DoorLock.Enums.CredentialTypeEnum.kPin - matter_client.send_device_command = AsyncMock( - side_effect=[ - { # User with credentials + _mock_get_user( + matter_client, + { + 1: { "userIndex": 1, "userStatus": 1, "userName": "User With PIN", @@ -862,8 +981,8 @@ async def test_get_lock_users_with_credentials( {"credentialType": pin_cred_type, "credentialIndex": 2}, ], "nextUserIndex": None, - }, - ] + } + }, ) result = await hass.services.async_call( @@ -874,11 +993,8 @@ async def test_get_lock_users_with_credentials( return_response=True, ) - assert matter_client.send_device_command.call_count == 1 - assert matter_client.send_device_command.call_args == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=1), + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, range(1, 11) ) assert result["lock.mock_door_lock"] == { @@ -911,9 +1027,10 @@ async def test_get_lock_users_with_nullvalue_credentials( matter_node: MatterNode, ) -> None: """Test get_lock_users handles NullValue credentials from Matter SDK.""" - matter_client.send_device_command = AsyncMock( - side_effect=[ - { + _mock_get_user( + matter_client, + { + 1: { "userIndex": 1, "userStatus": 1, "userName": "User No Creds", @@ -922,8 +1039,8 @@ async def test_get_lock_users_with_nullvalue_credentials( "credentialRule": 0, "credentials": NullValue, "nextUserIndex": None, - }, - ] + } + }, ) result = await hass.services.async_call( @@ -934,11 +1051,8 @@ async def test_get_lock_users_with_nullvalue_credentials( return_response=True, ) - assert matter_client.send_device_command.call_count == 1 - assert matter_client.send_device_command.call_args == call( - node_id=matter_node.node_id, - endpoint_id=1, - command=clusters.DoorLock.Commands.GetUser(userIndex=1), + assert matter_client.send_device_command.call_args_list == _get_user_calls( + matter_node.node_id, range(1, 11) ) lock_users = result["lock.mock_door_lock"] @@ -958,9 +1072,10 @@ async def test_get_lock_users_with_fabric_indices( matter_node: MatterNode, ) -> None: """Test get_lock_users returns fabric indices and normalizes NullValue.""" - matter_client.send_device_command = AsyncMock( - side_effect=[ - { + _mock_get_user( + matter_client, + { + 1: { "userIndex": 1, "userName": "HA User", "userUniqueID": None, @@ -972,7 +1087,7 @@ async def test_get_lock_users_with_fabric_indices( "lastModifiedFabricIndex": NullValue, "nextUserIndex": 2, }, - { + 2: { "userIndex": 2, "userName": "External User", "userUniqueID": None, @@ -984,7 +1099,7 @@ async def test_get_lock_users_with_fabric_indices( "lastModifiedFabricIndex": 5, "nextUserIndex": None, }, - ] + }, ) result = await hass.services.async_call( From 55024788e1f17d03d3e0ef6cb57a4af4d1f07cd6 Mon Sep 17 00:00:00 2001 From: Noam Okman Date: Tue, 6 Oct 2026 08:47:59 +0300 Subject: [PATCH 256/356] Bump pyElectra to 1.2.5 in electrasmart (#184187) Signed-off-by: noamokman Co-authored-by: noamokman --- homeassistant/components/electrasmart/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/electrasmart/manifest.json b/homeassistant/components/electrasmart/manifest.json index 8e9a4cfe4f91..1130581e5067 100644 --- a/homeassistant/components/electrasmart/manifest.json +++ b/homeassistant/components/electrasmart/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/electrasmart", "integration_type": "hub", "iot_class": "cloud_polling", - "requirements": ["pyElectra==1.2.4"] + "requirements": ["pyElectra==1.2.5"] } diff --git a/requirements_all.txt b/requirements_all.txt index 499db67496f1..7cfccb6c69ae 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2026,7 +2026,7 @@ pyControl4==2.0.2 pyDuotecno==2024.10.1 # homeassistant.components.electrasmart -pyElectra==1.2.4 +pyElectra==1.2.5 # homeassistant.components.emby pyEmby==1.10 From 441e2f7482c332e567df36b081a7070d0ec975f2 Mon Sep 17 00:00:00 2001 From: "Teemu R." Date: Fri, 9 Oct 2026 07:14:57 +0200 Subject: [PATCH 257/356] Bump python-kasa to 0.11.0.1 (#184235) --- homeassistant/components/tplink/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/tplink/manifest.json b/homeassistant/components/tplink/manifest.json index b72792c19ccb..948ff068bad2 100644 --- a/homeassistant/components/tplink/manifest.json +++ b/homeassistant/components/tplink/manifest.json @@ -302,5 +302,5 @@ "iot_class": "local_polling", "loggers": ["kasa"], "quality_scale": "platinum", - "requirements": ["python-kasa[speedups]==0.10.2"] + "requirements": ["python-kasa[speedups]==0.11.0.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 7cfccb6c69ae..97c1f2a8f965 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2753,7 +2753,7 @@ python-izone==1.3.10 python-join-api==0.1.1 # homeassistant.components.tplink -python-kasa[speedups]==0.10.2 +python-kasa[speedups]==0.11.0.1 # homeassistant.components.linkplay python-linkplay==0.2.14 From b0668584493f5d9298f1c1e89ddc9db29f158a2e Mon Sep 17 00:00:00 2001 From: Manu Date: Tue, 6 Oct 2026 08:33:59 +0200 Subject: [PATCH 258/356] Remove user-configurable polling interval from `omnilogic` (#184380) --- homeassistant/components/omnilogic/__init__.py | 4 ---- homeassistant/components/omnilogic/config_flow.py | 10 +--------- homeassistant/components/omnilogic/const.py | 2 +- homeassistant/components/omnilogic/coordinator.py | 5 ++--- tests/components/omnilogic/test_config_flow.py | 11 ++++------- 5 files changed, 8 insertions(+), 24 deletions(-) diff --git a/homeassistant/components/omnilogic/__init__.py b/homeassistant/components/omnilogic/__init__.py index 89bf1f3b85d3..b2c6a89bd02b 100644 --- a/homeassistant/components/omnilogic/__init__.py +++ b/homeassistant/components/omnilogic/__init__.py @@ -9,7 +9,6 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import aiohttp_client -from .const import CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL from .coordinator import OmniLogicConfigEntry, OmniLogicUpdateCoordinator _LOGGER = logging.getLogger(__name__) @@ -24,8 +23,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: OmniLogicConfigEntry) -> username = conf[CONF_USERNAME] password = conf[CONF_PASSWORD] - polling_interval = conf.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL) - session = aiohttp_client.async_get_clientsession(hass) api = OmniLogic(username, password, session) @@ -45,7 +42,6 @@ async def async_setup_entry(hass: HomeAssistant, entry: OmniLogicConfigEntry) -> api=api, name="Omnilogic", config_entry=entry, - polling_interval=polling_interval, ) await coordinator.async_config_entry_first_refresh() diff --git a/homeassistant/components/omnilogic/config_flow.py b/homeassistant/components/omnilogic/config_flow.py index 20b644b35e18..33b8462f4e37 100644 --- a/homeassistant/components/omnilogic/config_flow.py +++ b/homeassistant/components/omnilogic/config_flow.py @@ -16,7 +16,7 @@ from homeassistant.const import CONF_PASSWORD, CONF_USERNAME from homeassistant.core import callback from homeassistant.helpers import aiohttp_client -from .const import CONF_SCAN_INTERVAL, DEFAULT_PH_OFFSET, DEFAULT_SCAN_INTERVAL, DOMAIN +from .const import DEFAULT_PH_OFFSET, DOMAIN _LOGGER = logging.getLogger(__name__) @@ -90,14 +90,6 @@ class OptionsFlowHandler(OptionsFlow): step_id="init", data_schema=probatio.Schema( { - # Polling interval is user-configurable, which is no longer allowed - # pylint: disable-next=home-assistant-config-flow-polling-field - probatio.Optional( - CONF_SCAN_INTERVAL, - default=self.config_entry.options.get( - CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL - ), - ): int, probatio.Optional( "ph_offset", default=self.config_entry.options.get( diff --git a/homeassistant/components/omnilogic/const.py b/homeassistant/components/omnilogic/const.py index a00a7d7021d5..0e68255a8024 100644 --- a/homeassistant/components/omnilogic/const.py +++ b/homeassistant/components/omnilogic/const.py @@ -2,7 +2,7 @@ DOMAIN = "omnilogic" CONF_SCAN_INTERVAL = "polling_interval" -DEFAULT_SCAN_INTERVAL = 6 +SCAN_INTERVAL = 6 DEFAULT_PH_OFFSET = 0 COORDINATOR = "coordinator" OMNI_API = "omni_api" diff --git a/homeassistant/components/omnilogic/coordinator.py b/homeassistant/components/omnilogic/coordinator.py index a0f754e59466..3b24cde38f98 100644 --- a/homeassistant/components/omnilogic/coordinator.py +++ b/homeassistant/components/omnilogic/coordinator.py @@ -10,7 +10,7 @@ from homeassistant.config_entries import ConfigEntry from homeassistant.core import HomeAssistant from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed -from .const import ALL_ITEM_KINDS +from .const import ALL_ITEM_KINDS, SCAN_INTERVAL _LOGGER = logging.getLogger(__name__) @@ -29,7 +29,6 @@ class OmniLogicUpdateCoordinator(DataUpdateCoordinator[dict[tuple, dict[str, Any api: OmniLogic, name: str, config_entry: OmniLogicConfigEntry, - polling_interval: int, ) -> None: """Initialize the global Omnilogic data updater.""" self.api = api @@ -39,7 +38,7 @@ class OmniLogicUpdateCoordinator(DataUpdateCoordinator[dict[tuple, dict[str, Any logger=_LOGGER, config_entry=config_entry, name=name, - update_interval=timedelta(seconds=polling_interval), + update_interval=timedelta(seconds=SCAN_INTERVAL), ) @override diff --git a/tests/components/omnilogic/test_config_flow.py b/tests/components/omnilogic/test_config_flow.py index 4f138e5c5f07..61a33c0d40d6 100644 --- a/tests/components/omnilogic/test_config_flow.py +++ b/tests/components/omnilogic/test_config_flow.py @@ -5,7 +5,7 @@ from unittest.mock import patch from omnilogic import LoginException, OmniLogicException from homeassistant import config_entries -from homeassistant.components.omnilogic.const import DOMAIN +from homeassistant.components.omnilogic.const import DEFAULT_PH_OFFSET, DOMAIN from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @@ -130,19 +130,16 @@ async def test_option_flow(hass: HomeAssistant) -> None: with patch( "homeassistant.components.omnilogic.async_setup_entry", return_value=True ): - result = await hass.config_entries.options.async_init( - entry.entry_id, - data=None, - ) + result = await hass.config_entries.options.async_init(entry.entry_id) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "init" result = await hass.config_entries.options.async_configure( result["flow_id"], - user_input={"polling_interval": 9}, + user_input={"ph_offset": DEFAULT_PH_OFFSET}, ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == "" - assert result["data"]["polling_interval"] == 9 + assert result["data"]["ph_offset"] == DEFAULT_PH_OFFSET From c1194a29636d38a8a659d5d592df2f4dfbecca70 Mon Sep 17 00:00:00 2001 From: Chris <59744911+kleinc80@users.noreply.github.com> Date: Sat, 10 Oct 2026 17:00:50 +0200 Subject: [PATCH 259/356] Fix Spotify coordinator crash when playing without an item (#184723) --- .../components/spotify/coordinator.py | 7 +++-- tests/components/spotify/test_media_player.py | 30 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/spotify/coordinator.py b/homeassistant/components/spotify/coordinator.py index 94a716656384..eacf609f6bfd 100644 --- a/homeassistant/components/spotify/coordinator.py +++ b/homeassistant/components/spotify/coordinator.py @@ -163,8 +163,11 @@ class SpotifyCoordinator(DataUpdateCoordinator[SpotifyCoordinatorData]): ) self._playlist = None self._checked_playlist_id = None - if current.is_playing and current.progress_ms is not None: - assert current.item is not None + if ( + current.is_playing + and current.progress_ms is not None + and current.item is not None + ): time_left = timedelta( milliseconds=current.item.duration_ms - current.progress_ms ) diff --git a/tests/components/spotify/test_media_player.py b/tests/components/spotify/test_media_player.py index e5c2ab4f9526..34cd3af00ef3 100644 --- a/tests/components/spotify/test_media_player.py +++ b/tests/components/spotify/test_media_player.py @@ -852,6 +852,36 @@ async def test_smart_polling_interval_handles_paused( mock_spotify.return_value.get_playback.reset_mock() +@pytest.mark.usefixtures("setup_credentials") +async def test_playing_without_item( + hass: HomeAssistant, + mock_spotify: MagicMock, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Test playback that is reported as playing without an item.""" + mock_spotify.return_value.get_playback.return_value.item = None + + await setup_integration(hass, mock_config_entry) + + assert mock_spotify.return_value.get_playback.return_value.is_playing is True + assert mock_spotify.return_value.get_playback.return_value.progress_ms is not None + + assert (state := hass.states.get("media_player.spotify_spotify_1")) + assert state.state == MediaPlayerState.PLAYING + + mock_spotify.return_value.get_playback.assert_called_once() + mock_spotify.return_value.get_playback.reset_mock() + + freezer.tick(timedelta(seconds=30)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + mock_spotify.return_value.get_playback.assert_called_once() + assert (state := hass.states.get("media_player.spotify_spotify_1")) + assert state.state == MediaPlayerState.PLAYING + + @pytest.mark.usefixtures("setup_credentials") async def test_source_list_is_stable( hass: HomeAssistant, From 260b6b0dae97516f92a850e6d9ca09b2767e09cc Mon Sep 17 00:00:00 2001 From: Thomas55555 <59625598+Thomas55555@users.noreply.github.com> Date: Thu, 8 Oct 2026 20:12:06 +0200 Subject: [PATCH 260/356] Bump aioautomower to 3.1.0 (#184970) --- homeassistant/components/husqvarna_automower/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/husqvarna_automower/manifest.json b/homeassistant/components/husqvarna_automower/manifest.json index 4c33071c1c59..1ddeb68e0117 100644 --- a/homeassistant/components/husqvarna_automower/manifest.json +++ b/homeassistant/components/husqvarna_automower/manifest.json @@ -9,5 +9,5 @@ "iot_class": "cloud_push", "loggers": ["aioautomower"], "quality_scale": "silver", - "requirements": ["aioautomower==3.0.0"] + "requirements": ["aioautomower==3.1.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 97c1f2a8f965..a42c84b3189e 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -212,7 +212,7 @@ aioaseko==1.0.0 aioasuswrt==1.5.4 # homeassistant.components.husqvarna_automower -aioautomower==3.0.0 +aioautomower==3.1.0 # homeassistant.components.axle_energy aioaxlevpp==0.1.1 From 5cfef968a35d8a7e223b5ad6105295adcfdb67ba Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 10 Oct 2026 16:33:02 +0200 Subject: [PATCH 261/356] Don't toggle the OpenEVSE manual override when it is already in the requested state (#185257) --- homeassistant/components/openevse/switch.py | 23 ++++- tests/components/openevse/test_switch.py | 102 +++++++++++++++++--- 2 files changed, 108 insertions(+), 17 deletions(-) diff --git a/homeassistant/components/openevse/switch.py b/homeassistant/components/openevse/switch.py index a7cd45a6de80..fc8d50047cca 100644 --- a/homeassistant/components/openevse/switch.py +++ b/homeassistant/components/openevse/switch.py @@ -14,7 +14,11 @@ from .coordinator import OpenEVSEConfigEntry from .entity import OpenEVSEEntity from .helpers import openevse_exception_handler -PARALLEL_UPDATES = 0 +# Serialized, so a manual override toggle is done before the next state check +PARALLEL_UPDATES = 1 + +# Firmware from which the library toggles the override over HTTP, not RAPI +OVERRIDE_STATE_MIN_FIRMWARE = "4.0.1" @dataclass(frozen=True, kw_only=True) @@ -26,6 +30,19 @@ class OpenEVSESwitchDescription(SwitchEntityDescription): turn_off_fn: Callable[[OpenEVSE], Awaitable[Any]] +async def _set_manual_override(charger: OpenEVSE, enable: bool) -> None: + """Toggle the manual override, unless it is already in the requested state.""" + # Older firmware does not report the override state, so it can only toggle + if not charger.version_check(OVERRIDE_STATE_MIN_FIRMWARE): + await charger.toggle_override() + return + + # The cached status is not updated by a toggle, so fetch the current state + await charger.update(force_status=True) + if charger.manual_override != enable: + await charger.toggle_override() + + SWITCH_TYPES: tuple[OpenEVSESwitchDescription, ...] = ( OpenEVSESwitchDescription( key="solar_pv_divert", @@ -49,8 +66,8 @@ SWITCH_TYPES: tuple[OpenEVSESwitchDescription, ...] = ( key="manual_override", translation_key="manual_override", is_on_fn=lambda ev: ev.manual_override, - turn_on_fn=lambda ev: ev.toggle_override(), - turn_off_fn=lambda ev: ev.toggle_override(), + turn_on_fn=lambda ev: _set_manual_override(ev, True), + turn_off_fn=lambda ev: _set_manual_override(ev, False), ), ) diff --git a/tests/components/openevse/test_switch.py b/tests/components/openevse/test_switch.py index 337a52d06223..073e74cfe94f 100644 --- a/tests/components/openevse/test_switch.py +++ b/tests/components/openevse/test_switch.py @@ -77,20 +77,6 @@ async def test_entities( (False,), id="current_shaper_off", ), - pytest.param( - "switch.openevse_mock_config_manual_override", - SERVICE_TURN_ON, - "toggle_override", - (), - id="manual_override_on", - ), - pytest.param( - "switch.openevse_mock_config_manual_override", - SERVICE_TURN_OFF, - "toggle_override", - (), - id="manual_override_off", - ), ], ) async def test_switch_turn_on_off( @@ -116,6 +102,94 @@ async def test_switch_turn_on_off( getattr(mock_charger, method_name).assert_called_once_with(*args) +async def test_manual_override_switch_uses_current_state( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: MagicMock, +) -> None: + """Test the manual override checks the charger state before toggling.""" + mock_charger.version_check.return_value = True + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + mock_charger.update.reset_mock() + + async def _override_enabled_on_charger(force_status: bool = False) -> None: + mock_charger.manual_override = True + + # The cached state still says off, while the charger already has it on + mock_charger.update.side_effect = _override_enabled_on_charger + await hass.services.async_call( + SWITCH_DOMAIN, + SERVICE_TURN_ON, + {ATTR_ENTITY_ID: "switch.openevse_mock_config_manual_override"}, + blocking=True, + ) + + mock_charger.update.assert_awaited_once_with(force_status=True) + mock_charger.toggle_override.assert_not_called() + + +@pytest.mark.parametrize( + ("manual_override", "service", "toggled"), + [ + pytest.param(False, SERVICE_TURN_ON, True, id="turn_on_when_off"), + pytest.param(True, SERVICE_TURN_ON, False, id="turn_on_when_on"), + pytest.param(True, SERVICE_TURN_OFF, True, id="turn_off_when_on"), + pytest.param(False, SERVICE_TURN_OFF, False, id="turn_off_when_off"), + ], +) +async def test_manual_override_switch( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: MagicMock, + manual_override: bool, + service: str, + toggled: bool, +) -> None: + """Test the manual override only toggles when not already in that state.""" + mock_charger.version_check.return_value = True + mock_charger.manual_override = manual_override + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + await hass.services.async_call( + SWITCH_DOMAIN, + service, + {ATTR_ENTITY_ID: "switch.openevse_mock_config_manual_override"}, + blocking=True, + ) + + assert mock_charger.toggle_override.called is toggled + + +@pytest.mark.parametrize("service", [SERVICE_TURN_ON, SERVICE_TURN_OFF]) +async def test_manual_override_switch_old_firmware( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_charger: MagicMock, + service: str, +) -> None: + """Test the manual override toggles without a state check on old firmware.""" + mock_charger.version_check.return_value = False + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + mock_charger.update.reset_mock() + + await hass.services.async_call( + SWITCH_DOMAIN, + service, + {ATTR_ENTITY_ID: "switch.openevse_mock_config_manual_override"}, + blocking=True, + ) + + mock_charger.version_check.assert_called_once_with("4.0.1") + mock_charger.update.assert_not_called() + mock_charger.toggle_override.assert_called_once_with() + + @pytest.mark.parametrize( ("raised", "expected", "translation_key", "translation_placeholders"), [ From 864f62aa3b27a8cded09e333168f8cd349b803b6 Mon Sep 17 00:00:00 2001 From: Christian Lackas Date: Sat, 10 Oct 2026 08:27:35 +0200 Subject: [PATCH 262/356] Retry ViCare setup on transient API errors (#185534) --- homeassistant/components/vicare/__init__.py | 12 +++++++ tests/components/vicare/test_init.py | 39 +++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/homeassistant/components/vicare/__init__.py b/homeassistant/components/vicare/__init__.py index 3f9f74cf730e..dee2a3a69683 100644 --- a/homeassistant/components/vicare/__init__.py +++ b/homeassistant/components/vicare/__init__.py @@ -10,10 +10,14 @@ from PyViCare.PyViCare import PyViCare from PyViCare.PyViCareDeviceConfig import PyViCareDeviceConfig from PyViCare.PyViCareOAuthManager import obtain_token_via_basic_auth_pkce from PyViCare.PyViCareUtils import ( + PyViCareDeviceCommunicationError, + PyViCareInternalServerError, PyViCareInvalidConfigurationError, PyViCareInvalidCredentialsError, + PyViCareInvalidDataError, PyViCareRateLimitError, ) +import requests from homeassistant.components.application_credentials import ( ClientCredential, @@ -166,6 +170,14 @@ async def async_setup_entry(hass: HomeAssistant, entry: ViCareConfigEntry) -> bo raise ConfigEntryNotReady( f"ViCare API rate limit exceeded, resets at {err.limitResetDate}" ) from err + except ( + PyViCareDeviceCommunicationError, + PyViCareInternalServerError, + PyViCareInvalidDataError, + requests.RequestException, + ) as err: + # The coordinator treats the same errors as transient. + raise ConfigEntryNotReady("Unable to reach the ViCare API") from err # Group devices by gateway: in viaGateway mode one bulk fetch refreshes # every device behind a gateway, so one coordinator serves the gateway. diff --git a/tests/components/vicare/test_init.py b/tests/components/vicare/test_init.py index c2a4271cc6c0..cdf1e3929305 100644 --- a/tests/components/vicare/test_init.py +++ b/tests/components/vicare/test_init.py @@ -7,6 +7,7 @@ from aiohttp import ClientError from freezegun.api import FrozenDateTimeFactory import pytest from PyViCare.PyViCareUtils import ( + PyViCareDeviceCommunicationError, PyViCareInternalServerError, PyViCareInvalidConfigurationError, PyViCareInvalidCredentialsError, @@ -14,6 +15,7 @@ from PyViCare.PyViCareUtils import ( PyViCareNotSupportedFeatureError, PyViCareRateLimitError, ) +import requests from homeassistant.components.vicare.const import DEFAULT_CACHE_DURATION, DOMAIN from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState @@ -476,6 +478,43 @@ async def test_setup_entry_rate_limited( assert str(rate_limit_error.limitResetDate) in mock_config_entry.reason +@pytest.mark.parametrize( + "error", + [ + # From a real response, 2026-10-09T17:05:26Z. + PyViCareInternalServerError( + {"statusCode": 502, "message": "Non-JSON 502 response", "viErrorId": "n/a"} + ), + PyViCareDeviceCommunicationError( + {"extendedPayload": {"reason": "GATEWAY_OFFLINE"}} + ), + PyViCareInvalidDataError({"error": "no data"}), + requests.ConnectionError, + ], +) +async def test_setup_entry_transient_api_error( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + error: Exception | type[Exception], +) -> None: + """Test setup retries on a ViCare API error that resolves on its own.""" + mock_config_entry.add_to_hass(hass) + client = MockPyViCare([]) + client.initWithExternalOAuth.side_effect = error + + with ( + patch( + "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", + ), + patch(f"{MODULE}.PyViCare", return_value=client), + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert mock_config_entry.reason == "Unable to reach the ViCare API" + + async def test_setup_entry_invalid_configuration( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 9ee088c7a63d71d340a5610e4662d77deb8c099c Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Fri, 9 Oct 2026 15:34:36 -0400 Subject: [PATCH 263/356] Show app name in MCP discovery flow title (#185541) Co-authored-by: Claude --- homeassistant/components/mcp/config_flow.py | 1 + homeassistant/components/mcp/strings.json | 3 ++- tests/components/mcp/test_config_flow.py | 2 ++ 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/mcp/config_flow.py b/homeassistant/components/mcp/config_flow.py index 7a37ca8946e8..007e2d1839ce 100644 --- a/homeassistant/components/mcp/config_flow.py +++ b/homeassistant/components/mcp/config_flow.py @@ -214,6 +214,7 @@ class ModelContextProtocolConfigFlow(AbstractOAuth2FlowHandler, domain=DOMAIN): self.data[CONF_URL] = url self.data[CONF_SLUG] = discovery_info.slug self.addon_name = discovery_info.name + self.context["title_placeholders"] = {"name": self.addon_name} return await self.async_step_hassio_confirm() async def async_step_hassio_confirm( diff --git a/homeassistant/components/mcp/strings.json b/homeassistant/components/mcp/strings.json index 3b844220b51d..7b85fbe1add8 100644 --- a/homeassistant/components/mcp/strings.json +++ b/homeassistant/components/mcp/strings.json @@ -16,6 +16,7 @@ "timeout_connect": "[%key:common::config_flow::error::timeout_connect%]", "unknown": "[%key:common::config_flow::error::unknown%]" }, + "flow_title": "{name}", "step": { "credentials_choice": { "description": "You can either use existing credentials from another integration or set up new credentials.", @@ -30,7 +31,7 @@ "title": "Choose how to authenticate with the MCP server" }, "hassio_confirm": { - "description": "Do you want to configure Home Assistant to connect to the Model Context Protocol server provided by the app: {addon}?", + "description": "Do you want to configure Home Assistant to connect to the Model Context Protocol server provided by the app {addon}?", "title": "Model Context Protocol server via Home Assistant app" }, "pick_implementation": { diff --git a/tests/components/mcp/test_config_flow.py b/tests/components/mcp/test_config_flow.py index 4bb1f6f6ed1c..413a3f4c7461 100644 --- a/tests/components/mcp/test_config_flow.py +++ b/tests/components/mcp/test_config_flow.py @@ -1122,6 +1122,8 @@ async def test_hassio_discovery_flow( assert result["type"] is FlowResultType.FORM assert result["step_id"] == "hassio_confirm" assert result["description_placeholders"] == {"addon": ADDON_NAME} + flows = hass.config_entries.flow.async_progress() + assert flows[0]["context"]["title_placeholders"] == {"name": ADDON_NAME} response = Mock() response.serverInfo.name = TEST_API_NAME From 723cd8885f2e47183a8a73f5ba8bdab8e1210427 Mon Sep 17 00:00:00 2001 From: Robin Thoni Date: Sat, 10 Oct 2026 00:46:14 +0200 Subject: [PATCH 264/356] Ensure IMAP actions always close TCP stream (#185547) --- homeassistant/components/imap/services.py | 153 +++++++++++----------- 1 file changed, 79 insertions(+), 74 deletions(-) diff --git a/homeassistant/components/imap/services.py b/homeassistant/components/imap/services.py index 91fc674cf966..66ab116f208e 100644 --- a/homeassistant/components/imap/services.py +++ b/homeassistant/components/imap/services.py @@ -1,6 +1,7 @@ """Support for the imap services.""" import asyncio +from contextlib import asynccontextmanager, suppress from email.message import Message import logging from typing import Any @@ -54,8 +55,9 @@ SERVICE_FETCH_PART_SCHEMA = _SERVICE_UID_SCHEMA.extend( ) +@asynccontextmanager async def async_get_imap_client(hass: HomeAssistant, entry_id: str) -> IMAP4_SSL: - """Get IMAP client and connect.""" + """Get IMAP client and connect, as managed context.""" if (entry := hass.config_entries.async_get_entry(entry_id)) is None or ( entry.state is not ConfigEntryState.LOADED ): @@ -79,7 +81,15 @@ async def async_get_imap_client(hass: HomeAssistant, entry_id: str) -> IMAP4_SSL translation_key="imap_server_fail", translation_placeholders={"error": str(exc)}, ) from exc - return client + + try: + yield client + finally: + if client: + with suppress(BaseException): + await client.close() + with suppress(BaseException): + client.protocol.transport.close() @callback @@ -120,17 +130,16 @@ async def _async_seen(call: ServiceCall) -> None: uid, entry_id, ) - client = await async_get_imap_client(call.hass, entry_id) - try: - response = await client.store(uid, "+FLAGS (\\Seen)") - except (TimeoutError, AioImapException) as exc: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="imap_server_fail", - translation_placeholders={"error": str(exc)}, - ) from exc - raise_on_error(response, "seen_failed") - await client.close() + async with async_get_imap_client(call.hass, entry_id) as client: + try: + response = await client.store(uid, "+FLAGS (\\Seen)") + except (TimeoutError, AioImapException) as exc: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="imap_server_fail", + translation_placeholders={"error": str(exc)}, + ) from exc + raise_on_error(response, "seen_failed") async def _async_move(call: ServiceCall) -> None: @@ -146,26 +155,25 @@ async def _async_move(call: ServiceCall) -> None: seen, entry_id, ) - client = await async_get_imap_client(call.hass, entry_id) - try: - if seen: - response = await client.store(uid, "+FLAGS (\\Seen)") - raise_on_error(response, "seen_failed") - response = await client.copy(uid, target_folder) - raise_on_error(response, "copy_failed") - response = await client.store(uid, "+FLAGS (\\Deleted)") - raise_on_error(response, "delete_failed") - response = await asyncio.wait_for( - client.protocol.expunge(uid, by_uid=True), client.timeout - ) - raise_on_error(response, "expunge_failed") - except (TimeoutError, AioImapException) as exc: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="imap_server_fail", - translation_placeholders={"error": str(exc)}, - ) from exc - await client.close() + async with async_get_imap_client(call.hass, entry_id) as client: + try: + if seen: + response = await client.store(uid, "+FLAGS (\\Seen)") + raise_on_error(response, "seen_failed") + response = await client.copy(uid, target_folder) + raise_on_error(response, "copy_failed") + response = await client.store(uid, "+FLAGS (\\Deleted)") + raise_on_error(response, "delete_failed") + response = await asyncio.wait_for( + client.protocol.expunge(uid, by_uid=True), client.timeout + ) + raise_on_error(response, "expunge_failed") + except (TimeoutError, AioImapException) as exc: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="imap_server_fail", + translation_placeholders={"error": str(exc)}, + ) from exc async def _async_delete(call: ServiceCall) -> None: @@ -177,21 +185,20 @@ async def _async_delete(call: ServiceCall) -> None: uid, entry_id, ) - client = await async_get_imap_client(call.hass, entry_id) - try: - response = await client.store(uid, "+FLAGS (\\Deleted)") - raise_on_error(response, "delete_failed") - response = await asyncio.wait_for( - client.protocol.expunge(uid, by_uid=True), client.timeout - ) - raise_on_error(response, "expunge_failed") - except (TimeoutError, AioImapException) as exc: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="imap_server_fail", - translation_placeholders={"error": str(exc)}, - ) from exc - await client.close() + async with async_get_imap_client(call.hass, entry_id) as client: + try: + response = await client.store(uid, "+FLAGS (\\Deleted)") + raise_on_error(response, "delete_failed") + response = await asyncio.wait_for( + client.protocol.expunge(uid, by_uid=True), client.timeout + ) + raise_on_error(response, "expunge_failed") + except (TimeoutError, AioImapException) as exc: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="imap_server_fail", + translation_placeholders={"error": str(exc)}, + ) from exc async def _async_fetch(call: ServiceCall) -> ServiceResponse: @@ -203,19 +210,18 @@ async def _async_fetch(call: ServiceCall) -> ServiceResponse: uid, entry_id, ) - client = await async_get_imap_client(call.hass, entry_id) - try: - response = await client.fetch(uid, "BODY.PEEK[]") - except (TimeoutError, AioImapException) as exc: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="imap_server_fail", - translation_placeholders={"error": str(exc)}, - ) from exc - raise_on_error(response, "fetch_failed") - # Index 1 of of the response lines contains the bytearray with the message data - message = ImapMessage(response.lines[1]) - await client.close() + async with async_get_imap_client(call.hass, entry_id) as client: + try: + response = await client.fetch(uid, "BODY.PEEK[]") + except (TimeoutError, AioImapException) as exc: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="imap_server_fail", + translation_placeholders={"error": str(exc)}, + ) from exc + raise_on_error(response, "fetch_failed") + # Index 1 of of the response lines contains the bytearray with the message data + message = ImapMessage(response.lines[1]) return { "text": message.text, "sender": message.sender, @@ -237,19 +243,18 @@ async def _async_fetch_part(call: ServiceCall) -> ServiceResponse: uid, entry_id, ) - client = await async_get_imap_client(call.hass, entry_id) - try: - response = await client.fetch(uid, "BODY.PEEK[]") - except (TimeoutError, AioImapException) as exc: - raise ServiceValidationError( - translation_domain=DOMAIN, - translation_key="imap_server_fail", - translation_placeholders={"error": str(exc)}, - ) from exc - raise_on_error(response, "fetch_failed") - # Index 1 of of the response lines contains the bytearray with the message data - message = ImapMessage(response.lines[1]) - await client.close() + async with async_get_imap_client(call.hass, entry_id) as client: + try: + response = await client.fetch(uid, "BODY.PEEK[]") + except (TimeoutError, AioImapException) as exc: + raise ServiceValidationError( + translation_domain=DOMAIN, + translation_key="imap_server_fail", + translation_placeholders={"error": str(exc)}, + ) from exc + raise_on_error(response, "fetch_failed") + # Index 1 of of the response lines contains the bytearray with the message data + message = ImapMessage(response.lines[1]) part_data = _get_message_part(message.email_message, part_key) part_data_content = part_data.get_payload(decode=False) try: From c94250a879b2946e1c695a6dcd3571ff1d6792ed Mon Sep 17 00:00:00 2001 From: rubempoli <66323535+rubempoli@users.noreply.github.com> Date: Sat, 10 Oct 2026 02:42:23 -0300 Subject: [PATCH 265/356] Bump tplink-omada-client to 1.5.13 (#185585) --- homeassistant/components/tplink_omada/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/tplink_omada/manifest.json b/homeassistant/components/tplink_omada/manifest.json index 3a74f233bd0a..e4f7bacfd413 100644 --- a/homeassistant/components/tplink_omada/manifest.json +++ b/homeassistant/components/tplink_omada/manifest.json @@ -7,5 +7,5 @@ "integration_type": "hub", "iot_class": "local_polling", "quality_scale": "bronze", - "requirements": ["tplink-omada-client==1.5.10"] + "requirements": ["tplink-omada-client==1.5.13"] } diff --git a/requirements_all.txt b/requirements_all.txt index a42c84b3189e..d4ccb564da0d 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3287,7 +3287,7 @@ toonapi==0.3.0 total-connect-client==2026.9 # homeassistant.components.tplink_omada -tplink-omada-client==1.5.10 +tplink-omada-client==1.5.13 # homeassistant.components.transmission transmission-rpc==7.0.3 From 6b2c79a5fa93f7f4e20532f45aee1b2bbb30c7f5 Mon Sep 17 00:00:00 2001 From: Shay Levy Date: Sat, 10 Oct 2026 15:24:52 +0300 Subject: [PATCH 266/356] Report an uncalibrated Shelly RPC cover by its last direction (#185624) --- homeassistant/components/shelly/cover.py | 15 ++++++-- .../shelly/snapshots/test_devices.ambr | 5 +-- tests/components/shelly/test_cover.py | 34 ++++++++++++++++--- 3 files changed, 45 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/shelly/cover.py b/homeassistant/components/shelly/cover.py index a02045333502..6b3389261f33 100644 --- a/homeassistant/components/shelly/cover.py +++ b/homeassistant/components/shelly/cover.py @@ -238,7 +238,11 @@ class RpcShellyCover(ShellyRpcAttributeEntity, CoverEntity): self._attr_name = get_rpc_channel_name(coordinator.device, key) self._attr_unique_id: str = f"{coordinator.mac}-{key}" self._update_task: asyncio.Task | None = None - if self.status["pos_control"]: + self._positioning: bool = self.status["pos_control"] + # Without position control the direction it last travelled in is all + # there is, and that says nothing about where it stopped + self._attr_assumed_state = not self._positioning + if self._positioning: self._attr_supported_features |= CoverEntityFeature.SET_POSITION if coordinator.device.config[key].get("slat", {}).get("enable"): self._attr_supported_features |= ( @@ -252,13 +256,20 @@ class RpcShellyCover(ShellyRpcAttributeEntity, CoverEntity): @override def is_closed(self) -> bool | None: """If cover is closed.""" + if not self._positioning and self.status["state"] == "stopped": + # A stopped cover without position control only knows the + # direction it last travelled in + if not (last_direction := self.status.get("last_direction")): + return None + return cast(str, last_direction) == "close" + return cast(bool, self.status["state"] == "closed") @property @override def current_cover_position(self) -> int | None: """Position of the cover.""" - if not self.status["pos_control"]: + if not self._positioning: return None return cast(int, self.status["current_pos"]) diff --git a/tests/components/shelly/snapshots/test_devices.ambr b/tests/components/shelly/snapshots/test_devices.ambr index e614dd5471d0..ee5f8c8648dd 100644 --- a/tests/components/shelly/snapshots/test_devices.ambr +++ b/tests/components/shelly/snapshots/test_devices.ambr @@ -7674,9 +7674,10 @@ # name: test_shelly_2pm_gen3_cover[cover.test_name-state] StateSnapshot({ 'attributes': ReadOnlyDict({ + : True, : 'shutter', : 'Test name', - : False, + : None, : , }), 'context': , @@ -7684,7 +7685,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'open', + 'state': 'unknown', }) # --- # name: test_shelly_2pm_gen3_cover[sensor.test_name_current-entry] diff --git a/tests/components/shelly/test_cover.py b/tests/components/shelly/test_cover.py index 100a49506aab..7df70403ae14 100644 --- a/tests/components/shelly/test_cover.py +++ b/tests/components/shelly/test_cover.py @@ -226,6 +226,7 @@ async def test_rpc_device_services( mock_rpc_device.cover_set_position.assert_called_once_with(0, pos=50) assert (state := hass.states.get(entity_id)) assert state.attributes[ATTR_CURRENT_POSITION] == 50 + assert ATTR_ASSUMED_STATE not in state.attributes mutate_rpc_device_status( monkeypatch, mock_rpc_device, "cover:0", "state", "opening" @@ -303,18 +304,41 @@ async def test_rpc_device_update( assert state.state == CoverState.OPEN +@pytest.mark.parametrize( + ("device_state", "last_direction", "expected_state"), + [ + ("stopped", "close", CoverState.CLOSED), + ("stopped", "open", CoverState.OPEN), + # Nothing has moved since the device booted + ("stopped", None, STATE_UNKNOWN), + ], +) async def test_rpc_device_no_position_control( - hass: HomeAssistant, mock_rpc_device: Mock, monkeypatch: pytest.MonkeyPatch + hass: HomeAssistant, + mock_rpc_device: Mock, + monkeypatch: pytest.MonkeyPatch, + device_state: str, + last_direction: str | None, + expected_state: str, ) -> None: - """Test RPC device with no position control.""" + """Test RPC device with no position control reports its last direction.""" mutate_rpc_device_status( monkeypatch, mock_rpc_device, "cover:0", "pos_control", False ) + mutate_rpc_device_status( + monkeypatch, mock_rpc_device, "cover:0", "state", device_state + ) + mutate_rpc_device_status( + monkeypatch, mock_rpc_device, "cover:0", "last_direction", last_direction + ) await init_integration(hass, 2) - state = hass.states.get("cover.test_name_test_cover_0") - assert state - assert state.state == CoverState.OPEN + assert (state := hass.states.get("cover.test_name_test_cover_0")) + assert state.state == expected_state + assert state.attributes.get(ATTR_CURRENT_POSITION) is None + # Stopping mid travel leaves the direction saying more than it knows, so + # both buttons stay available + assert state.attributes[ATTR_ASSUMED_STATE] is True async def test_rpc_cover_tilt( From 3192102123920dd48be6c741c0b9454ccafd3f17 Mon Sep 17 00:00:00 2001 From: starkillerOG Date: Sat, 10 Oct 2026 14:24:20 +0200 Subject: [PATCH 267/356] Bump reolink_aio to 0.21.18 (#185631) --- homeassistant/components/reolink/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/reolink/manifest.json b/homeassistant/components/reolink/manifest.json index c6ec0e7f5fb4..b257aff3be20 100644 --- a/homeassistant/components/reolink/manifest.json +++ b/homeassistant/components/reolink/manifest.json @@ -20,5 +20,5 @@ "iot_class": "local_push", "loggers": ["reolink_aio"], "quality_scale": "platinum", - "requirements": ["reolink-aio==0.21.17"] + "requirements": ["reolink-aio==0.21.18"] } diff --git a/requirements_all.txt b/requirements_all.txt index d4ccb564da0d..037566292560 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2971,7 +2971,7 @@ renault-api==0.5.15 renson-endura-delta==1.7.2 # homeassistant.components.reolink -reolink-aio==0.21.17 +reolink-aio==0.21.18 # homeassistant.components.radio_frequency rf-protocols==4.3.0 From 53862b03e39b1a5bf70bc1e2edf9e2c6ac308f63 Mon Sep 17 00:00:00 2001 From: Andrea Di Benedetto Date: Sat, 10 Oct 2026 17:01:34 +0200 Subject: [PATCH 268/356] =?UTF-8?q?Preserve=20fractional=20transition=20ti?= =?UTF-8?q?mes=20for=20TR=C3=85DFRI=20lights=20(#185633)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homeassistant/components/tradfri/light.py | 4 +- tests/components/tradfri/test_light.py | 126 ++++++++++++++++++++++ 2 files changed, 128 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/tradfri/light.py b/homeassistant/components/tradfri/light.py index 42a3f530f87b..8d3cd220cdf1 100644 --- a/homeassistant/components/tradfri/light.py +++ b/homeassistant/components/tradfri/light.py @@ -153,7 +153,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): # to 1 for the next set_state(True) command transition_time = None if ATTR_TRANSITION in kwargs: - transition_time = int(kwargs[ATTR_TRANSITION]) * 10 + transition_time = int(kwargs[ATTR_TRANSITION] * 10) await self._api( self._device_control.set_dimmer( @@ -168,7 +168,7 @@ class TradfriLight(TradfriBaseEntity, LightEntity): """Instruct the light to turn on.""" transition_time = None if ATTR_TRANSITION in kwargs: - transition_time = int(kwargs[ATTR_TRANSITION]) * 10 + transition_time = int(kwargs[ATTR_TRANSITION] * 10) dimmer_command = None if ATTR_BRIGHTNESS in kwargs: diff --git a/tests/components/tradfri/test_light.py b/tests/components/tradfri/test_light.py index 6e7e81f3d1f2..c24ae183f3d9 100644 --- a/tests/components/tradfri/test_light.py +++ b/tests/components/tradfri/test_light.py @@ -1,5 +1,6 @@ """Tradfri lights platform tests.""" +import json from typing import Any import pytest @@ -14,6 +15,7 @@ from homeassistant.components.light import ( ATTR_MAX_COLOR_TEMP_KELVIN, ATTR_MIN_COLOR_TEMP_KELVIN, ATTR_SUPPORTED_COLOR_MODES, + ATTR_TRANSITION, DOMAIN as LIGHT_DOMAIN, ColorMode, ) @@ -44,6 +46,14 @@ def bulb_ws() -> str: return load_fixture("bulb_ws.json", DOMAIN) +@pytest.fixture(scope="module") +def bulb_ws_philips(bulb_ws: str) -> str: + """Return a white spectrum response supporting combined commands.""" + response = json.loads(bulb_ws) + response["3"]["0"] = "Philips" + return json.dumps(response) + + @pytest.fixture(scope="module") def bulb_cws() -> str: """Return a bulb CWS response.""" @@ -338,3 +348,119 @@ async def test_turn_off( state = hass.states.get(entity_id) assert state assert state.state == STATE_OFF + + +@pytest.mark.parametrize( + ("transition", "transition_payload"), + [ + pytest.param({}, {}, id="no_transition"), + pytest.param({ATTR_TRANSITION: 0}, {"5712": 0}, id="transition_0"), + pytest.param({ATTR_TRANSITION: 0.5}, {"5712": 5}, id="transition_0.5"), + pytest.param({ATTR_TRANSITION: 1}, {"5712": 10}, id="transition_1"), + pytest.param({ATTR_TRANSITION: 1.5}, {"5712": 15}, id="transition_1.5"), + ], +) +@pytest.mark.parametrize( + ("device", "entity_id", "service_data", "preceding_payloads", "light_payload"), + [ + pytest.param( + "bulb_ws", + "light.test_ws", + {ATTR_COLOR_TEMP_KELVIN: 4000}, + [{"3311": [{"5711": 250}]}], + {"5851": 200}, + id="ikea_white_spectrum", + ), + pytest.param( + "bulb_ws_philips", + "light.test_ws", + {ATTR_COLOR_TEMP_KELVIN: 4000}, + [], + {"5851": 200, "5711": 250}, + id="philips_white_spectrum", + ), + pytest.param( + "bulb_cws", + "light.test_cws", + {ATTR_HS_COLOR: [0, 100]}, + [], + {"5851": 200, "5707": 0, "5708": 65279}, + id="ikea_color", + ), + ], + indirect=["device"], +) +async def test_turn_on_commands( + hass: HomeAssistant, + command_store: CommandStore, + device: Device, + entity_id: str, + service_data: dict[str, int | list[int]], + transition: dict[str, float], + transition_payload: dict[str, int], + preceding_payloads: list[dict[str, list[dict[str, int]]]], + light_payload: dict[str, int], +) -> None: + """Test transition values, command combination and ordering sent to the gateway.""" + await setup_integration(hass) + command_store.sent_commands.clear() + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_ON, + { + "entity_id": entity_id, + ATTR_BRIGHTNESS: 200, + **service_data, + **transition, + }, + blocking=True, + ) + + expected_payloads = [ + *preceding_payloads, + {"3311": [{**light_payload, **transition_payload}]}, + ] + assert [ + (command.method, command.path, command.data) + for command in command_store.sent_commands + ] == [("put", device.path, payload) for payload in expected_payloads] + + +@pytest.mark.parametrize("device", ["bulb_w"], indirect=True) +@pytest.mark.parametrize( + ("transition", "light_payload"), + [ + pytest.param({}, {"5850": 0}, id="no_transition"), + pytest.param({ATTR_TRANSITION: 0}, {"5851": 0, "5712": 0}, id="transition_0"), + pytest.param( + {ATTR_TRANSITION: 0.5}, {"5851": 0, "5712": 5}, id="transition_0.5" + ), + pytest.param({ATTR_TRANSITION: 1}, {"5851": 0, "5712": 10}, id="transition_1"), + pytest.param( + {ATTR_TRANSITION: 1.5}, {"5851": 0, "5712": 15}, id="transition_1.5" + ), + ], +) +async def test_turn_off_commands( + hass: HomeAssistant, + command_store: CommandStore, + device: Device, + transition: dict[str, float], + light_payload: dict[str, int], +) -> None: + """Test transition values sent to the gateway when turning off.""" + await setup_integration(hass) + command_store.sent_commands.clear() + + await hass.services.async_call( + LIGHT_DOMAIN, + SERVICE_TURN_OFF, + {"entity_id": "light.test_w", **transition}, + blocking=True, + ) + + assert [ + (command.method, command.path, command.data) + for command in command_store.sent_commands + ] == [("put", device.path, {"3311": [light_payload]})] From df35eb2338c5af621c72f627378e6f28f3d193b6 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 10 Oct 2026 15:41:26 +0200 Subject: [PATCH 269/356] Bump tailscale to 1.0.0 (#185639) --- .../components/tailscale/diagnostics.py | 3 +++ .../components/tailscale/manifest.json | 2 +- requirements_all.txt | 2 +- .../tailscale/fixtures/devices.json | 7 +++++++ .../tailscale/snapshots/test_diagnostics.ambr | 20 +++++++++++++++++++ 5 files changed, 32 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/tailscale/diagnostics.py b/homeassistant/components/tailscale/diagnostics.py index 788b4efdcb5b..20ccd13cf4de 100644 --- a/homeassistant/components/tailscale/diagnostics.py +++ b/homeassistant/components/tailscale/diagnostics.py @@ -16,11 +16,14 @@ TO_REDACT = { "addresses", "device_id", "endpoints", + "hardware_addresses", "hostname", "machine_key", "name", "node_id", "node_key", + "oauth_client_id", + "serial_numbers", "tailnet_lock_key", "user", } diff --git a/homeassistant/components/tailscale/manifest.json b/homeassistant/components/tailscale/manifest.json index 8a8a7f3e851c..222ded1fa906 100644 --- a/homeassistant/components/tailscale/manifest.json +++ b/homeassistant/components/tailscale/manifest.json @@ -6,5 +6,5 @@ "documentation": "https://www.home-assistant.io/integrations/tailscale", "integration_type": "hub", "iot_class": "cloud_polling", - "requirements": ["tailscale==0.7.0"] + "requirements": ["tailscale==1.0.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 037566292560..0e34992f658f 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3201,7 +3201,7 @@ synology-srm==0.2.0 systembridgeconnector==5.4.3 # homeassistant.components.tailscale -tailscale==0.7.0 +tailscale==1.0.0 # homeassistant.components.tapsaff tapsaff==0.2.1 diff --git a/tests/components/tailscale/fixtures/devices.json b/tests/components/tailscale/fixtures/devices.json index a83be593fcec..04f06da0de6d 100644 --- a/tests/components/tailscale/fixtures/devices.json +++ b/tests/components/tailscale/fixtures/devices.json @@ -10,6 +10,13 @@ "clientVersion": "1.12.3-td91ea7286-ge1bbbd90c", "updateAvailable": true, "os": "iOS", + "distro": { "name": "ios", "version": "15.0" }, + "oauthClientId": "kclient1234CNTRL", + "postureIdentity": { + "serialNumbers": ["C02ABC123XYZ"], + "hardwareAddresses": ["00:11:22:33:44:55"], + "disabled": false + }, "created": "2021-08-19T09:25:22Z", "lastSeen": "2021-09-16T06:11:23Z", "keyExpiryDisabled": false, diff --git a/tests/components/tailscale/snapshots/test_diagnostics.ambr b/tests/components/tailscale/snapshots/test_diagnostics.ambr index b15b71f7f1b3..bda0dbeb8df4 100644 --- a/tests/components/tailscale/snapshots/test_diagnostics.ambr +++ b/tests/components/tailscale/snapshots/test_diagnostics.ambr @@ -25,6 +25,11 @@ 'connected_to_control': True, 'created': '2021-08-19T09:25:22+00:00', 'device_id': '**REDACTED**', + 'distro': dict({ + 'code_name': None, + 'name': '**REDACTED**', + 'version': '15.0', + }), 'enabled_routes': list([ ]), 'expires': '2022-02-15T09:25:22+00:00', @@ -38,7 +43,14 @@ 'name': '**REDACTED**', 'node_id': '**REDACTED**', 'node_key': '**REDACTED**', + 'oauth_client_id': '**REDACTED**', 'os': 'iOS', + 'posture_identity': dict({ + 'disabled': False, + 'hardware_addresses': '**REDACTED**', + 'serial_numbers': '**REDACTED**', + }), + 'posture_status': None, 'ssh_enabled': None, 'tags': list([ ]), @@ -117,6 +129,7 @@ 'connected_to_control': True, 'created': '2021-08-29T09:49:06+00:00', 'device_id': '**REDACTED**', + 'distro': None, 'enabled_routes': list([ '0.0.0.0/0', '10.10.10.0/23', @@ -133,7 +146,10 @@ 'name': '**REDACTED**', 'node_id': '**REDACTED**', 'node_key': '**REDACTED**', + 'oauth_client_id': None, 'os': 'linux', + 'posture_identity': None, + 'posture_status': None, 'ssh_enabled': None, 'tags': list([ ]), @@ -156,6 +172,7 @@ 'connected_to_control': False, 'created': '2021-08-29T09:49:06+00:00', 'device_id': '**REDACTED**', + 'distro': None, 'enabled_routes': list([ '0.0.0.0/0', '10.10.10.0/23', @@ -172,7 +189,10 @@ 'name': '**REDACTED**', 'node_id': '**REDACTED**', 'node_key': '**REDACTED**', + 'oauth_client_id': None, 'os': 'linux', + 'posture_identity': None, + 'posture_status': None, 'ssh_enabled': None, 'tags': list([ ]), From 6bcbfb10b2829d58f606cb9f153e51d6dd805cd3 Mon Sep 17 00:00:00 2001 From: Christian Lackas Date: Thu, 8 Oct 2026 11:09:26 +0200 Subject: [PATCH 270/356] Patch the PyViCare client instead of integration setup in ViCare tests (#184730) --- tests/components/vicare/conftest.py | 25 +---- tests/components/vicare/test_binary_sensor.py | 5 +- tests/components/vicare/test_button.py | 5 +- tests/components/vicare/test_climate.py | 20 +--- tests/components/vicare/test_diagnostics.py | 5 +- tests/components/vicare/test_fan.py | 28 +++--- tests/components/vicare/test_init.py | 97 +++++-------------- tests/components/vicare/test_number.py | 5 +- tests/components/vicare/test_select.py | 5 +- tests/components/vicare/test_sensor.py | 10 +- tests/components/vicare/test_switch.py | 5 +- tests/components/vicare/test_water_heater.py | 10 +- 12 files changed, 55 insertions(+), 165 deletions(-) diff --git a/tests/components/vicare/conftest.py b/tests/components/vicare/conftest.py index af731b2ea035..289db28dc334 100644 --- a/tests/components/vicare/conftest.py +++ b/tests/components/vicare/conftest.py @@ -15,8 +15,6 @@ from homeassistant.components.application_credentials import ( async_import_client_credential, ) from homeassistant.components.vicare.const import DOMAIN -from homeassistant.components.vicare.types import ViCareData, ViCareDevice -from homeassistant.components.vicare.utils import get_device_serial from homeassistant.core import HomeAssistant from homeassistant.setup import async_setup_component @@ -41,6 +39,9 @@ class MockPyViCare: def __init__(self, fixtures: list[Fixture]) -> None: """Init devices from json dumps, sharing one service per gateway.""" + self.loadViaGateway = Mock() + self.setCacheDuration = Mock() + self.initWithExternalOAuth = Mock() self.devices = [] self.services: dict[str, MockViCareService] = {} for idx, fixture in enumerate(fixtures): @@ -82,16 +83,6 @@ class MockPyViCare: ), ] - def as_vicare_data(self) -> ViCareData: - """Convert to ViCareData as returned by _setup_vicare_api.""" - devices = [] - for device in self.devices: - api = device.asAutoDetectDevice() - devices.append( - ViCareDevice(config=device, api=api, serial=get_device_serial(api)) - ) - return ViCareData(client=self, devices=devices) - class MockViCareService: """Mock of the gateway-wide service PyViCare shares in viaGateway mode. @@ -178,10 +169,7 @@ async def mock_vicare_gas_boiler( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), ): await setup_integration(hass, mock_config_entry) @@ -201,10 +189,7 @@ async def mock_vicare_room_sensors( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_binary_sensor.py b/tests/components/vicare/test_binary_sensor.py index 61622ee6cebc..a9d17801e3ea 100644 --- a/tests/components/vicare/test_binary_sensor.py +++ b/tests/components/vicare/test_binary_sensor.py @@ -56,10 +56,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.BINARY_SENSOR]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_button.py b/tests/components/vicare/test_button.py index e11a5b17d3bd..d57cd62ff0a2 100644 --- a/tests/components/vicare/test_button.py +++ b/tests/components/vicare/test_button.py @@ -28,10 +28,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.BUTTON]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_climate.py b/tests/components/vicare/test_climate.py index 6b903cfe3398..19af0466fbaa 100644 --- a/tests/components/vicare/test_climate.py +++ b/tests/components/vicare/test_climate.py @@ -37,10 +37,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.CLIMATE]), ): await setup_integration(hass, mock_config_entry) @@ -90,10 +87,7 @@ async def test_hvac_action_compressor_phase( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.CLIMATE]), patch( "homeassistant.components.vicare.climate.get_compressors", @@ -146,10 +140,7 @@ async def test_hvac_action_multi_compressor_cooling_takes_precedence( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.CLIMATE]), patch( "homeassistant.components.vicare.climate.get_compressors", @@ -188,10 +179,7 @@ async def test_hvac_mode_cooling( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.CLIMATE]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_diagnostics.py b/tests/components/vicare/test_diagnostics.py index 3dc22ac2ad9c..ffa62916f9f8 100644 --- a/tests/components/vicare/test_diagnostics.py +++ b/tests/components/vicare/test_diagnostics.py @@ -71,10 +71,7 @@ async def test_diagnostics_scopes_features_to_their_device( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_fan.py b/tests/components/vicare/test_fan.py index 2d89c454927c..4096fac20fe5 100644 --- a/tests/components/vicare/test_fan.py +++ b/tests/components/vicare/test_fan.py @@ -17,6 +17,10 @@ from .conftest import Fixture, MockPyViCare from tests.common import MockConfigEntry, snapshot_platform +GET_QUICKMODE = ( + "PyViCare.PyViCareVentilationDevice.VentilationDevice.getVentilationQuickmode" +) + @pytest.mark.usefixtures("entity_registry_enabled_by_default") async def test_all_entities( @@ -35,10 +39,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.FAN]), ): await setup_integration(hass, mock_config_entry) @@ -60,16 +61,14 @@ async def test_standby_quickmode( difference here. """ fixtures: list[Fixture] = [Fixture({"type:ventilation"}, "vicare/VitoPure.json")] - vicare_data = MockPyViCare(fixtures).as_vicare_data() - api = vicare_data.devices[0].api with ( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch(f"{MODULE}._setup_vicare_api", return_value=vicare_data), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.FAN]), - patch.object(api, "getVentilationQuickmode", return_value=True), + patch(GET_QUICKMODE, return_value=True), ): await setup_integration(hass, mock_config_entry) @@ -82,13 +81,12 @@ async def test_standby_quickmode( await async_update_entity(hass, entity_id) assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-auto" - with patch.object(api, "getVentilationQuickmode", return_value=True): + with patch(GET_QUICKMODE, return_value=True): await async_update_entity(hass, entity_id) assert hass.states.get(entity_id).attributes[ATTR_ICON] == "mdi:fan-off" - with patch.object( - api, - "getVentilationQuickmode", + with patch( + GET_QUICKMODE, side_effect=PyViCareNotSupportedFeatureError("standby"), ): await async_update_entity(hass, entity_id) @@ -105,16 +103,14 @@ async def test_standby_quickmode_with_a_second_fan( Fixture({"type:ventilation"}, "vicare/VitoPure.json"), Fixture({"type:ventilation"}, "vicare/ViAir300F.json"), ] - vicare_data = MockPyViCare(fixtures).as_vicare_data() - api = vicare_data.devices[0].api with ( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch(f"{MODULE}._setup_vicare_api", return_value=vicare_data), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.FAN]), - patch.object(api, "getVentilationQuickmode", return_value=True), + patch(GET_QUICKMODE, return_value=True), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_init.py b/tests/components/vicare/test_init.py index cdf1e3929305..ab144b4f779f 100644 --- a/tests/components/vicare/test_init.py +++ b/tests/components/vicare/test_init.py @@ -333,10 +333,7 @@ async def test_coordinator_backs_off_until_the_quota_resets( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), ): await setup_integration(hass, mock_config_entry) @@ -384,10 +381,7 @@ async def test_coordinator_backs_off_when_the_reset_has_passed( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), ): await setup_integration(hass, mock_config_entry) @@ -426,15 +420,14 @@ async def test_setup_entry_invalid_credentials( ) -> None: """Test setup raises ConfigEntryAuthFailed on PyViCare credentials error.""" mock_config_entry.add_to_hass(hass) + client = MockPyViCare([]) + client.initWithExternalOAuth.side_effect = PyViCareInvalidCredentialsError with ( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - side_effect=PyViCareInvalidCredentialsError, - ), + patch(f"{MODULE}.PyViCare", return_value=client), ): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() @@ -458,20 +451,19 @@ async def test_setup_entry_rate_limited( } } ) + client = MockPyViCare([]) + client.initWithExternalOAuth.side_effect = rate_limit_error with ( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - side_effect=rate_limit_error, - ) as setup_api, + patch(f"{MODULE}.PyViCare", return_value=client), ): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() - setup_api.assert_called_once() + client.initWithExternalOAuth.assert_called_once() assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY # SETUP_RETRY alone would also match an unrelated ConfigEntryNotReady. assert "rate limit" in mock_config_entry.reason @@ -521,15 +513,14 @@ async def test_setup_entry_invalid_configuration( ) -> None: """Test setup raises ConfigEntryAuthFailed on PyViCare config error.""" mock_config_entry.add_to_hass(hass) + client = MockPyViCare([]) + client.initWithExternalOAuth.side_effect = PyViCareInvalidConfigurationError with ( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - side_effect=PyViCareInvalidConfigurationError, - ), + patch(f"{MODULE}.PyViCare", return_value=client), ): await hass.config_entries.async_setup(mock_config_entry.entry_id) await hass.async_block_till_done() @@ -553,10 +544,7 @@ async def test_device_and_entity_migration( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.CLIMATE]), ): mock_config_entry.add_to_hass(hass) @@ -651,10 +639,7 @@ async def test_coordinator_recovers_after_transient_failure( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) @@ -705,10 +690,7 @@ async def test_coordinator_handles_invalid_data( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) @@ -745,10 +727,7 @@ async def test_per_gateway_failure_isolation( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) @@ -798,10 +777,7 @@ async def test_devices_on_same_gateway_share_coordinator( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) @@ -845,10 +821,7 @@ async def test_coordinator_auth_failure_triggers_reauth( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) @@ -890,10 +863,7 @@ async def test_device_via_device_links( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), ): await setup_integration(hass, mock_config_entry) @@ -922,10 +892,7 @@ async def test_device_via_device_missing_gateway( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), ): await setup_integration(hass, mock_config_entry) @@ -940,11 +907,7 @@ async def test_setup_runs_pyvicare_init_and_fetches_once_per_gateway( hass: HomeAssistant, mock_config_entry: MockConfigEntry, ) -> None: - """Set up through _setup_vicare_api instead of a prebuilt ViCareData. - - Covers the via-gateway init, the gateway-based cache duration, and one - fetch per gateway. - """ + """Test the via-gateway init, the cache duration and one fetch per gateway.""" # Two devices behind gwA, one behind gwB: two gateways, three devices. fixtures: list[Fixture] = [ Fixture({"type:climateSensor"}, "vicare/RoomSensor1.json", gateway_id="gwA"), @@ -954,11 +917,8 @@ async def test_setup_runs_pyvicare_init_and_fetches_once_per_gateway( client = MockPyViCare(fixtures) # viaGateway has to be set before init, the services are wired during init. setup_calls: list[str] = [] - client.loadViaGateway = Mock(side_effect=lambda _: setup_calls.append("gateway")) - client.setCacheDuration = Mock() - client.initWithExternalOAuth = Mock( - side_effect=lambda _: setup_calls.append("init") - ) + client.loadViaGateway.side_effect = lambda _: setup_calls.append("gateway") + client.initWithExternalOAuth.side_effect = lambda _: setup_calls.append("init") with ( patch( @@ -1003,9 +963,6 @@ async def test_offline_gateway_does_not_stretch_the_cache( ), ] client = MockPyViCare(fixtures) - client.loadViaGateway = Mock() - client.setCacheDuration = Mock() - client.initWithExternalOAuth = Mock() with ( patch( @@ -1038,9 +995,6 @@ async def test_setup_retries_until_a_device_is_online( Fixture({"type:boiler"}, "vicare/Vitodens300W.json", online=False) ] client = MockPyViCare(fixtures) - client.loadViaGateway = Mock() - client.setCacheDuration = Mock() - client.initWithExternalOAuth = Mock() with ( patch( @@ -1084,10 +1038,7 @@ async def test_setup_loads_with_unpaid_package_gateway( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): mock_config_entry.add_to_hass(hass) diff --git a/tests/components/vicare/test_number.py b/tests/components/vicare/test_number.py index 83471943edd8..0afcf138d363 100644 --- a/tests/components/vicare/test_number.py +++ b/tests/components/vicare/test_number.py @@ -28,10 +28,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.NUMBER]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_select.py b/tests/components/vicare/test_select.py index 5540ecb642ba..e57cc157aa7e 100644 --- a/tests/components/vicare/test_select.py +++ b/tests/components/vicare/test_select.py @@ -30,10 +30,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.SELECT]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_sensor.py b/tests/components/vicare/test_sensor.py index 99bab0689f8a..49940b9a379b 100644 --- a/tests/components/vicare/test_sensor.py +++ b/tests/components/vicare/test_sensor.py @@ -56,10 +56,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR]), ): await setup_integration(hass, mock_config_entry) @@ -108,10 +105,7 @@ async def test_no_api_read_on_event_loop( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SENSOR, Platform.FAN]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_switch.py b/tests/components/vicare/test_switch.py index 24e3b6c80478..b9fbd545f6c4 100644 --- a/tests/components/vicare/test_switch.py +++ b/tests/components/vicare/test_switch.py @@ -44,10 +44,7 @@ async def setup_switch_platform( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=mock_vicare.as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=mock_vicare), patch(f"{MODULE}.PLATFORMS", [Platform.SWITCH]), ): await setup_integration(hass, mock_config_entry) diff --git a/tests/components/vicare/test_water_heater.py b/tests/components/vicare/test_water_heater.py index 873a9f2af821..8d371d48e63a 100644 --- a/tests/components/vicare/test_water_heater.py +++ b/tests/components/vicare/test_water_heater.py @@ -31,10 +31,7 @@ async def test_all_entities( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.WATER_HEATER]), ): await setup_integration(hass, mock_config_entry) @@ -53,10 +50,7 @@ async def test_dhw_active_state( patch( "homeassistant.helpers.config_entry_oauth2_flow.OAuth2Session.async_ensure_token_valid", ), - patch( - f"{MODULE}._setup_vicare_api", - return_value=MockPyViCare(fixtures).as_vicare_data(), - ), + patch(f"{MODULE}.PyViCare", return_value=MockPyViCare(fixtures)), patch(f"{MODULE}.PLATFORMS", [Platform.WATER_HEATER]), ): await setup_integration(hass, mock_config_entry) From e572506ca9424c385ff93e3eaa1a33e6ef578cd5 Mon Sep 17 00:00:00 2001 From: Seb Ruiz Date: Thu, 15 Oct 2026 03:47:17 +1100 Subject: [PATCH 271/356] Fix IndexError on out-of-range heater levels in Tesla Fleet (#178049) Co-authored-by: Joost Lekkerkerker Co-authored-by: Claude Opus 5.5 --- .../components/tesla_fleet/select.py | 18 ++++++--- tests/components/tesla_fleet/test_select.py | 40 ++++++++++++++++++- 2 files changed, 51 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/tesla_fleet/select.py b/homeassistant/components/tesla_fleet/select.py index e5ad9238f84a..432410294d8c 100644 --- a/homeassistant/components/tesla_fleet/select.py +++ b/homeassistant/components/tesla_fleet/select.py @@ -137,10 +137,13 @@ class TeslaFleetSeatHeaterSelectEntity(TeslaFleetVehicleEntity, SelectEntity): """Handle updated data from the coordinator.""" self._attr_available = self.entity_description.available_fn(self) value = self._value - if value is None: - self._attr_current_option = None + # Tesla reports levels above the highest option (for example 4) and + # "SNA" (signal not available) instead of a level. + if isinstance(value, int): + options = self._attr_options + self._attr_current_option = options[max(0, min(value, len(options) - 1))] else: - self._attr_current_option = self._attr_options[value] + self._attr_current_option = None @override async def async_select_option(self, option: str) -> None: @@ -184,10 +187,13 @@ class TeslaFleetWheelHeaterSelectEntity(TeslaFleetVehicleEntity, SelectEntity): """Handle updated data from the coordinator.""" value = self._value - if value is None: - self._attr_current_option = None + # Tesla reports levels above the highest option (for example 4) and + # "SNA" (signal not available) instead of a level. + if isinstance(value, int): + options = self._attr_options + self._attr_current_option = options[max(0, min(value, len(options) - 1))] else: - self._attr_current_option = self._attr_options[value] + self._attr_current_option = None @override async def async_select_option(self, option: str) -> None: diff --git a/tests/components/tesla_fleet/test_select.py b/tests/components/tesla_fleet/test_select.py index 5aa05ab7976b..4cd9f337db5d 100644 --- a/tests/components/tesla_fleet/test_select.py +++ b/tests/components/tesla_fleet/test_select.py @@ -1,5 +1,6 @@ """Test the Tesla Fleet select platform.""" +from copy import deepcopy from unittest.mock import AsyncMock, patch import pytest @@ -12,7 +13,7 @@ from homeassistant.components.select import ( DOMAIN as SELECT_DOMAIN, SERVICE_SELECT_OPTION, ) -from homeassistant.components.tesla_fleet.select import LOW +from homeassistant.components.tesla_fleet.select import HIGH, LOW from homeassistant.const import ATTR_ENTITY_ID, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er @@ -49,6 +50,43 @@ async def test_select_offline( assert state.state == STATE_UNKNOWN +@pytest.mark.parametrize( + ("field", "entity_id", "value"), + [ + pytest.param( + "steering_wheel_heat_level", + "select.test_steering_wheel_heater", + 3, + id="steering_wheel_heater", + ), + pytest.param( + "seat_heater_left", + "select.test_seat_heater_front_left", + 4, + id="seat_heater", + ), + ], +) +async def test_select_heat_level_out_of_range( + hass: HomeAssistant, + mock_vehicle_data: AsyncMock, + normal_config_entry: MockConfigEntry, + field: str, + entity_id: str, + value: int, +) -> None: + """Tests that a heat level beyond the last modeled option clamps to it.""" + + data = deepcopy(VEHICLE_DATA_ALT) + data["response"]["climate_state"][field] = value + mock_vehicle_data.return_value = data + + await setup_platform(hass, normal_config_entry, [Platform.SELECT]) + + state = hass.states.get(entity_id) + assert state.state == HIGH + + async def test_select_services( hass: HomeAssistant, mock_vehicle_data: AsyncMock, From 713c14f0b147afec3b0c7de59d3240747b87af50 Mon Sep 17 00:00:00 2001 From: derekcentrico <1930094+derekcentrico@users.noreply.github.com> Date: Mon, 12 Oct 2026 10:23:42 -0400 Subject: [PATCH 272/356] Deduplicate sleepers within a single SleepIQ bed (#181461) --- homeassistant/components/sleepiq/__init__.py | 30 ++++++ tests/components/sleepiq/test_init.py | 102 ++++++++++++++++++- 2 files changed, 131 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/sleepiq/__init__.py b/homeassistant/components/sleepiq/__init__.py index 9662efb4ca57..54ba02775641 100644 --- a/homeassistant/components/sleepiq/__init__.py +++ b/homeassistant/components/sleepiq/__init__.py @@ -8,6 +8,7 @@ from asyncsleepiq import ( SleepIQAPIException, SleepIQConnectionException, SleepIQLoginException, + SleepIQSleeper, SleepIQTimeoutException, ) import probatio @@ -98,6 +99,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: SleepIQConfigEntry) -> b raise ConfigEntryNotReady(str(err) or "Error reading from SleepIQ API") from err _filter_duplicate_beds(gateway) + _deduplicate_sleepers(gateway) await _async_migrate_unique_ids(hass, entry, gateway) coordinator = SleepIQDataUpdateCoordinator(hass, entry, gateway) @@ -150,6 +152,34 @@ def _filter_duplicate_beds(gateway: AsyncSleepIQ) -> None: del gateway.beds[bed_id] +def _deduplicate_sleepers(gateway: AsyncSleepIQ) -> None: + """Remove duplicate sleepers within each bed. + + The API can return the same sleeper_id more than once per bed, which + causes entity platforms to create entities with colliding unique IDs. + Keep only the first occurrence of each effective identity, keyed by + str(sleeper_id) so that falsy values (None, "") are also deduplicated + rather than skipped. + """ + for bed in gateway.beds.values(): + seen: set[str] = set() + filtered: list[SleepIQSleeper] = [] + for sleeper in bed.sleepers: + key = str(sleeper.sleeper_id) + if key in seen: + continue + seen.add(key) + filtered.append(sleeper) + if len(filtered) != len(bed.sleepers): + _LOGGER.debug( + "Removed %d duplicate sleeper(s) from bed '%s' (id=%s)", + len(bed.sleepers) - len(filtered), + bed.name, + bed.id, + ) + bed.sleepers[:] = filtered + + async def _async_migrate_unique_ids( hass: HomeAssistant, entry: ConfigEntry, gateway: AsyncSleepIQ ) -> None: diff --git a/tests/components/sleepiq/test_init.py b/tests/components/sleepiq/test_init.py index ec7ee449bab7..599f5b3efae7 100644 --- a/tests/components/sleepiq/test_init.py +++ b/tests/components/sleepiq/test_init.py @@ -19,6 +19,7 @@ from asyncsleepiq import ( from freezegun.api import FrozenDateTimeFactory import pytest +from homeassistant.components.sleepiq import _deduplicate_sleepers from homeassistant.components.sleepiq.const import DOMAIN, IS_IN_BED, SLEEP_NUMBER from homeassistant.components.sleepiq.coordinator import ( LONGER_UPDATE_INTERVAL, @@ -26,7 +27,7 @@ from homeassistant.components.sleepiq.coordinator import ( UPDATE_INTERVAL, ) from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState -from homeassistant.const import CONF_USERNAME, PRESSURE +from homeassistant.const import CONF_USERNAME, PRESSURE, Platform from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er from homeassistant.setup import async_setup_component @@ -469,3 +470,102 @@ async def test_identical_sleepers_both_with_features_preserved( assert entry.state is ConfigEntryState.LOADED assert BED_ID in mock_asyncsleepiq.beds assert "bed_003" in mock_asyncsleepiq.beds + + +def test_deduplicate_sleepers_removes_duplicates() -> None: + """Test that duplicate sleepers with the same sleeper_id are removed.""" + gateway = MagicMock() + bed = create_autospec(SleepIQBed) + bed.name = "Test Bed" + bed.id = "bed_1" + + sleeper_a = create_autospec(SleepIQSleeper) + sleeper_a.sleeper_id = "0" + sleeper_a.side = Side.LEFT + + sleeper_b = create_autospec(SleepIQSleeper) + sleeper_b.sleeper_id = "0" + sleeper_b.side = Side.RIGHT + + bed.sleepers = [sleeper_a, sleeper_b] + gateway.beds = {"bed_1": bed} + + _deduplicate_sleepers(gateway) + + assert len(bed.sleepers) == 1 + assert bed.sleepers[0] is sleeper_a + + +def test_deduplicate_sleepers_keeps_distinct() -> None: + """Test that distinct sleeper IDs are preserved and falsy IDs are deduplicated.""" + gateway = MagicMock() + bed = create_autospec(SleepIQBed) + bed.name = "Test Bed" + bed.id = "bed_1" + + sleeper_a = create_autospec(SleepIQSleeper) + sleeper_a.sleeper_id = SLEEPER_L_ID + + sleeper_b = create_autospec(SleepIQSleeper) + sleeper_b.sleeper_id = SLEEPER_R_ID + + sleeper_c = create_autospec(SleepIQSleeper) + sleeper_c.sleeper_id = None + + sleeper_d = create_autospec(SleepIQSleeper) + sleeper_d.sleeper_id = None + + sleeper_e = create_autospec(SleepIQSleeper) + sleeper_e.sleeper_id = "" + + sleeper_f = create_autospec(SleepIQSleeper) + sleeper_f.sleeper_id = "" + + bed.sleepers = [sleeper_a, sleeper_b, sleeper_c, sleeper_d, sleeper_e, sleeper_f] + gateway.beds = {"bed_1": bed} + + _deduplicate_sleepers(gateway) + + assert len(bed.sleepers) == 4 + assert bed.sleepers[0] is sleeper_a + assert bed.sleepers[1] is sleeper_b + assert bed.sleepers[2] is sleeper_c + assert bed.sleepers[3] is sleeper_e + + +def test_deduplicate_sleepers_empty() -> None: + """Test that an empty sleeper list causes no error.""" + gateway = MagicMock() + bed = create_autospec(SleepIQBed) + bed.name = "Empty Bed" + bed.id = "bed_1" + bed.sleepers = [] + gateway.beds = {"bed_1": bed} + + _deduplicate_sleepers(gateway) + + assert bed.sleepers == [] + + +async def test_duplicate_sleepers_no_unique_id_errors( + hass: HomeAssistant, + mock_asyncsleepiq: MagicMock, + mock_bed: MagicMock, + caplog: pytest.LogCaptureFixture, +) -> None: + """Test that duplicate sleepers do not produce unique ID errors.""" + dup_sleeper = create_autospec(SleepIQSleeper) + dup_sleeper.side = Side.RIGHT + dup_sleeper.name = "Duplicate" + dup_sleeper.sleeper_id = SLEEPER_L_ID + dup_sleeper.in_bed = False + dup_sleeper.sleep_number = 50 + dup_sleeper.pressure = 1200 + dup_sleeper.sleep_data = SleepData( + duration=0, sleep_score=0, heart_rate=0, respiratory_rate=0, hrv=0 + ) + mock_bed.sleepers.append(dup_sleeper) + + entry = await setup_platform(hass, Platform.BINARY_SENSOR) + assert entry.state is ConfigEntryState.LOADED + assert "does not generate unique IDs" not in caplog.text From 5251ebb23fb978a3f6adec1cae2141a1b4c409e4 Mon Sep 17 00:00:00 2001 From: Arie Catsman <120491684+catsmanac@users.noreply.github.com> Date: Thu, 15 Oct 2026 21:47:38 +0200 Subject: [PATCH 273/356] Handle Enphase envoy Session is Closed in background tasks (#183172) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> Co-authored-by: Simon Lamon <32477463+silamon@users.noreply.github.com> --- .../components/enphase_envoy/__init__.py | 11 +- .../components/enphase_envoy/coordinator.py | 124 ++++-- tests/components/enphase_envoy/test_init.py | 365 ++++++++++++++++-- 3 files changed, 446 insertions(+), 54 deletions(-) diff --git a/homeassistant/components/enphase_envoy/__init__.py b/homeassistant/components/enphase_envoy/__init__.py index d9be4969e129..079f7132bfaf 100644 --- a/homeassistant/components/enphase_envoy/__init__.py +++ b/homeassistant/components/enphase_envoy/__init__.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING from pyenphase import Envoy from homeassistant.const import CONF_HOST -from homeassistant.core import HomeAssistant +from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import ConfigEntryNotReady from homeassistant.helpers import device_registry as dr from homeassistant.helpers.aiohttp_client import async_create_clientsession @@ -20,7 +20,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: EnphaseConfigEntry) -> b host = entry.data[CONF_HOST] session = async_create_clientsession(hass, verify_ssl=False) envoy = Envoy(host, session) - coordinator = EnphaseUpdateCoordinator(hass, envoy, entry) + coordinator = EnphaseUpdateCoordinator(hass, envoy, entry, session) await coordinator.async_config_entry_first_refresh() if not entry.unique_id: @@ -93,6 +93,13 @@ async def async_setup_entry(hass: HomeAssistant, entry: EnphaseConfigEntry) -> b await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) + @callback + def state_changes() -> None: + """Process config entry state change events.""" + coordinator.state_changes() + + entry.async_on_unload(entry.async_on_state_change(state_changes)) + return True diff --git a/homeassistant/components/enphase_envoy/coordinator.py b/homeassistant/components/enphase_envoy/coordinator.py index 08048b9b3656..1e75d1ad1ccb 100644 --- a/homeassistant/components/enphase_envoy/coordinator.py +++ b/homeassistant/components/enphase_envoy/coordinator.py @@ -7,10 +7,11 @@ import logging import math from typing import Any, override -from pyenphase import Envoy, EnvoyError, EnvoyTokenAuth +from aiohttp import ClientSession +from pyenphase import Envoy, EnvoyClientClosedError, EnvoyError, EnvoyTokenAuth from pyenphase.models.home import EnvoyInterfaceInformation -from homeassistant.config_entries import ConfigEntry +from homeassistant.config_entries import ConfigEntry, ConfigEntryState from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_TOKEN, CONF_USERNAME from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback from homeassistant.exceptions import ConfigEntryAuthFailed @@ -52,7 +53,11 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): token_lifetime: int # days of token life left def __init__( - self, hass: HomeAssistant, envoy: Envoy, entry: EnphaseConfigEntry + self, + hass: HomeAssistant, + envoy: Envoy, + entry: EnphaseConfigEntry, + session: ClientSession, ) -> None: """Initialize DataUpdateCoordinator for the envoy.""" self.envoy = envoy @@ -61,6 +66,7 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): self.password = entry_data.get(CONF_PASSWORD) self.manual_token = entry_data.get(CONF_MANUAL_TOKEN, False) self._setup_complete = False + self._background_started = False self._operational_timeout = False self.envoy_firmware = "" self.interface = None @@ -69,6 +75,7 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): self._cancel_mac_verification: CALLBACK_TYPE | None = None self.token_lifetime = 0 self._acb_sleep_soc_band: str | None = None + self._client_session: ClientSession = session super().__init__( hass, _LOGGER, @@ -135,8 +142,10 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): ) if not fresh: if not self.manual_token: - self.hass.async_create_background_task( - self._async_try_refresh_token(), f"{name} token refresh" + self.config_entry.async_create_background_task( + self.hass, + self._async_try_refresh_token(), + f"{self.name} token refresh", ) return @@ -183,15 +192,17 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): # If the token actually ends up expiring, we'll # re-authenticate with username/password and get a new token # or log an error if that fails - _LOGGER.debug("%s: Error refreshing token: %s", err, self.name) + _LOGGER.debug("%s: Error refreshing token: %s", self.name, err) return self._async_update_saved_token() @callback def _async_refresh_firmware(self, now: datetime.datetime) -> None: """Proactively check for firmware changes in Envoy.""" - self.hass.async_create_background_task( - self._async_try_refresh_firmware(), "{name} firmware refresh" + self.config_entry.async_create_background_task( + self.hass, + self._async_try_refresh_firmware(), + f"{self.name} firmware refresh", ) async def _async_try_refresh_firmware(self) -> None: @@ -201,8 +212,22 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): await self.envoy.setup() except EnvoyError as err: # just try again next time - _LOGGER.debug("%s: Error reading firmware: %s", err, self.name) + _LOGGER.debug("%s: Error reading firmware: %s", self.name, err) return + except EnvoyClientClosedError: + _LOGGER.debug("%s: Client is closed when reading firmware", self.name) + return + except RuntimeError as err: + # We may get session is closed if we still run at unload + if ( + self._client_session.closed + and self.config_entry.state is not ConfigEntryState.LOADED + ): + _LOGGER.debug( + "%s: Client is closed when reading firmware: %s", self.name, err + ) + return + raise if (current_firmware := self.envoy_firmware) and current_firmware != ( new_firmware := self.envoy.firmware ): @@ -232,15 +257,36 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): @callback def _async_verify_mac(self, now: datetime.datetime) -> None: """Verify Envoy active interface mac address in background.""" - self.hass.async_create_background_task( - self._async_fetch_and_compare_mac(), "{name} verify envoy mac address" + self.config_entry.async_create_background_task( + self.hass, + self._async_fetch_and_compare_mac(), + f"{self.name} verify envoy mac address", ) async def _async_fetch_and_compare_mac(self) -> None: """Get Envoy interface information and update mac in device connections.""" - interface: ( - EnvoyInterfaceInformation | None - ) = await self.envoy.interface_settings() + try: + interface: ( + EnvoyInterfaceInformation | None + ) = await self.envoy.interface_settings() + except EnvoyClientClosedError: + _LOGGER.debug( + "%s: Client is closed when reading interface information", self.name + ) + return + except RuntimeError as err: + # We may get session is closed if we still run at unload + if ( + self._client_session.closed + and self.config_entry.state is not ConfigEntryState.LOADED + ): + _LOGGER.debug( + "%s: Client is closed when reading interface information: %s", + self.name, + err, + ) + return + raise if interface is None: _LOGGER.debug("%s: interface information returned None", self.name) return @@ -280,9 +326,8 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): _LOGGER.debug("added connection: %s to %s", connection, self.name) @callback - def _async_mark_setup_complete(self) -> None: - """Mark setup as complete, setup firmware checks and token refresh.""" - self._setup_complete = True + def _async_start_background_task_timers(self) -> None: + """Setup firmware check, mac verification and token refresh background task timers.""" self.async_cancel_firmware_refresh() self._cancel_firmware_refresh = async_track_time_interval( self.hass, @@ -300,6 +345,7 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): TOKEN_REFRESH_CHECK_INTERVAL, cancel_on_shutdown=True, ) + self._background_started = True async def _async_setup_and_authenticate(self) -> None: """Set up and authenticate with the envoy.""" @@ -355,21 +401,34 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): for tries in range(2): try: if not self._setup_complete: - _LOGGER.debug("update on try %s, setup not complete", tries) + _LOGGER.debug( + "update on try %s, setup completed: %s, config state: %s", + tries, + self._setup_complete, + self.config_entry.state, + ) self.envoy.set_retry_policy(max_delay=SETUP_RETRY_TIMEOUT) self._operational_timeout = False await self._async_setup_and_authenticate() - self._async_mark_setup_complete() - # dump all received data in debug mode to assist troubleshooting + self._setup_complete = True envoy_data = await envoy.update() if not self._operational_timeout: self.envoy.set_retry_policy(max_delay=OPERATIONAL_RETRY_TIMEOUT) self._operational_timeout = True except INVALID_AUTH_ERRORS as err: - _LOGGER.debug("update on try %s, INVALID_AUTH_ERRORS %s", tries, err) + _LOGGER.debug( + "update on try %s, INVALID_AUTH_ERRORS %s, config state: %s", + tries, + err, + self.config_entry.state, + ) if self._setup_complete and tries == 0: # token likely expired or firmware changed, try to re-authenticate - _LOGGER.debug("update on try %s, setup was complete, retry", tries) + _LOGGER.debug( + "update on try %s, setup was complete, retry, config state: %s", + tries, + self.config_entry.state, + ) self._setup_complete = False continue raise ConfigEntryAuthFailed( @@ -381,7 +440,12 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): }, ) from err except EnvoyError as err: - _LOGGER.debug("update on try %s, EnvoyError %s", tries, err) + _LOGGER.debug( + "update on try %s, EnvoyError %s, config state: %s", + tries, + err, + self.config_entry.state, + ) raise UpdateFailed( translation_domain=DOMAIN, translation_key="envoy_error", @@ -416,21 +480,29 @@ class EnphaseUpdateCoordinator(DataUpdateCoordinator[dict[str, Any]]): @callback def async_cancel_token_refresh(self) -> None: - """Cancel token refresh.""" + """Cancel token refresh timer.""" if self._cancel_token_refresh: self._cancel_token_refresh() self._cancel_token_refresh = None @callback def async_cancel_firmware_refresh(self) -> None: - """Cancel firmware refresh.""" + """Cancel firmware refresh timer.""" if self._cancel_firmware_refresh: self._cancel_firmware_refresh() self._cancel_firmware_refresh = None @callback def async_cancel_mac_verification(self) -> None: - """Cancel mac verification.""" + """Cancel mac verification delayed starter.""" if self._cancel_mac_verification: self._cancel_mac_verification() self._cancel_mac_verification = None + + @callback + def state_changes(self) -> None: + """Process config entry state changes.""" + _LOGGER.debug("State changed for %s: %s", self.name, self.config_entry.state) + if self.config_entry.state is ConfigEntryState.LOADED: + _LOGGER.debug("Config entry loaded, starting background task timers") + self._async_start_background_task_timers() diff --git a/tests/components/enphase_envoy/test_init.py b/tests/components/enphase_envoy/test_init.py index 3c8ee548d0df..3e729b9f6eaf 100644 --- a/tests/components/enphase_envoy/test_init.py +++ b/tests/components/enphase_envoy/test_init.py @@ -1,12 +1,19 @@ """Test Enphase Envoy runtime.""" +import asyncio from datetime import timedelta import logging -from unittest.mock import AsyncMock, MagicMock, call, patch +from unittest.mock import DEFAULT, AsyncMock, MagicMock, PropertyMock, call, patch from freezegun.api import FrozenDateTimeFactory from jwt import encode -from pyenphase import EnvoyAuthenticationError, EnvoyError, EnvoyTokenAuth +from pyenphase import ( + Envoy, + EnvoyAuthenticationError, + EnvoyClientClosedError, + EnvoyError, + EnvoyTokenAuth, +) from pyenphase.auth import EnvoyLegacyAuth import pytest import respx @@ -627,30 +634,6 @@ async def test_coordinator_firmware_refresh( assert envoy.firmware == "9.9.9999" -@respx.mock -async def test_coordinator_firmware_refresh_with_envoy_error( - hass: HomeAssistant, - config_entry: MockConfigEntry, - mock_envoy: AsyncMock, - freezer: FrozenDateTimeFactory, - caplog: pytest.LogCaptureFixture, -) -> None: - """Test coordinator scheduled firmware check.""" - await setup_integration(hass, config_entry) - - caplog.set_level(logging.DEBUG) - logging.getLogger("homeassistant.components.enphase_envoy.coordinator").setLevel( - logging.DEBUG - ) - - mock_envoy.setup.side_effect = EnvoyError - freezer.tick(FIRMWARE_REFRESH_INTERVAL) - async_fire_time_changed(hass) - await hass.async_block_till_done(wait_background_tasks=True) - - assert "Error reading firmware:" in caplog.text - - @respx.mock async def test_coordinator_interface_information( hass: HomeAssistant, @@ -824,3 +807,333 @@ async def test_retry_timeout_settings( assert mock_envoy.mock_calls[-1] == call.set_retry_policy( max_delay=OPERATIONAL_RETRY_TIMEOUT ) + + +@respx.mock +async def test_background_task_cancel_at_unload( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_envoy: AsyncMock, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, +) -> None: + """Test coordinator background tasks cancel at unload.""" + await setup_integration(hass, config_entry) + caplog.set_level(logging.DEBUG) + logging.getLogger("homeassistant.components.enphase_envoy.coordinator").setLevel( + logging.DEBUG + ) + shared_event = asyncio.Event() + + async def mock_interface_settings() -> None: + logging.getLogger("homeassistant.components.enphase_envoy.coordinator").debug( + "Mock Interface settings start" + ) + await shared_event.wait() + # should not log if canceled while waiting + logging.getLogger("homeassistant.components.enphase_envoy.coordinator").debug( + "Mock Interface settings end" + ) + + mock_envoy.interface_settings.side_effect = mock_interface_settings + freezer.tick(MAC_VERIFICATION_DELAY) + async_fire_time_changed(hass) + + await hass.config_entries.async_unload(config_entry.entry_id) + shared_event.set() + + await hass.async_block_till_done(wait_background_tasks=True) + + assert "Mock Interface settings start" in caplog.text + assert "Mock Interface settings end" not in caplog.text + + +@pytest.mark.parametrize( + ("test_target", "envoy_method", "exc", "msg"), + [ + pytest.param( + "_async_fetch_and_compare_mac", + "interface_settings", + RuntimeError, + "Some other runtime error", + id="mac_verification_runtimeerror", + ), + pytest.param( + "_async_try_refresh_firmware", + "setup", + RuntimeError, + "Some other runtime error", + id="firmware_refresh_runtimeerror", + ), + pytest.param( + "_async_fetch_and_compare_mac", + "interface_settings", + ValueError, + "Some other error", + id="mac_verification_valueerror", + ), + pytest.param( + "_async_try_refresh_firmware", + "setup", + ValueError, + "Some other error", + id="firmware_refresh_valueerror", + ), + ], +) +@respx.mock +async def test_coordinator_background_tasks_reraised_error( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_envoy: AsyncMock, + test_target: str, + envoy_method: str, + exc: type[Exception], + msg: str, +) -> None: + """Test coordinator background task handling raised error.""" + await setup_integration(hass, config_entry) + coordinator = config_entry.runtime_data + + def raise_error() -> None: + raise exc(msg) + + test_with = getattr(coordinator, test_target) + setattr(mock_envoy, envoy_method, raise_error) + with pytest.raises(exc, match=msg): + await test_with() + + +@pytest.mark.parametrize( + ("envoy_method", "exc", "msg", "time_step"), + [ + pytest.param( + "interface_settings", + EnvoyClientClosedError("client closed before request"), + "Client is closed when reading interface information", + MAC_VERIFICATION_DELAY, + id="mac_verification_envoyclientclosederror", + ), + pytest.param( + "setup", + EnvoyClientClosedError("client closed before request"), + "Client is closed when reading firmware", + FIRMWARE_REFRESH_INTERVAL, + id="firmware_refresh_envoyclientclosederror", + ), + pytest.param( + "setup", + EnvoyError("some other envoy error"), + "Error reading firmware", + FIRMWARE_REFRESH_INTERVAL, + id="firmware_refresh_envoyerror", + ), + ], +) +@respx.mock +async def test_coordinator_background_tasks_session_is_closed( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_envoy: AsyncMock, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, + envoy_method: str, + exc: Exception, + msg: str, + time_step: timedelta, +) -> None: + """Test coordinator background task handling RuntimeError.""" + await setup_integration(hass, config_entry) + logging.getLogger("homeassistant.components.enphase_envoy.coordinator").setLevel( + logging.DEBUG + ) + caplog.set_level(logging.DEBUG) + + def raise_error() -> None: + raise exc + + with patch( + "aiohttp.ClientSession.closed", + new_callable=PropertyMock, + return_value=True, + ): + caplog.clear() + setattr(mock_envoy, envoy_method, raise_error) + freezer.tick(time_step) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert msg in caplog.text + + +@pytest.mark.parametrize( + ("envoy_method", "exc", "msg", "time_step"), + [ + pytest.param( + "interface_settings", + RuntimeError("Session is closed"), + "Client is closed when reading interface information", + MAC_VERIFICATION_DELAY, + id="mac_verification_sessionclosederror", + ), + pytest.param( + "setup", + RuntimeError("Session is closed"), + "Client is closed when reading firmware", + FIRMWARE_REFRESH_INTERVAL, + id="firmware_refresh_sessionclosederror", + ), + ], +) +@respx.mock +async def test_coordinator_background_tasks_session_is_closed_not_loaded( + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_envoy: AsyncMock, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, + envoy_method: str, + exc: Exception, + msg: str, + time_step: timedelta, +) -> None: + """Test coordinator background task handling RuntimeError when config is not LOADED.""" + await setup_integration(hass, config_entry) + logging.getLogger("homeassistant.components.enphase_envoy.coordinator").setLevel( + logging.DEBUG + ) + caplog.set_level(logging.DEBUG) + + def raise_error() -> None: + raise exc + + with ( + patch( + "aiohttp.ClientSession.closed", + new_callable=PropertyMock, + return_value=True, + ), + patch( + "homeassistant.components.enphase_envoy.async_unload_entry", + return_value=False, + ) as mock_unload, + ): + await hass.config_entries.async_unload(config_entry.entry_id) + mock_unload.assert_awaited_once() + + caplog.clear() + setattr(mock_envoy, envoy_method, raise_error) + freezer.tick(time_step) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert msg in caplog.text + + +@respx.mock +async def test_coordinator_background_task_start( + hass: HomeAssistant, + mock_envoy: AsyncMock, + config_entry: MockConfigEntry, + caplog: pytest.LogCaptureFixture, + freezer: FrozenDateTimeFactory, +) -> None: + """Test coordinator startup sequence and background task starting.""" + caplog.set_level(logging.DEBUG) + await setup_integration(hass, config_entry) + + # verify regular start sequence with resulting background task starting on loaded event + assert ( + f"setup completed: False, config state: {ConfigEntryState.SETUP_IN_PROGRESS}" + in caplog.text + ) + assert f"State changed for Envoy 1234: {ConfigEntryState.LOADED}" in caplog.text + assert "Config entry loaded, starting background task timers" in caplog.text + assert (entity_state := hass.states.get("sensor.inverter_1")) + assert entity_state.state == "116" + + # verify reload sequence resulting with background tasks starting + caplog.clear() + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + f"State changed for Envoy 1234: {ConfigEntryState.UNLOAD_IN_PROGRESS}" + in caplog.text + ) + assert ( + f"setup completed: False, config state: {ConfigEntryState.SETUP_IN_PROGRESS}" + in caplog.text + ) + assert f"State changed for Envoy 1234: {ConfigEntryState.LOADED}" in caplog.text + assert "Config entry loaded, starting background task timers" in caplog.text + assert (entity_state := hass.states.get("sensor.inverter_1")) + assert entity_state.state == "116" + + # verify failed load triggered by reload does not start background task timers + caplog.clear() + mock_envoy.setup.side_effect = EnvoyAuthenticationError("test auth error"), True + + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + f"State changed for Envoy 1234: {ConfigEntryState.UNLOAD_IN_PROGRESS}" + in caplog.text + ) + assert ( + f"setup completed: False, config state: {ConfigEntryState.SETUP_IN_PROGRESS}" + in caplog.text + ) + assert ( + f"INVALID_AUTH_ERRORS test auth error, config state: {ConfigEntryState.SETUP_IN_PROGRESS}" + in caplog.text + ) + assert f"State changed for Envoy 1234: {ConfigEntryState.LOADED}" not in caplog.text + assert "Config entry loaded, starting background task timers" not in caplog.text + assert (entity_state := hass.states.get("sensor.inverter_1")) + assert entity_state.state == "unavailable" + + # verify auth failure on update does not restart background task timers + # previous test left config entry in SETUP_FAILED. first reload regularly + caplog.clear() + mock_envoy.setup.reset_mock(return_value=True, side_effect=True) + await hass.config_entries.async_reload(config_entry.entry_id) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + f"setup completed: False, config state: {ConfigEntryState.SETUP_IN_PROGRESS}" + in caplog.text + ) + assert f"State changed for Envoy 1234: {ConfigEntryState.LOADED}" in caplog.text + assert "Config entry loaded, starting background task timers" in caplog.text + + # verify auth failure on update does not restart background task timers + caplog.clear() + mock_envoy.update.side_effect = [ + EnvoyAuthenticationError("test auth error at update"), + DEFAULT, + ] + mock_envoy.update.wraps = Envoy.update + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert ( + f"update on try 0, INVALID_AUTH_ERRORS test auth error at update, config state: {ConfigEntryState.LOADED}" + in caplog.text + ) + assert ( + f"update on try 0, setup was complete, retry, config state: {ConfigEntryState.LOADED}" + in caplog.text + ) + assert ( + f"update on try 1, setup completed: False, config state: {ConfigEntryState.LOADED}" + in caplog.text + ) + assert "Envoy setup complete for serial: 1234" in caplog.text + + assert "State changed for Envoy 1234" not in caplog.text + assert "Config entry loaded, starting background task timers" not in caplog.text + assert (entity_state := hass.states.get("sensor.inverter_1")) + assert entity_state.state == "116" From 855d7a488a7efacb23b75b4f5e0f56b6ff803f7e Mon Sep 17 00:00:00 2001 From: Mattias Arrelid Date: Mon, 12 Oct 2026 14:12:56 +0200 Subject: [PATCH 274/356] Treat MPD protocol errors as a connection failure (#184481) Co-authored-by: Claude Opus 5.5 (1M context) --- homeassistant/components/mpd/config_flow.py | 1 + tests/components/mpd/test_config_flow.py | 1 + 2 files changed, 2 insertions(+) diff --git a/homeassistant/components/mpd/config_flow.py b/homeassistant/components/mpd/config_flow.py index 1270068cca1f..d17c8b23f487 100644 --- a/homeassistant/components/mpd/config_flow.py +++ b/homeassistant/components/mpd/config_flow.py @@ -50,6 +50,7 @@ class MPDConfigFlow(ConfigFlow, domain=DOMAIN): TimeoutError, gaierror, mpd.ConnectionError, + mpd.ProtocolError, OSError, ): errors["base"] = "cannot_connect" diff --git a/tests/components/mpd/test_config_flow.py b/tests/components/mpd/test_config_flow.py index 5ae65b3c2dad..145b482cb1a6 100644 --- a/tests/components/mpd/test_config_flow.py +++ b/tests/components/mpd/test_config_flow.py @@ -49,6 +49,7 @@ async def test_full_flow( (TimeoutError, "cannot_connect"), (gaierror, "cannot_connect"), (mpd.ConnectionError, "cannot_connect"), + (mpd.ProtocolError, "cannot_connect"), (OSError, "cannot_connect"), (Exception, "unknown"), ], From 85f2a0ba7f741109ba449ecb62d14ec1136eb6bf Mon Sep 17 00:00:00 2001 From: g4bri3lDev Date: Thu, 8 Oct 2026 18:51:13 +0200 Subject: [PATCH 275/356] Bump py-opendisplay to 7.18.1 (#184911) --- homeassistant/components/opendisplay/diagnostics.py | 3 +++ homeassistant/components/opendisplay/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/opendisplay/__init__.py | 2 ++ tests/components/opendisplay/snapshots/test_diagnostics.ambr | 1 + 5 files changed, 8 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/opendisplay/diagnostics.py b/homeassistant/components/opendisplay/diagnostics.py index 0b8c54ba4a56..2eba19896338 100644 --- a/homeassistant/components/opendisplay/diagnostics.py +++ b/homeassistant/components/opendisplay/diagnostics.py @@ -20,6 +20,9 @@ TO_REDACT = { "custom_string_2", "custom_string_3", "encryption_key", + # Raw bytes of config packets the library does not recognise: unknown + # content, so never expose it. + "unparsed_tail", } diff --git a/homeassistant/components/opendisplay/manifest.json b/homeassistant/components/opendisplay/manifest.json index 1aa0ec871d2c..d66b02eee7e5 100644 --- a/homeassistant/components/opendisplay/manifest.json +++ b/homeassistant/components/opendisplay/manifest.json @@ -15,5 +15,5 @@ "iot_class": "local_push", "loggers": ["opendisplay"], "quality_scale": "silver", - "requirements": ["py-opendisplay==7.15.0"] + "requirements": ["py-opendisplay==7.18.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 0e34992f658f..f03e6688b8a0 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1999,7 +1999,7 @@ py-nightscout==1.2.2 py-nymta==0.4.1 # homeassistant.components.opendisplay -py-opendisplay==7.15.0 +py-opendisplay==7.18.1 # homeassistant.components.schluter py-schluter==0.1.7 diff --git a/tests/components/opendisplay/__init__.py b/tests/components/opendisplay/__init__.py index b081fe8655c0..10b0e0654e31 100644 --- a/tests/components/opendisplay/__init__.py +++ b/tests/components/opendisplay/__init__.py @@ -112,6 +112,8 @@ DEVICE_CONFIG = GlobalConfig( custom_string_2="custom two", custom_string_3="custom three", ), + # Raw bytes of config packets the parser does not recognise; must be redacted. + unparsed_tail=b"\xde\xad\xbe\xef", ) diff --git a/tests/components/opendisplay/snapshots/test_diagnostics.ambr b/tests/components/opendisplay/snapshots/test_diagnostics.ambr index d49308cebb2c..2c778f74f7f2 100644 --- a/tests/components/opendisplay/snapshots/test_diagnostics.ambr +++ b/tests/components/opendisplay/snapshots/test_diagnostics.ambr @@ -103,6 +103,7 @@ }), 'touch_controllers': list([ ]), + 'unparsed_tail': '**REDACTED**', 'version': 0, 'wifi_config': None, }), From 01d6c298479afe3c936ecc4042c950cbabe1d479 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Sat, 10 Oct 2026 21:24:48 +0200 Subject: [PATCH 276/356] Bump aiotankerkoenig to 0.5.5 (#185714) --- homeassistant/components/tankerkoenig/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/tankerkoenig/manifest.json b/homeassistant/components/tankerkoenig/manifest.json index db2cb4b58cfa..9231c05e835c 100644 --- a/homeassistant/components/tankerkoenig/manifest.json +++ b/homeassistant/components/tankerkoenig/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aiotankerkoenig"], "quality_scale": "platinum", - "requirements": ["aiotankerkoenig==0.5.3"] + "requirements": ["aiotankerkoenig==0.5.5"] } diff --git a/requirements_all.txt b/requirements_all.txt index f03e6688b8a0..c1a9d307f190 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -453,7 +453,7 @@ aioswitcher==6.1.3 aiosyncthing==0.7.1 # homeassistant.components.tankerkoenig -aiotankerkoenig==0.5.3 +aiotankerkoenig==0.5.5 # homeassistant.components.tedee aiotedee==0.3.0 From a5b34b039bb327e8f950256322d90aec37312f75 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Sat, 10 Oct 2026 23:39:40 +0200 Subject: [PATCH 277/356] Tankerkoenig handle api errors config flow (#185719) Co-authored-by: Claude Opus 5.5 --- .../components/tankerkoenig/config_flow.py | 7 ++ .../components/tankerkoenig/strings.json | 8 +- .../tankerkoenig/test_config_flow.py | 91 +++++++++++++++++-- 3 files changed, 96 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/tankerkoenig/config_flow.py b/homeassistant/components/tankerkoenig/config_flow.py index 196cda94eee7..62fa539c1c3e 100644 --- a/homeassistant/components/tankerkoenig/config_flow.py +++ b/homeassistant/components/tankerkoenig/config_flow.py @@ -8,6 +8,7 @@ from aiotankerkoenig import ( Sort, Station, Tankerkoenig, + TankerkoenigError, TankerkoenigInvalidKeyError, ) import probatio @@ -98,6 +99,8 @@ class FlowHandler(ConfigFlow, domain=DOMAIN): return self._show_form_user( user_input, errors={CONF_API_KEY: "invalid_auth"} ) + except TankerkoenigError: + return self._show_form_user(user_input, errors={"base": "cannot_connect"}) # no stations found if len(stations) == 0: @@ -155,6 +158,8 @@ class FlowHandler(ConfigFlow, domain=DOMAIN): await async_get_nearby_stations(tankerkoenig, user_input) except TankerkoenigInvalidKeyError: return self._show_form_reauth(user_input, {CONF_API_KEY: "invalid_auth"}) + except TankerkoenigError: + return self._show_form_reauth(user_input, {"base": "cannot_connect"}) return self.async_update_reload_and_abort(reauth_entry, data=user_input) @@ -262,6 +267,8 @@ class OptionsFlowHandler(OptionsFlowWithReload): ) except TankerkoenigInvalidKeyError: return self.async_show_form(step_id="init", errors={"base": "invalid_auth"}) + except TankerkoenigError: + return self.async_abort(reason="cannot_connect") if stations: for station in stations: diff --git a/homeassistant/components/tankerkoenig/strings.json b/homeassistant/components/tankerkoenig/strings.json index cecd83fec894..9c5ffb310672 100644 --- a/homeassistant/components/tankerkoenig/strings.json +++ b/homeassistant/components/tankerkoenig/strings.json @@ -11,7 +11,8 @@ "already_configured": "[%key:common::config_flow::abort::already_configured_location%]" }, "error": { - "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", + "invalid_auth": "Invalid API key. If you are sure the key is correct, the Tankerkoenig service may be temporarily unavailable; try again later.", "no_stations": "Could not find any station in range." }, "step": { @@ -177,8 +178,11 @@ } }, "options": { + "abort": { + "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]" + }, "error": { - "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]" + "invalid_auth": "[%key:component::tankerkoenig::config::error::invalid_auth%]" }, "step": { "init": { diff --git a/tests/components/tankerkoenig/test_config_flow.py b/tests/components/tankerkoenig/test_config_flow.py index 967470c2c163..9feb6107c5e6 100644 --- a/tests/components/tankerkoenig/test_config_flow.py +++ b/tests/components/tankerkoenig/test_config_flow.py @@ -1,8 +1,14 @@ """Tests for Tankerkoenig config flow.""" +from typing import Any from unittest.mock import AsyncMock, patch -from aiotankerkoenig.exceptions import TankerkoenigInvalidKeyError +from aiotankerkoenig.exceptions import ( + TankerkoenigConnectionError, + TankerkoenigError, + TankerkoenigInvalidKeyError, +) +import pytest from homeassistant.components.tankerkoenig.const import CONF_STATIONS, DOMAIN from homeassistant.config_entries import SOURCE_USER @@ -113,8 +119,24 @@ async def test_user_already_configured(hass: HomeAssistant) -> None: assert result["reason"] == "already_configured" -async def test_exception_security(hass: HomeAssistant) -> None: - """Test starting a flow by user with invalid api key.""" +@pytest.mark.parametrize( + ("side_effect", "errors"), + [ + pytest.param( + TankerkoenigInvalidKeyError, + {CONF_API_KEY: "invalid_auth"}, + id="invalid_key", + ), + pytest.param( + TankerkoenigConnectionError, {"base": "cannot_connect"}, id="connection" + ), + pytest.param(TankerkoenigError, {"base": "cannot_connect"}, id="api_error"), + ], +) +async def test_user_errors( + hass: HomeAssistant, side_effect: type[Exception], errors: dict[str, Any] +) -> None: + """Test starting a flow by user with an error from the API.""" result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_USER} ) @@ -123,14 +145,14 @@ async def test_exception_security(hass: HomeAssistant) -> None: with patch( "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations", - side_effect=TankerkoenigInvalidKeyError, + side_effect=side_effect, ): result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input=MOCK_USER_DATA ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "user" - assert result["errors"][CONF_API_KEY] == "invalid_auth" + assert result["errors"] == errors async def test_user_no_stations(hass: HomeAssistant) -> None: @@ -153,7 +175,30 @@ async def test_user_no_stations(hass: HomeAssistant) -> None: assert result["errors"][CONF_RADIUS] == "no_stations" -async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> None: +@pytest.mark.parametrize( + ("side_effect", "errors"), + [ + pytest.param( + TankerkoenigInvalidKeyError("Booom!"), + {CONF_API_KEY: "invalid_auth"}, + id="invalid_key", + ), + pytest.param( + TankerkoenigConnectionError("Booom!"), + {"base": "cannot_connect"}, + id="connection", + ), + pytest.param( + TankerkoenigError("Booom!"), {"base": "cannot_connect"}, id="api_error" + ), + ], +) +async def test_reauth( + hass: HomeAssistant, + config_entry: MockConfigEntry, + side_effect: Exception, + errors: dict[str, Any], +) -> None: """Test starting a flow by user to re-auth.""" config_entry.add_to_hass(hass) # re-auth initialized @@ -170,7 +215,7 @@ async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> Non ) as mock_nearby_stations, ): # re-auth unsuccessful - mock_nearby_stations.side_effect = TankerkoenigInvalidKeyError("Booom!") + mock_nearby_stations.side_effect = side_effect result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={ @@ -179,7 +224,7 @@ async def test_reauth(hass: HomeAssistant, config_entry: MockConfigEntry) -> Non ) assert result["type"] is FlowResultType.FORM assert result["step_id"] == "reauth_confirm" - assert result["errors"] == {CONF_API_KEY: "invalid_auth"} + assert result["errors"] == errors # re-auth successful mock_nearby_stations.side_effect = None @@ -270,3 +315,33 @@ async def test_options_flow_error(hass: HomeAssistant) -> None: ) assert result["type"] is FlowResultType.CREATE_ENTRY assert not mock_config.options[CONF_SHOW_ON_MAP] + + +@pytest.mark.parametrize( + "side_effect", + [ + pytest.param(TankerkoenigConnectionError("Booom!"), id="connection"), + pytest.param(TankerkoenigError("Booom!"), id="api_error"), + ], +) +async def test_options_flow_cannot_connect( + hass: HomeAssistant, side_effect: Exception +) -> None: + """Test options flow aborts when the API can't be reached.""" + + mock_config = MockConfigEntry( + domain=DOMAIN, + data=MOCK_OPTIONS_DATA, + options={CONF_SHOW_ON_MAP: True}, + unique_id=f"{DOMAIN}_{MOCK_USER_DATA[CONF_LOCATION][CONF_LATITUDE]}_{MOCK_USER_DATA[CONF_LOCATION][CONF_LONGITUDE]}", + ) + mock_config.add_to_hass(hass) + + with patch( + "homeassistant.components.tankerkoenig.config_flow.Tankerkoenig.nearby_stations", + side_effect=side_effect, + ): + result = await hass.config_entries.options.async_init(mock_config.entry_id) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "cannot_connect" From b9d9ebbe9a5c87740eaf495e1edf27bdf021ba13 Mon Sep 17 00:00:00 2001 From: oohhddaanngg <149027586+oohhddaanngg@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:41:01 -0400 Subject: [PATCH 278/356] Handle Gemini generation parameters and complete WAV TTS responses (#185723) --- .strict-typing | 1 + .../config_flow.py | 2 +- .../entity.py | 89 +++++-- .../strings.json | 22 +- .../google_generative_ai_conversation/tts.py | 14 +- mypy.ini | 10 + .../conftest.py | 30 +++ .../test_ai_task.py | 110 ++++++++ .../test_config_flow.py | 248 +++++++++++++++++- .../test_conversation.py | 241 ++++++++++++++++- .../test_stt.py | 51 ++++ .../test_tts.py | 125 +++++++++ 12 files changed, 918 insertions(+), 25 deletions(-) diff --git a/.strict-typing b/.strict-typing index 7fdccdc17dbc..d0a5d64109d3 100644 --- a/.strict-typing +++ b/.strict-typing @@ -251,6 +251,7 @@ homeassistant.components.google.* homeassistant.components.google_assistant_sdk.* homeassistant.components.google_cloud.* homeassistant.components.google_drive.* +homeassistant.components.google_generative_ai_conversation.* homeassistant.components.google_health.* homeassistant.components.google_photos.* homeassistant.components.google_sheets.* diff --git a/homeassistant/components/google_generative_ai_conversation/config_flow.py b/homeassistant/components/google_generative_ai_conversation/config_flow.py index 1d44f817fcf4..b353f0b53a3f 100644 --- a/homeassistant/components/google_generative_ai_conversation/config_flow.py +++ b/homeassistant/components/google_generative_ai_conversation/config_flow.py @@ -219,7 +219,7 @@ class LLMSubentryFlowHandler(ConfigSubentryFlow): @property def _genai_client(self) -> genai.Client: """Return the Google Generative AI client.""" - return self._get_entry().runtime_data + return cast(genai.Client, self._get_entry().runtime_data) @property def _is_new(self) -> bool: diff --git a/homeassistant/components/google_generative_ai_conversation/entity.py b/homeassistant/components/google_generative_ai_conversation/entity.py index 547b3d41ab3e..35ea6cafc735 100644 --- a/homeassistant/components/google_generative_ai_conversation/entity.py +++ b/homeassistant/components/google_generative_ai_conversation/entity.py @@ -8,6 +8,7 @@ from dataclasses import dataclass, replace import datetime import mimetypes from pathlib import Path +import re from typing import TYPE_CHECKING, Any, Literal, cast from google.genai import Client @@ -95,19 +96,65 @@ SUPPORTED_SCHEMA_KEYS = { } -def _is_thinking_model(model: str) -> bool: - """Check if the model supports thinking configuration.""" +_GEMINI_VERSION = re.compile(r"^gemini-(\d+)(?:\.(\d+))?(?=-|$)") +_GEMINI_TEXT_ALIASES = { + "gemini-flash-latest", + "gemini-pro-latest", + "gemini-flash-lite-latest", +} + + +def _gemini_version(name: str) -> tuple[int, int] | None: + """Parse the numeric Gemini version without confusing 3.10 with 3.1.""" + if match := _GEMINI_VERSION.match(name): + return int(match[1]), int(match[2] or 0) + return None + + +def supports_custom_sampling(model: str) -> bool: + """Keep sampling for older models and omit it for newer Gemini models.""" name = model.removeprefix("models/") - # Exclude non-text models (TTS, image generation) + if not name.startswith("gemini-"): + return True + # These newer families are exceptions to numeric version ordering. + for stem in ("gemini-3.5-flash-lite", "gemini-3.5-transcribe"): + if name == stem or name.startswith(f"{stem}-"): + return False + if version := _gemini_version(name): + return version < (3, 6) + # Preserve sampling behavior for the established older Robotics family. + stem = "gemini-robotics-er-1.6" + return name == stem or name.startswith(f"{stem}-") + + +def _is_thinking_model(model: str) -> bool: + """Check if the model uses the integration's thinking configuration.""" + name = model.removeprefix("models/") + # Preserve existing Gemini 2.5/3 handling of non-text models. if name.endswith(("tts", "image", "image-preview")): return False - return name.startswith(("gemini-2.5", "gemini-3")) + if name in _GEMINI_TEXT_ALIASES: + return True + if (version := _gemini_version(name)) is None: + return False + if version == (2, 5) or version[0] == 3: + return True + # Only extend thinking to ordinary text families, not new specialized APIs. + tokens = name.split("-")[2:] + return ( + version[0] > 3 + and bool(tokens) + and tokens[0] in {"flash", "pro"} + and not {"tts", "image", "live", "transcribe", "embedding"}.intersection(tokens) + ) def _is_gemini_3_model(model: str) -> bool: - """Check if the model is a Gemini 3 series model.""" + """Check if the model uses thinking levels rather than numeric budgets.""" name = model.removeprefix("models/") - return name.startswith("gemini-3") + return name in _GEMINI_TEXT_ALIASES or ( + (version := _gemini_version(name)) is not None and version[0] >= 3 + ) def _is_gemma_4_model(model: str) -> bool: @@ -155,7 +202,20 @@ def _create_thinking_config( "medium": ThinkingLevel.MEDIUM, "high": ThinkingLevel.HIGH, } - if name.startswith("gemini-3") and "pro" in name: + version = _gemini_version(name) + if ( + "pro" in name + or name in _GEMINI_TEXT_ALIASES + or ( + version is not None + and version >= (3, 6) + and not ( + version == (3, 6) + and name.startswith("gemini-3.6-flash") + and "lite" not in name.split("-") + ) + ) + ): level_map.pop("minimal") if thinking_level and thinking_level in level_map: return ThinkingConfig( @@ -644,10 +704,7 @@ class GoogleGenerativeAILLMBaseEntity(Entity): tool_results.append(chat_content) continue - if ( - not isinstance(chat_content, conversation.ToolResultContent) - and chat_content.content == "" - ): + if chat_content.content == "": # Skipping is not possible since the number of # function calls need to match the number of # function responses and skipping one would @@ -760,10 +817,7 @@ class GoogleGenerativeAILLMBaseEntity(Entity): options.get(CONF_THINKING_LEVEL, RECOMMENDED_THINKING_LEVEL), ) - return GenerateContentConfig( - temperature=options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE), - top_k=options.get(CONF_TOP_K, RECOMMENDED_TOP_K), - top_p=options.get(CONF_TOP_P, RECOMMENDED_TOP_P), + config = GenerateContentConfig( max_output_tokens=options.get( CONF_MAX_TOKENS, default_max_tokens @@ -799,6 +853,11 @@ class GoogleGenerativeAILLMBaseEntity(Entity): ], thinking_config=thinking_config, ) + if supports_custom_sampling(model): + config.temperature = options.get(CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE) + config.top_k = options.get(CONF_TOP_K, RECOMMENDED_TOP_K) + config.top_p = options.get(CONF_TOP_P, RECOMMENDED_TOP_P) + return config async def async_prepare_files_for_prompt( diff --git a/homeassistant/components/google_generative_ai_conversation/strings.json b/homeassistant/components/google_generative_ai_conversation/strings.json index 3d523e9f549e..754468910c23 100644 --- a/homeassistant/components/google_generative_ai_conversation/strings.json +++ b/homeassistant/components/google_generative_ai_conversation/strings.json @@ -47,6 +47,13 @@ "thinking_level": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::thinking_level%]", "top_k": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::top_k%]", "top_p": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::top_p%]" + }, + "data_description": { + "temperature": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::temperature%]", + "thinking_budget": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::thinking_budget%]", + "thinking_level": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::thinking_level%]", + "top_k": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::top_k%]", + "top_p": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::top_p%]" } } } @@ -86,8 +93,11 @@ "data_description": { "enable_google_search_tool": "Only works if there is nothing selected in the \"Control Home Assistant\" setting. See docs for a workaround using it with \"Assist\".", "prompt": "Instruct how the LLM should respond. This can be a template.", + "temperature": "Only sent for older Gemini models and non-Gemini models. Newer Gemini models and the latest text aliases use model defaults; your saved setting is kept.", "thinking_budget": "Token budget for model reasoning (Gemini 2.5 only). Use -1 for automatic or 0 to disable (not available for Gemini 2.5 Pro).", - "thinking_level": "Thinking level for Gemini 3 models. Ignored for Gemini 2.5 models, which use the thinking budget instead. \"Minimal\" does not guarantee that thinking is off." + "thinking_level": "Thinking level for Gemini 3 and later text models, including the latest aliases. Unsupported levels use the model default; the saved choice is kept. Gemini 2.5 uses the thinking budget instead. \"Minimal\" does not guarantee that thinking is off.", + "top_k": "Only sent for older Gemini models and non-Gemini models. Newer Gemini models and the latest text aliases use model defaults; your saved setting is kept.", + "top_p": "Only sent for older Gemini models and non-Gemini models. Newer Gemini models and the latest text aliases use model defaults; your saved setting is kept." } } } @@ -120,7 +130,12 @@ "top_p": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::top_p%]" }, "data_description": { - "prompt": "Instruct how the LLM should transcribe the audio." + "prompt": "Instruct how the LLM should transcribe the audio.", + "temperature": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::temperature%]", + "thinking_budget": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::thinking_budget%]", + "thinking_level": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::thinking_level%]", + "top_k": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::top_k%]", + "top_p": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data_description::top_p%]" } } } @@ -148,6 +163,9 @@ "temperature": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::temperature%]", "top_k": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::top_k%]", "top_p": "[%key:component::google_generative_ai_conversation::config_subentries::conversation::step::set_options::data::top_p%]" + }, + "data_description": { + "temperature": "Only sent for older Gemini text-to-speech models. Newer models use the model default; your saved setting is kept." } } } diff --git a/homeassistant/components/google_generative_ai_conversation/tts.py b/homeassistant/components/google_generative_ai_conversation/tts.py index 0b740cbe22b3..e86798ce28d6 100644 --- a/homeassistant/components/google_generative_ai_conversation/tts.py +++ b/homeassistant/components/google_generative_ai_conversation/tts.py @@ -25,7 +25,7 @@ from .const import ( RECOMMENDED_TEMPERATURE, RECOMMENDED_TTS_MODEL, ) -from .entity import GoogleGenerativeAILLMBaseEntity +from .entity import GoogleGenerativeAILLMBaseEntity, supports_custom_sampling from .helpers import convert_to_wav @@ -200,10 +200,12 @@ class GoogleGenerativeAITextToSpeechEntity( self, message: str, language: str, options: dict[str, Any] ) -> TtsAudioType: """Load tts audio file from the engine.""" + model = self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_TTS_MODEL) config = types.GenerateContentConfig() - config.temperature = self.subentry.data.get( - CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE - ) + if supports_custom_sampling(model): + config.temperature = self.subentry.data.get( + CONF_TEMPERATURE, RECOMMENDED_TEMPERATURE + ) config.response_modalities = ["AUDIO"] config.speech_config = types.SpeechConfig( voice_config=types.VoiceConfig( @@ -240,7 +242,7 @@ class GoogleGenerativeAITextToSpeechEntity( try: response = await self._genai_client.aio.models.generate_content( - model=self.subentry.data.get(CONF_CHAT_MODEL, RECOMMENDED_TTS_MODEL), + model=model, contents=message, config=config, ) @@ -249,4 +251,6 @@ class GoogleGenerativeAITextToSpeechEntity( except (APIError, ClientError, ValueError, TypeError) as exc: LOGGER.error("Error during TTS: %s", exc, exc_info=True) raise HomeAssistantError(exc) from exc + if mime_type == "audio/wav": + return "wav", data return "wav", convert_to_wav(data, mime_type) diff --git a/mypy.ini b/mypy.ini index 681a3c147fe5..4960be9622b3 100644 --- a/mypy.ini +++ b/mypy.ini @@ -2268,6 +2268,16 @@ disallow_untyped_defs = true warn_return_any = true warn_unreachable = true +[mypy-homeassistant.components.google_generative_ai_conversation.*] +check_untyped_defs = true +disallow_incomplete_defs = true +disallow_subclassing_any = true +disallow_untyped_calls = true +disallow_untyped_decorators = true +disallow_untyped_defs = true +warn_return_any = true +warn_unreachable = true + [mypy-homeassistant.components.google_health.*] check_untyped_defs = true disallow_incomplete_defs = true diff --git a/tests/components/google_generative_ai_conversation/conftest.py b/tests/components/google_generative_ai_conversation/conftest.py index 24422feb3246..8e4905d145ce 100644 --- a/tests/components/google_generative_ai_conversation/conftest.py +++ b/tests/components/google_generative_ai_conversation/conftest.py @@ -1,8 +1,11 @@ """Tests helpers.""" from collections.abc import AsyncGenerator, Generator +import json from unittest.mock import AsyncMock, Mock, patch +from google.genai._api_client import HttpRequest, HttpResponse +from google.genai.types import HttpOptionsOrDict import pytest from homeassistant.components.google_generative_ai_conversation.const import ( @@ -156,3 +159,30 @@ def mock_generate_content() -> Generator[AsyncMock]: "google.genai.models.AsyncModels.generate_content", ) as mock: yield mock + + +@pytest.fixture +def mock_genai_transport() -> Generator[AsyncMock]: + """Capture real SDK request construction, without making HTTP requests.""" + mock = AsyncMock() + mock.return_value = [ + { + "candidates": [ + { + "content": {"role": "model", "parts": [{"text": "Done"}]}, + "finishReason": "STOP", + } + ] + } + ] + + async def request( + http_request: HttpRequest, + http_options: HttpOptionsOrDict | None = None, + stream: bool = False, + ) -> HttpResponse: + return HttpResponse({}, [json.dumps(mock.return_value.pop(0))]) + + mock.side_effect = request + with patch("google.genai._api_client.BaseApiClient._async_request", mock): + yield mock 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 71cff4610b7e..c93b4cba19b0 100644 --- a/tests/components/google_generative_ai_conversation/test_ai_task.py +++ b/tests/components/google_generative_ai_conversation/test_ai_task.py @@ -9,6 +9,8 @@ import pytest from homeassistant.components import ai_task, media_source from homeassistant.components.google_generative_ai_conversation.const import ( + CONF_CHAT_MODEL, + CONF_THINKING_LEVEL, RECOMMENDED_IMAGE_MODEL, ) from homeassistant.core import HomeAssistant @@ -286,3 +288,111 @@ async def test_generate_image( assert call_args.kwargs["model"] == RECOMMENDED_IMAGE_MODEL assert call_args.kwargs["contents"] == ["Generate a test image"] assert call_args.kwargs["config"].response_modalities == ["TEXT", "IMAGE"] + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize("structured", [False, True]) +async def test_data_wire_parameters( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + structured: bool, +) -> None: + """AI Task DATA uses the shared config, preserving schema and actual output cap.""" + subentry = mock_config_entry.subentries["ulid-ai-task"] + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={ + **subentry.data, + CONF_CHAT_MODEL: "gemini-3.8-flash", + CONF_THINKING_LEVEL: "low", + }, + ) + await hass.async_block_till_done() + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "role": "model", + "parts": [{"text": '{"value": "Done"}'}], + }, + "finishReason": "STOP", + } + ] + } + ] + result = await ai_task.async_generate_data( + hass, + task_name="Test", + entity_id="ai_task.google_ai_task", + instructions="Test", + structure=probatio.Schema({probatio.Required("value"): str}) + if structured + else None, + ) + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert not {"temperature", "topP", "topK"}.intersection(config) + assert config["thinkingConfig"] == { + "include_thoughts": True, + "thinking_level": "LOW", + } + assert config["maxOutputTokens"] == 3000 + assert ("responseSchema" in config) is structured + assert result.data == ({"value": "Done"} if structured else '{"value": "Done"}') + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize( + "model", ["models/gemini-2.5-flash-image", "gemini-nano-banana-2.1"] +) +async def test_image_wire_parameters( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + model: str, +) -> None: + """The dedicated IMAGE path is clean independently of model classification.""" + subentry = mock_config_entry.subentries["ulid-ai-task"] + hass.config_entries.async_update_subentry( + mock_config_entry, subentry, data={**subentry.data, CONF_CHAT_MODEL: model} + ) + await hass.async_block_till_done() + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "role": "model", + "parts": [ + { + "inlineData": { + "data": "aW1hZ2U=", + "mimeType": "image/png", + } + } + ], + } + } + ] + } + ] + with patch.object( + media_source.local_source.LocalSource, + "async_upload_media", + return_value="media-source://ai_task/image/test.png", + ): + result = await ai_task.async_generate_image( + hass, + task_name="Test", + entity_id="ai_task.google_ai_task", + instructions="Image", + ) + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert config == {"responseModalities": ["TEXT", "IMAGE"]} + assert result["mime_type"] == "image/png" diff --git a/tests/components/google_generative_ai_conversation/test_config_flow.py b/tests/components/google_generative_ai_conversation/test_config_flow.py index 3fec08da3456..d3b4f9ce1572 100644 --- a/tests/components/google_generative_ai_conversation/test_config_flow.py +++ b/tests/components/google_generative_ai_conversation/test_config_flow.py @@ -1,12 +1,14 @@ """Test the Google Generative AI Conversation config flow.""" +from collections.abc import AsyncGenerator from typing import Any -from unittest.mock import Mock, patch +from unittest.mock import AsyncMock, Mock, patch import pytest from requests.exceptions import Timeout from homeassistant import config_entries +from homeassistant.components import tts from homeassistant.components.google_generative_ai_conversation.const import ( CONF_CHAT_MODEL, CONF_DANGEROUS_BLOCK_THRESHOLD, @@ -41,6 +43,9 @@ from homeassistant.components.google_generative_ai_conversation.const import ( RECOMMENDED_TTS_OPTIONS, RECOMMENDED_USE_GOOGLE_SEARCH_TOOL, ) +from homeassistant.components.google_generative_ai_conversation.entity import ( + GoogleGenerativeAILLMBaseEntity, +) from homeassistant.const import CONF_API_KEY, CONF_LLM_HASS_API, CONF_NAME, CONF_PROMPT from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType @@ -852,3 +857,244 @@ async def test_subentry_chat_model_labels_keep_the_full_model_id( "learnlm-2.0-flash-experimental", "lyria-realtime-exp", ] + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize( + "subentry_id", ["ulid-conversation", "ulid-ai-task", "ulid-stt"] +) +async def test_sampling_options_model_switch_and_reset( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + subentry_id: str, +) -> None: + """Reconfigure and reload saved choices before building actual SDK requests.""" + + async def sampling_models_pager() -> AsyncGenerator[Mock]: + async for model in get_models_pager(): + yield model + for name in ( + "models/gemini-3.8-flash", + "models/gemini-3.6-flash", + "models/gemini-2.5-pro", + ): + model = Mock(supported_actions=["generateContent"]) + model.name = name + yield model + + subentry = mock_config_entry.subentries[subentry_id] + advanced = { + **subentry.data, + CONF_RECOMMENDED: False, + CONF_TEMPERATURE: 0.2, + CONF_TOP_P: 0.7, + CONF_TOP_K: 17, + CONF_THINKING_LEVEL: "minimal", + CONF_THINKING_BUDGET: 512, + CONF_MAX_TOKENS: 900, + } + hass.config_entries.async_update_subentry( + mock_config_entry, subentry, data=advanced + ) + await hass.async_block_till_done() + preserved = {"temperature": 0.2, "topP": 0.7, "topK": 17} + minimal = {"include_thoughts": True, "thinking_level": "MINIMAL"} + default = {"include_thoughts": True} + budget = {"include_thoughts": True, "thinking_budget": 512} + for model, expected, thinking in ( + ("models/gemini-3.1-flash-lite", preserved, minimal), + ("models/gemini-3.8-flash", {}, default), + ("models/gemini-3.1-flash-lite", preserved, minimal), + ("models/gemini-3.6-flash", {}, minimal), + ("models/gemini-3.8-flash", {}, default), + ("models/gemini-3.6-flash", {}, minimal), + ("models/gemini-2.5-pro", preserved, budget), + ("models/gemini-3.8-flash", {}, default), + ("models/gemini-2.5-pro", preserved, budget), + ): + with patch( + "google.genai.models.AsyncModels.list", return_value=sampling_models_pager() + ): + flow = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry_id + ) + result = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {**advanced, CONF_CHAT_MODEL: model} + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + assert subentry.data[CONF_TEMPERATURE] == 0.2 + assert subentry.data[CONF_THINKING_LEVEL] == "minimal" + assert subentry.data[CONF_THINKING_BUDGET] == 512 + mock_genai_transport.return_value = [ + {"candidates": [{"content": {"parts": [{"text": "Done"}]}}]} + ] + entity = GoogleGenerativeAILLMBaseEntity(mock_config_entry, subentry) + await mock_config_entry.runtime_data.aio.models.generate_content( + model=subentry.data[CONF_CHAT_MODEL], + contents="Hello", + config=entity.create_generate_content_config(), + ) + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert { + key: config[key] for key in ("temperature", "topP", "topK") if key in config + } == expected + assert config["thinkingConfig"] == thinking + assert config["maxOutputTokens"] == 900 + with patch( + "google.genai.models.AsyncModels.list", return_value=sampling_models_pager() + ): + flow = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry_id + ) + flow = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {CONF_RECOMMENDED: True} + ) + result = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {CONF_RECOMMENDED: True} + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.ABORT + assert subentry.data == {CONF_RECOMMENDED: True} + mock_genai_transport.return_value = [ + {"candidates": [{"content": {"parts": [{"text": "Done"}]}}]} + ] + entity = GoogleGenerativeAILLMBaseEntity(mock_config_entry, subentry) + await mock_config_entry.runtime_data.aio.models.generate_content( + model=RECOMMENDED_CHAT_MODEL, + contents="Hello", + config=entity.create_generate_content_config(), + ) + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert config["temperature"] == 1.0 + assert config["topP"] == RECOMMENDED_TOP_P + assert config["topK"] == RECOMMENDED_TOP_K + + +@pytest.mark.usefixtures("mock_init_component") +async def test_tts_sampling_options_model_switch_and_reset( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, +) -> None: + """TTS keeps dormant temperature through actual reconfigure/reload requests.""" + + async def sampling_models_pager() -> AsyncGenerator[Mock]: + async for model in get_models_pager(): + yield model + model = Mock(supported_actions=["generateContent"]) + model.name = "models/gemini-3.8-flash-tts" + yield model + + subentry = mock_config_entry.subentries["ulid-tts"] + advanced = { + CONF_RECOMMENDED: False, + CONF_TEMPERATURE: 0.2, + CONF_CHAT_MODEL: RECOMMENDED_TTS_MODEL, + } + hass.config_entries.async_update_subentry( + mock_config_entry, subentry, data=advanced + ) + await hass.async_block_till_done() + for model, expected in ( + (RECOMMENDED_TTS_MODEL, {"temperature": 0.2}), + ("models/gemini-3.8-flash-tts", {}), + (RECOMMENDED_TTS_MODEL, {"temperature": 0.2}), + ): + with patch( + "google.genai.models.AsyncModels.list", return_value=sampling_models_pager() + ): + flow = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry.subentry_id + ) + result = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {**advanced, CONF_CHAT_MODEL: model} + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.ABORT + assert subentry.data[CONF_TEMPERATURE] == 0.2 + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "parts": [ + { + "inlineData": { + "data": "YXVkaW8=", + "mimeType": "audio/L16;rate=24000", + } + } + ] + } + } + ] + } + ] + entity = hass.data[tts.DOMAIN].get_entity("tts.google_ai_tts") + with patch( + "homeassistant.components.google_generative_ai_conversation.tts.convert_to_wav", + return_value=b"wav", + ): + assert await entity.async_get_tts_audio( + "Hello", "en-US", {tts.ATTR_VOICE: "zephyr"} + ) == ("wav", b"wav") + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert { + key: config[key] for key in ("temperature", "topP", "topK") if key in config + } == expected + assert "thinkingConfig" not in config + with patch( + "google.genai.models.AsyncModels.list", return_value=sampling_models_pager() + ): + flow = await mock_config_entry.start_subentry_reconfigure_flow( + hass, subentry.subentry_id + ) + flow = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {CONF_RECOMMENDED: True} + ) + result = await hass.config_entries.subentries.async_configure( + flow["flow_id"], {CONF_RECOMMENDED: True} + ) + await hass.async_block_till_done() + assert result["type"] is FlowResultType.ABORT + assert subentry.data == {CONF_RECOMMENDED: True} + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "parts": [ + { + "inlineData": { + "data": "YXVkaW8=", + "mimeType": "audio/L16;rate=24000", + } + } + ] + } + } + ] + } + ] + entity = hass.data[tts.DOMAIN].get_entity("tts.google_ai_tts") + with patch( + "homeassistant.components.google_generative_ai_conversation.tts.convert_to_wav", + return_value=b"wav", + ): + assert await entity.async_get_tts_audio( + "Hello", "en-US", {tts.ATTR_VOICE: "zephyr"} + ) == ("wav", b"wav") + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert config["temperature"] == 1.0 + assert "thinkingConfig" not in config diff --git a/tests/components/google_generative_ai_conversation/test_conversation.py b/tests/components/google_generative_ai_conversation/test_conversation.py index e25f1a68fbe2..744f40ba6954 100644 --- a/tests/components/google_generative_ai_conversation/test_conversation.py +++ b/tests/components/google_generative_ai_conversation/test_conversation.py @@ -4,7 +4,13 @@ import datetime from unittest.mock import AsyncMock, patch from freezegun import freeze_time -from google.genai.types import GenerateContentResponse, ThinkingConfig, ThinkingLevel +from google.genai import Client +from google.genai.types import ( + GenerateContentConfig, + GenerateContentResponse, + ThinkingConfig, + ThinkingLevel, +) import pytest from syrupy.assertion import SnapshotAssertion @@ -15,8 +21,17 @@ from homeassistant.components.conversation import ( UserContent, trace, ) +from homeassistant.components.google_generative_ai_conversation.const import ( + CONF_CHAT_MODEL, + CONF_TEMPERATURE, + CONF_THINKING_BUDGET, + CONF_THINKING_LEVEL, + CONF_TOP_K, + CONF_TOP_P, +) from homeassistant.components.google_generative_ai_conversation.entity import ( ERROR_GETTING_RESPONSE, + GoogleGenerativeAILLMBaseEntity, _create_thinking_config, _escape_decode, _format_schema, @@ -1044,3 +1059,227 @@ async def test_token_stats_reported( "cached_input_tokens": 5, "output_tokens": 20, } + + +@pytest.mark.parametrize("prefix", ["", "models/"]) +@pytest.mark.parametrize( + ("model", "sampling"), + [ + ("gemini-2.0-flash", True), + ("gemini-2.5-pro", True), + ("gemini-3-flash", True), + ("gemini-3.1-flash-lite", True), + ("gemini-3.1-pro", True), + ("gemini-3.5-flash", True), + ("gemini-3.5-flash-preview-x", True), + ("gemini-3.5-flash-lite", False), + ("gemini-3.5-flash-lite-preview-x", False), + ("gemini-3.5-flash-liteish", True), + ("gemini-robotics-er-1.60-preview", False), + ("models/models/gemini-3.8-flash", True), + ("gemini-3.5-transcribe", False), + ("gemini-3.6-flash", False), + ("gemini-3.8-flash", False), + ("gemini-3.10-flash", False), + ("gemini-4-flash", False), + ("gemini-10-pro", False), + ("gemini-30-flash", False), + ("gemini-flash-latest", False), + ("gemini-pro-latest", False), + ("gemini-flash-lite-latest", False), + ("gemini-unknown-latest", False), + ("gemini-nano-banana-2.1", False), + ("gemini-robotics-er-2-preview", False), + ("gemini-robotics-er-1.6-preview", True), + ("gemini-3.1-flash-image", True), + ("gemini-3.8-flash-image", False), + ("gemini-3foo", False), + ("gemini-2.50-flash", True), + ("gemma-4-31b-it", True), + ("custom-latest", True), + ], +) +async def test_generation_sampling_request( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + prefix: str, + model: str, + sampling: bool, +) -> None: + """Prove field omission through the real SDK converter and request builder.""" + subentry = mock_config_entry.subentries["ulid-conversation"] + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={ + CONF_CHAT_MODEL: prefix + model, + CONF_TEMPERATURE: 0.2, + CONF_TOP_P: 0.7, + CONF_TOP_K: 17, + CONF_THINKING_BUDGET: 512, + CONF_THINKING_LEVEL: "low", + }, + ) + client = Client(api_key="test-api-key") + mock_config_entry.runtime_data = client + entity = GoogleGenerativeAILLMBaseEntity(mock_config_entry, subentry) + try: + await client.aio.models.generate_content( + model=prefix + model, + contents="Hello", + config=entity.create_generate_content_config(), + ) + finally: + await client.aio.aclose() + client.close() + request = mock_genai_transport.call_args.kwargs["http_request"] + config = request.data["generationConfig"] + assert { + key: config[key] for key in ("temperature", "topP", "topK") if key in config + } == ({"temperature": 0.2, "topP": 0.7, "topK": 17} if sampling else {}) + assert config["maxOutputTokens"] == 3000 + assert len(request.data["safetySettings"]) == 4 + assert subentry.data[CONF_TEMPERATURE] == 0.2 + + +@pytest.mark.parametrize("prefix", ["", "models/"]) +@pytest.mark.parametrize( + ("model", "level", "expected"), + [ + ("gemini-3.6-flash", "minimal", ThinkingLevel.MINIMAL), + ("gemini-3.5-flash-lite", "minimal", ThinkingLevel.MINIMAL), + ("gemini-3.5-flash", "minimal", ThinkingLevel.MINIMAL), + ("gemini-3.8-flash", "minimal", None), + ("gemini-3.8-flash", "low", ThinkingLevel.LOW), + ("gemini-3.8-flash", "medium", ThinkingLevel.MEDIUM), + ("gemini-3.8-flash", "high", ThinkingLevel.HIGH), + ("gemini-flash-latest", "low", ThinkingLevel.LOW), + ("gemini-pro-latest", "medium", ThinkingLevel.MEDIUM), + ("gemini-flash-lite-latest", "high", ThinkingLevel.HIGH), + ("gemini-flash-lite-latest", "minimal", None), + ("gemini-flash-latest", "auto", None), + ("gemini-pro-latest", None, None), + ("gemini-3.10-flash", "low", ThinkingLevel.LOW), + ("gemini-4-flash", "high", ThinkingLevel.HIGH), + ("gemini-4-pro", "minimal", None), + ("gemini-10-pro", "medium", ThinkingLevel.MEDIUM), + ("gemini-30-flash", "low", ThinkingLevel.LOW), + ("gemini-3.5-transcribe", "low", ThinkingLevel.LOW), + ], +) +async def test_generation_thinking_levels( + mock_genai_transport: AsyncMock, + prefix: str, + model: str, + level: str | None, + expected: ThinkingLevel | None, +) -> None: + """Supported configured levels survive; budgets never leak into level models.""" + config = _create_thinking_config(prefix + model, 512, level) + assert config is not None + assert config.include_thoughts is True + assert config.thinking_level == expected + assert config.thinking_budget is None + client = Client(api_key="test-api-key") + try: + await client.aio.models.generate_content( + model=prefix + model, + contents="Hello", + config=GenerateContentConfig(thinking_config=config), + ) + finally: + await client.aio.aclose() + client.close() + body = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert body["thinkingConfig"] == config.model_dump(exclude_none=True) + assert "thinking_budget" not in body["thinkingConfig"] + + +@pytest.mark.parametrize( + "model", + [ + "gemini-3foo", + "gemini-2.50-flash", + "gemini-4-flash-tts-preview", + "gemini-4-flash-image-preview", + "gemini-4-live", + "gemini-robotics-er-2-preview", + "gemini-nano-banana-2.1", + "custom-latest", + ], +) +def test_no_new_specialized_thinking(model: str) -> None: + """Do not invent thinking capability for specialized or unknown model names.""" + assert _create_thinking_config(model, 512, "low") is None + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize( + "model", ["gemini-3.8-flash", "gemini-flash-latest", "gemini-4-flash"] +) +async def test_conversation_wire_tool_continuation( + hass: HomeAssistant, + mock_config_entry_with_assist: MockConfigEntry, + mock_chat_log: MockChatLog, # noqa: F811 + mock_genai_transport: AsyncMock, + model: str, +) -> None: + """Exercise both streamed HTTP bodies with a real SDK chat and a tool result.""" + subentry = mock_config_entry_with_assist.subentries["ulid-conversation"] + hass.config_entries.async_update_subentry( + mock_config_entry_with_assist, + subentry, + data={**subentry.data, CONF_CHAT_MODEL: model, CONF_THINKING_LEVEL: "low"}, + ) + await hass.async_block_till_done() + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "role": "model", + "parts": [{"functionCall": {"name": "test_tool", "args": {}}}], + }, + "finishReason": "STOP", + } + ] + }, + { + "candidates": [ + { + "content": {"role": "model", "parts": [{"text": "Done"}]}, + "finishReason": "STOP", + } + ] + }, + ] + mock_chat_log.mock_tool_results({"mock-tool-call": {"result": "Done"}}) + result = await conversation.async_converse( + hass, + "Call the test tool", + mock_chat_log.conversation_id, + Context(), + agent_id="conversation.google_ai_conversation", + ) + assert result.response.response_type is intent.IntentResponseType.ACTION_DONE + assert mock_genai_transport.call_count == 2 + for call in mock_genai_transport.call_args_list: + assert call.kwargs["stream"] is True + body = call.kwargs["http_request"].data + config = body["generationConfig"] + assert not {"temperature", "topP", "topK"}.intersection(config) + assert config["thinkingConfig"] == { + "include_thoughts": True, + "thinking_level": "LOW", + } + assert config["maxOutputTokens"] == 3000 + assert body["tools"] + assert ( + "functionResponse" + in mock_genai_transport.call_args_list[1] + .kwargs["http_request"] + .data["contents"][-1]["parts"][0] + ) diff --git a/tests/components/google_generative_ai_conversation/test_stt.py b/tests/components/google_generative_ai_conversation/test_stt.py index 62b382d0a7f8..1d43aad175fb 100644 --- a/tests/components/google_generative_ai_conversation/test_stt.py +++ b/tests/components/google_generative_ai_conversation/test_stt.py @@ -9,6 +9,7 @@ import pytest from homeassistant.components import stt from homeassistant.components.google_generative_ai_conversation.const import ( CONF_CHAT_MODEL, + CONF_THINKING_LEVEL, DEFAULT_STT_PROMPT, DOMAIN, RECOMMENDED_STT_MODEL, @@ -359,3 +360,53 @@ async def test_stt_uses_default_model( call_args = mock_genai_client.aio.models.generate_content.call_args assert call_args.kwargs["model"] == RECOMMENDED_STT_MODEL + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize( + ("model", "sampling"), + [ + ("gemini-3.1-flash-lite", True), + ("gemini-3.8-flash", False), + ("gemini-flash-latest", False), + ("gemini-3.5-transcribe", False), + ], +) +async def test_stt_wire_parameters( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + model: str, + sampling: bool, +) -> None: + """Run a loaded STT entity through real SDK unary request construction.""" + subentry = mock_config_entry.subentries["ulid-stt"] + hass.config_entries.async_update_subentry( + mock_config_entry, + subentry, + data={**subentry.data, CONF_CHAT_MODEL: model, CONF_THINKING_LEVEL: "low"}, + ) + await hass.async_block_till_done() + entity = hass.data[stt.DOMAIN].get_entity("stt.google_ai_stt") + metadata = stt.SpeechMetadata( + language="en-US", + format=stt.AudioFormats.OGG, + codec=stt.AudioCodecs.OPUS, + bit_rate=stt.AudioBitRates.BITRATE_16, + sample_rate=stt.AudioSampleRates.SAMPLERATE_16000, + channel=stt.AudioChannels.CHANNEL_MONO, + ) + result = await entity.async_process_audio_stream( + metadata, _async_get_audio_stream(b"audio") + ) + assert result.result is stt.SpeechResultState.SUCCESS + assert result.text == "Done" + body = mock_genai_transport.call_args.kwargs["http_request"].data + config = body["generationConfig"] + assert {"temperature", "topP", "topK"}.issubset(config) is sampling + assert config["thinkingConfig"] == { + "include_thoughts": True, + "thinking_level": "LOW", + } + assert "en-US" in body["contents"][0]["parts"][0]["text"] + assert body["contents"][0]["parts"][1]["inlineData"]["mime_type"] == "audio/ogg" diff --git a/tests/components/google_generative_ai_conversation/test_tts.py b/tests/components/google_generative_ai_conversation/test_tts.py index 96382cbdd5a4..ce6dd12e640b 100644 --- a/tests/components/google_generative_ai_conversation/test_tts.py +++ b/tests/components/google_generative_ai_conversation/test_tts.py @@ -2,9 +2,11 @@ from collections.abc import Generator from http import HTTPStatus +from io import BytesIO from pathlib import Path from typing import Any from unittest.mock import AsyncMock, MagicMock, Mock, patch +import wave from google.genai import types from google.genai.errors import APIError @@ -25,6 +27,7 @@ from homeassistant.config_entries import ConfigSubentry from homeassistant.const import ATTR_ENTITY_ID, CONF_API_KEY from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.core_config import async_process_ha_core_config +from homeassistant.exceptions import HomeAssistantError from homeassistant.setup import async_setup_component from tests.common import MockConfigEntry, async_mock_service @@ -230,3 +233,125 @@ async def test_tts_service_speak_error( temperature=RECOMMENDED_TEMPERATURE, ), ) + + +@pytest.mark.usefixtures("mock_init_component") +@pytest.mark.parametrize( + ("model", "sampling"), + [ + ("gemini-2.5-flash-preview-tts", True), + ("gemini-3.1-flash-tts-preview", True), + ("gemini-3.8-flash-tts", False), + ("models/gemini-3.8-flash-lite-tts", False), + ("gemini-4-flash-tts-preview", False), + ], +) +async def test_tts_wire_parameters( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_genai_transport: AsyncMock, + model: str, + sampling: bool, +) -> None: + """TTS independently omits temperature, without adding thinking or changing voices.""" + subentry = mock_config_entry.subentries["ulid-tts"] + hass.config_entries.async_update_subentry( + mock_config_entry, subentry, data={**subentry.data, CONF_CHAT_MODEL: model} + ) + await hass.async_block_till_done() + mock_genai_transport.return_value = [ + { + "candidates": [ + { + "content": { + "role": "model", + "parts": [ + { + "inlineData": { + "data": "YXVkaW8=", + "mimeType": "audio/L16;rate=24000", + } + } + ], + } + } + ] + } + ] + entity = hass.data[tts.DOMAIN].get_entity("tts.google_ai_tts") + with patch( + "homeassistant.components.google_generative_ai_conversation.tts.convert_to_wav", + return_value=b"wav", + ): + assert await entity.async_get_tts_audio( + "Hello", "en-US", {tts.ATTR_VOICE: "zephyr"} + ) == ("wav", b"wav") + config = mock_genai_transport.call_args.kwargs["http_request"].data[ + "generationConfig" + ] + assert ("temperature" in config) is sampling + assert not {"thinkingConfig", "topP", "topK"}.intersection(config) + assert config["responseModalities"] == ["AUDIO"] + assert ( + config["speechConfig"]["voice_config"]["prebuilt_voice_config"]["voice_name"] + == "zephyr" + ) + + +@pytest.fixture +def wav_audio() -> bytes: + """Create a complete WAV with known PCM samples.""" + output = BytesIO() + with wave.open(output, "wb") as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(24000) + audio.writeframes(b"\x00\x00\x01\x00\xff\x7f\x00\x80") + return output.getvalue() + + +@pytest.mark.usefixtures("setup") +@pytest.mark.parametrize( + ("mime_type", "header_size"), + [("audio/wav", 0), ("audio/L16;rate=24000", 44)], +) +async def test_tts_audio_formats( + hass: HomeAssistant, + wav_audio: bytes, + mime_type: str, + header_size: int, +) -> None: + """Preserve complete WAV output and wrap legacy PCM exactly once.""" + entity = hass.data[tts.DOMAIN].get_entity("tts.google_ai_tts") + response = entity._genai_client.aio.models.generate_content.return_value + response.candidates[0].content.parts[0].inline_data = types.Blob( + data=wav_audio[header_size:], mime_type=mime_type + ) + + audio_format, audio_data = await entity.async_get_tts_audio( + "Hello", "en-US", dict(entity.default_options) + ) + + assert audio_format == "wav" + assert audio_data == wav_audio + with wave.open(BytesIO(audio_data), "rb") as audio: + assert audio.getnchannels() == 1 + assert audio.getsampwidth() == 2 + assert audio.getframerate() == 24000 + assert audio.getnframes() == 4 + assert audio.readframes(4) == b"\x00\x00\x01\x00\xff\x7f\x00\x80" + + +@pytest.mark.usefixtures("setup") +async def test_tts_unsupported_audio_format(hass: HomeAssistant) -> None: + """Keep unsupported audio formats as visible failures.""" + entity = hass.data[tts.DOMAIN].get_entity("tts.google_ai_tts") + response = entity._genai_client.aio.models.generate_content.return_value + response.candidates[0].content.parts[0].inline_data = types.Blob( + data=b"unsupported-audio", mime_type="audio/mpeg" + ) + + with pytest.raises( + HomeAssistantError, match="Unsupported audio MIME type: audio/mpeg" + ): + await entity.async_get_tts_audio("Hello", "en-US", dict(entity.default_options)) From 3cb08289ae3a684365ab31f22e4d2157217bed52 Mon Sep 17 00:00:00 2001 From: Matt Zimmerman Date: Sat, 10 Oct 2026 14:37:53 -0700 Subject: [PATCH 279/356] Fix SmartTub error sensor reporting stale historical errors (#185726) Co-authored-by: Claude Sonnet 5.5 --- .../components/smarttub/binary_sensor.py | 32 +++++-- .../components/smarttub/test_binary_sensor.py | 89 ++++++++++++++++++- 2 files changed, 110 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/smarttub/binary_sensor.py b/homeassistant/components/smarttub/binary_sensor.py index 3ec93fc049fa..d15db59bd0ed 100644 --- a/homeassistant/components/smarttub/binary_sensor.py +++ b/homeassistant/components/smarttub/binary_sensor.py @@ -16,7 +16,7 @@ from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import VolDictType from homeassistant.helpers.update_coordinator import DataUpdateCoordinator -from .const import ATTR_ERRORS, ATTR_REMINDERS, ATTR_SENSORS +from .const import ATTR_ERRORS, ATTR_REMINDERS, ATTR_SENSORS, ATTR_STATUS from .controller import SmartTubConfigEntry from .entity import ( SmartTubEntity, @@ -172,9 +172,12 @@ class SmartTubReminder(SmartTubEntity, BinarySensorEntity): class SmartTubError(SmartTubEntity, BinarySensorEntity): - """Indicates whether an error code is present. + """Indicates whether the spa is currently reporting an error. - There may be 0 or more errors. If there are >0, we show the first one. + The spa's status reports the current error code (0 means "All Clear"). The + errors endpoint also returns past errors, whose `active` flag can remain set + after the condition has cleared, so it is only used to look up details for + the error the status currently reports. """ _attr_device_class = BinarySensorDeviceClass.PROBLEM @@ -190,26 +193,37 @@ class SmartTubError(SmartTubEntity, BinarySensorEntity): "Error", ) + @property + def error_code(self) -> int: + """Return the error code currently reported by the spa (0 if none).""" + status = self.coordinator.data[self.spa.id][ATTR_STATUS] + return getattr(status, "error_code", None) or 0 + @property def error(self) -> SpaError | None: - """Return the underlying SpaError object for this entity.""" - errors = self.coordinator.data[self.spa.id][ATTR_ERRORS] - if len(errors) == 0: + """Return the SpaError for the current error code, if known.""" + if not (code := self.error_code): return None - return errors[0] + errors: list[SpaError] = self.coordinator.data[self.spa.id][ATTR_ERRORS] + matches = [error for error in errors if error.code == code] + return next((error for error in matches if error.active), None) or next( + iter(matches), None + ) @property @override def is_on(self) -> bool: """Return true if an error is signaled.""" - return self.error is not None + return self.error_code != 0 @property @override def extra_state_attributes(self) -> dict[str, Any]: """Return the state attributes.""" if (error := self.error) is None: - return {} + if not self.error_code: + return {} + return {ATTR_ERROR_CODE: self.error_code} return { ATTR_ERROR_CODE: error.code, diff --git a/tests/components/smarttub/test_binary_sensor.py b/tests/components/smarttub/test_binary_sensor.py index 2396b79e85ba..21c316bd37f6 100644 --- a/tests/components/smarttub/test_binary_sensor.py +++ b/tests/components/smarttub/test_binary_sensor.py @@ -1,6 +1,6 @@ """Test the SmartTub binary sensor platform.""" -from unittest.mock import create_autospec +from unittest.mock import MagicMock, create_autospec import pytest import smarttub @@ -9,6 +9,8 @@ from homeassistant.components.binary_sensor import STATE_OFF, STATE_ON from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util +from tests.common import MockConfigEntry + async def test_binary_sensors(spa, setup_entry, hass: HomeAssistant) -> None: """Test simple binary sensors.""" @@ -49,10 +51,17 @@ def mock_error(spa): return error -async def test_error(spa, hass: HomeAssistant, config_entry, mock_error) -> None: +async def test_error( + spa: MagicMock, + spa_state: smarttub.SpaStateFull, + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_error: MagicMock, +) -> None: """Test the error sensor.""" spa.get_errors.return_value = [mock_error] + spa_state.error_code = mock_error.code config_entry.add_to_hass(hass) await hass.config_entries.async_setup(config_entry.entry_id) @@ -66,6 +75,82 @@ async def test_error(spa, hass: HomeAssistant, config_entry, mock_error) -> None assert state.attributes["error_code"] == 11 +async def test_error_matches_current_code( + spa: MagicMock, + spa_state: smarttub.SpaStateFull, + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_error: MagicMock, +) -> None: + """Test details come from the entry matching the current status code.""" + + older_error = create_autospec(smarttub.SpaError, instance=True) + older_error.code = 1002 + older_error.title = "AC POWER DISCONNECTED" + older_error.description = None + older_error.active = True + older_error.created_at = dt_util.utcnow() + older_error.updated_at = dt_util.utcnow() + older_error.error_type = "SYS_ERROR" + + spa.get_errors.return_value = [older_error, mock_error] + spa_state.error_code = mock_error.code + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(f"binary_sensor.{spa.brand}_{spa.model}_error") + assert state is not None + assert state.state == STATE_ON + assert state.attributes["error_code"] == mock_error.code + assert state.attributes["error_title"] == mock_error.title + + +async def test_error_history_ignored( + spa: MagicMock, + spa_state: smarttub.SpaStateFull, + hass: HomeAssistant, + config_entry: MockConfigEntry, + mock_error: MagicMock, +) -> None: + """Test a stale error in the errors list does not trigger the sensor.""" + + spa.get_errors.return_value = [mock_error] + spa_state.error_code = 0 + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(f"binary_sensor.{spa.brand}_{spa.model}_error") + assert state is not None + assert state.state == STATE_OFF + assert "error_code" not in state.attributes + + +async def test_error_without_history_entry( + spa: MagicMock, + spa_state: smarttub.SpaStateFull, + hass: HomeAssistant, + config_entry: MockConfigEntry, +) -> None: + """Test the sensor is on, with only the code, when no history entry matches.""" + + spa.get_errors.return_value = [] + spa_state.error_code = 42 + + config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get(f"binary_sensor.{spa.brand}_{spa.model}_error") + assert state is not None + assert state.state == STATE_ON + assert state.attributes["error_code"] == 42 + assert "error_title" not in state.attributes + + async def test_snooze_reminder(spa, setup_entry, hass: HomeAssistant) -> None: """Test snoozing a reminder.""" From 5cfab0df7e639441364b37affa3ed9c5b34efb35 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 10 Oct 2026 15:35:18 -1000 Subject: [PATCH 280/356] Bump aiohttp to 3.14.5 (#185746) --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 2c44ba8fcffe..3a4297a52227 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -6,7 +6,7 @@ aiodns==4.0.4 aiogithubapi==26.0.0 aiohttp-asyncmdnsresolver==0.2.0 aiohttp-fast-zlib==0.3.0 -aiohttp==3.14.4 +aiohttp==3.14.5 aiohttp_cors==0.8.1 aiousbwatcher==1.1.2 aiozoneinfo==0.2.3 diff --git a/pyproject.toml b/pyproject.toml index f530c7d4333b..6bde6016a742 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,7 +28,7 @@ dependencies = [ # module level in `bootstrap.py` and its requirements thus need to be in # requirements.txt to ensure they are always installed "aiogithubapi==26.0.0", - "aiohttp==3.14.4", + "aiohttp==3.14.5", "aiohttp_cors==0.8.1", "aiohttp-fast-zlib==0.3.0", "aiohttp-asyncmdnsresolver==0.2.0", diff --git a/requirements.txt b/requirements.txt index 2bd1fe3f0a70..42160d92f3ed 100644 --- a/requirements.txt +++ b/requirements.txt @@ -7,7 +7,7 @@ aiodns==4.0.4 aiogithubapi==26.0.0 aiohttp-asyncmdnsresolver==0.2.0 aiohttp-fast-zlib==0.3.0 -aiohttp==3.14.4 +aiohttp==3.14.5 aiohttp_cors==0.8.1 aiozoneinfo==0.2.3 annotatedyaml==1.0.2 From 547e1aaec5b20e819ea46bbe94fb6d386aa02f22 Mon Sep 17 00:00:00 2001 From: alexborro Date: Mon, 12 Oct 2026 14:18:47 +0200 Subject: [PATCH 281/356] Mark Aquacell sensors unavailable when data is stale (#185762) --- homeassistant/components/aquacell/const.py | 1 + homeassistant/components/aquacell/entity.py | 8 +++ homeassistant/components/aquacell/sensor.py | 14 +++++ tests/components/aquacell/test_sensor.py | 67 ++++++++++++++++++++- 4 files changed, 89 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/aquacell/const.py b/homeassistant/components/aquacell/const.py index 818c96fc53a1..28323d9a59f6 100644 --- a/homeassistant/components/aquacell/const.py +++ b/homeassistant/components/aquacell/const.py @@ -11,3 +11,4 @@ CONF_REFRESH_TOKEN_CREATION_TIME = "refresh_token_creation_time" REFRESH_TOKEN_EXPIRY_TIME = timedelta(days=30) UPDATE_INTERVAL = timedelta(days=1) +STALE_DATA_TIMEOUT = timedelta(days=3) diff --git a/homeassistant/components/aquacell/entity.py b/homeassistant/components/aquacell/entity.py index 8d4fea5d39d0..c136de3899dc 100644 --- a/homeassistant/components/aquacell/entity.py +++ b/homeassistant/components/aquacell/entity.py @@ -1,5 +1,7 @@ """Aquacell entity.""" +from typing import override + from aioaquacell import Softener from homeassistant.helpers.device_registry import DeviceInfo @@ -35,6 +37,12 @@ class AquacellEntity(CoordinatorEntity[AquacellCoordinator]): serial_number=softener_key, ) + @property + @override + def available(self) -> bool: + """Return if the softener is still returned by the API.""" + return super().available and self.softener_key in self.coordinator.data + @property def softener(self) -> Softener: """Handle updated data from the coordinator.""" diff --git a/homeassistant/components/aquacell/sensor.py b/homeassistant/components/aquacell/sensor.py index 256635a5bad8..d714f19e7934 100644 --- a/homeassistant/components/aquacell/sensor.py +++ b/homeassistant/components/aquacell/sensor.py @@ -17,7 +17,9 @@ from homeassistant.const import PERCENTAGE, UnitOfTime from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.helpers.typing import StateType +from homeassistant.util import dt as dt_util +from .const import STALE_DATA_TIMEOUT from .coordinator import AquacellConfigEntry, AquacellCoordinator from .entity import AquacellEntity @@ -29,6 +31,7 @@ class SoftenerSensorEntityDescription(SensorEntityDescription): """Describes Softener sensor entity.""" value_fn: Callable[[Softener], StateType | datetime] + available_when_stale: bool = False SENSORS: tuple[SoftenerSensorEntityDescription, ...] = ( @@ -82,6 +85,7 @@ SENSORS: tuple[SoftenerSensorEntityDescription, ...] = ( translation_key="last_update", device_class=SensorDeviceClass.TIMESTAMP, value_fn=lambda softener: softener.diagnostics.last_update, + available_when_stale=True, ), ) @@ -116,6 +120,16 @@ class SoftenerSensor(AquacellEntity, SensorEntity): self.entity_description = description + @property + @override + def available(self) -> bool: + """Return if the softener reported to the cloud recently.""" + return super().available and ( + self.entity_description.available_when_stale + or dt_util.utcnow() - self.softener.diagnostics.last_update + < STALE_DATA_TIMEOUT + ) + @property @override def native_value(self) -> StateType | datetime: diff --git a/tests/components/aquacell/test_sensor.py b/tests/components/aquacell/test_sensor.py index 49f724c6753e..b4e8cfad3673 100644 --- a/tests/components/aquacell/test_sensor.py +++ b/tests/components/aquacell/test_sensor.py @@ -2,16 +2,27 @@ from unittest.mock import AsyncMock +from freezegun.api import FrozenDateTimeFactory +import pytest from syrupy.assertion import SnapshotAssertion +from homeassistant.components.aquacell.const import STALE_DATA_TIMEOUT, UPDATE_INTERVAL +from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er +from homeassistant.util import dt as dt_util from . import setup_integration -from tests.common import MockConfigEntry, snapshot_platform +from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform + +ENTITY_ID = "sensor.aquacell_name_battery" +LAST_UPDATE_ENTITY_ID = "sensor.aquacell_name_last_update" +# Matches lastUpdate in the softener fixture +LAST_UPDATE = "2024-05-10 07:44:30+00:00" +@pytest.mark.freeze_time(LAST_UPDATE) async def test_sensors( hass: HomeAssistant, mock_aquacell_api: AsyncMock, @@ -22,3 +33,57 @@ async def test_sensors( """Test the creation of Aquacell sensors.""" await setup_integration(hass, mock_config_entry) await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) + + +@pytest.mark.freeze_time(LAST_UPDATE) +async def test_sensors_unavailable_when_softener_missing( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_aquacell_api: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test sensors become unavailable when the softener is no longer returned.""" + await setup_integration(hass, mock_config_entry) + softeners = mock_aquacell_api.get_all_softeners.return_value + assert hass.states.get(ENTITY_ID).state == "40" + + mock_aquacell_api.get_all_softeners.return_value = [] + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + mock_aquacell_api.get_all_softeners.return_value = softeners + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == "40" + + +@pytest.mark.freeze_time(LAST_UPDATE) +async def test_sensors_unavailable_when_data_is_stale( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_aquacell_api: AsyncMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test sensors become unavailable when the softener stops reporting.""" + await setup_integration(hass, mock_config_entry) + assert hass.states.get(ENTITY_ID).state == "40" + + freezer.tick(STALE_DATA_TIMEOUT) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + assert hass.states.get(LAST_UPDATE_ENTITY_ID).state == "2024-05-10T07:44:30+00:00" + + softener = mock_aquacell_api.get_all_softeners.return_value[0] + softener.diagnostics.last_update = dt_util.utcnow() + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert hass.states.get(ENTITY_ID).state == "40" From 81a9817b9e4fa2efc87f0f01af3403b2816e583c Mon Sep 17 00:00:00 2001 From: feixm1 Date: Mon, 12 Oct 2026 14:42:44 +0200 Subject: [PATCH 282/356] Bump aionanoleaf2 to 1.0.5 (#185777) --- homeassistant/components/nanoleaf/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nanoleaf/manifest.json b/homeassistant/components/nanoleaf/manifest.json index faf0cf72e7ff..d345b6dd0e18 100644 --- a/homeassistant/components/nanoleaf/manifest.json +++ b/homeassistant/components/nanoleaf/manifest.json @@ -16,7 +16,7 @@ "integration_type": "device", "iot_class": "local_push", "loggers": ["aionanoleaf2"], - "requirements": ["aionanoleaf2==1.0.2"], + "requirements": ["aionanoleaf2==1.0.5"], "ssdp": [ { "st": "Nanoleaf_aurora:light" diff --git a/requirements_all.txt b/requirements_all.txt index c1a9d307f190..699251254f9a 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -354,7 +354,7 @@ aiomodernforms==0.3.1 aiomusiccast==0.15.0 # homeassistant.components.nanoleaf -aionanoleaf2==1.0.2 +aionanoleaf2==1.0.5 # homeassistant.components.notion aionotion==2024.03.0 From 0e24d9ff500a3226320bc98b5c5cd5b1fc7d81df Mon Sep 17 00:00:00 2001 From: rrooggiieerr Date: Sun, 11 Oct 2026 15:20:14 +0200 Subject: [PATCH 283/356] Bump my-pv to 0.0.13 (#185797) --- homeassistant/components/my_pv/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/my_pv/manifest.json b/homeassistant/components/my_pv/manifest.json index e4d9b11bce15..3953dae93709 100644 --- a/homeassistant/components/my_pv/manifest.json +++ b/homeassistant/components/my_pv/manifest.json @@ -16,6 +16,6 @@ "iot_class": "local_polling", "loggers": ["my_pv"], "quality_scale": "bronze", - "requirements": ["my-pv==0.0.12"], + "requirements": ["my-pv==0.0.13"], "zeroconf": ["_mypv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 699251254f9a..2696cce55482 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1686,7 +1686,7 @@ mutesync==0.0.1 mvg==1.6.0 # homeassistant.components.my_pv -my-pv==0.0.12 +my-pv==0.0.13 # homeassistant.components.myuplink myuplink==0.7.0 From 5c52c970417cb057b37785103594fad6f8ca9865 Mon Sep 17 00:00:00 2001 From: Maciej Bieniek Date: Sun, 11 Oct 2026 15:49:08 +0200 Subject: [PATCH 284/356] Catch TimeoutError in the Nettigo Air Monitor integration (#185812) --- homeassistant/components/nam/__init__.py | 2 +- homeassistant/components/nam/button.py | 2 +- homeassistant/components/nam/coordinator.py | 2 +- tests/components/nam/test_button.py | 2 +- tests/components/nam/test_init.py | 7 +++++-- tests/components/nam/test_sensor.py | 2 +- 6 files changed, 10 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/nam/__init__.py b/homeassistant/components/nam/__init__.py index f5824c988ab8..cac7553e28ff 100644 --- a/homeassistant/components/nam/__init__.py +++ b/homeassistant/components/nam/__init__.py @@ -36,7 +36,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: NAMConfigEntry) -> bool: options = ConnectionOptions(host=host, username=username, password=password) try: nam = await NettigoAirMonitor.create(websession, options) - except (ApiError, ClientError) as err: + except (ApiError, ClientError, TimeoutError) as err: raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="device_communication_error", diff --git a/homeassistant/components/nam/button.py b/homeassistant/components/nam/button.py index d43de40d8da3..916d8d06b776 100644 --- a/homeassistant/components/nam/button.py +++ b/homeassistant/components/nam/button.py @@ -66,7 +66,7 @@ class NAMButton(CoordinatorEntity[NAMDataUpdateCoordinator], ButtonEntity): """Triggers the restart.""" try: await self.coordinator.nam.async_restart() - except (ApiError, ClientError) as err: + except (ApiError, ClientError, TimeoutError) as err: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="device_communication_action_error", diff --git a/homeassistant/components/nam/coordinator.py b/homeassistant/components/nam/coordinator.py index 31579e34d1bb..dddc877436e5 100644 --- a/homeassistant/components/nam/coordinator.py +++ b/homeassistant/components/nam/coordinator.py @@ -64,7 +64,7 @@ class NAMDataUpdateCoordinator(DataUpdateCoordinator[NAMSensors]): data = await self.nam.async_update() # We do not need to catch AuthFailed exception here because sensor data is # always available without authorization. - except (ApiError, InvalidSensorDataError, RetryError) as error: + except (ApiError, InvalidSensorDataError, RetryError, TimeoutError) as error: raise UpdateFailed( translation_domain=DOMAIN, translation_key="update_error", diff --git a/tests/components/nam/test_button.py b/tests/components/nam/test_button.py index b812fc7d3c0a..fed058b770b3 100644 --- a/tests/components/nam/test_button.py +++ b/tests/components/nam/test_button.py @@ -62,7 +62,7 @@ async def test_button_press(hass: HomeAssistant) -> None: assert state.state == now.isoformat() -@pytest.mark.parametrize(("exc"), [ApiError("API Error"), ClientError]) +@pytest.mark.parametrize(("exc"), [ApiError("API Error"), ClientError, TimeoutError]) async def test_button_press_exc(hass: HomeAssistant, exc: Exception) -> None: """Test button press when exception occurs.""" await init_integration(hass) diff --git a/tests/components/nam/test_init.py b/tests/components/nam/test_init.py index 878d90e19ceb..18e4101b77b6 100644 --- a/tests/components/nam/test_init.py +++ b/tests/components/nam/test_init.py @@ -2,7 +2,9 @@ from unittest.mock import patch +from aiohttp.client_exceptions import ClientError from nettigo_air_monitor import ApiError, AuthFailedError +import pytest from homeassistant.components.air_quality import DOMAIN as AIR_QUALITY_DOMAIN from homeassistant.components.nam.const import DOMAIN @@ -26,7 +28,8 @@ async def test_async_setup_entry(hass: HomeAssistant) -> None: assert state.state == "11.03" -async def test_config_not_ready(hass: HomeAssistant) -> None: +@pytest.mark.parametrize("exc", [ApiError("API Error"), ClientError, TimeoutError]) +async def test_config_not_ready(hass: HomeAssistant, exc: Exception) -> None: """Test for setup failure if the connection to the device fails.""" entry = MockConfigEntry( domain=DOMAIN, @@ -38,7 +41,7 @@ async def test_config_not_ready(hass: HomeAssistant) -> None: with patch( "homeassistant.components.nam.NettigoAirMonitor.initialize", - side_effect=ApiError("API Error"), + side_effect=exc, ): await hass.config_entries.async_setup(entry.entry_id) assert entry.state is ConfigEntryState.SETUP_RETRY diff --git a/tests/components/nam/test_sensor.py b/tests/components/nam/test_sensor.py index 2e3a1be72ac9..0da873342ac6 100644 --- a/tests/components/nam/test_sensor.py +++ b/tests/components/nam/test_sensor.py @@ -102,7 +102,7 @@ async def test_incompleta_data_after_device_restart(hass: HomeAssistant) -> None assert state.state == STATE_UNAVAILABLE -@pytest.mark.parametrize("exc", [ApiError("API Error"), RetryError]) +@pytest.mark.parametrize("exc", [ApiError("API Error"), RetryError, TimeoutError]) async def test_availability( hass: HomeAssistant, freezer: FrozenDateTimeFactory, exc: Exception ) -> None: From d562ad3ff78d5add72f47dbef4ab711f0f6523f8 Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Sun, 11 Oct 2026 15:58:52 +0200 Subject: [PATCH 285/356] Ignore devices without TR-064 support during FRITZ!Box Tools SSDP discovery (#185816) Co-authored-by: Copilot --- homeassistant/components/fritz/config_flow.py | 18 ++++++++++++++ homeassistant/components/fritz/strings.json | 3 ++- tests/components/fritz/test_config_flow.py | 24 +++++++++++++++++-- 3 files changed, 42 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/fritz/config_flow.py b/homeassistant/components/fritz/config_flow.py index b5012cb0b40a..55c9b98c1bdf 100644 --- a/homeassistant/components/fritz/config_flow.py +++ b/homeassistant/components/fritz/config_flow.py @@ -116,6 +116,21 @@ class FritzBoxToolsFlowHandler(ConfigFlow, domain=DOMAIN): return None + async def async_has_tr064_support(self) -> bool: + """Check if the device supports TR-064.""" + return await self.hass.async_add_executor_job(self.has_tr064_support) + + def has_tr064_support(self) -> bool: + """Check if the device supports TR-064.""" + try: + # During initialization, FritzConnection tries to fetch the TR-064 + # description file from the device. If it does not exist, the + # library raises a FritzConnectionException. + FritzConnection(address=self._host) + except FritzConnectionException: + return False + return True + async def async_check_configured_entry(self) -> FritzConfigEntry | None: """Check if entry is configured.""" current_host = await self.hass.async_add_executor_job( @@ -185,6 +200,9 @@ class FritzBoxToolsFlowHandler(ConfigFlow, domain=DOMAIN): self.hass.config_entries.async_update_entry(entry, unique_id=uuid) return self.async_abort(reason="already_configured") + if not await self.async_has_tr064_support(): + return self.async_abort(reason="not_supported") + self.context.update( { "title_placeholders": {"name": self._name.replace("FRITZ!Box ", "")}, diff --git a/homeassistant/components/fritz/strings.json b/homeassistant/components/fritz/strings.json index 122306d5faeb..750aeac95b33 100644 --- a/homeassistant/components/fritz/strings.json +++ b/homeassistant/components/fritz/strings.json @@ -12,7 +12,8 @@ "abort": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", "already_in_progress": "[%key:common::config_flow::abort::already_in_progress%]", - "ignore_ip6_link_local": "IPv6 link local address is not supported." + "ignore_ip6_link_local": "IPv6 link local address is not supported.", + "not_supported": "This device does not support the TR-064 API." }, "error": { "already_configured": "[%key:common::config_flow::abort::already_configured_device%]", diff --git a/tests/components/fritz/test_config_flow.py b/tests/components/fritz/test_config_flow.py index cea7bca83cd1..4b2a62839f1a 100644 --- a/tests/components/fritz/test_config_flow.py +++ b/tests/components/fritz/test_config_flow.py @@ -734,11 +734,11 @@ async def test_ssdp(hass: HomeAssistant, fc_class_mock) -> None: async def test_ssdp_exception(hass: HomeAssistant) -> None: - """Test starting a flow from discovery but no device found.""" + """Test starting a flow from discovery but setup fails later.""" with ( patch( "homeassistant.components.fritz.config_flow.FritzConnection", - side_effect=FritzConnectionException, + side_effect=[MagicMock(), FritzConnectionException], ), patch( "homeassistant.components.fritz.config_flow.socket.gethostbyname", @@ -763,6 +763,26 @@ async def test_ssdp_exception(hass: HomeAssistant) -> None: assert result["step_id"] == "confirm" +async def test_ssdp_not_supported(hass: HomeAssistant) -> None: + """Test discovery is aborted when the router does not provide TR-064.""" + with ( + patch( + "homeassistant.components.fritz.config_flow.FritzConnection", + side_effect=FritzConnectionException, + ), + patch( + "homeassistant.components.fritz.config_flow.socket.gethostbyname", + return_value=MOCK_IPS["fritz.box"], + ), + ): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "not_supported" + + async def test_options_flow(hass: HomeAssistant, fc_class_mock) -> None: """Test options flow.""" From e6412cc39814266d0136afb93d58b2238fc44fdd Mon Sep 17 00:00:00 2001 From: Joakim Plate Date: Mon, 12 Oct 2026 01:08:01 +0200 Subject: [PATCH 286/356] Bump arcam-fmj to 3.0.1 (#185887) --- homeassistant/components/arcam_fmj/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/arcam_fmj/manifest.json b/homeassistant/components/arcam_fmj/manifest.json index 05afce105545..24b253c46afc 100644 --- a/homeassistant/components/arcam_fmj/manifest.json +++ b/homeassistant/components/arcam_fmj/manifest.json @@ -7,7 +7,7 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["arcam"], - "requirements": ["arcam-fmj==3.0.0"], + "requirements": ["arcam-fmj==3.0.1"], "ssdp": [ { "deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1", diff --git a/requirements_all.txt b/requirements_all.txt index 2696cce55482..604e5b69c11b 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -573,7 +573,7 @@ aqualogic==2.6 aranet4==2.6.0 # homeassistant.components.arcam_fmj -arcam-fmj==3.0.0 +arcam-fmj==3.0.1 # homeassistant.components.arris_tg2492lg arris-tg2492lg==2.2.0 From 4caf8ddcc05c3e5dfdd8963bb47341e1102eaed5 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Mon, 12 Oct 2026 08:20:18 -0400 Subject: [PATCH 287/356] Handle Alexa RequireRelink on cloud entity registry updates (#185894) Co-authored-by: Claude --- .../components/cloud/alexa_config.py | 2 +- tests/components/cloud/test_alexa_config.py | 48 +++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/cloud/alexa_config.py b/homeassistant/components/cloud/alexa_config.py index 4768d7e9f2b4..d9c5cc69a194 100644 --- a/homeassistant/components/cloud/alexa_config.py +++ b/homeassistant/components/cloud/alexa_config.py @@ -559,5 +559,5 @@ class CloudAlexaConfig(alexa_config.AbstractConfig): if "old_entity_id" in event.data: to_remove.append(event.data["old_entity_id"]) - with suppress(alexa_errors.NoTokenAvailable): + with suppress(alexa_errors.NoTokenAvailable, alexa_errors.RequireRelink): await self._sync_helper(to_update, to_remove) diff --git a/tests/components/cloud/test_alexa_config.py b/tests/components/cloud/test_alexa_config.py index bc4773a5ff26..1063a43c63fa 100644 --- a/tests/components/cloud/test_alexa_config.py +++ b/tests/components/cloud/test_alexa_config.py @@ -968,3 +968,51 @@ async def test_alexa_config_prefs_update_without_linked_skill( # The sync could not authenticate, so the skill is marked as needing a relink. assert conf.authorized is False assert "RequireRelink" not in caplog.text + + +@pytest.mark.parametrize( + "lib_exception", + [ + pytest.param( + AlexaApiNeedsRelinkError("RefreshTokenNotFound"), id="needs_relink" + ), + pytest.param(AlexaApiNoTokenError("OtherReason"), id="no_token"), + ], +) +async def test_alexa_entity_registry_sync_without_linked_skill( + hass: HomeAssistant, + cloud_prefs: CloudPreferences, + entity_registry: er.EntityRegistry, + caplog: pytest.LogCaptureFixture, + lib_exception: Exception, +) -> None: + """Test entity registry updates when the Alexa skill is not linked.""" + assert await async_setup_component(hass, "homeassistant", {}) + expose_new(hass, True) + + await cloud_prefs.async_update(alexa_enabled=True, alexa_report_state=False) + conf = alexa_config.CloudAlexaConfig( + hass, + ALEXA_SCHEMA({}), + "mock-user-id", + cloud_prefs, + Mock( + is_logged_in=True, + subscription_expired=False, + servicehandlers_server="example", + auth=Mock(async_check_token=AsyncMock()), + websession=async_get_clientsession(hass), + alexa_api=Mock(access_token=AsyncMock(side_effect=lib_exception)), + ), + ) + await conf.async_initialize() + await hass.async_block_till_done() + + entity_registry.async_get_or_create( + "light", "test", "unique", suggested_object_id="kitchen" + ) + await hass.async_block_till_done() + + conf._cloud.alexa_api.access_token.assert_awaited() + assert "RequireRelink" not in caplog.text + assert "NoTokenAvailable" not in caplog.text From 708c1cb23918f598c7cfbbcb31c1dece7c739a4c Mon Sep 17 00:00:00 2001 From: Brett Adams Date: Mon, 12 Oct 2026 22:19:23 +1000 Subject: [PATCH 288/356] Redact schedule coordinates in Teslemetry and Tesla Fleet diagnostics (#185905) --- .../components/tesla_fleet/diagnostics.py | 7 +++ .../components/teslemetry/diagnostics.py | 7 +++ .../tesla_fleet/fixtures/vehicle_data.json | 48 +++++++++++++++++++ .../snapshots/test_diagnostics.ambr | 40 ++++++++++++++++ .../teslemetry/fixtures/vehicle_data.json | 48 +++++++++++++++++++ .../snapshots/test_diagnostics.ambr | 40 ++++++++++++++++ 6 files changed, 190 insertions(+) diff --git a/homeassistant/components/tesla_fleet/diagnostics.py b/homeassistant/components/tesla_fleet/diagnostics.py index d2b94fd62fd4..8be9ead4e4ec 100644 --- a/homeassistant/components/tesla_fleet/diagnostics.py +++ b/homeassistant/components/tesla_fleet/diagnostics.py @@ -20,6 +20,13 @@ VEHICLE_REDACT = [ "drive_state_longitude", "drive_state_native_latitude", "drive_state_native_longitude", + "charge_schedule_data_charge_schedule_window_latitude", + "charge_schedule_data_charge_schedule_window_longitude", + "preconditioning_schedule_data_preconditioning_schedule_window_latitude", + "preconditioning_schedule_data_preconditioning_schedule_window_longitude", + # Schedule lists are not flattened, so their entries keep plain keys + "latitude", + "longitude", ] ENERGY_LIVE_REDACT = ["vin"] diff --git a/homeassistant/components/teslemetry/diagnostics.py b/homeassistant/components/teslemetry/diagnostics.py index 00532eecdb77..6f8e4cff00f1 100644 --- a/homeassistant/components/teslemetry/diagnostics.py +++ b/homeassistant/components/teslemetry/diagnostics.py @@ -21,6 +21,13 @@ VEHICLE_REDACT = [ "drive_state_longitude", "drive_state_native_latitude", "drive_state_native_longitude", + "charge_schedule_data_charge_schedule_window_latitude", + "charge_schedule_data_charge_schedule_window_longitude", + "preconditioning_schedule_data_preconditioning_schedule_window_latitude", + "preconditioning_schedule_data_preconditioning_schedule_window_longitude", + # Schedule lists are not flattened, so their entries keep plain keys + "latitude", + "longitude", ] ENERGY_LIVE_REDACT = ["vin", "din"] diff --git a/tests/components/tesla_fleet/fixtures/vehicle_data.json b/tests/components/tesla_fleet/fixtures/vehicle_data.json index d99bc8de5a80..76110df6e7e7 100644 --- a/tests/components/tesla_fleet/fixtures/vehicle_data.json +++ b/tests/components/tesla_fleet/fixtures/vehicle_data.json @@ -71,6 +71,54 @@ "usable_battery_level": 77, "user_charge_enable_request": null }, + "charge_schedule_data": { + "charge_schedule_window": { + "enabled": false, + "end_time": 0, + "latitude": -30.222626, + "longitude": -97.6236871, + "start_time": 0 + }, + "charge_schedules": [ + { + "days_of_week": 127, + "enabled": true, + "end_enabled": false, + "end_time": 0, + "id": 1, + "latitude": -30.222626, + "longitude": -97.6236871, + "name": "Home", + "one_time": false, + "start_enabled": true, + "start_time": 1320 + } + ], + "max_num_charge_schedules": 10, + "next_schedule": false + }, + "preconditioning_schedule_data": { + "max_num_precondition_schedules": 10, + "preconditioning_schedule_window": { + "enabled": false, + "end_time": 0, + "latitude": -30.222626, + "longitude": -97.6236871, + "start_time": 0 + }, + "precondition_schedules": [ + { + "days_of_week": 31, + "enabled": true, + "id": 1, + "latitude": -30.222626, + "longitude": -97.6236871, + "name": "Work", + "one_time": false, + "precondition_time": 450 + } + ] + }, "climate_state": { "allow_cabin_overheat_protection": true, "auto_seat_climate_left": true, diff --git a/tests/components/tesla_fleet/snapshots/test_diagnostics.ambr b/tests/components/tesla_fleet/snapshots/test_diagnostics.ambr index cdb24b1d2b59..dd824e8184d3 100644 --- a/tests/components/tesla_fleet/snapshots/test_diagnostics.ambr +++ b/tests/components/tesla_fleet/snapshots/test_diagnostics.ambr @@ -180,6 +180,28 @@ 'backseat_token_updated_at': None, 'ble_autopair_enrolled': False, 'calendar_enabled': True, + 'charge_schedule_data_charge_schedule_window_enabled': False, + 'charge_schedule_data_charge_schedule_window_end_time': 0, + 'charge_schedule_data_charge_schedule_window_latitude': '**REDACTED**', + 'charge_schedule_data_charge_schedule_window_longitude': '**REDACTED**', + 'charge_schedule_data_charge_schedule_window_start_time': 0, + 'charge_schedule_data_charge_schedules': list([ + dict({ + 'days_of_week': 127, + 'enabled': True, + 'end_enabled': False, + 'end_time': 0, + 'id': '**REDACTED**', + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'name': 'Home', + 'one_time': False, + 'start_enabled': True, + 'start_time': 1320, + }), + ]), + 'charge_schedule_data_max_num_charge_schedules': 10, + 'charge_schedule_data_next_schedule': False, 'charge_state_battery_heater_on': False, 'charge_state_battery_level': 77, 'charge_state_battery_range': 266.87, @@ -300,6 +322,24 @@ 'id': '**REDACTED**', 'id_s': '**REDACTED**', 'in_service': False, + 'preconditioning_schedule_data_max_num_precondition_schedules': 10, + 'preconditioning_schedule_data_precondition_schedules': list([ + dict({ + 'days_of_week': 31, + 'enabled': True, + 'id': '**REDACTED**', + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'name': 'Work', + 'one_time': False, + 'precondition_time': 450, + }), + ]), + 'preconditioning_schedule_data_preconditioning_schedule_window_enabled': False, + 'preconditioning_schedule_data_preconditioning_schedule_window_end_time': 0, + 'preconditioning_schedule_data_preconditioning_schedule_window_latitude': '**REDACTED**', + 'preconditioning_schedule_data_preconditioning_schedule_window_longitude': '**REDACTED**', + 'preconditioning_schedule_data_preconditioning_schedule_window_start_time': 0, 'state': 'online', 'tokens': '**REDACTED**', 'user_id': '**REDACTED**', diff --git a/tests/components/teslemetry/fixtures/vehicle_data.json b/tests/components/teslemetry/fixtures/vehicle_data.json index 8396ac74d23c..1c8e35cb31d5 100644 --- a/tests/components/teslemetry/fixtures/vehicle_data.json +++ b/tests/components/teslemetry/fixtures/vehicle_data.json @@ -71,6 +71,54 @@ "usable_battery_level": 77, "user_charge_enable_request": null }, + "charge_schedule_data": { + "charge_schedule_window": { + "enabled": false, + "end_time": 0, + "latitude": -30.222626, + "longitude": -97.6236871, + "start_time": 0 + }, + "charge_schedules": [ + { + "days_of_week": 127, + "enabled": true, + "end_enabled": false, + "end_time": 0, + "id": 1, + "latitude": -30.222626, + "longitude": -97.6236871, + "name": "Home", + "one_time": false, + "start_enabled": true, + "start_time": 1320 + } + ], + "max_num_charge_schedules": 10, + "next_schedule": false + }, + "preconditioning_schedule_data": { + "max_num_precondition_schedules": 10, + "preconditioning_schedule_window": { + "enabled": false, + "end_time": 0, + "latitude": -30.222626, + "longitude": -97.6236871, + "start_time": 0 + }, + "precondition_schedules": [ + { + "days_of_week": 31, + "enabled": true, + "id": 1, + "latitude": -30.222626, + "longitude": -97.6236871, + "name": "Work", + "one_time": false, + "precondition_time": 450 + } + ] + }, "climate_state": { "allow_cabin_overheat_protection": true, "auto_seat_climate_left": true, diff --git a/tests/components/teslemetry/snapshots/test_diagnostics.ambr b/tests/components/teslemetry/snapshots/test_diagnostics.ambr index 7903b73bd571..a51c751b338c 100644 --- a/tests/components/teslemetry/snapshots/test_diagnostics.ambr +++ b/tests/components/teslemetry/snapshots/test_diagnostics.ambr @@ -333,6 +333,28 @@ 'backseat_token_updated_at': None, 'ble_autopair_enrolled': False, 'calendar_enabled': True, + 'charge_schedule_data_charge_schedule_window_enabled': False, + 'charge_schedule_data_charge_schedule_window_end_time': 0, + 'charge_schedule_data_charge_schedule_window_latitude': '**REDACTED**', + 'charge_schedule_data_charge_schedule_window_longitude': '**REDACTED**', + 'charge_schedule_data_charge_schedule_window_start_time': 0, + 'charge_schedule_data_charge_schedules': list([ + dict({ + 'days_of_week': 127, + 'enabled': True, + 'end_enabled': False, + 'end_time': 0, + 'id': '**REDACTED**', + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'name': 'Home', + 'one_time': False, + 'start_enabled': True, + 'start_time': 1320, + }), + ]), + 'charge_schedule_data_max_num_charge_schedules': 10, + 'charge_schedule_data_next_schedule': False, 'charge_state_battery_heater_on': False, 'charge_state_battery_level': 77, 'charge_state_battery_range': 266.87, @@ -453,6 +475,24 @@ 'id': '**REDACTED**', 'id_s': '**REDACTED**', 'in_service': False, + 'preconditioning_schedule_data_max_num_precondition_schedules': 10, + 'preconditioning_schedule_data_precondition_schedules': list([ + dict({ + 'days_of_week': 31, + 'enabled': True, + 'id': '**REDACTED**', + 'latitude': '**REDACTED**', + 'longitude': '**REDACTED**', + 'name': 'Work', + 'one_time': False, + 'precondition_time': 450, + }), + ]), + 'preconditioning_schedule_data_preconditioning_schedule_window_enabled': False, + 'preconditioning_schedule_data_preconditioning_schedule_window_end_time': 0, + 'preconditioning_schedule_data_preconditioning_schedule_window_latitude': '**REDACTED**', + 'preconditioning_schedule_data_preconditioning_schedule_window_longitude': '**REDACTED**', + 'preconditioning_schedule_data_preconditioning_schedule_window_start_time': 0, 'state': 'online', 'tokens': '**REDACTED**', 'user_id': '**REDACTED**', From 1d87a07b0fb92201592ec996b44d9bbcb11381ed Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Mon, 12 Oct 2026 09:13:24 +0200 Subject: [PATCH 289/356] Report a dedicated error when the Tedee bridge has no locks (#185907) --- homeassistant/components/tedee/coordinator.py | 14 +++++++++++++- homeassistant/components/tedee/strings.json | 3 +++ tests/components/tedee/test_init.py | 15 +++++++++++++++ 3 files changed, 31 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/tedee/coordinator.py b/homeassistant/components/tedee/coordinator.py index bc3faa020db6..655324a901e4 100644 --- a/homeassistant/components/tedee/coordinator.py +++ b/homeassistant/components/tedee/coordinator.py @@ -79,7 +79,7 @@ class TedeeApiCoordinator(DataUpdateCoordinator[dict[int, TedeeLock]]): # once every hours get all lock details, otherwise use the sync endpoint if self._next_get_locks <= time.time(): _LOGGER.debug("Updating through /my/lock endpoint") - await self._async_update(self.tedee_client.get_locks) + await self._async_update(self._async_get_locks) self._next_get_locks = time.time() + GET_LOCKS_INTERVAL_SECONDS else: _LOGGER.debug("Updating through /sync endpoint") @@ -93,6 +93,18 @@ class TedeeApiCoordinator(DataUpdateCoordinator[dict[int, TedeeLock]]): self._async_add_remove_locks() return self.tedee_client.locks_dict + async def _async_get_locks(self) -> None: + """Get all locks paired with the bridge.""" + try: + await self.tedee_client.get_locks() + except TedeeClientException as ex: + if self.tedee_client.locks_dict: + raise + # aiotedee raises a generic exception when the bridge reports no locks + raise UpdateFailed( + translation_domain=DOMAIN, translation_key="no_locks" + ) from ex + async def _async_update(self, update_fn: Callable[[], Awaitable[None]]) -> None: """Update locks based on update function.""" try: diff --git a/homeassistant/components/tedee/strings.json b/homeassistant/components/tedee/strings.json index 56bf787f8430..0cba51c3bf69 100644 --- a/homeassistant/components/tedee/strings.json +++ b/homeassistant/components/tedee/strings.json @@ -73,6 +73,9 @@ "lock_failed": { "message": "Failed to lock the door. Lock {lock_id}" }, + "no_locks": { + "message": "The bridge does not report any paired locks" + }, "open_failed": { "message": "Failed to unlatch the door. Lock {lock_id}" }, diff --git a/tests/components/tedee/test_init.py b/tests/components/tedee/test_init.py index 8400855a3d7f..c8e0a5fc5140 100644 --- a/tests/components/tedee/test_init.py +++ b/tests/components/tedee/test_init.py @@ -61,6 +61,21 @@ async def test_config_entry_not_ready( assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY +async def test_config_entry_not_ready_no_locks( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_tedee: MagicMock, +) -> None: + """Test a dedicated error is reported when the bridge has no locks.""" + mock_tedee.locks_dict = {} + mock_tedee.get_locks.side_effect = TedeeClientException("No lock found") + + await setup_integration(hass, mock_config_entry) + + assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY + assert mock_config_entry.error_reason_translation_key == "no_locks" + + async def test_cleanup_on_shutdown( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 7458371726cf07acec42c979de2fb861eba12e24 Mon Sep 17 00:00:00 2001 From: Linkplay2020 <65423368+Linkplay2020@users.noreply.github.com> Date: Mon, 12 Oct 2026 20:08:38 +0800 Subject: [PATCH 290/356] Prevent WiiM browse failures from marking devices unavailable (#185926) Co-authored-by: Tao Jiang --- homeassistant/components/wiim/media_player.py | 15 +++- tests/components/wiim/test_media_player.py | 78 +++++++++++++------ 2 files changed, 66 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/wiim/media_player.py b/homeassistant/components/wiim/media_player.py index f383a88d69ce..b1c8642fb3cd 100644 --- a/homeassistant/components/wiim/media_player.py +++ b/homeassistant/components/wiim/media_player.py @@ -12,6 +12,7 @@ from urllib.parse import urlparse import aiohttp from aiohttp.hdrs import CONTENT_TYPE from async_upnp_client.client import UpnpService, UpnpStateVariable +from async_upnp_client.exceptions import UpnpError from wiim.consts import PlayingStatus as SDKPlayingStatus from wiim.exceptions import WiimDeviceException, WiimException, WiimRequestException from wiim.models import ( @@ -945,7 +946,11 @@ class WiimMediaPlayerEntity(WiimBaseEntity, MediaPlayerEntity): ) if media_content_id == MEDIA_CONTENT_ID_FAVORITES: - sdk_favorites = await self._device.async_get_presets() + try: + sdk_favorites = await self._device.async_get_presets() + except (WiimException, UpnpError, aiohttp.ClientError, TimeoutError) as err: + LOGGER.info("Unable to browse presets for %s: %s", self.entity_id, err) + sdk_favorites = () favorites_items = [ BrowseMedia( media_class=MediaClass.PLAYLIST, @@ -970,8 +975,12 @@ class WiimMediaPlayerEntity(WiimBaseEntity, MediaPlayerEntity): ) if media_content_id == MEDIA_CONTENT_ID_PLAYLISTS: - queue_snapshot = await self._device.async_get_queue_snapshot() - if not queue_snapshot.is_active: + try: + queue_snapshot = await self._device.async_get_queue_snapshot() + except (WiimException, UpnpError, aiohttp.ClientError, TimeoutError) as err: + LOGGER.info("Unable to browse queue for %s: %s", self.entity_id, err) + queue_snapshot = None + if queue_snapshot is None or not queue_snapshot.is_active: return BrowseMedia( media_class=MediaClass.PLAYLIST, media_content_id=MEDIA_CONTENT_ID_PLAYLISTS, diff --git a/tests/components/wiim/test_media_player.py b/tests/components/wiim/test_media_player.py index b7b22f0fc807..ebdbc4d7df9a 100644 --- a/tests/components/wiim/test_media_player.py +++ b/tests/components/wiim/test_media_player.py @@ -3,12 +3,18 @@ from collections.abc import Callable from functools import partial from http import HTTPStatus +import logging from unittest.mock import AsyncMock, MagicMock, patch import aiohttp +from async_upnp_client.exceptions import UpnpError import pytest from wiim.consts import PlayingStatus -from wiim.exceptions import WiimRequestException +from wiim.exceptions import ( + WiimDeviceException, + WiimInvalidDataException, + WiimRequestException, +) from wiim.models import ( WiimGroupRole, WiimGroupSnapshot, @@ -1155,39 +1161,63 @@ async def test_browse_media_error_uses_translation( ], ) @pytest.mark.usefixtures("mock_wiim_controller") -async def test_browse_media_sdk_error_uses_translation( +@pytest.mark.parametrize( + "error", + [ + pytest.param(WiimDeviceException("UPnP failed"), id="sdk-upnp"), + pytest.param(WiimRequestException("HTTP 500"), id="sdk-http"), + pytest.param( + WiimInvalidDataException("Invalid response"), id="sdk-invalid-data" + ), + pytest.param(UpnpError("UPnP failed"), id="upnp"), + pytest.param(aiohttp.ClientError("Connection failed"), id="http"), + pytest.param(TimeoutError("Timed out"), id="timeout"), + ], +) +async def test_browse_media_failure_returns_empty_without_changing_state( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_wiim_device: MagicMock, + caplog: pytest.LogCaptureFixture, *, sdk_method: str, media_content_id: str, + error: Exception, ) -> None: - """Test browse media SDK errors raise a translated Home Assistant error.""" + """Test browse failures return an empty folder without marking the device offline.""" await setup_integration(hass, mock_config_entry) - getattr(mock_wiim_device, sdk_method).side_effect = WiimRequestException( - "request failed" + initial_state = hass.states.get(MEDIA_PLAYER_ENTITY_ID) + assert initial_state is not None + assert initial_state.state != STATE_UNAVAILABLE + getattr(mock_wiim_device, sdk_method).side_effect = error + + caplog.clear() + result = await hass.services.async_call( + MEDIA_PLAYER_DOMAIN, + SERVICE_BROWSE_MEDIA, + { + ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, + ATTR_MEDIA_CONTENT_TYPE: MediaType.PLAYLIST, + ATTR_MEDIA_CONTENT_ID: media_content_id, + }, + blocking=True, + return_response=True, ) - with pytest.raises(HomeAssistantError) as exc_info: - await hass.services.async_call( - MEDIA_PLAYER_DOMAIN, - SERVICE_BROWSE_MEDIA, - { - ATTR_ENTITY_ID: MEDIA_PLAYER_ENTITY_ID, - ATTR_MEDIA_CONTENT_TYPE: MediaType.PLAYLIST, - ATTR_MEDIA_CONTENT_ID: media_content_id, - }, - blocking=True, - return_response=True, - ) - - assert exc_info.value.translation_domain == DOMAIN - assert exc_info.value.translation_key == "command_failed" - assert exc_info.value.translation_placeholders == { - "command": "async_browse_media", - "entity_id": MEDIA_PLAYER_ENTITY_ID, - } + browse = result[MEDIA_PLAYER_ENTITY_ID] + assert browse.media_content_id == media_content_id + assert browse.children == [] + assert not browse.can_play + assert browse.can_expand + assert hass.states.get(MEDIA_PLAYER_ENTITY_ID) == initial_state + mock_wiim_device.set_available.assert_not_called() + getattr(mock_wiim_device, sdk_method).assert_awaited_once_with() + folder = "presets" if sdk_method == "async_get_presets" else "queue" + assert ( + "homeassistant.components.wiim", + logging.INFO, + f"Unable to browse {folder} for {MEDIA_PLAYER_ENTITY_ID}: {error}", + ) in caplog.record_tuples async def test_join_and_unjoin_services_use_resolved_member_udns( From a1848366ac3f3886f97ce360d19b810a6f4c8bac Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Tue, 13 Oct 2026 15:42:23 +0200 Subject: [PATCH 291/356] Fix group sensor crash when the group has no members (#185931) Co-authored-by: Claude --- homeassistant/components/group/sensor.py | 2 +- tests/components/group/test_sensor.py | 29 +++++++++++++++++++++++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/group/sensor.py b/homeassistant/components/group/sensor.py index bfd653d63df6..4baf4d519ebc 100644 --- a/homeassistant/components/group/sensor.py +++ b/homeassistant/components/group/sensor.py @@ -475,7 +475,7 @@ class SensorGroup(GroupEntity, SensorEntity): ) valid_state_numeric = self.mode(numeric_state for numeric_state in valid_states) - if not valid_state or not valid_state_numeric: + if not sensor_values or not valid_state or not valid_state_numeric: self._attr_native_value = None self._extra_state_attribute = {} return diff --git a/tests/components/group/test_sensor.py b/tests/components/group/test_sensor.py index 07f18d6c661e..b19ac87ed89d 100644 --- a/tests/components/group/test_sensor.py +++ b/tests/components/group/test_sensor.py @@ -37,7 +37,7 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import entity_registry as er, issue_registry as ir from homeassistant.setup import async_setup_component -from tests.common import get_fixture_path +from tests.common import MockConfigEntry, get_fixture_path VALUES = [17, 20, 15.3] @@ -237,6 +237,33 @@ async def test_not_enough_sensor_value(hass: HomeAssistant) -> None: assert state.attributes.get("max_entity_id") is None +@pytest.mark.parametrize( + "sensor_type", + ["min", "max", "mean", "median", "last", "range", "stdev", "sum", "product"], +) +async def test_no_members(hass: HomeAssistant, sensor_type: str) -> None: + """Test a group without members does not try to calculate a value.""" + config_entry = MockConfigEntry( + data={}, + domain=DOMAIN, + options={ + "entities": [], + "group_type": "sensor", + "hide_members": False, + "ignore_non_numeric": False, + "name": "My sensor group", + "type": sensor_type, + }, + title="My sensor group", + ) + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get("sensor.my_sensor_group") + assert state.state == STATE_UNAVAILABLE + + async def test_reload(hass: HomeAssistant) -> None: """Verify we can reload sensors.""" hass.states.async_set("sensor.test_1", "12345") From 574b39172d1a9a9637166af0f99ed1780e9ee25a Mon Sep 17 00:00:00 2001 From: Matthias Alphart Date: Mon, 12 Oct 2026 15:03:17 +0200 Subject: [PATCH 292/356] Do not cut off KNX SQLite telegram store initialization with a timeout (#185940) Co-authored-by: Claude Fable 5.1 --- homeassistant/components/knx/telegrams.py | 30 ++++++--- tests/components/knx/test_telegrams.py | 75 +++++++++++++++++++---- 2 files changed, 84 insertions(+), 21 deletions(-) diff --git a/homeassistant/components/knx/telegrams.py b/homeassistant/components/knx/telegrams.py index d4c838ee066d..d9bfbc62bf0a 100644 --- a/homeassistant/components/knx/telegrams.py +++ b/homeassistant/components/knx/telegrams.py @@ -61,15 +61,16 @@ FLUSH_INTERVAL_SECONDS_POSTGRES = 1 MAX_BUFFER_TELEGRAMS_SQLITE = FLUSH_INTERVAL_SECONDS_SQLITE * 50 * 4 MAX_BUFFER_TELEGRAMS_POSTGRES = FLUSH_INTERVAL_SECONDS_POSTGRES * 50 * 4 -# Timeout for the migration probe and store initialization, so an unreachable -# database cannot block KNX setup until the driver/OS connection timeout expires. +# Timeout for the migration probe and initialization of a PostgreSQL store, so an +# unreachable database cannot block KNX setup until the driver/OS connection timeout +# expires. SQLite runs unbounded: cancelling a slow startup pass only restarts it. STORE_INIT_TIMEOUT = 10 -# When store initialization times out during startup (busy event loop, cold or large -# database on low-power hardware), the failure is usually transient. Instead of giving -# up until the next reload, retry in the background with a capped backoff. This many -# retries are allowed on top of the initial attempt, i.e. the store is only disabled -# after STORE_INIT_MAX_RETRIES + 1 consecutive timeouts. +# When PostgreSQL store initialization times out during startup (busy event loop, +# slow network), the failure is usually transient. Instead of giving up until the +# next reload, retry in the background with a capped backoff. This many retries +# are allowed on top of the initial attempt, i.e. the store is only disabled after +# STORE_INIT_MAX_RETRIES + 1 consecutive timeouts. STORE_INIT_RETRY_BACKOFF = (15, 30, 60, 120, 300, 300) STORE_INIT_MAX_RETRIES = len(STORE_INIT_RETRY_BACKOFF) @@ -167,7 +168,7 @@ class Telegrams: if self._uninitialized_store is None: return try: - async with asyncio.timeout(STORE_INIT_TIMEOUT): + async with self._store_init_timeout(): needs_migration = await self._uninitialized_store.needs_migration() if needs_migration: _LOGGER.warning( @@ -180,7 +181,7 @@ class Telegrams: "Initializing KNX telegram storage backend '%s'", self.backend, ) - async with asyncio.timeout(STORE_INIT_TIMEOUT): + async with self._store_init_timeout(): await self._uninitialized_store.initialize() _LOGGER.info( "Successfully initialized KNX telegram storage backend '%s'", @@ -268,6 +269,17 @@ class Telegrams: self.last_ga_telegrams[t_dict["destination"]] = t_dict _LOGGER.debug("Hydrated %d unique telegrams from store", len(result)) + def _store_init_timeout(self) -> contextlib.AbstractAsyncContextManager[Any]: + """Bound store initialization for PostgreSQL only. + + A SQLite startup pass that takes longer than the timeout is not helped by + cancelling it: the next attempt starts over, so a large database on slow + hardware would never finish (XKNX/knx-telegram-store#76). + """ + if self.backend == KNX_TELEGRAM_BACKEND_POSTGRES: + return asyncio.timeout(STORE_INIT_TIMEOUT) + return contextlib.nullcontext() + async def _async_retry_load_history(self, now: datetime) -> None: """Retry telegram store initialization after a transient timeout.""" self._store_init_retry_unsub = None diff --git a/tests/components/knx/test_telegrams.py b/tests/components/knx/test_telegrams.py index 4047abfe4ce2..758ce1df7a19 100644 --- a/tests/components/knx/test_telegrams.py +++ b/tests/components/knx/test_telegrams.py @@ -8,7 +8,12 @@ from datetime import datetime from unittest.mock import AsyncMock, patch from freezegun.api import FrozenDateTimeFactory -from knx_telegram_store import KnxTelegramStoreException, StoredTelegram, TelegramQuery +from knx_telegram_store import ( + BufferedSqliteStore, + KnxTelegramStoreException, + StoredTelegram, + TelegramQuery, +) import pytest from xknx.telegram import Telegram, TelegramDirection from xknx.telegram.address import GroupAddress, IndividualAddress @@ -205,33 +210,79 @@ async def test_sqlite_store_is_told_the_configured_timezone( assert store._legacy_timestamp_timezone is dt_util.get_default_time_zone() -async def test_store_telegram_history_needs_migration_timeout( +@pytest.mark.parametrize( + "hanging_method", + [ + pytest.param("needs_migration", id="needs_migration"), + pytest.param("initialize", id="initialize"), + ], +) +async def test_postgres_store_init_timeout( hass: HomeAssistant, knx: KNXTestKit, issue_registry: ir.IssueRegistry, + hanging_method: str, ) -> None: - """Test store init aborts when needs_migration times out and retries are off.""" + """A hanging PostgreSQL store init is cut off by the timeout and aborts when retries are off.""" - async def hanging_probe() -> bool: + async def hang() -> None: await asyncio.Event().wait() - return False + knx.mock_config_entry.add_to_hass(hass) + hass.config_entries.async_update_entry( + knx.mock_config_entry, + options=knx.mock_config_entry.options + | { + CONF_KNX_TELEGRAM_DB_BACKEND: KNX_TELEGRAM_BACKEND_POSTGRES, + CONF_KNX_TELEGRAM_DB_POSTGRES_DSN: "postgresql://user:secret@db.local:5432/knx", + }, + ) + mock_store = AsyncMock() + mock_store.needs_migration.return_value = False + getattr(mock_store, hanging_method).side_effect = hang with ( patch("homeassistant.components.knx.telegrams.STORE_INIT_TIMEOUT", 0.05), patch("homeassistant.components.knx.telegrams.STORE_INIT_MAX_RETRIES", 0), patch( - "knx_telegram_store.BufferedSqliteStore.needs_migration", - side_effect=hanging_probe, + "homeassistant.components.knx.telegrams.BufferedPostgresStore", + return_value=mock_store, ), + ): + await knx.setup_integration(add_entry_to_hass=False, real_telegram_store=True) + + telegrams_module = hass.data[KNX_MODULE_KEY].telegrams + assert telegrams_module.store is None + assert ( + issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) + is not None + ) + + +async def test_sqlite_store_init_is_not_cut_off_by_timeout( + hass: HomeAssistant, + knx: KNXTestKit, + issue_registry: ir.IssueRegistry, +) -> None: + """A slow SQLite store init runs to completion instead of being cancelled and retried.""" + original_initialize = BufferedSqliteStore.initialize + + async def slow_initialize(self: BufferedSqliteStore) -> None: + await asyncio.sleep(0.2) + await original_initialize(self) + + with ( + patch("homeassistant.components.knx.telegrams.STORE_INIT_TIMEOUT", 0.05), + patch.object(BufferedSqliteStore, "initialize", slow_initialize), ): await knx.setup_integration(real_telegram_store=True) telegrams_module = hass.data[KNX_MODULE_KEY].telegrams - assert telegrams_module.store is None - - # Check that the repair issue was created - issue = issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) - assert issue is not None + assert telegrams_module.store is not None + assert telegrams_module._store_init_retry_unsub is None + assert ( + issue_registry.async_get_issue(DOMAIN, REPAIR_ISSUE_TELEGRAM_BACKEND_ERROR) + is None + ) async def test_store_init_timeout_retries_and_succeeds( From e30923e15cc2d14f4b73d84d3dbb92695d302e6b Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Mon, 12 Oct 2026 15:21:52 +0200 Subject: [PATCH 293/356] Bump nyt_games to 1.0.1 (#185968) Co-authored-by: Claude --- homeassistant/components/nyt_games/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nyt_games/manifest.json b/homeassistant/components/nyt_games/manifest.json index c4e2ba1cc9be..63914f9563b3 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==1.0.0"] + "requirements": ["nyt_games==1.0.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 604e5b69c11b..68c402e485c7 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1773,7 +1773,7 @@ numato-gpio==0.13.0 numpy==2.3.2 # homeassistant.components.nyt_games -nyt_games==1.0.0 +nyt_games==1.0.1 # homeassistant.components.oasa_telematics oasatelematics==0.4 From de05ac826fd8f880c5de30e23122ba647d934160 Mon Sep 17 00:00:00 2001 From: Andy Date: Tue, 13 Oct 2026 12:45:37 +0200 Subject: [PATCH 294/356] Gate Nanoleaf event listener on supports_events (#185977) --- homeassistant/components/nanoleaf/__init__.py | 23 ++++++------ tests/components/nanoleaf/conftest.py | 1 + tests/components/nanoleaf/test_init.py | 37 +++++++++++++++++++ 3 files changed, 50 insertions(+), 11 deletions(-) create mode 100644 tests/components/nanoleaf/test_init.py diff --git a/homeassistant/components/nanoleaf/__init__.py b/homeassistant/components/nanoleaf/__init__.py index 1638fd91ab9a..afaf75877de2 100644 --- a/homeassistant/components/nanoleaf/__init__.py +++ b/homeassistant/components/nanoleaf/__init__.py @@ -64,20 +64,21 @@ async def async_setup_entry(hass: HomeAssistant, entry: NanoleafConfigEntry) -> hass, f"nanoleaf_gesture_{nanoleaf.serial_no}", gesture_type ) - event_listener = asyncio.create_task( - nanoleaf.listen_events( - state_callback=light_event_callback, - effects_callback=light_event_callback, - touch_callback=touch_event_callback if supports_touch else None, + if nanoleaf.supports_events: + event_listener = asyncio.create_task( + nanoleaf.listen_events( + state_callback=light_event_callback, + effects_callback=light_event_callback, + touch_callback=touch_event_callback if supports_touch else None, + ) ) - ) - async def _cancel_listener() -> None: - event_listener.cancel() - with suppress(asyncio.CancelledError): - await event_listener + async def _cancel_listener() -> None: + event_listener.cancel() + with suppress(asyncio.CancelledError): + await event_listener - entry.async_on_unload(_cancel_listener) + entry.async_on_unload(_cancel_listener) entry.runtime_data = coordinator diff --git a/tests/components/nanoleaf/conftest.py b/tests/components/nanoleaf/conftest.py index 5dae7727eec3..b70de0ccfc31 100644 --- a/tests/components/nanoleaf/conftest.py +++ b/tests/components/nanoleaf/conftest.py @@ -46,4 +46,5 @@ async def mock_nanoleaf() -> AsyncGenerator[AsyncMock]: client.firmware_version = "4.0.0" client.name = "Nanoleaf" client.manufacturer = "Nanoleaf" + client.supports_events = True yield client diff --git a/tests/components/nanoleaf/test_init.py b/tests/components/nanoleaf/test_init.py new file mode 100644 index 000000000000..237223712c3f --- /dev/null +++ b/tests/components/nanoleaf/test_init.py @@ -0,0 +1,37 @@ +"""Tests for the Nanoleaf integration init.""" + +from unittest.mock import AsyncMock + +from homeassistant.core import HomeAssistant + +from tests.common import MockConfigEntry + + +async def test_setup_entry_without_event_support( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_nanoleaf: AsyncMock, +) -> None: + """Test setup entry when device does not support events.""" + mock_nanoleaf.supports_events = False + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_nanoleaf.listen_events.assert_not_called() + + +async def test_setup_entry_with_event_support( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_nanoleaf: AsyncMock, +) -> None: + """Test setup entry when device supports events.""" + mock_nanoleaf.supports_events = True + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_nanoleaf.listen_events.assert_called_once() From 6a83ce629155de72728589541c567f5fac6c2506 Mon Sep 17 00:00:00 2001 From: Krisjanis Lejejs Date: Mon, 12 Oct 2026 23:50:47 +0300 Subject: [PATCH 295/356] Fix MQTT device triggers and tags firing twice after reload (#185998) --- homeassistant/components/mqtt/entity.py | 3 +- tests/components/mqtt/test_device_trigger.py | 136 ++++++++++++++++++- tests/components/mqtt/test_tag.py | 47 ++++++- 3 files changed, 181 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/mqtt/entity.py b/homeassistant/components/mqtt/entity.py index d588f421c8b1..3d9704d06a40 100644 --- a/homeassistant/components/mqtt/entity.py +++ b/homeassistant/components/mqtt/entity.py @@ -807,7 +807,8 @@ class MqttDiscoveryDeviceUpdateMixin(ABC): MQTT_DISCOVERY_UPDATED.format(*discovery_hash), self.async_discovery_update, ) - config_entry.async_on_unload(self._entry_unload) + # Tear down before the client disconnects, so subscriptions are not restored + hass.data[DATA_MQTT].reload_dispatchers.append(self._entry_unload) if device_id is not None: self._remove_device_updated = async_track_device_registry_updated_event( hass, device_id, self._async_device_removed diff --git a/tests/components/mqtt/test_device_trigger.py b/tests/components/mqtt/test_device_trigger.py index 3c34ae1f5ca8..1aac6b849c73 100644 --- a/tests/components/mqtt/test_device_trigger.py +++ b/tests/components/mqtt/test_device_trigger.py @@ -1,5 +1,7 @@ """The tests for MQTT device triggers.""" +from collections.abc import Awaitable, Callable +from datetime import timedelta import json from typing import Any from unittest.mock import patch @@ -7,18 +9,31 @@ from unittest.mock import patch import pytest from pytest_unordered import unordered -from homeassistant.components import automation +from homeassistant.components import automation, mqtt from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.mqtt import _LOGGER, DOMAIN, debug_info +from homeassistant.components.mqtt.models import DATA_MQTT +from homeassistant.config_entries import ( + RELOAD_AFTER_UPDATE_DELAY, + ConfigEntry, + ConfigEntryState, +) +from homeassistant.const import Platform from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import HomeAssistantError -from homeassistant.helpers import device_registry as dr +from homeassistant.helpers import device_registry as dr, entity_registry as er from homeassistant.helpers.trigger import async_initialize_triggers from homeassistant.setup import async_setup_component +from homeassistant.util import dt as dt_util from .common import help_test_unload_config_entry -from tests.common import async_fire_mqtt_message, async_get_device_automations +from tests.common import ( + MockConfigEntry, + async_fire_mqtt_message, + async_fire_time_changed, + async_get_device_automations, +) from tests.typing import MqttMockHAClientGenerator, WebSocketGenerator @@ -1865,3 +1880,118 @@ async def test_unload_entry( await hass.async_block_till_done() assert len(service_calls) == 2 await hass.async_block_till_done(wait_background_tasks=True) + + +async def _async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None: + """Reload the MQTT config entry.""" + assert await hass.config_entries.async_reload(entry.entry_id) + + +async def _async_enable_disabled_entity( + hass: HomeAssistant, entry: ConfigEntry +) -> None: + """Enable a disabled entity, which makes the entity registry reload the entry.""" + entity_registry = er.async_get(hass) + entity_id = entity_registry.async_get_entity_id( + Platform.SENSOR, DOMAIN, "0AFFD2_battery" + ) + assert entity_id is not None + entity_registry.async_update_entity(entity_id, disabled_by=None) + await hass.async_block_till_done() + async_fire_time_changed( + hass, dt_util.utcnow() + timedelta(seconds=RELOAD_AFTER_UPDATE_DELAY + 1) + ) + await hass.async_block_till_done() + + +@pytest.mark.parametrize( + "reload_entry", + [ + pytest.param(_async_reload_entry, id="reload"), + pytest.param(_async_enable_disabled_entity, id="enable_entity"), + ], +) +@pytest.mark.usefixtures("mqtt_client_mock") +@patch("homeassistant.components.mqtt.client.DISCOVERY_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.INITIAL_SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.0) +async def test_fires_once_after_entry_reload( + hass: HomeAssistant, + device_registry: dr.DeviceRegistry, + service_calls: list[ServiceCall], + reload_entry: Callable[[HomeAssistant, ConfigEntry], Awaitable[None]], +) -> None: + """Test a device trigger fires once per message after the MQTT entry reloads.""" + # Uses a real MQTT client, so subscriptions are restored on reload + entry = MockConfigEntry( + domain=DOMAIN, + data={mqtt.CONF_BROKER: "mock-broker"}, + version=mqtt.CONFIG_ENTRY_VERSION, + minor_version=mqtt.CONFIG_ENTRY_MINOR_VERSION, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + trigger_discovery_topic = "homeassistant/device_automation/0AFFD2/scene_1/config" + trigger_config = ( + '{ "automation_type":"trigger",' + ' "device":{"identifiers":["0AFFD2"]},' + ' "payload": "scene_1",' + ' "topic": "zigbee2mqtt/0AFFD2/action",' + ' "type": "action",' + ' "subtype": "scene_1" }' + ) + async_fire_mqtt_message(hass, trigger_discovery_topic, trigger_config, retain=True) + async_fire_mqtt_message( + hass, + "homeassistant/sensor/0AFFD2/battery/config", + '{ "name": "Battery",' + ' "unique_id": "0AFFD2_battery",' + ' "state_topic": "zigbee2mqtt/0AFFD2",' + ' "enabled_by_default": false,' + ' "device":{"identifiers":["0AFFD2"]} }', + retain=True, + ) + await hass.async_block_till_done() + device_entry = device_registry.async_get_device_by_identifier( + ("mqtt", "0AFFD2"), entry.entry_id + ) + + assert await async_setup_component( + hass, + automation.DOMAIN, + { + automation.DOMAIN: [ + { + "trigger": { + "platform": "device", + "domain": DOMAIN, + "device_id": device_entry.id, + "type": "action", + "subtype": "scene_1", + }, + "action": {"service": "test.automation"}, + }, + ] + }, + ) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "zigbee2mqtt/0AFFD2/action", "scene_1") + await hass.async_block_till_done() + assert len(service_calls) == 1 + + client_before_reload = hass.data[DATA_MQTT].client + await reload_entry(hass, entry) + assert entry.state is ConfigEntryState.LOADED + assert hass.data[DATA_MQTT].client is not client_before_reload + + # The broker replays the retained discovery payload after the reload + async_fire_mqtt_message(hass, trigger_discovery_topic, trigger_config, retain=True) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "zigbee2mqtt/0AFFD2/action", "scene_1") + await hass.async_block_till_done() + assert len(service_calls) == 2 diff --git a/tests/components/mqtt/test_tag.py b/tests/components/mqtt/test_tag.py index 866dde7b73d2..46165ea0c8b2 100644 --- a/tests/components/mqtt/test_tag.py +++ b/tests/components/mqtt/test_tag.py @@ -3,12 +3,15 @@ import copy import json from typing import Any -from unittest.mock import ANY, AsyncMock +from unittest.mock import ANY, AsyncMock, patch import pytest +from homeassistant.components import mqtt from homeassistant.components.device_automation import DeviceAutomationType from homeassistant.components.mqtt.const import DOMAIN +from homeassistant.components.mqtt.models import DATA_MQTT +from homeassistant.config_entries import ConfigEntryState from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from homeassistant.setup import async_setup_component @@ -1028,6 +1031,48 @@ async def test_unload_entry( tag_mock.assert_not_called() +@pytest.mark.usefixtures("mqtt_client_mock") +@patch("homeassistant.components.mqtt.client.DISCOVERY_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.INITIAL_SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.SUBSCRIBE_COOLDOWN", 0.0) +@patch("homeassistant.components.mqtt.client.UNSUBSCRIBE_COOLDOWN", 0.0) +async def test_fires_once_after_entry_reload( + hass: HomeAssistant, device_registry: dr.DeviceRegistry, tag_mock: AsyncMock +) -> None: + """Test a tag scanner fires once per message after the MQTT entry reloads.""" + # Uses a real MQTT client, so subscriptions are restored on reload + entry = MockConfigEntry( + domain=DOMAIN, + data={mqtt.CONF_BROKER: "mock-broker"}, + version=mqtt.CONFIG_ENTRY_VERSION, + minor_version=mqtt.CONFIG_ENTRY_MINOR_VERSION, + ) + entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + config = json.dumps(DEFAULT_CONFIG_DEVICE) + async_fire_mqtt_message(hass, "homeassistant/tag/bla1/config", config, retain=True) + await hass.async_block_till_done() + device_entry = device_registry.async_get_device_by_identifier( + ("mqtt", "0AFFD2"), entry.entry_id + ) + + client_before_reload = hass.data[DATA_MQTT].client + assert await hass.config_entries.async_reload(entry.entry_id) + await hass.async_block_till_done() + assert entry.state is ConfigEntryState.LOADED + assert hass.data[DATA_MQTT].client is not client_before_reload + + # The broker replays the retained discovery payload after the reload + async_fire_mqtt_message(hass, "homeassistant/tag/bla1/config", config, retain=True) + await hass.async_block_till_done() + + async_fire_mqtt_message(hass, "foobar/tag_scanned", DEFAULT_TAG_SCAN) + await hass.async_block_till_done() + tag_mock.assert_called_once_with(ANY, DEFAULT_TAG_ID, device_entry.id) + + @pytest.mark.usefixtures("mqtt_mock", "tag_mock") async def test_value_template_fails( hass: HomeAssistant, caplog: pytest.LogCaptureFixture From 37c4c3cb53ec95f1a5bd757a53425713ed31b72b Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Wed, 14 Oct 2026 07:02:05 +0200 Subject: [PATCH 296/356] Fix FRITZ!SmartHome SSDP host selection (#186029) Co-authored-by: Copilot --- .../components/fritzbox/config_flow.py | 61 ++++-- tests/components/fritzbox/test_config_flow.py | 193 +++++++++++++++++- 2 files changed, 227 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/fritzbox/config_flow.py b/homeassistant/components/fritzbox/config_flow.py index f20f8febedc9..383cce4499c8 100644 --- a/homeassistant/components/fritzbox/config_flow.py +++ b/homeassistant/components/fritzbox/config_flow.py @@ -9,7 +9,7 @@ from pyfritzhome import Fritzhome, LoginError from requests.exceptions import HTTPError from yarl import URL -from homeassistant.config_entries import ConfigFlow, ConfigFlowResult +from homeassistant.config_entries import SOURCE_IGNORE, ConfigFlow, ConfigFlowResult from homeassistant.const import ( CONF_HOST, CONF_PASSWORD, @@ -17,7 +17,7 @@ from homeassistant.const import ( CONF_USERNAME, CONF_VERIFY_SSL, ) -from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN +from homeassistant.core import DOMAIN as HOMEASSISTANT_DOMAIN, HomeAssistant from homeassistant.helpers.selector import ( TextSelector, TextSelectorConfig, @@ -25,7 +25,6 @@ from homeassistant.helpers.selector import ( ) from homeassistant.helpers.service_info.ssdp import ( ATTR_UPNP_FRIENDLY_NAME, - ATTR_UPNP_PRESENTATION_URL, ATTR_UPNP_UDN, SsdpServiceInfo, ) @@ -60,13 +59,24 @@ RESULT_NOT_SUPPORTED = "not_supported" RESULT_SUCCESS = "success" -def _is_ipv6_link_local(host: str) -> bool: - """Return True if host is an IPv6 link-local address.""" +def _is_ip(host: str, ipv6_link_local: bool = False) -> bool: + """Return whether host is an IP address, optionally requiring IPv6 link-local.""" try: ip = ipaddress.ip_address(host) except ValueError: return False - return ip.version == 6 and ip.is_link_local + if ipv6_link_local: + return ip.version == 6 and ip.is_link_local + return True + + +async def _async_resolves_to(hass: HomeAssistant, host: str, ip: str) -> bool: + """Return whether host resolves to the given IP address.""" + try: + addresses = await hass.loop.getaddrinfo(host, None) + except OSError: + return False + return any(address[4][0] == ip for address in addresses) class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): @@ -167,24 +177,27 @@ class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): ) -> ConfigFlowResult: """Handle a flow initialized by discovery.""" assert isinstance(discovery_info.ssdp_location, str) - host = URL(discovery_info.ssdp_location).host - assert isinstance(host, str) + ssdp_host = URL(discovery_info.ssdp_location).host + assert isinstance(ssdp_host, str) - # presentationURL may be relative according to the UPnP spec - presentation_url = discovery_info.upnp.get(ATTR_UPNP_PRESENTATION_URL) - if presentation_url and (presentation_host := URL(presentation_url).host): - self._url = presentation_url - else: - presentation_host = host - self._url = str(URL.build(scheme="http", host=host)) + self._url = str(URL.build(scheme="http", host=ssdp_host)) - if _is_ipv6_link_local(host) or _is_ipv6_link_local(presentation_host): + if _is_ip(ssdp_host, ipv6_link_local=True): return self.async_abort(reason="ignore_ip6_link_local") if uuid := discovery_info.upnp.get(ATTR_UPNP_UDN): uuid = uuid.removeprefix("uuid:") - await self.async_set_unique_id(uuid) - self._abort_if_unique_id_configured({CONF_HOST: self._url}) + updates = None + if ( + (existing_entry := await self.async_set_unique_id(uuid)) + and existing_entry.source != SOURCE_IGNORE + and (existing_host := URL(existing_entry.data[CONF_HOST]).host) + and _is_ip(existing_host) + and _is_ip(ssdp_host) + ): + # keep user-configured hostnames + updates = {CONF_HOST: self._url} + self._abort_if_unique_id_configured(updates) if self.hass.config_entries.flow.async_has_matching_flow(self): return self.async_abort( @@ -193,7 +206,17 @@ class FritzboxConfigFlow(ConfigFlow, domain=DOMAIN): # update old and user-configured config entries for entry in self._async_current_entries(include_ignore=False): - if entry.data[CONF_HOST] == self._url: + if (entry_host := URL(entry.data[CONF_HOST]).host) and ( + (entry_host == ssdp_host) + or ( + _is_ip(entry_host) + and await _async_resolves_to(self.hass, ssdp_host, entry_host) + ) + or ( + _is_ip(ssdp_host) + and await _async_resolves_to(self.hass, entry_host, ssdp_host) + ) + ): if uuid and not entry.unique_id: self.hass.config_entries.async_update_entry(entry, unique_id=uuid) return self.async_abort(reason="already_configured") diff --git a/tests/components/fritzbox/test_config_flow.py b/tests/components/fritzbox/test_config_flow.py index 6b70a0724670..a36825a3e31f 100644 --- a/tests/components/fritzbox/test_config_flow.py +++ b/tests/components/fritzbox/test_config_flow.py @@ -1,6 +1,7 @@ """Tests for AVM Fritz!Box config flow.""" import dataclasses +import socket from unittest import mock from unittest.mock import Mock, patch @@ -9,7 +10,7 @@ import pytest from requests.exceptions import HTTPError from homeassistant.components.fritzbox.const import DOMAIN -from homeassistant.config_entries import SOURCE_SSDP, SOURCE_USER +from homeassistant.config_entries import SOURCE_IGNORE, SOURCE_SSDP, SOURCE_USER from homeassistant.const import ( CONF_DEVICES, CONF_HOST, @@ -48,6 +49,16 @@ MOCK_SSDP_DATA = { ATTR_UPNP_PRESENTATION_URL: "http://10.0.0.1", }, ), + "hostname_valid": SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location="http://fritz-new.repeater:49000/fboxdesc.xml", + upnp={ + ATTR_UPNP_FRIENDLY_NAME: CONF_FAKE_NAME, + ATTR_UPNP_UDN: "uuid:only-a-test", + ATTR_UPNP_PRESENTATION_URL: "http://fritz-new.repeater", + }, + ), "ip4_ssdp_fallback": SsdpServiceInfo( ssdp_usn="mock_usn", ssdp_st="mock_st", @@ -361,8 +372,13 @@ async def test_reconfigure_failed(hass: HomeAssistant, fritz: Mock) -> None: ("test_data", "expected_host", "expected_result"), [ (MOCK_SSDP_DATA["ip4_valid"], "http://10.0.0.1", FlowResultType.FORM), + ( + MOCK_SSDP_DATA["hostname_valid"], + "http://fritz-new.repeater", + FlowResultType.FORM, + ), (MOCK_SSDP_DATA["ip4_ssdp_fallback"], "http://10.0.0.1", FlowResultType.FORM), - (MOCK_SSDP_DATA["ip4_hostname"], "http://fritz.repeater", FlowResultType.FORM), + (MOCK_SSDP_DATA["ip4_hostname"], "http://10.0.0.1", FlowResultType.FORM), ( MOCK_SSDP_DATA["ip4_relative_presentation_url"], "http://10.0.0.1", @@ -548,12 +564,81 @@ async def test_ssdp_already_in_progress_host(hass: HomeAssistant, fritz: Mock) - assert result["reason"] == "already_in_progress" -async def test_ssdp_already_configured(hass: HomeAssistant, fritz: Mock) -> None: +@pytest.mark.parametrize( + ("configured_host", "ssdp_host", "expected_type", "expected_reason", "unique_id"), + [ + pytest.param( + "http://192.168.178.1", + "http://192.168.178.1", + FlowResultType.ABORT, + "already_configured", + "only-a-test", + id="ip-entry-ip-discovery", + ), + pytest.param( + "http://192.168.178.1", + "http://fritz.box", + FlowResultType.ABORT, + "already_configured", + "only-a-test", + id="ip-entry-hostname-discovery", + ), + pytest.param( + "http://fritz.box", + "http://192.168.178.1", + FlowResultType.ABORT, + "already_configured", + "only-a-test", + id="hostname-entry-ip-discovery", + ), + pytest.param( + "http://fritz.box", + "http://fritz.box", + FlowResultType.ABORT, + "already_configured", + "only-a-test", + id="hostname-entry-hostname-discovery", + ), + pytest.param( + "http://192.168.178.10", + "http://192.168.178.1", + FlowResultType.FORM, + None, + None, + id="other-ip-entry-ip-discovery", + ), + pytest.param( + "http://192.168.178.10", + "http://fritz.box", + FlowResultType.FORM, + None, + None, + id="other-ip-entry-hostname-discovery", + ), + pytest.param( + "http://fritz.box", + "http://192.168.178.10", + FlowResultType.FORM, + None, + None, + id="hostname-entry-other-ip-discovery", + ), + ], +) +async def test_ssdp_already_configured( + hass: HomeAssistant, + fritz: Mock, + configured_host: str, + ssdp_host: str, + expected_type: FlowResultType, + expected_reason: str | None, + unique_id: str | None, +) -> None: """Test starting a flow from discovery when already configured.""" mock_config = MockConfigEntry( domain=DOMAIN, data={ - CONF_HOST: "http://10.0.0.1", + CONF_HOST: configured_host, CONF_PASSWORD: "fake_pass", CONF_USERNAME: "fake_user", CONF_VERIFY_SSL: False, @@ -562,9 +647,101 @@ async def test_ssdp_already_configured(hass: HomeAssistant, fritz: Mock) -> None mock_config.add_to_hass(hass) assert not mock_config.unique_id - result2 = await hass.config_entries.flow.async_init( + discovery_info = SsdpServiceInfo( + ssdp_usn="mock_usn", + ssdp_st="mock_st", + ssdp_location=f"{ssdp_host}:49000/fboxdesc.xml", + upnp={ + ATTR_UPNP_FRIENDLY_NAME: CONF_FAKE_NAME, + ATTR_UPNP_UDN: "uuid:only-a-test", + ATTR_UPNP_PRESENTATION_URL: ssdp_host, + }, + ) + + async def mock_getaddrinfo(host: str, port: int | None) -> list[tuple]: + if host == "fritz.box": + return [(socket.AF_INET, socket.SOCK_STREAM, 6, "", ("192.168.178.1", 0))] + raise socket.gaierror + + with patch.object(hass.loop, "getaddrinfo", mock_getaddrinfo): + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SSDP}, data=discovery_info + ) + + assert result["type"] is expected_type + assert result.get("reason") == expected_reason + assert mock_config.unique_id == unique_id + + +@pytest.mark.parametrize( + ("existing_host", "discovery_info", "expected_host"), + [ + pytest.param( + "http://fritz.repeater", + MOCK_SSDP_DATA["ip4_valid"], + "http://fritz.repeater", + id="hostname-entry-ip-discovery", + ), + pytest.param( + "http://fritz.repeater", + MOCK_SSDP_DATA["hostname_valid"], + "http://fritz.repeater", + id="hostname-entry-hostname-discovery", + ), + pytest.param( + "http://10.0.0.2", + MOCK_SSDP_DATA["ip4_valid"], + "http://10.0.0.1", + id="ip-entry-ip-discovery", + ), + pytest.param( + "http://10.0.0.2", + MOCK_SSDP_DATA["hostname_valid"], + "http://10.0.0.2", + id="ip-entry-hostname-discovery", + ), + ], +) +async def test_ssdp_already_configured_unique_id( + hass: HomeAssistant, + fritz: Mock, + existing_host: str, + discovery_info: SsdpServiceInfo, + expected_host: str, +) -> None: + """Test discovery for an existing entry with the same unique ID.""" + mock_config = MockConfigEntry( + domain=DOMAIN, + unique_id="only-a-test", + data={ + CONF_HOST: existing_host, + CONF_PASSWORD: "fake_pass", + CONF_USERNAME: "fake_user", + CONF_VERIFY_SSL: False, + }, + ) + mock_config.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SSDP}, data=discovery_info + ) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config.data[CONF_HOST] == expected_host + + +async def test_ssdp_ignored_entry(hass: HomeAssistant, fritz: Mock) -> None: + """Test discovery of an ignored device is aborted without updating it.""" + mock_config = MockConfigEntry( + domain=DOMAIN, unique_id="only-a-test", source=SOURCE_IGNORE, data={} + ) + mock_config.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=MOCK_SSDP_DATA["ip4_valid"] ) - assert result2["type"] is FlowResultType.ABORT - assert result2["reason"] == "already_configured" - assert mock_config.unique_id == "only-a-test" + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + assert mock_config.data == {} From 59573e64ff9786aa9fbad69f7842d641d5b671e5 Mon Sep 17 00:00:00 2001 From: David <128871138+DAB-LABS@users.noreply.github.com> Date: Wed, 14 Oct 2026 08:48:23 -0700 Subject: [PATCH 297/356] switch Broadlink to broadlink-async (fixes #184800, replaces #184806) (#186053) --- homeassistant/components/broadlink/config_flow.py | 4 ++-- homeassistant/components/broadlink/device.py | 4 ++-- homeassistant/components/broadlink/heartbeat.py | 2 +- homeassistant/components/broadlink/infrared.py | 4 ++-- homeassistant/components/broadlink/light.py | 2 +- homeassistant/components/broadlink/manifest.json | 4 ++-- homeassistant/components/broadlink/radio_frequency.py | 6 +++--- homeassistant/components/broadlink/remote.py | 2 +- homeassistant/components/broadlink/switch.py | 2 +- homeassistant/components/broadlink/updater.py | 4 ++-- requirements_all.txt | 6 +++--- tests/components/broadlink/__init__.py | 2 +- tests/components/broadlink/test_config_flow.py | 2 +- tests/components/broadlink/test_device.py | 2 +- tests/components/broadlink/test_infrared.py | 4 ++-- tests/components/broadlink/test_radio_frequency.py | 2 +- tests/components/broadlink/test_remote.py | 2 +- 17 files changed, 27 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/broadlink/config_flow.py b/homeassistant/components/broadlink/config_flow.py index 2fff0f7cbf3d..5072d29ca73c 100644 --- a/homeassistant/components/broadlink/config_flow.py +++ b/homeassistant/components/broadlink/config_flow.py @@ -6,8 +6,8 @@ import logging import socket from typing import Any, override -import broadlink as blk -from broadlink.exceptions import ( +import broadlink_async as blk +from broadlink_async.exceptions import ( AuthenticationError, BroadlinkException, NetworkTimeoutError, diff --git a/homeassistant/components/broadlink/device.py b/homeassistant/components/broadlink/device.py index ee464cbc445b..e5ee54c5f985 100644 --- a/homeassistant/components/broadlink/device.py +++ b/homeassistant/components/broadlink/device.py @@ -4,8 +4,8 @@ from collections.abc import Awaitable, Callable from contextlib import suppress import logging -import broadlink as blk -from broadlink.exceptions import ( +import broadlink_async as blk +from broadlink_async.exceptions import ( AuthenticationError, AuthorizationError, BroadlinkException, diff --git a/homeassistant/components/broadlink/heartbeat.py b/homeassistant/components/broadlink/heartbeat.py index 4a10e654e356..593213cba7c4 100644 --- a/homeassistant/components/broadlink/heartbeat.py +++ b/homeassistant/components/broadlink/heartbeat.py @@ -3,7 +3,7 @@ import datetime as dt import logging -import broadlink as blk +import broadlink_async as blk from homeassistant.const import CONF_HOST from homeassistant.core import CALLBACK_TYPE, HomeAssistant diff --git a/homeassistant/components/broadlink/infrared.py b/homeassistant/components/broadlink/infrared.py index baf623f0923e..d800583603e9 100644 --- a/homeassistant/components/broadlink/infrared.py +++ b/homeassistant/components/broadlink/infrared.py @@ -2,8 +2,8 @@ from typing import TYPE_CHECKING, override -from broadlink.exceptions import BroadlinkException -from broadlink.remote import pulses_to_data as _bl_pulses_to_data +from broadlink_async.exceptions import BroadlinkException +from broadlink_async.remote import pulses_to_data as _bl_pulses_to_data from homeassistant.components.infrared import InfraredCommand, InfraredEmitterEntity from homeassistant.config_entries import ConfigEntry diff --git a/homeassistant/components/broadlink/light.py b/homeassistant/components/broadlink/light.py index 5f3d53c84cc2..37e93fec0056 100644 --- a/homeassistant/components/broadlink/light.py +++ b/homeassistant/components/broadlink/light.py @@ -3,7 +3,7 @@ import logging from typing import Any, override -from broadlink.exceptions import BroadlinkException +from broadlink_async.exceptions import BroadlinkException from homeassistant.components.light import ( ATTR_BRIGHTNESS, diff --git a/homeassistant/components/broadlink/manifest.json b/homeassistant/components/broadlink/manifest.json index d365e1adbe2a..23670793ad52 100644 --- a/homeassistant/components/broadlink/manifest.json +++ b/homeassistant/components/broadlink/manifest.json @@ -38,6 +38,6 @@ "documentation": "https://www.home-assistant.io/integrations/broadlink", "integration_type": "device", "iot_class": "local_polling", - "loggers": ["broadlink"], - "requirements": ["python-broadlink==1.0.6"] + "loggers": ["broadlink_async"], + "requirements": ["broadlink-async==1.1.0"] } diff --git a/homeassistant/components/broadlink/radio_frequency.py b/homeassistant/components/broadlink/radio_frequency.py index 152654b63e7b..30899dac69b0 100644 --- a/homeassistant/components/broadlink/radio_frequency.py +++ b/homeassistant/components/broadlink/radio_frequency.py @@ -3,8 +3,8 @@ import logging from typing import override -from broadlink.exceptions import BroadlinkException -from broadlink.remote import TICK +from broadlink_async.exceptions import BroadlinkException +from broadlink_async.remote import TICK from rf_protocols import RadioFrequencyCommand from homeassistant.components.radio_frequency import RadioFrequencyTransmitterEntity @@ -64,7 +64,7 @@ def encode_rf_packet( 0x00 followed by a 2-byte big-endian tick count Each pulse is expressed as multiples of the Broadlink timing unit - (about 30.45 µs, ``broadlink.remote.TICK``), which is the timing + (about 30.45 µs, ``broadlink_async.remote.TICK``), which is the timing resolution of the RF front-end. """ buf = bytearray([type_byte, repeat_count, 0, 0]) diff --git a/homeassistant/components/broadlink/remote.py b/homeassistant/components/broadlink/remote.py index f5a58bfe9b02..94e495ef77cc 100644 --- a/homeassistant/components/broadlink/remote.py +++ b/homeassistant/components/broadlink/remote.py @@ -9,7 +9,7 @@ from itertools import product import logging from typing import Any, override -from broadlink.exceptions import ( +from broadlink_async.exceptions import ( AuthorizationError, BroadlinkException, NetworkTimeoutError, diff --git a/homeassistant/components/broadlink/switch.py b/homeassistant/components/broadlink/switch.py index dbdca230dcd5..939339010fce 100644 --- a/homeassistant/components/broadlink/switch.py +++ b/homeassistant/components/broadlink/switch.py @@ -5,7 +5,7 @@ from abc import ABC, abstractmethod import logging from typing import Any, override -from broadlink.exceptions import BroadlinkException +from broadlink_async.exceptions import BroadlinkException import probatio from homeassistant.components.switch import ( diff --git a/homeassistant/components/broadlink/updater.py b/homeassistant/components/broadlink/updater.py index a871a232e32d..3ed4b3d656d4 100644 --- a/homeassistant/components/broadlink/updater.py +++ b/homeassistant/components/broadlink/updater.py @@ -5,8 +5,8 @@ from datetime import datetime, timedelta import logging from typing import TYPE_CHECKING, Any, Generic, TypeVar, override -import broadlink as blk -from broadlink.exceptions import AuthorizationError, BroadlinkException +import broadlink_async as blk +from broadlink_async.exceptions import AuthorizationError, BroadlinkException from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed from homeassistant.util import dt as dt_util diff --git a/requirements_all.txt b/requirements_all.txt index 68c402e485c7..3e79d9e89b19 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -733,6 +733,9 @@ boto3==1.42.97 # homeassistant.components.bring bring-api==1.1.2 +# homeassistant.components.broadlink +broadlink-async==1.1.0 + # homeassistant.components.brother brother==6.2.0 @@ -2695,9 +2698,6 @@ python-awair==0.2.5 # homeassistant.components.blockchain python-blockchain-api==0.0.2 -# homeassistant.components.broadlink -python-broadlink==1.0.6 - # homeassistant.components.bsblan python-bsblan==6.1.8 diff --git a/tests/components/broadlink/__init__.py b/tests/components/broadlink/__init__.py index 358252587e83..d8703dd6b844 100644 --- a/tests/components/broadlink/__init__.py +++ b/tests/components/broadlink/__init__.py @@ -4,7 +4,7 @@ from dataclasses import dataclass import inspect from unittest.mock import AsyncMock, MagicMock, patch -import broadlink as blk +import broadlink_async as blk from homeassistant.components.broadlink.const import DOMAIN from homeassistant.core import HomeAssistant diff --git a/tests/components/broadlink/test_config_flow.py b/tests/components/broadlink/test_config_flow.py index 2d2f5da17867..48d227e9d7bd 100644 --- a/tests/components/broadlink/test_config_flow.py +++ b/tests/components/broadlink/test_config_flow.py @@ -4,7 +4,7 @@ import errno import socket from unittest.mock import call, patch -import broadlink.exceptions as blke +import broadlink_async.exceptions as blke import pytest from homeassistant import config_entries diff --git a/tests/components/broadlink/test_device.py b/tests/components/broadlink/test_device.py index 5ff5e275b05c..5bd3e285b18e 100644 --- a/tests/components/broadlink/test_device.py +++ b/tests/components/broadlink/test_device.py @@ -2,7 +2,7 @@ from unittest.mock import patch -import broadlink.exceptions as blke +import broadlink_async.exceptions as blke import pytest from homeassistant.components.broadlink.const import DOMAIN diff --git a/tests/components/broadlink/test_infrared.py b/tests/components/broadlink/test_infrared.py index b64e4984109c..94d68c7810f6 100644 --- a/tests/components/broadlink/test_infrared.py +++ b/tests/components/broadlink/test_infrared.py @@ -2,8 +2,8 @@ from unittest.mock import call -from broadlink.exceptions import BroadlinkException -from broadlink.remote import pulses_to_data +from broadlink_async.exceptions import BroadlinkException +from broadlink_async.remote import pulses_to_data from infrared_protocols.commands.nec import NECCommand import pytest diff --git a/tests/components/broadlink/test_radio_frequency.py b/tests/components/broadlink/test_radio_frequency.py index 5fd081100ed0..e10b5b8becb2 100644 --- a/tests/components/broadlink/test_radio_frequency.py +++ b/tests/components/broadlink/test_radio_frequency.py @@ -3,7 +3,7 @@ from datetime import timedelta from unittest.mock import MagicMock, call -from broadlink.exceptions import BroadlinkException +from broadlink_async.exceptions import BroadlinkException import pytest from rf_protocols.commands.ook import OOKCommand diff --git a/tests/components/broadlink/test_remote.py b/tests/components/broadlink/test_remote.py index 217a6b8cc9b7..08ebbd1221c3 100644 --- a/tests/components/broadlink/test_remote.py +++ b/tests/components/broadlink/test_remote.py @@ -3,7 +3,7 @@ from base64 import b64decode from unittest.mock import call -from broadlink.exceptions import BroadlinkException +from broadlink_async.exceptions import BroadlinkException from freezegun.api import FrozenDateTimeFactory import pytest From 4c3af079afa6fd2779686bd9a75ec57a541c966f Mon Sep 17 00:00:00 2001 From: Jeef Date: Tue, 13 Oct 2026 12:00:29 -0600 Subject: [PATCH 298/356] Fix weatherflow last_reset updating on every device report (#186141) --- .../components/weatherflow/sensor.py | 9 ++- tests/components/weatherflow/test_sensor.py | 60 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/weatherflow/sensor.py b/homeassistant/components/weatherflow/sensor.py index 519604814898..22de00e0d9a6 100644 --- a/homeassistant/components/weatherflow/sensor.py +++ b/homeassistant/components/weatherflow/sensor.py @@ -381,6 +381,7 @@ class WeatherFlowSensorEntity(RestoreSensor): """Initialize a WeatherFlow sensor entity.""" self.device = device self.entity_description = description + self._last_reset: datetime | None = None self._attr_device_info = DeviceInfo( identifiers={(DOMAIN, device.serial_number)}, @@ -398,11 +399,17 @@ class WeatherFlowSensorEntity(RestoreSensor): def last_reset(self) -> datetime | None: """Return the time when the sensor was last reset, if any.""" if self.entity_description.state_class == SensorStateClass.TOTAL: - return self.device.last_report + return self._last_reset return None def _async_update_state(self) -> None: """Update entity state.""" + if self.entity_description.state_class == SensorStateClass.TOTAL and ( + self._last_reset is None or self._attr_native_value + ): + # A new accumulation cycle only needs to be recorded once the + # previous report actually accumulated a nonzero amount. + self._last_reset = self.device.last_report value = self.entity_description.get_native_value(self.device) self._attr_available = ( value is not None or self.entity_description.none_is_unknown diff --git a/tests/components/weatherflow/test_sensor.py b/tests/components/weatherflow/test_sensor.py index 02edaadaed0a..1efed685fd81 100644 --- a/tests/components/weatherflow/test_sensor.py +++ b/tests/components/weatherflow/test_sensor.py @@ -1,11 +1,13 @@ """Tests for the WeatherFlow sensor platform.""" +import json from unittest.mock import patch import pytest from pyweatherflowudp.aioudp import LocalEndpoint from syrupy.assertion import SnapshotAssertion +from homeassistant.components.sensor import ATTR_LAST_RESET from homeassistant.const import ATTR_UNIT_OF_MEASUREMENT, STATE_UNKNOWN, Platform from homeassistant.core import HomeAssistant, State from homeassistant.helpers import entity_registry as er @@ -20,6 +22,7 @@ from . import HUB_ADDRESS, setup_integration from tests.common import ( MockConfigEntry, load_fixture_bytes, + load_json_object_fixture, mock_restore_cache_with_extra_data, snapshot_platform, ) @@ -27,6 +30,7 @@ from tests.common import ( LAST_STRIKE_DISTANCE = "sensor.st_00000001_lightning_last_distance" LAST_STRIKE_ENERGY = "sensor.st_00000001_lightning_last_energy" LAST_STRIKE_TIME = "sensor.st_00000001_lightning_last_strike" +LIGHTNING_COUNT = "sensor.st_00000001_lightning_count" RAIN_LAST_MINUTE = "sensor.st_00000001_precipitation" STATION_PRESSURE = "sensor.st_00000001_air_pressure" VAPOR_PRESSURE = "sensor.st_00000001_vapor_pressure" @@ -73,6 +77,62 @@ async def test_unit_system( assert hass.states.get(entity_id).attributes[ATTR_UNIT_OF_MEASUREMENT] == unit +async def test_last_reset_only_advances_after_accumulation( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_udp_endpoint: LocalEndpoint, +) -> None: + """Test last_reset only changes when the previous report accumulated.""" + + def feed_observation(epoch: int, rain: float, strikes: int = 0) -> None: + data = load_json_object_fixture("obs_st.json", "weatherflow") + data["obs"][0][0] = epoch + data["obs"][0][12] = rain + data["obs"][0][15] = strikes + mock_udp_endpoint.feed_datagram(json.dumps(data).encode(), HUB_ADDRESS) + + # The setup observation reports 0.12 mm of rain at epoch 1510855980. + await setup_integration(hass, mock_config_entry, mock_udp_endpoint) + + state = hass.states.get(RAIN_LAST_MINUTE) + assert state.state == "0.12" + assert state.attributes[ATTR_LAST_RESET] == "2017-11-16T18:13:00+00:00" + assert ( + hass.states.get(LIGHTNING_COUNT).attributes[ATTR_LAST_RESET] + == "2017-11-16T18:13:00+00:00" + ) + + # The previous report accumulated rain, so this report starts a new cycle. + feed_observation(1510856040, 0) + await hass.async_block_till_done() + state = hass.states.get(RAIN_LAST_MINUTE) + assert state.state == "0" + assert state.attributes[ATTR_LAST_RESET] == "2017-11-16T18:14:00+00:00" + + # Nothing accumulated since, so a run of empty reports keeps the cycle. + feed_observation(1510856100, 0) + await hass.async_block_till_done() + state = hass.states.get(RAIN_LAST_MINUTE) + assert state.attributes[ATTR_LAST_RESET] == "2017-11-16T18:14:00+00:00" + feed_observation(1510856160, 0.5) + await hass.async_block_till_done() + state = hass.states.get(RAIN_LAST_MINUTE) + assert state.state == "0.5" + assert state.attributes[ATTR_LAST_RESET] == "2017-11-16T18:14:00+00:00" + + # The 0.5 mm report is flushed into statistics by the next report's reset. + feed_observation(1510856220, 0) + await hass.async_block_till_done() + state = hass.states.get(RAIN_LAST_MINUTE) + assert state.attributes[ATTR_LAST_RESET] == "2017-11-16T18:17:00+00:00" + + # A sensor that never accumulates keeps its initial last_reset. + assert ( + hass.states.get(LIGHTNING_COUNT).attributes[ATTR_LAST_RESET] + == "2017-11-16T18:13:00+00:00" + ) + + async def test_last_strike_restored_until_next_strike( hass: HomeAssistant, mock_config_entry: MockConfigEntry, From 7b85f466815e33d716b72588dfc4be584d50b79d Mon Sep 17 00:00:00 2001 From: Jeef Date: Tue, 13 Oct 2026 11:58:39 -0600 Subject: [PATCH 299/356] Bump weatherflow4py to 1.5.12 (#186142) --- homeassistant/components/weatherflow_cloud/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/weatherflow_cloud/manifest.json b/homeassistant/components/weatherflow_cloud/manifest.json index 02c7527562db..776e3371fec9 100644 --- a/homeassistant/components/weatherflow_cloud/manifest.json +++ b/homeassistant/components/weatherflow_cloud/manifest.json @@ -7,5 +7,5 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["weatherflow4py"], - "requirements": ["weatherflow4py==1.5.8"] + "requirements": ["weatherflow4py==1.5.12"] } diff --git a/requirements_all.txt b/requirements_all.txt index 3e79d9e89b19..35cf78512e6d 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3427,7 +3427,7 @@ waterfurnace==1.9.7 watergate-local-api==2026.2.2 # homeassistant.components.weatherflow_cloud -weatherflow4py==1.5.8 +weatherflow4py==1.5.12 # homeassistant.components.cisco_webex_teams webexpythonsdk==2.0.6 From d5b1e01fd43530531c8cc72e277cf649db187ea1 Mon Sep 17 00:00:00 2001 From: Jeef Date: Tue, 13 Oct 2026 11:56:12 -0600 Subject: [PATCH 300/356] Bump intellifire4py to 4.5.6 (#186143) --- homeassistant/components/intellifire/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/intellifire/manifest.json b/homeassistant/components/intellifire/manifest.json index ffe8bed9117f..7edefc24401a 100644 --- a/homeassistant/components/intellifire/manifest.json +++ b/homeassistant/components/intellifire/manifest.json @@ -12,5 +12,5 @@ "integration_type": "device", "iot_class": "local_polling", "loggers": ["intellifire4py"], - "requirements": ["intellifire4py==4.5.0"] + "requirements": ["intellifire4py==4.5.6"] } diff --git a/requirements_all.txt b/requirements_all.txt index 35cf78512e6d..ca1c870bc2fd 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1414,7 +1414,7 @@ inkbird-ble==1.7.1 insteon-frontend-home-assistant==0.7.0 # homeassistant.components.intellifire -intellifire4py==4.5.0 +intellifire4py==4.5.6 # homeassistant.components.iometer iometer==1.0.2 From 7bca3ee8c21e0fe635d7a720d77a392eeb0279fc Mon Sep 17 00:00:00 2001 From: Joost Lekkerkerker Date: Tue, 13 Oct 2026 15:20:37 +0200 Subject: [PATCH 301/356] Fix scrape subentry reconfigure flow not finishing (#186144) Co-authored-by: Claude --- homeassistant/components/scrape/config_flow.py | 2 +- tests/components/scrape/test_config_flow.py | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/scrape/config_flow.py b/homeassistant/components/scrape/config_flow.py index 9f497971956a..44be0a23a69c 100644 --- a/homeassistant/components/scrape/config_flow.py +++ b/homeassistant/components/scrape/config_flow.py @@ -306,7 +306,7 @@ class ScrapeSubentryFlowHandler(ConfigSubentryFlow): ) -> SubentryFlowResult: """User flow to reconfigure a sensor subentry.""" if user_input is not None: - self.async_update_and_abort( + return self.async_update_and_abort( self._get_entry(), self._get_reconfigure_subentry(), data=user_input ) diff --git a/tests/components/scrape/test_config_flow.py b/tests/components/scrape/test_config_flow.py index 955b780ac28c..d6849c0ef869 100644 --- a/tests/components/scrape/test_config_flow.py +++ b/tests/components/scrape/test_config_flow.py @@ -310,7 +310,7 @@ async def test_reconfigure_sensor_subentry( "homeassistant.components.rest.RestData", return_value=get_data, ): - await hass.config_entries.subentries.async_configure( + result = await hass.config_entries.subentries.async_configure( result["flow_id"], { CONF_ADDITIONAL: { @@ -322,5 +322,8 @@ async def test_reconfigure_sensor_subentry( ) await hass.async_block_till_done() + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reconfigure_successful" + state = hass.states.get("sensor.current_version") assert state.state == "2021.12.10" From e5f179648faf559903a383aec3f1e370a0102cd0 Mon Sep 17 00:00:00 2001 From: Anthony Clerici Date: Tue, 13 Oct 2026 10:51:27 -0700 Subject: [PATCH 302/356] pin pycares to 5.0.1 (#186164) --- homeassistant/package_constraints.txt | 5 +++++ script/gen_requirements_all.py | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 3a4297a52227..0569518bb75c 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -263,6 +263,11 @@ python-backoff<2.4.0 # https://github.com/home-assistant/core/issues/184918 graphql-core<3.3 +# pycares 5.1.0 uses c-ares 1.34.8 which includes a regression. +# https://github.com/home-assistant/core/issues/185645 +# https://github.com/c-ares/c-ares/pull/1256 +pycares==5.0.1 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained diff --git a/script/gen_requirements_all.py b/script/gen_requirements_all.py index ac259c588e83..b13af224d335 100755 --- a/script/gen_requirements_all.py +++ b/script/gen_requirements_all.py @@ -247,6 +247,11 @@ python-backoff<2.4.0 # https://github.com/home-assistant/core/issues/184918 graphql-core<3.3 +# pycares 5.1.0 uses c-ares 1.34.8 which includes a regression. +# https://github.com/home-assistant/core/issues/185645 +# https://github.com/c-ares/c-ares/pull/1256 +pycares==5.0.1 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained From fd36dcd0269dcb2f23faf9c57c9021c746eb79c8 Mon Sep 17 00:00:00 2001 From: Erik Montnemery Date: Tue, 13 Oct 2026 17:03:10 +0100 Subject: [PATCH 303/356] Allow a list of states for state conditions with a duration (#186165) --- homeassistant/helpers/config_validation.py | 18 +++---- tests/helpers/test_condition.py | 59 ++++++++++++++++------ 2 files changed, 51 insertions(+), 26 deletions(-) diff --git a/homeassistant/helpers/config_validation.py b/homeassistant/helpers/config_validation.py index 4e682a48bbeb..5d4e047a409a 100644 --- a/homeassistant/helpers/config_validation.py +++ b/homeassistant/helpers/config_validation.py @@ -1552,19 +1552,15 @@ def STATE_CONDITION_SCHEMA(value: Any) -> dict[str, Any]: validated = key_dependency("for", "state")(validated) if CONF_FOR in validated: - # `for` is anchored to the entity's last_changed, which only reflects a - # single current state. It therefore can't track an attribute, multiple - # states, or a state resolved from another entity. + # `for` is anchored to the entity's last_changed, so it can't track an + # attribute or a state resolved from another entity. With a list of + # states, the entity must stay in one of them for the whole duration. if CONF_ATTRIBUTE in validated: raise probatio.Invalid("Cannot use 'for' with an attribute") - state = validated[CONF_STATE] - # A single-element list is just that one state; unwrap it so the - # input-entity check below also rejects `state: [input_select.x]`. - if isinstance(state, list): - if len(state) != 1: - raise probatio.Invalid("Cannot use 'for' with a list of states") - state = state[0] - if INPUT_ENTITY_ID.match(state): + states = validated[CONF_STATE] + if not isinstance(states, list): + states = [states] + if any(INPUT_ENTITY_ID.match(state) for state in states): raise probatio.Invalid( "Cannot use 'for' with a state referencing an entity" ) diff --git a/tests/helpers/test_condition.py b/tests/helpers/test_condition.py index c5a624194a79..8bf8999cc87b 100644 --- a/tests/helpers/test_condition.py +++ b/tests/helpers/test_condition.py @@ -1420,6 +1420,42 @@ async def test_state_for(hass: HomeAssistant, req_state: str | list[str]) -> Non assert test.async_check() +async def test_state_for_list_of_states( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Test state with duration and a list of states. + + The entity must stay in one of the listed states for the whole duration; + changing between listed states restarts the duration. + """ + config = { + "condition": "state", + "entity_id": "light.kitchen", + "state": ["off", "unavailable"], + "for": {"minutes": 5}, + } + 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("light.kitchen", "on") + freezer.tick(timedelta(minutes=10)) + assert not test.async_check() + + hass.states.async_set("light.kitchen", "off") + freezer.tick(timedelta(minutes=4)) + assert not test.async_check() + freezer.tick(timedelta(minutes=1, seconds=1)) + assert test.async_check() + + # Changing to another listed state restarts the duration + hass.states.async_set("light.kitchen", "unavailable") + freezer.tick(timedelta(minutes=4)) + assert not test.async_check() + freezer.tick(timedelta(minutes=1, seconds=1)) + assert test.async_check() + + async def test_state_for_template(hass: HomeAssistant) -> None: """Test state with templated duration.""" config = { @@ -1480,16 +1516,6 @@ async def test_state_for_invalid_template( r"Cannot use 'for' with an attribute", id="attribute", ), - pytest.param( - {"state": ["100", "200"]}, - r"Cannot use 'for' with a list of states", - id="list_of_states", - ), - pytest.param( - {"state": []}, - r"Cannot use 'for' with a list of states", - id="empty_list", - ), pytest.param( {"state": "input_number.threshold"}, r"Cannot use 'for' with a state referencing an entity", @@ -1500,16 +1526,19 @@ async def test_state_for_invalid_template( r"Cannot use 'for' with a state referencing an entity", id="single_item_list_from_entity", ), + pytest.param( + {"state": ["100", "input_number.threshold"]}, + r"Cannot use 'for' with a state referencing an entity", + id="list_with_state_from_entity", + ), ], ) def test_state_for_not_allowed(extra_config: dict[str, Any], error: str) -> None: """Test state condition rejects `for` with unsupported `state`/`attribute`. - `for` is anchored to the entity's last_changed, which reflects a single - current state. It therefore cannot be combined with an attribute, a list - that is not a single state, or a state resolved from another entity (even as - a single-element list). A single-element literal list behaves like the - scalar form (see `test_state_for`). + `for` is anchored to the entity's last_changed. It therefore cannot be + combined with an attribute or a state resolved from another entity, also + when that entity is one item of a list. """ config = { "condition": "state", From 40c86e1462af7c2dffbc35585f675b62ba4af6f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A5le=20Stor=C3=B8=20Hauknes?= <270292+LaStrada@users.noreply.github.com> Date: Wed, 14 Oct 2026 14:44:51 +0200 Subject: [PATCH 304/356] Bump airthings-ble to 1.3.1 (#186387) --- homeassistant/components/airthings_ble/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/airthings_ble/manifest.json b/homeassistant/components/airthings_ble/manifest.json index 4dd203bd3af9..d3855c01e20b 100644 --- a/homeassistant/components/airthings_ble/manifest.json +++ b/homeassistant/components/airthings_ble/manifest.json @@ -29,5 +29,5 @@ "documentation": "https://www.home-assistant.io/integrations/airthings_ble", "integration_type": "device", "iot_class": "local_polling", - "requirements": ["airthings-ble==1.2.0"] + "requirements": ["airthings-ble==1.3.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index ca1c870bc2fd..8673e1eaa3f8 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -510,7 +510,7 @@ airos==0.6.12 airpatrol==0.1.0 # homeassistant.components.airthings_ble -airthings-ble==1.2.0 +airthings-ble==1.3.1 # homeassistant.components.airthings airthings-cloud==0.2.0 From ea95900595a9e8c1e0906f7db9e83dae32b11e4f Mon Sep 17 00:00:00 2001 From: Josef Zweck Date: Thu, 15 Oct 2026 08:16:11 +0200 Subject: [PATCH 305/356] Guard owner and existing credentials in auth provider create command (#186398) --- .../config/auth_provider_homeassistant.py | 36 +++++- .../test_auth_provider_homeassistant.py | 118 +++++++++++++++++- 2 files changed, 147 insertions(+), 7 deletions(-) diff --git a/homeassistant/components/config/auth_provider_homeassistant.py b/homeassistant/components/config/auth_provider_homeassistant.py index e8b5396c73c6..05a97ed51647 100644 --- a/homeassistant/components/config/auth_provider_homeassistant.py +++ b/homeassistant/components/config/auth_provider_homeassistant.py @@ -1,5 +1,6 @@ """Offer API to configure the Home Assistant auth provider.""" +import asyncio from typing import Any import probatio @@ -8,11 +9,17 @@ from homeassistant.auth.providers import homeassistant as auth_ha from homeassistant.components import websocket_api from homeassistant.core import HomeAssistant, callback from homeassistant.exceptions import Unauthorized +from homeassistant.util.hass_dict import HassKey + +CREATE_LOCK: HassKey[asyncio.Lock] = HassKey( + "config_auth_provider_homeassistant_create_lock" +) @callback def async_setup(hass: HomeAssistant) -> bool: """Enable the Home Assistant views.""" + hass.data[CREATE_LOCK] = asyncio.Lock() websocket_api.async_register_command(hass, websocket_create) websocket_api.async_register_command(hass, websocket_delete) websocket_api.async_register_command(hass, websocket_change_password) @@ -51,12 +58,31 @@ async def websocket_create( ) return - await provider.async_add_auth(msg["username"], msg["password"]) + if user.is_owner and not connection.user.is_owner: + raise Unauthorized(context=connection.context(msg)) - credentials = await provider.async_get_or_create_credentials( - {"username": msg["username"]} - ) - await hass.auth.async_link_user(user, credentials) + # Serialize the check with the link so concurrent requests can't both + # pass it and attach two passwords. + async with hass.data[CREATE_LOCK]: + # A second password would let an admin log in as the user without + # going through the owner-only admin_change_password command. + if any( + credential.auth_provider_type == provider.type + for credential in user.credentials + ): + connection.send_error( + msg["id"], + "credentials_exist", + "User already has credentials for this provider", + ) + return + + await provider.async_add_auth(msg["username"], msg["password"]) + + credentials = await provider.async_get_or_create_credentials( + {"username": msg["username"]} + ) + await hass.auth.async_link_user(user, credentials) connection.send_result(msg["id"]) diff --git a/tests/components/config/test_auth_provider_homeassistant.py b/tests/components/config/test_auth_provider_homeassistant.py index 56fa85859d01..2e0a8e04c0a5 100644 --- a/tests/components/config/test_auth_provider_homeassistant.py +++ b/tests/components/config/test_auth_provider_homeassistant.py @@ -74,9 +74,123 @@ async def test_create_auth_system_generated_user( assert result["error"]["code"] == "system_generated" -async def test_create_auth_user_already_credentials() -> None: +async def test_create_auth_user_already_credentials( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + auth_provider: prov_ha.HassAuthProvider, +) -> None: """Test we can't create auth for user with pre-existing credentials.""" - # assert False + client = await hass_ws_client(hass) + user = MockUser().add_to_hass(hass) + + await client.send_json( + { + "id": 5, + "type": "config/auth_provider/homeassistant/create", + "user_id": user.id, + "username": "test-user2", + "password": "test-pass", + } + ) + result = await client.receive_json() + assert result["success"], result + + await client.send_json( + { + "id": 6, + "type": "config/auth_provider/homeassistant/create", + "user_id": user.id, + "username": "test-user3", + "password": "test-pass", + } + ) + result = await client.receive_json() + assert not result["success"], result + assert result["error"]["code"] == "credentials_exist" + assert len(user.credentials) == 1 + + with pytest.raises(prov_ha.InvalidAuth): + await auth_provider.async_validate_login("test-user3", "test-pass") + + +async def test_create_auth_concurrent( + hass: HomeAssistant, hass_ws_client: WebSocketGenerator +) -> None: + """Test concurrent creates for the same user attach only one credential.""" + client = await hass_ws_client(hass) + user = MockUser().add_to_hass(hass) + + for msg_id, username in ((5, "test-user2"), (6, "test-user3")): + await client.send_json( + { + "id": msg_id, + "type": "config/auth_provider/homeassistant/create", + "user_id": user.id, + "username": username, + "password": "test-pass", + } + ) + + results = { + result["id"]: result + for result in (await client.receive_json(), await client.receive_json()) + } + assert results[5]["success"], results[5] + assert not results[6]["success"], results[6] + assert results[6]["error"]["code"] == "credentials_exist" + assert len(user.credentials) == 1 + + +async def test_create_auth_owner_not_owner( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + hass_owner_user: MockUser, + auth_provider: prov_ha.HassAuthProvider, +) -> None: + """Test an admin that is not the owner can't add credentials to the owner.""" + client = await hass_ws_client(hass) + + await client.send_json( + { + "id": 5, + "type": "config/auth_provider/homeassistant/create", + "user_id": hass_owner_user.id, + "username": "test-user2", + "password": "test-pass", + } + ) + + result = await client.receive_json() + assert not result["success"], result + assert result["error"]["code"] == "unauthorized" + assert len(hass_owner_user.credentials) == 0 + + with pytest.raises(prov_ha.InvalidAuth): + await auth_provider.async_validate_login("test-user2", "test-pass") + + +async def test_create_auth_owner( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + hass_owner_user: MockUser, + owner_access_token: str, +) -> None: + """Test the owner can add credentials to itself.""" + client = await hass_ws_client(hass, owner_access_token) + + await client.send_json( + { + "id": 5, + "type": "config/auth_provider/homeassistant/create", + "user_id": hass_owner_user.id, + "username": "test-user2", + "password": "test-pass", + } + ) + + result = await client.receive_json() + assert result["success"], result + assert len(hass_owner_user.credentials) == 1 async def test_create_auth_unknown_user( From 7f567f60cb157a76c8666292d69441a7f5646a1f Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Wed, 14 Oct 2026 12:24:54 +0200 Subject: [PATCH 306/356] Fetch missing Renault vehicle details (#186402) --- .../components/renault/renault_hub.py | 12 ++++- tests/components/renault/conftest.py | 12 +++++ tests/components/renault/test_config_flow.py | 48 +++++++++++++++++++ tests/components/renault/test_init.py | 8 ++-- 4 files changed, 75 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/renault/renault_hub.py b/homeassistant/components/renault/renault_hub.py index 8a9b56201485..6235d7c6fcf1 100644 --- a/homeassistant/components/renault/renault_hub.py +++ b/homeassistant/components/renault/renault_hub.py @@ -1,6 +1,7 @@ """Proxy to handle account communication with Renault servers.""" import asyncio +import contextlib from datetime import timedelta import logging from time import time @@ -8,6 +9,7 @@ from typing import TYPE_CHECKING from renault_api.exceptions import NotAuthenticatedException from renault_api.gigya.exceptions import InvalidCredentialsException +from renault_api.kamereon.exceptions import KamereonResponseException from renault_api.kamereon.models import KamereonVehiclesLink from renault_api.renault_account import RenaultAccount from renault_api.renault_client import RenaultClient @@ -38,15 +40,21 @@ LOGGER = logging.getLogger(__name__) async def _get_filtered_vehicles(account: RenaultAccount) -> list[KamereonVehiclesLink]: - """Filter out vehicles with missing details. + """Get the vehicles, filtering out those with missing details. - May be due to new purchases, or issue with the Renault servers. + The vehicle list sometimes omits the details, so they are requested + separately. They may still be missing for new purchases, or due to an + issue with the Renault servers. """ vehicles = await account.get_vehicles() if not vehicles.vehicleLinks: return [] result: list[KamereonVehiclesLink] = [] for link in vehicles.vehicleLinks: + if link.vehicleDetails is None and link.vin: + vehicle = await account.get_api_vehicle(link.vin) + with contextlib.suppress(KamereonResponseException): + link.vehicleDetails = await vehicle.get_details() if link.vehicleDetails is None: LOGGER.warning("Ignoring vehicle with missing details: %s", link.vin) continue diff --git a/tests/components/renault/conftest.py b/tests/components/renault/conftest.py index 2fcd78a78a4f..3191d1108159 100644 --- a/tests/components/renault/conftest.py +++ b/tests/components/renault/conftest.py @@ -28,6 +28,18 @@ def mock_setup_entry() -> Generator[AsyncMock]: yield mock_setup_entry +@pytest.fixture(autouse=True) +def mock_get_vehicle_details() -> Generator[AsyncMock]: + """Fail the separate request for details missing from the vehicle list.""" + with patch( + "renault_api.renault_vehicle.RenaultVehicle.get_details", + side_effect=exceptions.ResourceNotFoundException( + "err.func.wired.notFound", "Resource not found" + ), + ) as mock_get_details: + yield mock_get_details + + @pytest.fixture(name="vehicle_type", params=MOCK_VEHICLES.keys()) def get_vehicle_type(request: pytest.FixtureRequest) -> str: """Parametrize vehicle type.""" diff --git a/tests/components/renault/test_config_flow.py b/tests/components/renault/test_config_flow.py index fe98ee33de11..6f887293d026 100644 --- a/tests/components/renault/test_config_flow.py +++ b/tests/components/renault/test_config_flow.py @@ -164,6 +164,54 @@ async def test_config_flow_no_account( assert len(mock_setup_entry.mock_calls) == 0 +async def test_config_flow_missing_vehicle_details( + hass: HomeAssistant, mock_setup_entry: AsyncMock +) -> None: + """Test vehicle details missing from the vehicle list are requested separately.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": config_entries.SOURCE_USER} + ) + + renault_vehicles = schemas.KamereonVehiclesResponseSchema.loads( + await async_load_fixture(hass, "vehicle_zoe_40.json", DOMAIN) + ) + renault_vehicles.vehicleLinks = renault_vehicles.vehicleLinks[:1] + vehicle_details = renault_vehicles.vehicleLinks[0].vehicleDetails + renault_vehicles.vehicleLinks[0].vehicleDetails = None + renault_account = AsyncMock() + type(renault_account).account_id = PropertyMock(return_value="account_id_1") + renault_account.get_vehicles.return_value = renault_vehicles + renault_account.get_api_vehicle.return_value.get_details.return_value = ( + vehicle_details + ) + + with ( + patch( + "renault_api.renault_session.RenaultSession.login", + autospec=True, + side_effect=_mock_login, + ), + patch( + "renault_api.renault_client.RenaultClient.get_api_accounts", + return_value=[renault_account], + ), + ): + result = await hass.config_entries.flow.async_configure( + result["flow_id"], + user_input={ + RenaultConfigurationKeys.LOCALE: "fr_FR", + RenaultConfigurationKeys.USERNAME: "email@test.com", + RenaultConfigurationKeys.PASSWORD: "test", + }, + ) + + renault_account.get_api_vehicle.assert_awaited_once_with("VF1ZOE40VIN") + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "account_id_1" + + assert len(mock_setup_entry.mock_calls) == 1 + + async def test_config_flow_multiple_accounts( hass: HomeAssistant, mock_setup_entry: AsyncMock ) -> None: diff --git a/tests/components/renault/test_init.py b/tests/components/renault/test_init.py index 7846d154297f..eb3875e5dfb2 100644 --- a/tests/components/renault/test_init.py +++ b/tests/components/renault/test_init.py @@ -1,7 +1,7 @@ """Tests for Renault setup process.""" from collections.abc import Generator -from unittest.mock import Mock, patch +from unittest.mock import AsyncMock, Mock, patch import aiohttp import pytest @@ -283,14 +283,16 @@ async def test_account_not_found_issue_deleted_on_removal( @pytest.mark.usefixtures("patch_renault_account", "patch_get_vehicles") @pytest.mark.parametrize("vehicle_type", ["missing_details"], indirect=True) async def test_setup_entry_missing_vehicle_details( - hass: HomeAssistant, config_entry: ConfigEntry + hass: HomeAssistant, config_entry: ConfigEntry, mock_get_vehicle_details: AsyncMock ) -> None: """Test ConfigEntryNotReady when vehicleDetails is missing.""" # In this case we are testing the condition where renault_hub fails to retrieve - # vehicle details (see #99127). + # vehicle details (see #99127), even when requested separately. await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() + # Requested for each vehicle without details in the vehicle list. + assert mock_get_vehicle_details.await_count == 2 assert len(hass.config_entries.async_entries(DOMAIN)) == 1 assert config_entry.state is ConfigEntryState.SETUP_RETRY From 7d588ac9c0d5302093dc03ed74cc0cf224612f8c Mon Sep 17 00:00:00 2001 From: cerealkiller57540 Date: Wed, 14 Oct 2026 14:53:37 +0200 Subject: [PATCH 307/356] Fix Discogs random record sensor when release has no format description (#186405) Co-authored-by: cerealkiller57540 <248219023+cerealkiller57540@users.noreply.github.com> --- homeassistant/components/discogs/sensor.py | 7 +++-- tests/components/discogs/test_sensor.py | 30 ++++++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/discogs/sensor.py b/homeassistant/components/discogs/sensor.py index e7f0bd1a93d1..3b58fdafa0f6 100644 --- a/homeassistant/components/discogs/sensor.py +++ b/homeassistant/components/discogs/sensor.py @@ -174,12 +174,15 @@ class DiscogsSensor(SensorEntity): self.entity_description.key == SENSOR_RANDOM_RECORD_TYPE and self._attr_native_value is not None ): + record_format = self._attrs["formats"][0] + descriptions = record_format.get("descriptions") return { "cat_no": self._attrs["labels"][0]["catno"], "cover_image": self._attrs["cover_image"], "format": ( - f"{self._attrs['formats'][0]['name']}" - f" ({self._attrs['formats'][0]['descriptions'][0]})" + f"{record_format['name']} ({descriptions[0]})" + if descriptions + else record_format["name"] ), "label": self._attrs["labels"][0]["name"], "released": self._attrs["year"], diff --git a/tests/components/discogs/test_sensor.py b/tests/components/discogs/test_sensor.py index 63bc54e2cf3d..a5721731a602 100644 --- a/tests/components/discogs/test_sensor.py +++ b/tests/components/discogs/test_sensor.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock, patch +import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import Platform @@ -66,3 +67,32 @@ async def test_sensors_empty_collection( state = hass.states.get("sensor.testuser_random_record") assert state is not None assert state.state == "unknown" + + +@pytest.mark.parametrize( + ("record_format", "expected_format"), + [ + ({"name": "CD", "descriptions": []}, "CD"), + ({"name": "CD"}, "CD"), + ({"name": "Vinyl", "descriptions": ["LP", "Album"]}, "Vinyl (LP)"), + ], +) +async def test_random_record_format_without_descriptions( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_discogs_client: MagicMock, + mock_discogs_data: dict, + record_format: dict, + expected_format: str, +) -> None: + """Test the random record format when the release has no descriptions.""" + mock_discogs_data["formats"] = [record_format] + + mock_config_entry.add_to_hass(hass) + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + state = hass.states.get("sensor.testuser_random_record") + assert state is not None + assert state.state == "Artist Name - Album Title" + assert state.attributes["format"] == expected_format From aa883cab66a638da81407c819a14ccbc6676c94a Mon Sep 17 00:00:00 2001 From: Tom Date: Wed, 14 Oct 2026 18:08:14 +0200 Subject: [PATCH 308/356] Fix permissions validation for ProxmoxVE (#186420) --- homeassistant/components/proxmoxve/helpers.py | 12 ++--- tests/components/proxmoxve/__init__.py | 5 ++- tests/components/proxmoxve/test_helpers.py | 45 +++++++++++++++++++ 3 files changed, 54 insertions(+), 8 deletions(-) create mode 100644 tests/components/proxmoxve/test_helpers.py diff --git a/homeassistant/components/proxmoxve/helpers.py b/homeassistant/components/proxmoxve/helpers.py index c968cc5583a9..50381243ebbd 100644 --- a/homeassistant/components/proxmoxve/helpers.py +++ b/homeassistant/components/proxmoxve/helpers.py @@ -26,12 +26,12 @@ def is_granted( permission: ProxmoxPermission = ProxmoxPermission.POWER, ) -> bool: """Validate user permissions for the given type and permission.""" - paths = [f"/{p_type}/{p_id}", f"/{p_type}", "/"] - for path in paths: - value = permissions.get(path, {}).get(permission) - if value is not None: - return value == 1 - return False + if (privileges := permissions.get(f"/{p_type}/{p_id}")) is not None: + return permission in privileges + + # Proxmox omits /{p_type} only when nothing reaches it, so "/" never applies. + # Known limitation: an exact path denied via NoAccess is omitted as well. + return permissions.get(f"/{p_type}", {}).get(permission) == 1 def is_proxmox_package(update: dict[str, Any]) -> bool: diff --git a/tests/components/proxmoxve/__init__.py b/tests/components/proxmoxve/__init__.py index 3667225079e5..4ad301ecb76c 100644 --- a/tests/components/proxmoxve/__init__.py +++ b/tests/components/proxmoxve/__init__.py @@ -36,15 +36,16 @@ POWER_PERMISSIONS = { "VM.PowerMgmt": 1, }, "/vms": {"VM.PowerMgmt": 1}, - "/vms/101": {"VM.PowerMgmt": 0}, + "/vms/101": {"VM.Audit": 1}, } SNAPSHOT_PERMISSIONS = { "/vms": {"VM.Snapshot": 1}, - "/vms/101": {"VM.Snapshot": 0}, + "/vms/101": {"VM.Audit": 1}, } SYSMOD_PERMISSIONS = { "/": {"Sys.Modify": 1}, + "/nodes": {"Sys.Modify": 1}, } MERGED_PERMISSIONS = { diff --git a/tests/components/proxmoxve/test_helpers.py b/tests/components/proxmoxve/test_helpers.py new file mode 100644 index 000000000000..d551302b0b25 --- /dev/null +++ b/tests/components/proxmoxve/test_helpers.py @@ -0,0 +1,45 @@ +"""Tests for Proxmox VE helpers.""" + +import pytest + +from homeassistant.components.proxmoxve.const import ProxmoxPermission +from homeassistant.components.proxmoxve.helpers import is_granted + + +@pytest.mark.parametrize( + ("permissions", "expected"), + [ + pytest.param( + {"/vms/100": {ProxmoxPermission.POWER: 0}}, True, id="exact_no_propagate" + ), + pytest.param( + {"/vms/100": {ProxmoxPermission.POWER: 1}}, True, id="exact_propagate" + ), + pytest.param( + { + "/vms/100": {ProxmoxPermission.VMAUDIT: 1}, + "/vms": {ProxmoxPermission.POWER: 1}, + }, + False, + id="exact_overrides_parent", + ), + pytest.param( + {"/vms": {ProxmoxPermission.POWER: 1}}, True, id="parent_propagate" + ), + pytest.param( + {"/vms": {ProxmoxPermission.POWER: 0}}, False, id="parent_no_propagate" + ), + pytest.param( + {"/": {ProxmoxPermission.POWER: 1}}, False, id="root_not_consulted" + ), + pytest.param({}, False, id="no_permissions"), + ], +) +def test_is_granted(permissions: dict[str, dict[str, int]], expected: bool) -> None: + """Test permission resolution against the Proxmox VE permissions tree.""" + assert ( + is_granted( + permissions, p_type="vms", p_id=100, permission=ProxmoxPermission.POWER + ) + is expected + ) From 0a114d7dcc4c32326dd5f18b335e2d916dbf51ad Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Wed, 14 Oct 2026 18:01:29 +0200 Subject: [PATCH 309/356] Hide MELCloud Home swing modes on units without vanes (#186468) --- .../components/melcloud_home/climate.py | 6 +- .../components/melcloud_home/test_climate.py | 56 +++++++++++++++++++ 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/melcloud_home/climate.py b/homeassistant/components/melcloud_home/climate.py index f2f8cff92436..c7e18b1086be 100644 --- a/homeassistant/components/melcloud_home/climate.py +++ b/homeassistant/components/melcloud_home/climate.py @@ -158,7 +158,11 @@ class ATAClimateEntity(MelCloudHomeATAUnitEntity, ClimateEntity): | ClimateEntityFeature.TURN_ON | ClimateEntityFeature.TURN_OFF ) - if (settings := self.unit.settings) is not None: + if (settings := self.unit.settings) is not None and ( + self.unit.capabilities is None + or self.unit.capabilities.has_air_direction is not False + or self.unit.capabilities.has_swing is not False + ): if settings.get("VaneVerticalDirection") is not None: features |= ClimateEntityFeature.SWING_MODE if settings.get("VaneHorizontalDirection") is not None: diff --git a/tests/components/melcloud_home/test_climate.py b/tests/components/melcloud_home/test_climate.py index bd155257a35b..c7130136600a 100644 --- a/tests/components/melcloud_home/test_climate.py +++ b/tests/components/melcloud_home/test_climate.py @@ -29,12 +29,14 @@ from homeassistant.components.climate import ( SERVICE_SET_SWING_HORIZONTAL_MODE, SERVICE_SET_SWING_MODE, SERVICE_SET_TEMPERATURE, + ClimateEntityFeature, HVACAction, HVACMode, ) from homeassistant.components.melcloud_home.const import DOMAIN from homeassistant.const import ( ATTR_ENTITY_ID, + ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE, SERVICE_TURN_OFF, SERVICE_TURN_ON, @@ -220,6 +222,60 @@ async def test_ata_set_fan_mode( ) +@pytest.mark.parametrize( + ("apply_capabilities", "expected_features"), + [ + pytest.param( + lambda _: None, + ClimateEntityFeature.SWING_MODE + | ClimateEntityFeature.SWING_HORIZONTAL_MODE, + id="no_capabilities", + ), + pytest.param( + lambda caps: {**caps, "hasAirDirection": False}, + ClimateEntityFeature.SWING_MODE + | ClimateEntityFeature.SWING_HORIZONTAL_MODE, + id="swing_only", + ), + pytest.param( + lambda caps: {**caps, "hasSwing": False}, + ClimateEntityFeature.SWING_MODE + | ClimateEntityFeature.SWING_HORIZONTAL_MODE, + id="air_direction_only", + ), + pytest.param( + lambda caps: {**caps, "hasAirDirection": False, "hasSwing": False}, + ClimateEntityFeature(0), + id="no_vanes", + ), + ], +) +async def test_ata_swing_features( + hass: HomeAssistant, + mock_melcloud_client: AsyncMock, + mock_config_entry: MockConfigEntry, + apply_capabilities: Callable[[dict[str, Any]], dict[str, Any] | None], + expected_features: ClimateEntityFeature, +) -> None: + """Test ATA swing features follow the unit's capabilities.""" + context: dict[str, Any] = await async_load_json_object_fixture( + hass, "context.json", DOMAIN + ) + ata_unit = context["buildings"][0]["airToAirUnits"][0] + ata_unit["capabilities"] = apply_capabilities(ata_unit["capabilities"]) + mock_melcloud_client.get_context.return_value = UserContext.model_validate(context) + + await setup_integration(hass, mock_config_entry) + + assert (state := hass.states.get(ATA_ENTITY_ID)) + swing_features = ( + ClimateEntityFeature.SWING_MODE | ClimateEntityFeature.SWING_HORIZONTAL_MODE + ) + assert ( + state.attributes[ATTR_SUPPORTED_FEATURES] & swing_features == expected_features + ) + + @pytest.mark.parametrize( ("swing_mode", "expected_vane"), [ From f96b0c69ab0dde1c467d518141e830ce27b8e001 Mon Sep 17 00:00:00 2001 From: Joyjit Nath <96009+joyjit@users.noreply.github.com> Date: Fri, 16 Oct 2026 03:08:10 -0700 Subject: [PATCH 310/356] Fix modbus reload without YAML config (#186554) --- homeassistant/components/modbus/services.py | 11 ++-- .../fixtures/configuration_no_modbus.yaml | 2 + tests/components/modbus/test_services.py | 66 +++++++++++++++++++ 3 files changed, 75 insertions(+), 4 deletions(-) create mode 100644 tests/components/modbus/fixtures/configuration_no_modbus.yaml diff --git a/homeassistant/components/modbus/services.py b/homeassistant/components/modbus/services.py index 03c0da93f13d..7ed8b57e37f6 100644 --- a/homeassistant/components/modbus/services.py +++ b/homeassistant/components/modbus/services.py @@ -110,10 +110,12 @@ async def _async_stop_hub(service: ServiceCall) -> None: async def _async_reload_config(call: ServiceCall) -> None: """Reload Modbus.""" hass = call.hass - if DATA_MODBUS_HUBS not in hass.data: - LOGGER.error("Modbus cannot reload, because it was never loaded") + # A failed setup stays cached, so the platforms would be rejected + if DOMAIN not in hass.config.components: + LOGGER.error("Modbus failed to set up, restart Home Assistant to retry") return - hubs = hass.data[DATA_MODBUS_HUBS] + # Without YAML hubs there is nothing to close, but YAML may have been added + hubs = hass.data.get(DATA_MODBUS_HUBS, {}) for hub in hubs.values(): await hub.async_close() reset_platforms = async_get_platforms(hass, DOMAIN) @@ -121,7 +123,8 @@ async def _async_reload_config(call: ServiceCall) -> None: LOGGER.debug("Reload modbus resetting platform: %s", reset_platform.domain) await reset_platform.async_reset() reload_config = await async_integration_yaml_config(hass, DOMAIN) - if not reload_config: + # The loaded YAML holds every integration's config, not just this one's + if not reload_config or DOMAIN not in reload_config: LOGGER.debug("Modbus not present anymore") hubs.clear() return diff --git a/tests/components/modbus/fixtures/configuration_no_modbus.yaml b/tests/components/modbus/fixtures/configuration_no_modbus.yaml new file mode 100644 index 000000000000..e34b6be35a45 --- /dev/null +++ b/tests/components/modbus/fixtures/configuration_no_modbus.yaml @@ -0,0 +1,2 @@ +logger: + default: info diff --git a/tests/components/modbus/test_services.py b/tests/components/modbus/test_services.py index 14ea2ce635fb..a2aa0ac06c23 100644 --- a/tests/components/modbus/test_services.py +++ b/tests/components/modbus/test_services.py @@ -29,6 +29,7 @@ from homeassistant.const import ( from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError from homeassistant.helpers.entity_platform import async_get_platforms +from homeassistant.helpers.typing import ConfigType from homeassistant.setup import async_setup_component from tests.common import get_fixture_path @@ -165,6 +166,71 @@ async def test_service_after_failed_reload_raises( assert err.value.translation_key == "not_loaded" +@pytest.mark.usefixtures("mock_pymodbus") +async def test_reload_after_failed_setup( + hass: HomeAssistant, caplog: pytest.LogCaptureFixture +) -> None: + """Test reload does not set the hubs up after a failed setup.""" + with patch( + "homeassistant.components.modbus.modbus.ModbusHub.async_setup", + return_value=False, + ): + assert not await async_setup_component(hass, DOMAIN, HUB_CONFIG) + await hass.async_block_till_done() + + yaml_path = get_fixture_path("configuration.yaml", DOMAIN) + with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): + await hass.services.async_call(DOMAIN, SERVICE_RELOAD, {}, blocking=True) + await hass.async_block_till_done() + + assert "Modbus failed to set up, restart Home Assistant to retry" in caplog.text + assert DATA_MODBUS_HUBS not in hass.data + + +@pytest.mark.usefixtures("mock_pymodbus") +@pytest.mark.parametrize( + "start_config", + [ + pytest.param({}, id="no_hubs"), + pytest.param(HUB_CONFIG, id="yaml_hub"), + ], +) +@pytest.mark.parametrize( + ("yaml_file", "expected_hubs", "expected_entities"), + [ + pytest.param("configuration_empty.yaml", set(), [], id="empty_yaml"), + pytest.param("configuration_no_modbus.yaml", set(), [], id="no_modbus_yaml"), + pytest.param( + "configuration.yaml", {"testModbus"}, ["sensor.dummy"], id="yaml_added" + ), + ], +) +async def test_reload_yaml( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + start_config: ConfigType, + yaml_file: str, + expected_hubs: set[str], + expected_entities: list[str], +) -> None: + """Test the reload result depends only on the YAML, with or without hubs.""" + assert await async_setup_component(hass, DOMAIN, start_config) + await hass.async_block_till_done() + + yaml_path = get_fixture_path(yaml_file, DOMAIN) + with patch.object(hass_config, "YAML_CONFIG_FILE", yaml_path): + await hass.services.async_call(DOMAIN, SERVICE_RELOAD, {}, blocking=True) + await hass.async_block_till_done() + + assert "ERROR" not in caplog.text + assert set(hass.data.get(DATA_MODBUS_HUBS, {})) == expected_hubs + assert [ + entity.entity_id + for platform in async_get_platforms(hass, DOMAIN) + for entity in platform.entities.values() + ] == expected_entities + + TEST_HUB_A = "hub_a" TEST_HUB_B = "hub_b" From 50405c7a71a6862e9d52cd71d17ca0ff1eab4c65 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Thu, 15 Oct 2026 04:31:25 +0200 Subject: [PATCH 311/356] Revoke refresh tokens when removing a user (#186558) --- homeassistant/auth/__init__.py | 4 ++++ tests/auth/test_init.py | 18 +++++++++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/homeassistant/auth/__init__.py b/homeassistant/auth/__init__.py index a58509781e20..0314c4b749e7 100644 --- a/homeassistant/auth/__init__.py +++ b/homeassistant/auth/__init__.py @@ -354,6 +354,10 @@ class AuthManager: if tasks: await asyncio.gather(*tasks) + # Revoking runs the callbacks, which close connections using the tokens. + for refresh_token in list(user.refresh_tokens.values()): + self.async_remove_refresh_token(refresh_token) + await self._store.async_remove_user(user) self.hass.bus.async_fire(EVENT_USER_REMOVED, {"user_id": user.id}) diff --git a/tests/auth/test_init.py b/tests/auth/test_init.py index 9bc4cd10f671..1f9f8482becb 100644 --- a/tests/auth/test_init.py +++ b/tests/auth/test_init.py @@ -3,7 +3,7 @@ from datetime import timedelta import time from typing import Any -from unittest.mock import patch +from unittest.mock import Mock, patch from freezegun import freeze_time import jwt @@ -1132,6 +1132,22 @@ async def test_async_remove_user(hass: HomeAssistant) -> None: assert events[0].data["user_id"] == user.id +async def test_async_remove_user_revokes_refresh_tokens(hass: HomeAssistant) -> None: + """Test removing a user revokes its refresh tokens.""" + manager = await auth.auth_manager_from_config(hass, [], []) + user = MockUser(is_owner=False).add_to_auth_manager(manager) + refresh_token = await manager.async_create_refresh_token(user, CLIENT_ID) + access_token = manager.async_create_access_token(refresh_token) + revoked = Mock() + manager.async_register_revoke_token_callback(refresh_token.id, revoked) + + await manager.async_remove_user(user) + + revoked.assert_called_once_with() + assert manager.async_get_refresh_token(refresh_token.id) is None + assert manager.async_validate_access_token(access_token) is None + + async def test_async_remove_user_fail_if_remove_credential_fails( hass: HomeAssistant, hass_admin_user: MockUser, hass_admin_credential: Credentials ) -> None: From 328e85a7b83ebe97def922062280c17614f319a2 Mon Sep 17 00:00:00 2001 From: epenet <6771947+epenet@users.noreply.github.com> Date: Thu, 15 Oct 2026 14:28:31 +0200 Subject: [PATCH 312/356] Redact credentials and host in SFR Box diagnostics (#186668) --- homeassistant/components/sfr_box/diagnostics.py | 13 +++++++++++-- .../sfr_box/snapshots/test_diagnostics.ambr | 8 ++++++-- tests/components/sfr_box/test_diagnostics.py | 15 ++++++++++----- 3 files changed, 27 insertions(+), 9 deletions(-) diff --git a/homeassistant/components/sfr_box/diagnostics.py b/homeassistant/components/sfr_box/diagnostics.py index 67a2169c1724..66f35cba9477 100644 --- a/homeassistant/components/sfr_box/diagnostics.py +++ b/homeassistant/components/sfr_box/diagnostics.py @@ -4,6 +4,7 @@ import dataclasses from typing import TYPE_CHECKING, Any from homeassistant.components.diagnostics import async_redact_data +from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from .coordinator import SFRConfigEntry @@ -11,7 +12,15 @@ from .coordinator import SFRConfigEntry if TYPE_CHECKING: from _typeshed import DataclassInstance -TO_REDACT = {"mac_addr", "serial_number", "ip_addr", "ipv6_addr"} +TO_REDACT = { + CONF_HOST, + CONF_PASSWORD, + CONF_USERNAME, + "mac_addr", + "serial_number", + "ip_addr", + "ipv6_addr", +} def _async_redact_data(obj: DataclassInstance | None) -> dict[str, Any] | None: @@ -29,7 +38,7 @@ async def async_get_config_entry_diagnostics( return { "entry": { "title": entry.title, - "data": dict(entry.data), + "data": async_redact_data(entry.data, TO_REDACT), }, "data": { "dsl": _async_redact_data(await data.system.box.dsl_get_info()), diff --git a/tests/components/sfr_box/snapshots/test_diagnostics.ambr b/tests/components/sfr_box/snapshots/test_diagnostics.ambr index 39a872750de2..d54fd4bae973 100644 --- a/tests/components/sfr_box/snapshots/test_diagnostics.ambr +++ b/tests/components/sfr_box/snapshots/test_diagnostics.ambr @@ -49,7 +49,9 @@ }), 'entry': dict({ 'data': dict({ - 'host': '192.168.0.1', + 'host': '**REDACTED**', + 'password': '**REDACTED**', + 'username': '**REDACTED**', }), 'title': 'Mock Title', }), @@ -94,7 +96,9 @@ }), 'entry': dict({ 'data': dict({ - 'host': '192.168.0.1', + 'host': '**REDACTED**', + 'password': '**REDACTED**', + 'username': '**REDACTED**', }), 'title': 'Mock Title', }), diff --git a/tests/components/sfr_box/test_diagnostics.py b/tests/components/sfr_box/test_diagnostics.py index cec0b50db149..b1fa7e8f1554 100644 --- a/tests/components/sfr_box/test_diagnostics.py +++ b/tests/components/sfr_box/test_diagnostics.py @@ -14,14 +14,17 @@ from tests.components.diagnostics import get_diagnostics_for_config_entry from tests.typing import ClientSessionGenerator pytestmark = pytest.mark.usefixtures( - "dsl_get_info", "ftth_get_info", "system_get_info", "wan_get_info" + "dsl_get_info", "ftth_get_info", "system_get_info", "voip_get_info", "wan_get_info" ) @pytest.fixture(autouse=True) def override_platforms() -> Generator[None]: """Override PLATFORMS.""" - with patch("homeassistant.components.sfr_box.PLATFORMS", []): + with ( + patch("homeassistant.components.sfr_box.PLATFORMS", []), + patch("homeassistant.components.sfr_box.coordinator.SFRBox.authenticate"), + ): yield @@ -31,7 +34,7 @@ def override_platforms() -> Generator[None]: ) async def test_entry_diagnostics( hass: HomeAssistant, - config_entry: ConfigEntry, + config_entry_with_auth: ConfigEntry, hass_client: ClientSessionGenerator, snapshot: SnapshotAssertion, system_get_info: SystemInfo, @@ -40,7 +43,7 @@ async def test_entry_diagnostics( ) -> None: """Test config entry diagnostics.""" system_get_info.net_infra = net_infra - await hass.config_entries.async_setup(config_entry.entry_id) + await hass.config_entries.async_setup(config_entry_with_auth.entry_id) await hass.async_block_till_done() with patch( @@ -48,6 +51,8 @@ async def test_entry_diagnostics( return_value=None, ): assert ( - await get_diagnostics_for_config_entry(hass, hass_client, config_entry) + await get_diagnostics_for_config_entry( + hass, hass_client, config_entry_with_auth + ) == snapshot ) From 6130fff25220cf259aa9a8fe7f374cbb6aca1d32 Mon Sep 17 00:00:00 2001 From: tronikos Date: Fri, 16 Oct 2026 05:15:07 -0700 Subject: [PATCH 313/356] Fix SolarEdge module statistics sum resetting after a gap (#186753) --- .../components/solaredge/coordinator.py | 70 ++-- .../components/solaredge/test_coordinator.py | 308 ++++++++++++++++++ 2 files changed, 354 insertions(+), 24 deletions(-) diff --git a/homeassistant/components/solaredge/coordinator.py b/homeassistant/components/solaredge/coordinator.py index b3860c66d371..d63049ed7ed6 100644 --- a/homeassistant/components/solaredge/coordinator.py +++ b/homeassistant/components/solaredge/coordinator.py @@ -608,42 +608,64 @@ class SolarEdgeModulesCoordinator(DataUpdateCoordinator[None]): self, equipment_ids: Iterable[int | str], start_time: datetime ) -> dict[str, float]: """Get the last sum from the recorder before start_time for each statistic.""" - start = start_time - timedelta(hours=1) statistic_ids = {self.get_statistic_id(eq_id) for eq_id in equipment_ids} LOGGER.debug( - "Getting sum for %s statistic IDs at: %s", len(statistic_ids), start + "Getting sum for %s statistic IDs before: %s", + len(statistic_ids), + start_time, ) + # The statistics are cumulative, so the sums must continue from the last + # sum before the window. Taking it from the change of the first statistic + # in the window works even when the previous statistics are older than + # the window, and unlike the absolute last statistic it is not reset by + # an earlier update that already wrote statistics inside the window. + # See https://github.com/home-assistant/core/issues/186653 . current_stats = await get_instance(self.hass).async_add_executor_job( statistics_during_period, self.hass, - start, - start + timedelta(seconds=1), + start_time, + None, statistic_ids, "hour", None, - {"sum"}, + {"sum", "change"}, ) result = {} for statistic_id in statistic_ids: - if statistic_id in current_stats: - statistic_sum = current_stats[statistic_id][0]["sum"] - else: - # If no statistics found right before start_time, - # try to get the last statistic but use it only - # if it's before start_time. This is needed if - # the integration hasn't run for at least a week. - last_stat = await get_instance(self.hass).async_add_executor_job( - get_last_statistics, self.hass, 1, statistic_id, True, {"sum"} + statistic_sum: float | None = None + window_stats = current_stats.get(statistic_id) or [] + # The change is relative to the last sum before start_time, so + # subtracting it from the first statistic that has a sum recovers + # that sum. Leading statistics without a sum are skipped. + for stat in window_stats: + stat_sum = stat["sum"] + stat_change = stat["change"] + if stat_sum is not None and stat_change is not None: + statistic_sum = stat_sum - stat_change + break + if statistic_sum is None: + # No statistic in the window has a usable sum, so continue from + # the last statistic before start_time. Fetch one more than the + # number of statistics in the window, since all of them can be + # missing a sum. + last_stats = await get_instance(self.hass).async_add_executor_job( + get_last_statistics, + self.hass, + len(window_stats) + 1, + statistic_id, + True, + {"sum"}, ) - if ( - last_stat - and last_stat[statistic_id][0]["start"] < start_time.timestamp() - ): - statistic_sum = last_stat[statistic_id][0]["sum"] - else: - # Expected for new installations or if the statistics were cleared, - # e.g. from the developer tools - statistic_sum = 0.0 - assert isinstance(statistic_sum, float) + for last_stat in last_stats.get(statistic_id, []): + if ( + last_stat["start"] < start_time.timestamp() + and last_stat["sum"] is not None + ): + statistic_sum = last_stat["sum"] + break + if statistic_sum is None: + # Expected for new installations or if the statistics were + # cleared, e.g. from the developer tools + statistic_sum = 0.0 result[statistic_id] = statistic_sum return result diff --git a/tests/components/solaredge/test_coordinator.py b/tests/components/solaredge/test_coordinator.py index f61501348c92..32c6d21e022a 100644 --- a/tests/components/solaredge/test_coordinator.py +++ b/tests/components/solaredge/test_coordinator.py @@ -11,6 +11,7 @@ from solaredge_web import EnergyData from homeassistant.components.recorder import Recorder from homeassistant.components.recorder.models import ( + StatisticData, StatisticMeanType, StatisticMetaData, ) @@ -34,6 +35,7 @@ from homeassistant.const import ( CONF_PASSWORD, CONF_USERNAME, STATE_UNKNOWN, + UnitOfEnergy, ) from homeassistant.core import HomeAssistant from homeassistant.util import dt as dt_util @@ -339,6 +341,312 @@ async def test_modules_coordinator_subsequent_run_with_gap( } +async def test_modules_coordinator_reprocess_same_window_after_gap( + recorder_mock: Recorder, + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_solar_edge_web: AsyncMock, +) -> None: + """Test the sum doesn't reset when the same window is refreshed again. + + After a gap the window is filled starting from the last sum before it. A + later refresh of the same window, e.g. after reloading the integration the + same day, must keep continuing from that sum. The window is taken from the + energy data returned by the API, so the gap is simulated by moving the + returned data instead of the clock. + + Regression test for https://github.com/home-assistant/core/issues/186653 . + """ + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_SITE_ID: SITE_ID, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + await async_wait_recording_done(hass) + + coordinator: SolarEdgeModulesCoordinator = entry.runtime_data[ + DATA_MODULES_COORDINATOR + ] + + # Values a month later, simulating a gap in data. The first row is also + # exactly at the start of the window, with older statistics before it. + mock_solar_edge_web.async_get_energy_data.return_value = [ + EnergyData( + start_time=dt_util.as_utc(datetime(2025, 2, 1, 11, 0)), + values={"7A012345-CA": 24.0, "7A012346-CA": 30.0}, + ), + ] + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + # Refresh the same window again, e.g. after reloading the integration the + # same day. The sums must not reset to 0. + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + stats = await hass.async_add_executor_job( + statistics_during_period, + hass, + dt_util.as_utc(datetime(1970, 1, 1, 0, 0)), + None, + {f"{DOMAIN}:{SITE_ID}_7a012345_ca", f"{DOMAIN}:{SITE_ID}_7a012346_ca"}, + "hour", + None, + {"state", "sum"}, + ) + assert stats == { + f"{DOMAIN}:{SITE_ID}_7a012345_ca": [ + {"start": 1735783200.0, "end": 1735786800.0, "state": 10.0, "sum": 10.0}, + {"start": 1735786800.0, "end": 1735790400.0, "state": 14.0, "sum": 24.0}, + {"start": 1738465200.0, "end": 1738468800.0, "state": 24.0, "sum": 48.0}, + ], + f"{DOMAIN}:{SITE_ID}_7a012346_ca": [ + {"start": 1735783200.0, "end": 1735786800.0, "state": 20.0, "sum": 20.0}, + {"start": 1735786800.0, "end": 1735790400.0, "state": 24.0, "sum": 44.0}, + {"start": 1738465200.0, "end": 1738468800.0, "state": 30.0, "sum": 74.0}, + ], + } + + +async def test_modules_coordinator_reprocess_same_window_new_equipment( + recorder_mock: Recorder, + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_solar_edge_web: AsyncMock, +) -> None: + """Test reprocessing the same window with a newly added optimizer. + + The optimizer that already has statistics continues from the last sum before + the window, while the newly added one, which has no earlier statistics, + starts from 0. + """ + mock_solar_edge_web.async_get_equipment.return_value = { + "7A012345-CA": {"name": "Optimizer 1.1"}, + } + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_SITE_ID: SITE_ID, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + await async_wait_recording_done(hass) + + coordinator: SolarEdgeModulesCoordinator = entry.runtime_data[ + DATA_MODULES_COORDINATOR + ] + + # A second optimizer is added a month later, after a gap in the data. + mock_solar_edge_web.async_get_equipment.return_value = { + "7A012345-CA": {"name": "Optimizer 1.1"}, + "7A012346-CA": {"name": "Optimizer 1.2"}, + } + mock_solar_edge_web.async_get_energy_data.return_value = [ + EnergyData( + start_time=dt_util.as_utc(datetime(2025, 2, 1, 11, 0)), + values={"7A012345-CA": 24.0, "7A012346-CA": 30.0}, + ), + ] + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + # Refresh the same window again, e.g. after reloading the integration the + # same day. + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + stats = await hass.async_add_executor_job( + statistics_during_period, + hass, + dt_util.as_utc(datetime(1970, 1, 1, 0, 0)), + None, + {f"{DOMAIN}:{SITE_ID}_7a012345_ca", f"{DOMAIN}:{SITE_ID}_7a012346_ca"}, + "hour", + None, + {"state", "sum"}, + ) + assert stats == { + f"{DOMAIN}:{SITE_ID}_7a012345_ca": [ + {"start": 1735783200.0, "end": 1735786800.0, "state": 10.0, "sum": 10.0}, + {"start": 1735786800.0, "end": 1735790400.0, "state": 14.0, "sum": 24.0}, + {"start": 1738465200.0, "end": 1738468800.0, "state": 24.0, "sum": 48.0}, + ], + f"{DOMAIN}:{SITE_ID}_7a012346_ca": [ + {"start": 1738465200.0, "end": 1738468800.0, "state": 30.0, "sum": 30.0}, + ], + } + + +async def test_modules_coordinator_first_window_statistic_without_sum( + recorder_mock: Recorder, + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_solar_edge_web: AsyncMock, +) -> None: + """Test the sum is still recovered when the first in-window statistic has no sum. + + The recorder computes the change relative to the last sum before the window, + so the first in-window statistic that has a sum recovers the baseline even + when preceding statistics in the window have none. + """ + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_SITE_ID: SITE_ID, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + await async_wait_recording_done(hass) + + statistic_id = f"{DOMAIN}:{SITE_ID}_7a012345_ca" + # The first statistic in the window has no sum, the next one does. Its sum + # of 34 equals the 24 from the last statistic before the window plus 10. + async_add_external_statistics( + hass, + StatisticMetaData( + mean_type=StatisticMeanType.ARITHMETIC, + has_sum=True, + name=f"{entry.title} Optimizer 1.1", + source=DOMAIN, + statistic_id=statistic_id, + unit_class=EnergyConverter.UNIT_CLASS, + unit_of_measurement=UnitOfEnergy.WATT_HOUR, + ), + [ + StatisticData( + start=dt_util.as_utc(datetime(2025, 2, 1, 11, 0)).replace( + tzinfo=dt_util.get_default_time_zone() + ), + state=None, + sum=None, + ), + StatisticData( + start=dt_util.as_utc(datetime(2025, 2, 1, 12, 0)).replace( + tzinfo=dt_util.get_default_time_zone() + ), + state=10.0, + sum=34.0, + ), + ], + ) + await async_wait_recording_done(hass) + + mock_solar_edge_web.async_get_energy_data.return_value = [ + EnergyData( + start_time=dt_util.as_utc(datetime(2025, 2, 1, 11, 0)), + values={"7A012345-CA": 10.0}, + ), + ] + coordinator: SolarEdgeModulesCoordinator = entry.runtime_data[ + DATA_MODULES_COORDINATOR + ] + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + stats = await hass.async_add_executor_job( + statistics_during_period, + hass, + dt_util.as_utc(datetime(1970, 1, 1, 0, 0)), + None, + {statistic_id}, + "hour", + None, + {"state", "sum"}, + ) + assert stats == { + statistic_id: [ + {"start": 1735783200.0, "end": 1735786800.0, "state": 10.0, "sum": 10.0}, + {"start": 1735786800.0, "end": 1735790400.0, "state": 14.0, "sum": 24.0}, + {"start": 1738465200.0, "end": 1738468800.0, "state": 10.0, "sum": 34.0}, + {"start": 1738468800.0, "end": 1738472400.0, "state": 10.0, "sum": 34.0}, + ] + } + + +async def test_modules_coordinator_window_statistics_without_sum( + recorder_mock: Recorder, + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + mock_solar_edge_web: AsyncMock, +) -> None: + """Test the sum is recovered when no in-window statistic has a sum. + + With no usable sum in the window, the baseline must come from the last + statistic before the window rather than from the last in-window statistic. + """ + entry = MockConfigEntry( + domain=DOMAIN, + data={CONF_SITE_ID: SITE_ID, CONF_USERNAME: USERNAME, CONF_PASSWORD: PASSWORD}, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + await async_wait_recording_done(hass) + + statistic_id = f"{DOMAIN}:{SITE_ID}_7a012345_ca" + # Every statistic in the window has no sum. + async_add_external_statistics( + hass, + StatisticMetaData( + mean_type=StatisticMeanType.ARITHMETIC, + has_sum=True, + name=f"{entry.title} Optimizer 1.1", + source=DOMAIN, + statistic_id=statistic_id, + unit_class=EnergyConverter.UNIT_CLASS, + unit_of_measurement=UnitOfEnergy.WATT_HOUR, + ), + [ + StatisticData( + start=dt_util.as_utc(datetime(2025, 2, 1, hour, 0)).replace( + tzinfo=dt_util.get_default_time_zone() + ), + state=None, + sum=None, + ) + for hour in (11, 12) + ], + ) + await async_wait_recording_done(hass) + + mock_solar_edge_web.async_get_energy_data.return_value = [ + EnergyData( + start_time=dt_util.as_utc(datetime(2025, 2, 1, 11, 0)), + values={"7A012345-CA": 10.0}, + ), + EnergyData( + start_time=dt_util.as_utc(datetime(2025, 2, 1, 12, 0)), + values={"7A012345-CA": 5.0}, + ), + ] + coordinator: SolarEdgeModulesCoordinator = entry.runtime_data[ + DATA_MODULES_COORDINATOR + ] + await _trigger_and_wait_for_refresh(hass, freezer, coordinator) + await async_wait_recording_done(hass) + + stats = await hass.async_add_executor_job( + statistics_during_period, + hass, + dt_util.as_utc(datetime(1970, 1, 1, 0, 0)), + None, + {statistic_id}, + "hour", + None, + {"state", "sum"}, + ) + assert stats == { + statistic_id: [ + {"start": 1735783200.0, "end": 1735786800.0, "state": 10.0, "sum": 10.0}, + {"start": 1735786800.0, "end": 1735790400.0, "state": 14.0, "sum": 24.0}, + {"start": 1738465200.0, "end": 1738468800.0, "state": 10.0, "sum": 34.0}, + {"start": 1738468800.0, "end": 1738472400.0, "state": 5.0, "sum": 39.0}, + ] + } + + async def test_modules_coordinator_no_energy_data( recorder_mock: Recorder, hass: HomeAssistant, From 9765b22546ab0f0edfe21ea7be84dc1e949f2b89 Mon Sep 17 00:00:00 2001 From: Robert Resch Date: Fri, 16 Oct 2026 10:16:12 +0200 Subject: [PATCH 314/356] Bump deebot-client to 18.7.0 (#186779) --- homeassistant/components/ecovacs/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/ecovacs/manifest.json b/homeassistant/components/ecovacs/manifest.json index 932e805c13eb..11bef886c506 100644 --- a/homeassistant/components/ecovacs/manifest.json +++ b/homeassistant/components/ecovacs/manifest.json @@ -7,5 +7,5 @@ "integration_type": "hub", "iot_class": "cloud_push", "loggers": ["sleekxmppfs", "sucks", "deebot_client"], - "requirements": ["py-sucks==0.9.11", "deebot-client==18.6.0"] + "requirements": ["py-sucks==0.9.11", "deebot-client==18.7.0"] } diff --git a/requirements_all.txt b/requirements_all.txt index 8673e1eaa3f8..fc24b24ce6f7 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -837,7 +837,7 @@ debugpy==1.8.22 decora-wifi==1.4 # homeassistant.components.ecovacs -deebot-client==18.6.0 +deebot-client==18.7.0 # homeassistant.components.ihc # homeassistant.components.ohmconnect From f90861812c7e53dd91fd4a2742e811cac7327ff3 Mon Sep 17 00:00:00 2001 From: Andreas Jakl Date: Fri, 16 Oct 2026 14:09:17 +0200 Subject: [PATCH 315/356] Redact identifying data in NRGkick diagnostics (#186781) --- .../components/nrgkick/diagnostics.py | 9 +++ tests/components/nrgkick/fixtures/info.json | 57 +++++++++++-------- .../nrgkick/snapshots/test_diagnostics.ambr | 33 ++++++----- .../nrgkick/snapshots/test_init.ambr | 4 +- .../nrgkick/snapshots/test_sensor.ambr | 6 +- 5 files changed, 66 insertions(+), 43 deletions(-) diff --git a/homeassistant/components/nrgkick/diagnostics.py b/homeassistant/components/nrgkick/diagnostics.py index dbe928cf9c2f..5e73ee4c6df7 100644 --- a/homeassistant/components/nrgkick/diagnostics.py +++ b/homeassistant/components/nrgkick/diagnostics.py @@ -7,6 +7,7 @@ from homeassistant.components.diagnostics import async_redact_data from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, + CONF_HOST, CONF_PASSWORD, CONF_USERNAME, ) @@ -18,8 +19,16 @@ TO_REDACT = { ATTR_LATITUDE, ATTR_LONGITUDE, "altitude", + CONF_HOST, CONF_PASSWORD, CONF_USERNAME, + "imei", + "imsi", + "ip_address", + "mac_address", + "serial", + "serial_number", + "ssid", } diff --git a/tests/components/nrgkick/fixtures/info.json b/tests/components/nrgkick/fixtures/info.json index 0f71494922e5..90a3589a6e90 100644 --- a/tests/components/nrgkick/fixtures/info.json +++ b/tests/components/nrgkick/fixtures/info.json @@ -1,40 +1,49 @@ { "general": { - "device_name": "NRGkick Test", "serial_number": "TEST123456", "model_type": "NRGkick Gen2 SIM", - "rated_current": 32.0, - "json_api_version": "v1" + "device_name": "NRGkick Test", + "rated_current": 32.0 }, "connector": { - "type": "TYPE2", - "serial_number": "CONN123", + "phase_count": 3, "max_current": 32.0, - "phase_count": 3 + "type": 3, + "serial": "CONN123" + }, + "grid": { + "voltage": 230, + "frequency": 50.0, + "phases": 7 + }, + "network": { + "ip_address": "192.168.1.100", + "mac_address": "AA:BB:CC:DD:EE:FF", + "ssid": "TestNetwork", + "rssi": -45 + }, + "cellular": { + "imei": "123456789012345", + "imsi": "001010123456789", + "operator": "Test operator", + "rssi": -85, + "mode": 3 }, - "cellular": { "mode": 3, "rssi": -85, "operator": "Test operator" }, "gps": { "latitude": 47.0748, "longitude": 15.4376, "altitude": 353.0, "accuracy": 1.5 }, - "grid": { - "voltage": 230, - "frequency": 50.0, - "phases": "L1, L2, L3" - }, - "network": { - "ip_address": "192.168.1.100", - "mac_address": "AA:BB:CC:DD:EE:FF", - "wifi_ssid": "TestNetwork", - "wifi_rssi": -45 - }, - "hardware": { - "smartmodule_version": "4.0.0.0", - "bluetooth_version": "1.2.3" - }, - "software": { - "firmware_version": "2.1.0" + "versions": { + "sw_sm": "4.1.0.0", + "hw_sm": "1.0.0.0", + "sw_ma": "1.0.0", + "hw_ma": "1.0.0", + "sw_to": "1.0.0", + "hw_to": "1.0.0", + "sw_st": "1.0.0", + "hw_st": "1.0.0", + "sw_cm": "1.0.0" } } diff --git a/tests/components/nrgkick/snapshots/test_diagnostics.ambr b/tests/components/nrgkick/snapshots/test_diagnostics.ambr index a27ec1ba83fa..46f5b8ffc483 100644 --- a/tests/components/nrgkick/snapshots/test_diagnostics.ambr +++ b/tests/components/nrgkick/snapshots/test_diagnostics.ambr @@ -10,6 +10,8 @@ }), 'info': dict({ 'cellular': dict({ + 'imei': '**REDACTED**', + 'imsi': '**REDACTED**', 'mode': 3, 'operator': 'Test operator', 'rssi': -85, @@ -17,15 +19,14 @@ 'connector': dict({ 'max_current': 32.0, 'phase_count': 3, - 'serial_number': 'CONN123', + 'serial': '**REDACTED**', 'type': 3, }), 'general': dict({ 'device_name': 'NRGkick Test', - 'json_api_version': 'v1', 'model_type': 'NRGkick Gen2 SIM', 'rated_current': 32.0, - 'serial_number': 'TEST123456', + 'serial_number': '**REDACTED**', }), 'gps': dict({ 'accuracy': 1.5, @@ -38,18 +39,22 @@ 'phases': 7, 'voltage': 230, }), - 'hardware': dict({ - 'bluetooth_version': '1.2.3', - 'smartmodule_version': '4.0.0.0', - }), 'network': dict({ - 'ip_address': '192.168.1.100', - 'mac_address': 'AA:BB:CC:DD:EE:FF', - 'wifi_rssi': -45, - 'wifi_ssid': 'TestNetwork', + 'ip_address': '**REDACTED**', + 'mac_address': '**REDACTED**', + 'rssi': -45, + 'ssid': '**REDACTED**', }), - 'software': dict({ - 'firmware_version': '2.1.0', + 'versions': dict({ + 'hw_ma': '1.0.0', + 'hw_sm': '1.0.0.0', + 'hw_st': '1.0.0', + 'hw_to': '1.0.0', + 'sw_cm': '1.0.0', + 'sw_ma': '1.0.0', + 'sw_sm': '4.1.0.0', + 'sw_st': '1.0.0', + 'sw_to': '1.0.0', }), }), 'values': dict({ @@ -116,7 +121,7 @@ }), }), 'entry_data': dict({ - 'host': '192.168.1.100', + 'host': '**REDACTED**', 'password': '**REDACTED**', 'username': '**REDACTED**', }), diff --git a/tests/components/nrgkick/snapshots/test_init.ambr b/tests/components/nrgkick/snapshots/test_init.ambr index 4723836a404f..712ced0dea70 100644 --- a/tests/components/nrgkick/snapshots/test_init.ambr +++ b/tests/components/nrgkick/snapshots/test_init.ambr @@ -13,7 +13,7 @@ }), 'disabled_by': None, 'entry_type': None, - 'hw_version': None, + 'hw_version': '1.0.0.0', 'id': , 'identifiers': set({ tuple( @@ -29,7 +29,7 @@ 'name': 'NRGkick Test', 'name_by_user': None, 'serial_number': 'TEST123456', - 'sw_version': None, + 'sw_version': '4.1.0.0', 'via_device_id': None, }) # --- diff --git a/tests/components/nrgkick/snapshots/test_sensor.ambr b/tests/components/nrgkick/snapshots/test_sensor.ambr index d51e2ad5d8f4..90fd924b8845 100644 --- a/tests/components/nrgkick/snapshots/test_sensor.ambr +++ b/tests/components/nrgkick/snapshots/test_sensor.ambr @@ -785,7 +785,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'unknown', + 'state': 'CONN123', }) # --- # name: test_sensor_entities[sensor.nrgkick_test_connector_type-entry] @@ -2649,7 +2649,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'unknown', + 'state': '-45', }) # --- # name: test_sensor_entities[sensor.nrgkick_test_ssid-entry] @@ -2699,7 +2699,7 @@ 'last_changed': , 'last_reported': , 'last_updated': , - 'state': 'unknown', + 'state': 'TestNetwork', }) # --- # name: test_sensor_entities[sensor.nrgkick_test_status-entry] From 55e2838210a01d546c78963e71cda29e677989fe Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Fri, 16 Oct 2026 11:41:05 +0200 Subject: [PATCH 316/356] Persist Ecovacs account credentials to avoid device verification (#186796) --- homeassistant/components/ecovacs/__init__.py | 2 +- .../components/ecovacs/config_flow.py | 6 ++ homeassistant/components/ecovacs/const.py | 1 + .../components/ecovacs/controller.py | 32 +++++++- .../components/ecovacs/diagnostics.py | 7 +- tests/components/ecovacs/conftest.py | 17 ++++- tests/components/ecovacs/const.py | 9 +++ .../ecovacs/snapshots/test_diagnostics.ambr | 2 + tests/components/ecovacs/test_config_flow.py | 42 ++++++++-- tests/components/ecovacs/test_diagnostics.py | 11 ++- tests/components/ecovacs/test_init.py | 76 ++++++++++++++++++- 11 files changed, 185 insertions(+), 20 deletions(-) diff --git a/homeassistant/components/ecovacs/__init__.py b/homeassistant/components/ecovacs/__init__.py index 2b8e8f7c78dd..caa159279d21 100644 --- a/homeassistant/components/ecovacs/__init__.py +++ b/homeassistant/components/ecovacs/__init__.py @@ -38,7 +38,7 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: EcovacsConfigEntry) -> bool: """Set up this integration using UI.""" - controller = EcovacsController(hass, entry.data) + controller = EcovacsController(hass, entry) entry.async_on_unload(controller.teardown) diff --git a/homeassistant/components/ecovacs/config_flow.py b/homeassistant/components/ecovacs/config_flow.py index 0dd997f60a37..2210960f2d75 100644 --- a/homeassistant/components/ecovacs/config_flow.py +++ b/homeassistant/components/ecovacs/config_flow.py @@ -1,6 +1,7 @@ """Config flow for Ecovacs mqtt integration.""" from collections.abc import Mapping +from dataclasses import asdict from functools import partial import logging import ssl @@ -34,6 +35,7 @@ from homeassistant.helpers.typing import VolDictType from homeassistant.util.ssl import get_default_no_verify_context from .const import ( + CONF_ACCOUNT_CREDENTIALS, CONF_OVERRIDE_MQTT_URL, CONF_OVERRIDE_REST_URL, CONF_VERIFICATION_CODE, @@ -206,6 +208,10 @@ class EcovacsConfigFlow(ConfigFlow, domain=DOMAIN): def _finish_flow(self) -> ConfigFlowResult: """Create or update the config entry.""" self._input[CONF_DEVICE_ID] = self._device_id + if self._authenticator is not None and ( + account := self._authenticator.account_credentials + ): + self._input[CONF_ACCOUNT_CREDENTIALS] = asdict(account) if self.source == SOURCE_REAUTH: return self.async_update_reload_and_abort( self._get_reauth_entry(), data_updates=self._input diff --git a/homeassistant/components/ecovacs/const.py b/homeassistant/components/ecovacs/const.py index 685ff9533c64..b365e34c5a13 100644 --- a/homeassistant/components/ecovacs/const.py +++ b/homeassistant/components/ecovacs/const.py @@ -7,6 +7,7 @@ from deebot_client.events import LifeSpan DOMAIN = "ecovacs" +CONF_ACCOUNT_CREDENTIALS = "account_credentials" CONF_CONTINENT = "continent" CONF_OVERRIDE_REST_URL = "override_rest_url" CONF_OVERRIDE_MQTT_URL = "override_mqtt_url" diff --git a/homeassistant/components/ecovacs/controller.py b/homeassistant/components/ecovacs/controller.py index 2bd4389c5081..0b8be365a427 100644 --- a/homeassistant/components/ecovacs/controller.py +++ b/homeassistant/components/ecovacs/controller.py @@ -1,11 +1,10 @@ """Controller module.""" import asyncio -from collections.abc import Mapping +from dataclasses import asdict from functools import partial import logging import ssl -from typing import Any from deebot_client.api_client import ApiClient from deebot_client.authentication import Authenticator, create_rest_config @@ -16,11 +15,13 @@ from deebot_client.exceptions import ( DeviceVerificationRequiredError, InvalidAuthenticationError, ) +from deebot_client.models import AccountCredentials from deebot_client.mqtt_client import MqttClient, create_mqtt_config from deebot_client.util import md5 from deebot_client.util.continents import get_continent from sucks import EcoVacsAPI, VacBot +from homeassistant.config_entries import ConfigEntry from homeassistant.const import ( CONF_COUNTRY, CONF_DEVICE_ID, @@ -33,6 +34,7 @@ from homeassistant.helpers import aiohttp_client from homeassistant.util.ssl import get_default_no_verify_context from .const import ( + CONF_ACCOUNT_CREDENTIALS, CONF_OVERRIDE_MQTT_URL, CONF_OVERRIDE_REST_URL, CONF_VERIFY_MQTT_CERTIFICATE, @@ -44,9 +46,11 @@ _LOGGER = logging.getLogger(__name__) class EcovacsController: """Ecovacs controller.""" - def __init__(self, hass: HomeAssistant, config: Mapping[str, Any]) -> None: + def __init__(self, hass: HomeAssistant, entry: ConfigEntry) -> None: """Initialize controller.""" self._hass = hass + self._entry = entry + config = entry.data self._devices: list[Device] = [] self._legacy_devices: list[VacBot] = [] rest_url = config.get(CONF_OVERRIDE_REST_URL) @@ -63,6 +67,18 @@ class EcovacsController: ), config[CONF_USERNAME], md5(config[CONF_PASSWORD]), + # Renewing with the stored account credentials avoids the password + # login, which keeps asking some accounts for device verification + account_credentials=( + AccountCredentials(**account) + if (account := config.get(CONF_ACCOUNT_CREDENTIALS)) + else None + ), + ) + self._unsubscribe_account_credentials = ( + self._authenticator.subscribe_account_credentials( + self._async_store_account_credentials + ) ) self._api_client = ApiClient(self._authenticator) @@ -133,8 +149,18 @@ class EcovacsController: _LOGGER.debug("Controller initialize complete") + async def _async_store_account_credentials( + self, account: AccountCredentials + ) -> None: + """Store new account credentials in the config entry.""" + self._hass.config_entries.async_update_entry( + self._entry, + data={**self._entry.data, CONF_ACCOUNT_CREDENTIALS: asdict(account)}, + ) + async def teardown(self) -> None: """Disconnect controller.""" + self._unsubscribe_account_credentials() for device in self._devices: await device.teardown() for legacy_device in self._legacy_devices: diff --git a/homeassistant/components/ecovacs/diagnostics.py b/homeassistant/components/ecovacs/diagnostics.py index 6a8a3716c55d..2aefb131192d 100644 --- a/homeassistant/components/ecovacs/diagnostics.py +++ b/homeassistant/components/ecovacs/diagnostics.py @@ -7,9 +7,14 @@ from homeassistant.const import CONF_NAME, CONF_PASSWORD, CONF_USERNAME from homeassistant.core import HomeAssistant from . import EcovacsConfigEntry -from .const import CONF_OVERRIDE_MQTT_URL, CONF_OVERRIDE_REST_URL +from .const import ( + CONF_ACCOUNT_CREDENTIALS, + CONF_OVERRIDE_MQTT_URL, + CONF_OVERRIDE_REST_URL, +) REDACT_CONFIG = { + CONF_ACCOUNT_CREDENTIALS, CONF_USERNAME, CONF_PASSWORD, "title", diff --git a/tests/components/ecovacs/conftest.py b/tests/components/ecovacs/conftest.py index ed80fd78f28d..2128eccb5eb4 100644 --- a/tests/components/ecovacs/conftest.py +++ b/tests/components/ecovacs/conftest.py @@ -9,7 +9,7 @@ from deebot_client import const from deebot_client.command import DeviceCommandResult from deebot_client.device import Device from deebot_client.exceptions import ApiError -from deebot_client.models import Credentials +from deebot_client.models import AccountCredentials, Credentials import pytest from sucks import EventEmitter @@ -67,8 +67,8 @@ def device_fixture() -> str: @pytest.fixture -def mock_authenticator(device_fixture: str) -> Generator[Mock]: - """Mock the authenticator.""" +def mock_authenticator_class(device_fixture: str) -> Generator[Mock]: + """Mock the authenticator class.""" with ( patch( "homeassistant.components.ecovacs.controller.Authenticator", @@ -81,6 +81,9 @@ def mock_authenticator(device_fixture: str) -> Generator[Mock]: ): authenticator = mock.return_value authenticator.authenticate.return_value = Credentials("token", "user_id", 0) + authenticator.account_credentials = AccountCredentials( + "account_token", "account_user_id" + ) devices = [ load_json_object_fixture(f"devices/{device_fixture}/device.json", DOMAIN) @@ -102,7 +105,13 @@ def mock_authenticator(device_fixture: str) -> Generator[Mock]: raise ApiError("Path not mocked: {path}") authenticator.post_authenticated.side_effect = post_authenticated - yield authenticator + yield mock + + +@pytest.fixture +def mock_authenticator(mock_authenticator_class: Mock) -> Mock: + """Mock the authenticator.""" + return mock_authenticator_class.return_value @pytest.fixture diff --git a/tests/components/ecovacs/const.py b/tests/components/ecovacs/const.py index 51bfd6bdb5d3..ba75d1f4387e 100644 --- a/tests/components/ecovacs/const.py +++ b/tests/components/ecovacs/const.py @@ -1,6 +1,7 @@ """Test ecovacs constants.""" from homeassistant.components.ecovacs.const import ( + CONF_ACCOUNT_CREDENTIALS, CONF_CONTINENT, CONF_OVERRIDE_MQTT_URL, CONF_OVERRIDE_REST_URL, @@ -40,3 +41,11 @@ STORED_ENTRY_DATA_CLOUD = VALID_ENTRY_DATA_CLOUD | {CONF_DEVICE_ID: CLOUD_DEVICE STORED_ENTRY_DATA_SELF_HOSTED = VALID_ENTRY_DATA_SELF_HOSTED | { CONF_DEVICE_ID: SELF_HOSTED_DEVICE_ID } + +# The account credentials of the mocked authenticator, as stored in the entry +ACCOUNT_CREDENTIALS_DATA = { + CONF_ACCOUNT_CREDENTIALS: { + "access_token": "account_token", + "user_id": "account_user_id", + } +} diff --git a/tests/components/ecovacs/snapshots/test_diagnostics.ambr b/tests/components/ecovacs/snapshots/test_diagnostics.ambr index 2736ea80fce7..eddac17401bc 100644 --- a/tests/components/ecovacs/snapshots/test_diagnostics.ambr +++ b/tests/components/ecovacs/snapshots/test_diagnostics.ambr @@ -3,6 +3,7 @@ dict({ 'config': dict({ 'data': dict({ + 'account_credentials': '**REDACTED**', 'country': 'IT', 'device_id': 'AAAAAAAA', 'password': '**REDACTED**', @@ -57,6 +58,7 @@ dict({ 'config': dict({ 'data': dict({ + 'account_credentials': '**REDACTED**', 'country': 'IT', 'device_id': 'HA-test_home', 'override_mqtt_url': '**REDACTED**', diff --git a/tests/components/ecovacs/test_config_flow.py b/tests/components/ecovacs/test_config_flow.py index f465f9cedb35..f80d07ce973a 100644 --- a/tests/components/ecovacs/test_config_flow.py +++ b/tests/components/ecovacs/test_config_flow.py @@ -31,6 +31,7 @@ from homeassistant.core import HomeAssistant from homeassistant.data_entry_flow import FlowResultType from .const import ( + ACCOUNT_CREDENTIALS_DATA, CLOUD_DEVICE_ID, SELF_HOSTED_DEVICE_ID, STORED_ENTRY_DATA_CLOUD, @@ -122,12 +123,26 @@ async def test_user_flow( result = await _test_user_flow(hass, test_fn_user_input) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == entry_data[CONF_USERNAME] - assert result["data"] == entry_data + assert result["data"] == entry_data | ACCOUNT_CREDENTIALS_DATA mock_setup_entry.assert_called() mock_authenticator_authenticate.assert_called() mock_mqtt_client.verify_config.assert_called() +@pytest.mark.usefixtures("mock_device_id", "mock_setup_entry", "mock_mqtt_client") +async def test_user_flow_without_account_credentials( + hass: HomeAssistant, + mock_authenticator: Mock, +) -> None: + """Test no account credentials are stored when the login returned none.""" + mock_authenticator.account_credentials = None + + result = await _test_user_flow(hass, _TestFnUserInput(VALID_ENTRY_DATA_CLOUD)) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["data"] == STORED_ENTRY_DATA_CLOUD + + def _cannot_connect_error(user_input: dict[str, Any]) -> dict[str, str]: field = "base" if CONF_OVERRIDE_MQTT_URL in user_input: @@ -219,7 +234,7 @@ async def test_user_flow_raise_error( ) assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == entry_data[CONF_USERNAME] - assert result["data"] == entry_data + assert result["data"] == entry_data | ACCOUNT_CREDENTIALS_DATA mock_setup_entry.assert_called() mock_authenticator_authenticate.assert_called() mock_mqtt_client.verify_config.assert_called() @@ -276,7 +291,10 @@ async def test_user_flow_self_hosted_error( assert result["type"] is FlowResultType.CREATE_ENTRY assert result["title"] == data[CONF_USERNAME] - assert result["data"] == data | {CONF_DEVICE_ID: SELF_HOSTED_DEVICE_ID} + assert ( + result["data"] + == data | {CONF_DEVICE_ID: SELF_HOSTED_DEVICE_ID} | ACCOUNT_CREDENTIALS_DATA + ) mock_setup_entry.assert_called() mock_authenticator_authenticate.assert_called() mock_mqtt_client.verify_config.assert_called() @@ -345,7 +363,7 @@ async def test_device_verification( await hass.async_block_till_done() assert result["type"] is FlowResultType.CREATE_ENTRY - assert result["data"] == entry_data + assert result["data"] == entry_data | ACCOUNT_CREDENTIALS_DATA mock_authenticator.verify_device.assert_awaited_once_with("123456") mock_authenticator.teardown.assert_awaited_once() mock_mqtt_client.verify_config.assert_called_once() @@ -457,7 +475,12 @@ async def test_mqtt_retry_after_device_verification( assert mock_create_rest_config.call_args_list[1].kwargs["device_id"] == device_id assert result["type"] is FlowResultType.CREATE_ENTRY - assert result["data"] == VALID_ENTRY_DATA_CLOUD | {CONF_DEVICE_ID: device_id} + assert ( + result["data"] + == VALID_ENTRY_DATA_CLOUD + | {CONF_DEVICE_ID: device_id} + | ACCOUNT_CREDENTIALS_DATA + ) mock_authenticator.request_device_verification_code.assert_awaited_once() mock_authenticator.verify_device.assert_awaited_once_with("123456") # The superseded authenticator and the one of the created entry are torn down @@ -483,9 +506,12 @@ async def test_reauth( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reauth_successful" # The already verified device ID is kept, so no new verification is required - assert mock_config_entry.data == STORED_ENTRY_DATA_CLOUD | { - CONF_PASSWORD: "new-password" - } + assert ( + mock_config_entry.data + == STORED_ENTRY_DATA_CLOUD + | {CONF_PASSWORD: "new-password"} + | ACCOUNT_CREDENTIALS_DATA + ) mock_authenticator.request_device_verification_code.assert_not_called() mock_authenticator.verify_device.assert_not_called() mock_setup_entry.assert_called_once() diff --git a/tests/components/ecovacs/test_diagnostics.py b/tests/components/ecovacs/test_diagnostics.py index beac891d9086..5ac14a647f3a 100644 --- a/tests/components/ecovacs/test_diagnostics.py +++ b/tests/components/ecovacs/test_diagnostics.py @@ -7,7 +7,11 @@ from syrupy.filters import props from homeassistant.const import CONF_USERNAME from homeassistant.core import HomeAssistant -from .const import STORED_ENTRY_DATA_CLOUD, STORED_ENTRY_DATA_SELF_HOSTED +from .const import ( + ACCOUNT_CREDENTIALS_DATA, + STORED_ENTRY_DATA_CLOUD, + STORED_ENTRY_DATA_SELF_HOSTED, +) from tests.common import MockConfigEntry from tests.components.diagnostics import get_diagnostics_for_config_entry @@ -16,7 +20,10 @@ from tests.typing import ClientSessionGenerator @pytest.mark.parametrize( "mock_config_entry_data", - [STORED_ENTRY_DATA_CLOUD, STORED_ENTRY_DATA_SELF_HOSTED], + [ + STORED_ENTRY_DATA_CLOUD | ACCOUNT_CREDENTIALS_DATA, + STORED_ENTRY_DATA_SELF_HOSTED | ACCOUNT_CREDENTIALS_DATA, + ], ids=lambda data: data[CONF_USERNAME], ) async def test_diagnostics( diff --git a/tests/components/ecovacs/test_init.py b/tests/components/ecovacs/test_init.py index 38ac8d3ec387..49064f9079a9 100644 --- a/tests/components/ecovacs/test_init.py +++ b/tests/components/ecovacs/test_init.py @@ -7,10 +7,11 @@ from deebot_client.exceptions import ( DeviceVerificationRequiredError, InvalidAuthenticationError, ) +from deebot_client.models import AccountCredentials import pytest from syrupy.assertion import SnapshotAssertion -from homeassistant.components.ecovacs.const import DOMAIN +from homeassistant.components.ecovacs.const import CONF_ACCOUNT_CREDENTIALS, DOMAIN from homeassistant.components.ecovacs.controller import EcovacsController from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState from homeassistant.const import CONF_DEVICE_ID @@ -18,8 +19,10 @@ from homeassistant.core import HomeAssistant from homeassistant.helpers import device_registry as dr from .const import ( + ACCOUNT_CREDENTIALS_DATA, CLOUD_DEVICE_ID, SELF_HOSTED_DEVICE_ID, + STORED_ENTRY_DATA_CLOUD, VALID_ENTRY_DATA_CLOUD, VALID_ENTRY_DATA_SELF_HOSTED, ) @@ -152,6 +155,77 @@ async def test_migrate_entry_keeps_device_id( assert entry.data == entry_data +@pytest.mark.parametrize( + ("mock_config_entry_data", "account_credentials"), + [ + pytest.param(STORED_ENTRY_DATA_CLOUD, None, id="not_stored"), + pytest.param( + STORED_ENTRY_DATA_CLOUD | ACCOUNT_CREDENTIALS_DATA, + AccountCredentials("account_token", "account_user_id"), + id="stored", + ), + ], +) +@pytest.mark.usefixtures("mock_mqtt_client") +async def test_stored_account_credentials_seed_authenticator( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_authenticator_class: Mock, + account_credentials: AccountCredentials | None, +) -> None: + """Test the authenticator starts from the stored account credentials.""" + mock_config_entry.add_to_hass(hass) + + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert ( + mock_authenticator_class.call_args.kwargs["account_credentials"] + == account_credentials + ) + + +@pytest.mark.usefixtures("mock_mqtt_client") +async def test_new_account_credentials_are_stored( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_authenticator: Mock, +) -> None: + """Test new account credentials of the authenticator are stored in the entry.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + store_account_credentials = ( + mock_authenticator.subscribe_account_credentials.call_args.args[0] + ) + await store_account_credentials(AccountCredentials("new_token", "new_user_id")) + + assert mock_config_entry.data == STORED_ENTRY_DATA_CLOUD | { + CONF_ACCOUNT_CREDENTIALS: { + "access_token": "new_token", + "user_id": "new_user_id", + } + } + + +@pytest.mark.usefixtures("mock_mqtt_client") +async def test_unload_unsubscribes_account_credentials( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_authenticator: Mock, +) -> None: + """Test unloading stops storing new account credentials.""" + mock_config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + await hass.config_entries.async_unload(mock_config_entry.entry_id) + await hass.async_block_till_done() + + mock_authenticator.subscribe_account_credentials.return_value.assert_called_once() + + async def test_devices_in_dr( device_registry: dr.DeviceRegistry, controller: EcovacsController, From f02bca760817dbf71839669849d7b739e1646260 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Fri, 16 Oct 2026 17:56:49 +0200 Subject: [PATCH 317/356] Update frontend to 20260930.4 (#186813) --- homeassistant/components/frontend/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- pylint/plugins/pylint_home_assistant/generated/mdi_icons.py | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 75c866a736ac..873ade3dd9cd 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -22,5 +22,5 @@ "integration_type": "system", "preview_features": { "winter_mode": {} }, "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20260930.3"] + "requirements": ["home-assistant-frontend==20260930.4"] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index 0569518bb75c..e710f89ce907 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -40,7 +40,7 @@ habluetooth==7.1.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-frontend==20260930.3 +home-assistant-frontend==20260930.4 home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 diff --git a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py index a78564d99a7e..387e1de7f35e 100644 --- a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py +++ b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py @@ -5,7 +5,7 @@ To update, run python3 -m script.hassfest from typing import Final -FRONTEND_VERSION: Final[str] = "20260930.3" +FRONTEND_VERSION: Final[str] = "20260930.4" MDI_ICONS: Final[set[str]] = { "ab-testing", diff --git a/requirements_all.txt b/requirements_all.txt index fc24b24ce6f7..a992b46a3a45 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1315,7 +1315,7 @@ hole==0.9.2 holidays==0.106 # homeassistant.components.frontend -home-assistant-frontend==20260930.3 +home-assistant-frontend==20260930.4 # homeassistant.components.conversation home-assistant-intents==2026.10.6 From 84a8df22f93fdeeba0238a5a3410e839f3bf815f Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Fri, 16 Oct 2026 18:44:06 +0200 Subject: [PATCH 318/356] Fix Fritz setup failing when UPnP info lacks NewEnable key (#186896) --- homeassistant/components/fritz/__init__.py | 7 +++---- tests/components/fritz/test_init.py | 10 +++++++++- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/homeassistant/components/fritz/__init__.py b/homeassistant/components/fritz/__init__.py index f7819a1c02c7..2974b1fe048e 100644 --- a/homeassistant/components/fritz/__init__.py +++ b/homeassistant/components/fritz/__init__.py @@ -64,10 +64,9 @@ async def async_setup_entry(hass: HomeAssistant, entry: FritzConfigEntry) -> boo translation_placeholders={"error": str(ex)}, ) from ex - if ( - "X_AVM-DE_UPnP1" in avm_wrapper.connection.services - and not (await avm_wrapper.async_get_upnp_configuration())["NewEnable"] - ): + if "X_AVM-DE_UPnP1" in avm_wrapper.connection.services and not ( + await avm_wrapper.async_get_upnp_configuration() + ).get("NewEnable"): raise ConfigEntryNotReady( translation_domain=DOMAIN, translation_key="error_upnp_disabled", diff --git a/tests/components/fritz/test_init.py b/tests/components/fritz/test_init.py index ac008417ca19..561f838d6ce6 100644 --- a/tests/components/fritz/test_init.py +++ b/tests/components/fritz/test_init.py @@ -138,11 +138,19 @@ async def test_setup_fail_parse_error(hass: HomeAssistant, fc_class_mock) -> Non assert entry.error_reason_translation_key == "error_parse_device_info" +@pytest.mark.parametrize( + "upnp_config", + [ + pytest.param({"NewEnable": False}, id="disabled"), + pytest.param({}, id="missing_key"), + ], +) async def test_upnp_missing( hass: HomeAssistant, fc_class_mock, fh_class_mock, fs_class_mock, + upnp_config: dict[str, bool], ) -> None: """Test UPNP configuration is missing.""" @@ -152,7 +160,7 @@ async def test_upnp_missing( with ( patch( "homeassistant.components.fritz.coordinator.AvmWrapper.async_get_upnp_configuration", - return_value={"NewEnable": False}, + return_value=upnp_config, ), ): await hass.config_entries.async_setup(entry.entry_id) From 85524d0785f34fe2ed3bfcee9262c81b5106936d Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 16 Oct 2026 18:28:27 +0000 Subject: [PATCH 319/356] Bump version to 2026.10.2 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index 15550e2590fe..e65cc0f31e60 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "1" +PATCH_VERSION: Final = "2" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 6bde6016a742..cf1ee4ef4f6c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.1" +version = "2026.10.2" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From a00996dbbb2285d9a67cc03122aabb137b6398ab Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 16 Oct 2026 18:51:43 +0000 Subject: [PATCH 320/356] Fix CI for Fritz --- tests/components/fritz/test_config_flow.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/components/fritz/test_config_flow.py b/tests/components/fritz/test_config_flow.py index 4b2a62839f1a..87e5a78a1ac7 100644 --- a/tests/components/fritz/test_config_flow.py +++ b/tests/components/fritz/test_config_flow.py @@ -2,7 +2,7 @@ from copy import deepcopy import dataclasses -from unittest.mock import patch +from unittest.mock import MagicMock, patch from fritzconnection.core.exceptions import ( FritzAuthorizationError, From e424569e978b82b5269fa3cf1d2d3d7325fc3559 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Sun, 11 Oct 2026 15:23:02 +0200 Subject: [PATCH 321/356] Bump aiomelcloudhome to 0.3.0 (#185769) --- .../components/melcloud_home/climate.py | 3 +++ .../components/melcloud_home/manifest.json | 2 +- .../components/melcloud_home/sensor.py | 3 +++ requirements_all.txt | 2 +- .../melcloud_home/fixtures/context.json | 5 ++--- .../snapshots/test_diagnostics.ambr | 17 ++++++++++++++++- tests/components/melcloud_home/test_climate.py | 5 +++++ tests/components/melcloud_home/test_sensor.py | 5 ++++- tests/components/melcloud_home/test_switch.py | 2 +- 9 files changed, 36 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/melcloud_home/climate.py b/homeassistant/components/melcloud_home/climate.py index c7e18b1086be..8b747d48c31d 100644 --- a/homeassistant/components/melcloud_home/climate.py +++ b/homeassistant/components/melcloud_home/climate.py @@ -100,7 +100,10 @@ ATW_OPERATION_TO_HVAC_ACTION: dict[ATWOperationMode, HVACAction] = { ATWOperationMode.HOT_WATER: HVACAction.IDLE, ATWOperationMode.HEAT: HVACAction.HEATING, ATWOperationMode.HEAT_ZONES: HVACAction.HEATING, + ATWOperationMode.HEATING: HVACAction.HEATING, + ATWOperationMode.FREEZE_STAT: HVACAction.HEATING, ATWOperationMode.COOL: HVACAction.COOLING, + ATWOperationMode.COOLING: HVACAction.COOLING, } diff --git a/homeassistant/components/melcloud_home/manifest.json b/homeassistant/components/melcloud_home/manifest.json index 5a401f391914..3b2d69f433f7 100644 --- a/homeassistant/components/melcloud_home/manifest.json +++ b/homeassistant/components/melcloud_home/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aiomelcloudhome"], "quality_scale": "silver", - "requirements": ["aiomelcloudhome==0.2.4"] + "requirements": ["aiomelcloudhome==0.3.0"] } diff --git a/homeassistant/components/melcloud_home/sensor.py b/homeassistant/components/melcloud_home/sensor.py index 48122626b5ac..5a8b201dea04 100644 --- a/homeassistant/components/melcloud_home/sensor.py +++ b/homeassistant/components/melcloud_home/sensor.py @@ -49,7 +49,10 @@ ATW_OPERATION_STATUS: dict[ATWOperationMode, str] = { ATWOperationMode.HOT_WATER: "heating_water", ATWOperationMode.HEAT: "heating_zones", ATWOperationMode.HEAT_ZONES: "heating_zones", + ATWOperationMode.HEATING: "heating_zones", + ATWOperationMode.FREEZE_STAT: "heating_zones", ATWOperationMode.COOL: "cooling", + ATWOperationMode.COOLING: "cooling", } OUTDOOR_TEMPERATURE_DESCRIPTION = SensorEntityDescription( diff --git a/requirements_all.txt b/requirements_all.txt index a992b46a3a45..88760e45e949 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -345,7 +345,7 @@ aiolyric==2.1.2 aiomealie==2.1.2 # homeassistant.components.melcloud_home -aiomelcloudhome==0.2.4 +aiomelcloudhome==0.3.0 # homeassistant.components.modern_forms aiomodernforms==0.3.1 diff --git a/tests/components/melcloud_home/fixtures/context.json b/tests/components/melcloud_home/fixtures/context.json index 1bc4fc35f8f0..ac7158c704fe 100644 --- a/tests/components/melcloud_home/fixtures/context.json +++ b/tests/components/melcloud_home/fixtures/context.json @@ -23,7 +23,7 @@ "capabilities": { "isMultiSplitSystem": false, "isLegacyDevice": false, - "hasStandby": false, + "hasStandby": true, "hasCoolOperationMode": true, "hasHeatOperationMode": true, "hasAutoOperationMode": true, @@ -45,8 +45,7 @@ "supportsWideVane": false, "hasOutdoorTemperatureSensor": true, "hasVaneVertical": true, - "hasVaneHorizontal": true, - "hasStandbyMode": true + "hasVaneHorizontal": true }, "frostProtection": { "active": false, diff --git a/tests/components/melcloud_home/snapshots/test_diagnostics.ambr b/tests/components/melcloud_home/snapshots/test_diagnostics.ambr index 0bd21f6ad154..f93e88298268 100644 --- a/tests/components/melcloud_home/snapshots/test_diagnostics.ambr +++ b/tests/components/melcloud_home/snapshots/test_diagnostics.ambr @@ -30,16 +30,24 @@ dict({ 'actual_fan_speed': 'Off', 'capabilities': dict({ + 'has_air_direction': True, 'has_auto_operation_mode': True, + 'has_automatic_fan_speed': True, 'has_cool_operation_mode': True, + 'has_demand_side_control': False, 'has_dry_operation_mode': True, 'has_energy_consumed_meter': True, + 'has_extended_temperature_range': True, 'has_fan_operation_mode': None, 'has_half_degree_increments': True, + 'has_heat_operation_mode': True, 'has_outdoor_temperature_sensor': True, 'has_standby_mode': True, + 'has_swing': True, 'has_vane_horizontal': True, 'has_vane_vertical': True, + 'is_legacy_device': False, + 'is_multi_split_system': False, 'max_temp_auto': 31.0, 'max_temp_cool': 31.0, 'max_temp_heat': 31.0, @@ -47,6 +55,7 @@ 'min_temp_cool': 16.0, 'min_temp_heat': 10.0, 'number_of_fan_speeds': 5, + 'supports_wide_vane': False, }), 'frost_protection': dict({ 'active': False, @@ -139,8 +148,12 @@ 'capabilities': dict({ 'has_cooling_mode': True, 'has_energy_consumed_meter': True, + 'has_estimated_energy_consumption': None, + 'has_estimated_energy_production': None, 'has_half_degrees': False, 'has_hot_water': True, + 'has_measured_energy_consumption': None, + 'has_measured_energy_production': None, 'has_standby_mode': True, 'has_zone2': True, 'max_set_tank_temperature': 60.0, @@ -156,8 +169,10 @@ 'enabled': True, 'max': 8.0, 'min': 5.0, + 'zone1_active': False, + 'zone2_active': False, }), - 'has_zone2': False, + 'has_zone2': True, 'holiday_mode': None, 'id': '**REDACTED**', 'in_standby_mode': False, diff --git a/tests/components/melcloud_home/test_climate.py b/tests/components/melcloud_home/test_climate.py index c7130136600a..aa5944a2e60c 100644 --- a/tests/components/melcloud_home/test_climate.py +++ b/tests/components/melcloud_home/test_climate.py @@ -595,6 +595,11 @@ async def test_atw_zone_temperature_range( {"OperationMode": "HeatZones"}, HVACAction.HEATING, id="heat_zones" ), pytest.param({"OperationMode": "Cool"}, HVACAction.COOLING, id="cool"), + pytest.param({"OperationMode": "Heating"}, HVACAction.HEATING, id="heating"), + pytest.param( + {"OperationMode": "FreezeStat"}, HVACAction.HEATING, id="freeze_stat" + ), + pytest.param({"OperationMode": "Cooling"}, HVACAction.COOLING, id="cooling"), pytest.param({"OperationMode": "Unknown"}, None, id="unknown"), pytest.param( {"OperationMode": "Heat", "Power": "False"}, HVACAction.OFF, id="off" diff --git a/tests/components/melcloud_home/test_sensor.py b/tests/components/melcloud_home/test_sensor.py index 60320b8861fd..fd99fd45d62a 100644 --- a/tests/components/melcloud_home/test_sensor.py +++ b/tests/components/melcloud_home/test_sensor.py @@ -53,7 +53,10 @@ async def test_all_entities( pytest.param("HotWater", "heating_water", id="heating_water"), pytest.param("Heat", "heating_zones", id="heat"), pytest.param("HeatZones", "heating_zones", id="heating_zones"), - pytest.param("Cool", "cooling", id="cooling"), + pytest.param("Cool", "cooling", id="cool"), + pytest.param("Heating", "heating_zones", id="heating"), + pytest.param("FreezeStat", "heating_zones", id="freeze_stat"), + pytest.param("Cooling", "cooling", id="cooling"), pytest.param("Defrost", STATE_UNKNOWN, id="unsupported_mode"), ], ) diff --git a/tests/components/melcloud_home/test_switch.py b/tests/components/melcloud_home/test_switch.py index fd1010625112..1d9f4c80d142 100644 --- a/tests/components/melcloud_home/test_switch.py +++ b/tests/components/melcloud_home/test_switch.py @@ -172,7 +172,7 @@ async def test_no_standby_switch_without_support( """Test units without standby support get no standby switch.""" context = await async_load_json_object_fixture(hass, "context.json", DOMAIN) building = context["buildings"][0] - building["airToAirUnits"][0]["capabilities"]["hasStandbyMode"] = False + building["airToAirUnits"][0]["capabilities"]["hasStandby"] = False building["airToWaterUnits"][0]["capabilities"]["hasStandbyMode"] = False mock_melcloud_client.get_context.return_value = UserContext.model_validate(context) From 9be859ea950379b1cdd2d8cd26f6e77b6cd56034 Mon Sep 17 00:00:00 2001 From: Erwin Douna Date: Wed, 14 Oct 2026 22:06:17 +0200 Subject: [PATCH 322/356] Pin pypasser below 1.0.0 (#186527) --- homeassistant/package_constraints.txt | 3 +++ script/gen_requirements_all.py | 3 +++ 2 files changed, 6 insertions(+) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index e710f89ce907..f3eb4bbd7c86 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -268,6 +268,9 @@ graphql-core<3.3 # https://github.com/c-ares/c-ares/pull/1256 pycares==5.0.1 +# pypasser 1.0.0 removed reCaptchaV3, which Tami4EdgeAPI imports +pypasser<1.0.0 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained diff --git a/script/gen_requirements_all.py b/script/gen_requirements_all.py index b13af224d335..2c817fd29c5b 100755 --- a/script/gen_requirements_all.py +++ b/script/gen_requirements_all.py @@ -252,6 +252,9 @@ graphql-core<3.3 # https://github.com/c-ares/c-ares/pull/1256 pycares==5.0.1 +# pypasser 1.0.0 removed reCaptchaV3, which Tami4EdgeAPI imports +pypasser<1.0.0 + # Pin dependencies with '.pth' files to exact versions, only update manually! # https://github.com/Azure/azure-kusto-python/ -> '.pth' files removed with >=5.0.5 # https://github.com/xolox/python-coloredlogs -> unmaintained From f515d208857587e2d48e0deb4ea5d49d447ccab1 Mon Sep 17 00:00:00 2001 From: ezaekiel <130962901+ezaekiel@users.noreply.github.com> Date: Fri, 9 Oct 2026 08:52:28 +0200 Subject: [PATCH 323/356] Fix Proxmox VE update version detection (#184823) Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- homeassistant/components/proxmoxve/helpers.py | 27 +-- .../proxmoxve/snapshots/test_update.ambr | 194 +++++++++++++++++- tests/components/proxmoxve/test_update.py | 51 ++++- 3 files changed, 249 insertions(+), 23 deletions(-) diff --git a/homeassistant/components/proxmoxve/helpers.py b/homeassistant/components/proxmoxve/helpers.py index 50381243ebbd..9e2927d6d633 100644 --- a/homeassistant/components/proxmoxve/helpers.py +++ b/homeassistant/components/proxmoxve/helpers.py @@ -3,8 +3,6 @@ from dataclasses import dataclass from typing import Any -from packaging.version import parse as parse_version - from .const import ProxmoxPermission @@ -46,13 +44,6 @@ def is_proxmox_package(update: dict[str, Any]) -> bool: ) -def latest_version(versions: list[str]) -> str: - """Return the latest version from a list of version strings.""" - # Fix proxmox -pve1 style suffixes - safe_versions = [v.split("-")[0] for v in versions] - return max(safe_versions, key=parse_version) - - def update_version( current_version: str, updates: list[dict[str, Any]], @@ -61,14 +52,18 @@ def update_version( count = len(updates) pve_count = sum(is_proxmox_package(u) for u in updates) - other_count = len(updates) - pve_count - versions = [current_version] + [ - u["Version"] for u in updates if is_proxmox_package(u) - ] - - latest = latest_version(versions) if pve_count else current_version + other_count = count - pve_count + pve_manager_update = next( + (update for update in updates if update.get("Package") == "pve-manager"), + None, + ) + latest = ( + pve_manager_update["Version"].split("-")[0] + if pve_manager_update + else current_version + ) return ProxmoxUpdateInfo( - latest_version=latest if count else current_version, + latest_version=latest, latest_version_id=f"{latest}-p{pve_count}-d{other_count}" if count else current_version, diff --git a/tests/components/proxmoxve/snapshots/test_update.ambr b/tests/components/proxmoxve/snapshots/test_update.ambr index 169283b73a1b..96133b90953f 100644 --- a/tests/components/proxmoxve/snapshots/test_update.ambr +++ b/tests/components/proxmoxve/snapshots/test_update.ambr @@ -1,5 +1,5 @@ # serializer version: 1 -# name: test_all_entities[update.pve1_software_update-entry] +# name: test_all_entities[all-entities][update.pve1_software_update-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ None, @@ -36,7 +36,7 @@ 'unit_of_measurement': None, }) # --- -# name: test_all_entities[update.pve1_software_update-state] +# name: test_all_entities[all-entities][update.pve1_software_update-state] StateSnapshot({ 'attributes': ReadOnlyDict({ : False, @@ -45,8 +45,194 @@ : 'pve1 Software update', : False, : '9.1.6', - : '9.1.9-p4-d1', - : 'A total of 5 package update(s) are pending installation: of these 4 relate to Proxmox and 1 to other updates. Please visit the [Proxmox VE node](https://127.0.0.1:8006/#v1:0:=node/pve1) for details on the pending updates and to upgrade to 9.1.9.', + : '9.1.7-p4-d1', + : 'A total of 5 package update(s) are pending installation: of these 4 relate to Proxmox and 1 to other updates. Please visit the [Proxmox VE node](https://127.0.0.1:8006/#v1:0:=node/pve1) for details on the pending updates and to upgrade to 9.1.7.', + : None, + : None, + : , + : None, + : None, + }), + 'context': , + 'entity_id': 'update.pve1_software_update', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'on', + }) +# --- +# name: test_all_entities[debian-package-version-is-not-parsed][update.pve1_software_update-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'update', + 'entity_category': , + 'entity_id': 'update.pve1_software_update', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Software update', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Software update', + 'platform': 'proxmoxve', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'node_update', + 'unique_id': '1234_node/pve1_node_update', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[debian-package-version-is-not-parsed][update.pve1_software_update-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : False, + : 0, + : '/api/brands/integration/proxmoxve/icon.png', + : 'pve1 Software update', + : False, + : '9.1.6', + : '9.1.6-p1-d0', + : 'A total of 1 package update(s) are pending installation: of these 1 relate to Proxmox and 0 to other updates. Please visit the [Proxmox VE node](https://127.0.0.1:8006/#v1:0:=node/pve1) for details on the pending updates and to upgrade to 9.1.6.', + : None, + : None, + : , + : None, + : None, + }), + 'context': , + 'entity_id': 'update.pve1_software_update', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_all_entities[higher-ceph-version-is-not-pve-version][update.pve1_software_update-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'update', + 'entity_category': , + 'entity_id': 'update.pve1_software_update', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Software update', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Software update', + 'platform': 'proxmoxve', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'node_update', + 'unique_id': '1234_node/pve1_node_update', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[higher-ceph-version-is-not-pve-version][update.pve1_software_update-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : False, + : 0, + : '/api/brands/integration/proxmoxve/icon.png', + : 'pve1 Software update', + : False, + : '9.1.6', + : '9.1.6-p1-d0', + : 'A total of 1 package update(s) are pending installation: of these 1 relate to Proxmox and 0 to other updates. Please visit the [Proxmox VE node](https://127.0.0.1:8006/#v1:0:=node/pve1) for details on the pending updates and to upgrade to 9.1.6.', + : None, + : None, + : , + : None, + : None, + }), + 'context': , + 'entity_id': 'update.pve1_software_update', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'off', + }) +# --- +# name: test_all_entities[pve-manager-version-is-used][update.pve1_software_update-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'update', + 'entity_category': , + 'entity_id': 'update.pve1_software_update', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Software update', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Software update', + 'platform': 'proxmoxve', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': , + 'translation_key': 'node_update', + 'unique_id': '1234_node/pve1_node_update', + 'unit_of_measurement': None, + }) +# --- +# name: test_all_entities[pve-manager-version-is-used][update.pve1_software_update-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : False, + : 0, + : '/api/brands/integration/proxmoxve/icon.png', + : 'pve1 Software update', + : False, + : '9.1.6', + : '9.2.21-p2-d0', + : 'A total of 2 package update(s) are pending installation: of these 2 relate to Proxmox and 0 to other updates. Please visit the [Proxmox VE node](https://127.0.0.1:8006/#v1:0:=node/pve1) for details on the pending updates and to upgrade to 9.2.21.', : None, : None, : , diff --git a/tests/components/proxmoxve/test_update.py b/tests/components/proxmoxve/test_update.py index d15f2327ca3d..31fe33b45e6a 100644 --- a/tests/components/proxmoxve/test_update.py +++ b/tests/components/proxmoxve/test_update.py @@ -2,6 +2,7 @@ from unittest.mock import MagicMock, patch +import pytest from syrupy.assertion import SnapshotAssertion from homeassistant.const import STATE_OFF, STATE_UNAVAILABLE, Platform @@ -16,24 +17,68 @@ from tests.typing import WebSocketGenerator ENTITY_ID = "update.pve1_software_update" +@pytest.mark.parametrize( + ("updates", "expected_latest_version"), + [ + pytest.param( + [ + {"Package": "bind9-host", "Version": "1", "Origin": "Debian"}, + {"Package": "pve-manager", "Version": "9.1.7", "Origin": "Proxmox"}, + { + "Package": "libpve-common-perl", + "Version": "9.1.9", + "Origin": "Proxmox", + }, + {"Package": "corosync", "Version": "3.1.10", "Origin": "Proxmox"}, + {"Package": "pve-firmware", "Version": "3.18", "Origin": "Proxmox"}, + ], + "9.1.7-p4-d1", + id="all-entities", + ), + pytest.param( + [{"Package": "ceph-common", "Version": "19.2.6", "Origin": "Proxmox"}], + "9.1.6-p1-d0", + id="higher-ceph-version-is-not-pve-version", + ), + pytest.param( + [{"Package": "libpve-storage-perl", "Version": "1+16.1+2+pmx1"}], + "9.1.6-p1-d0", + id="debian-package-version-is-not-parsed", + ), + pytest.param( + [ + {"Package": "ceph-common", "Version": "19.2.6", "Origin": "Proxmox"}, + {"Package": "pve-manager", "Version": "9.2.21-1"}, + ], + "9.2.21-p2-d0", + id="pve-manager-version-is-used", + ), + ], +) async def test_all_entities( hass: HomeAssistant, snapshot: SnapshotAssertion, mock_proxmox_client: MagicMock, mock_config_entry: MockConfigEntry, entity_registry: er.EntityRegistry, + updates: list[dict[str, str]] | None, + expected_latest_version: str, ) -> None: """Test all entities.""" # Ensure Sys.Modify permissions to ensure update status can be determined mock_proxmox_client.access.permissions.get.return_value = MERGED_PERMISSIONS + mock_proxmox_client.nodes.return_value.apt.update.get.return_value = updates + with patch( "homeassistant.components.proxmoxve.PLATFORMS", [Platform.UPDATE], ): await setup_integration(hass, mock_config_entry) - await snapshot_platform( - hass, entity_registry, snapshot, mock_config_entry.entry_id - ) + + state = hass.states.get(ENTITY_ID) + assert state.attributes["latest_version"] == expected_latest_version + + await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id) async def test_update_entities_ignored( From 966fbaf10e02192d4477f85b7ab269f74420ebac Mon Sep 17 00:00:00 2001 From: Anis Kadri Date: Wed, 21 Oct 2026 06:29:21 -0700 Subject: [PATCH 324/356] Fix duplicate access events in UniFi Access integration (#185160) --- .../components/unifi_access/coordinator.py | 60 +++ .../components/unifi_access/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/unifi_access/test_event.py | 380 ++++++++++++++++++ 4 files changed, 442 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/unifi_access/coordinator.py b/homeassistant/components/unifi_access/coordinator.py index a17989b44871..188bc5f6e570 100644 --- a/homeassistant/components/unifi_access/coordinator.py +++ b/homeassistant/components/unifi_access/coordinator.py @@ -5,6 +5,7 @@ from collections.abc import Callable from dataclasses import dataclass, replace import logging import math +import time from typing import Any, cast, override import unicodedata @@ -53,7 +54,12 @@ from .const import ( _LOGGER = logging.getLogger(__name__) +# Expiry window for deduplicating access events, in seconds +_ACCESS_EVENT_DEDUP_WINDOW = 10.0 + type UnifiAccessConfigEntry = ConfigEntry[UnifiAccessCoordinator] +# (event object, event type, published, result, auth, actor, door) +type _AccessEventKey = tuple[str, str, int, str, str, str, str] @dataclass(frozen=True) @@ -101,6 +107,7 @@ class UnifiAccessCoordinator(DataUpdateCoordinator[UnifiAccessData]): self.client = client self._event_listeners: list[Callable[[DoorEvent], None]] = [] self._device_to_door: dict[str, str] = {} + self._recent_access_events: dict[_AccessEventKey, float] = {} @callback def async_subscribe_door_events( @@ -490,6 +497,39 @@ class UnifiAccessCoordinator(DataUpdateCoordinator[UnifiAccessData]): if update.data.unique_id and update.data.door and update.data.door.unique_id: self._device_to_door[update.data.unique_id] = update.data.door.unique_id + def _is_duplicate_access_event( + self, + event_object_id: str, + event_type: str, + published: int | None, + result: str, + auth_id: str, + actor: str, + door_id: str, + ) -> bool: + """Record an access event and return True when it was already dispatched. + + The controller can deliver the same door event twice — once as an + ``access.logs.insights.add`` and once as an ``access.logs.add`` + message. Only events that reach this point are recorded, so a copy + that could not be resolved to a door does not shadow its pair. + """ + published = published or 0 + if not published: + return False + now = time.monotonic() + self._recent_access_events = { + key: seen_at + for key, seen_at in self._recent_access_events.items() + if now - seen_at <= _ACCESS_EVENT_DEDUP_WINDOW + } + key = (event_object_id, event_type, published, result, auth_id, actor, door_id) + if key in self._recent_access_events: + _LOGGER.debug("Suppressing duplicate access event %s", key) + return True + self._recent_access_events[key] = now + return False + async def _handle_insights_add(self, msg: WebsocketMessage) -> None: """Handle access insights events (entry/exit).""" insights = cast(InsightsAdd, msg) @@ -510,6 +550,16 @@ class UnifiAccessCoordinator(DataUpdateCoordinator[UnifiAccessData]): attrs["direction"] = insights.data.metadata.direction for door in door_entries: if door.id: + if self._is_duplicate_access_event( + insights.event_object_id, + insights.data.event_type, + insights.data.published, + insights.data.result, + insights.data.metadata.authentication.id or "", + insights.data.metadata.actor.display_name, + door.id, + ): + continue self._dispatch_door_event(door.id, "access", event_type, attrs) async def _handle_logs_add(self, msg: WebsocketMessage) -> None: @@ -538,6 +588,16 @@ class UnifiAccessCoordinator(DataUpdateCoordinator[UnifiAccessData]): attrs["result"] = source.event.result if source.direction: attrs["direction"] = source.direction + if self._is_duplicate_access_event( + log.event_object_id, + source.event.type, + source.event.published, + source.event.result, + source.authentication.issuer or "", + source.actor.display_name, + door_id, + ): + return self._dispatch_door_event(door_id, "access", event_type, attrs) def get_lock_rule_status(self, door_id: str) -> DoorLockRuleStatus | None: diff --git a/homeassistant/components/unifi_access/manifest.json b/homeassistant/components/unifi_access/manifest.json index f02eb1a76885..6f9716c62a19 100644 --- a/homeassistant/components/unifi_access/manifest.json +++ b/homeassistant/components/unifi_access/manifest.json @@ -9,5 +9,5 @@ "iot_class": "local_push", "loggers": ["unifi_access_api"], "quality_scale": "platinum", - "requirements": ["py-unifi-access==1.6.1"] + "requirements": ["py-unifi-access==1.6.2"] } diff --git a/requirements_all.txt b/requirements_all.txt index 88760e45e949..3b77f2ed18d9 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2014,7 +2014,7 @@ py-sucks==0.9.11 py-synologydsm-api==2.10.3 # homeassistant.components.unifi_access -py-unifi-access==1.6.1 +py-unifi-access==1.6.2 # homeassistant.components.atome pyAtome==0.1.2 diff --git a/tests/components/unifi_access/test_event.py b/tests/components/unifi_access/test_event.py index 8854f08bfbc3..d00fcf260591 100644 --- a/tests/components/unifi_access/test_event.py +++ b/tests/components/unifi_access/test_event.py @@ -1261,3 +1261,383 @@ async def test_logs_add_direction( assert state.attributes["event_type"] == "access_granted" assert state.attributes["direction"] == "entry" assert state.state == "2025-01-01T00:00:00.000+00:00" + + +def _make_insights_add( + event_object_id: str = "hub-001", + result: str = "ACCESS", + actor: str = "John Doe", + auth_id: str = "auth-001", + published: int = 1700000000, +) -> InsightsAdd: + """Build an access.logs.insights.add message for the front door.""" + return InsightsAdd( + event="access.logs.insights.add", + event_object_id=event_object_id, + data=InsightsAddData.model_construct( + event_type="access.door.unlock", + result=result, + published=published, + metadata=InsightsMetadata( + door=[InsightsMetadataEntry(id="door-001", display_name="Front Door")], + actor=InsightsMetadataEntry(display_name=actor), + authentication=InsightsMetadataEntry(id=auth_id, display_name="FACE"), + ), + ), + ) + + +def _make_logs_add( + event_object_id: str = "hub-001", + result: str = "ACCESS", + actor: str = "John Doe", + auth_id: str | None = "auth-001", + published: int | None = 1700000000, + device_id: str = "hub-device-001", +) -> LogAdd: + """Build an access.logs.add message for the front door.""" + return LogAdd( + event="access.logs.add", + event_object_id=event_object_id, + data=LogAddData( + source=LogSource( + target=[ + LogTarget( + type="device_config", + id=device_id, + display_name="UA Hub Door", + ), + ], + actor=LogActor(display_name=actor), + event=LogEvent( + type="access.door.unlock", result=result, published=published + ), + authentication=LogAuthentication( + credential_provider="FACE", issuer=auth_id + ), + ), + ), + ) + + +@pytest.mark.parametrize( + ("first_event", "second_event"), + [ + pytest.param( + "access.logs.insights.add", + "access.logs.add", + id="insights-first", + ), + pytest.param( + "access.logs.add", + "access.logs.insights.add", + id="logs-first", + ), + ], +) +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_duplicate_access_event_dispatched_once( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, + first_event: str, + second_event: str, +) -> None: + """Test a door event sent as both insights.add and logs.add dispatches once.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + messages = { + "access.logs.insights.add": _make_insights_add(), + "access.logs.add": _make_logs_add(), + } + await handlers[first_event](messages[first_event]) + await handlers[second_event](messages[second_event]) + await hass.async_block_till_done() + + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.attributes["event_type"] == "access_granted" + # A single dispatch keeps the first trigger's timestamp; a suppressed + # duplicate would have advanced it by one millisecond. + assert state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.parametrize( + ("insights", "logs"), + [ + pytest.param( + _make_insights_add(published=1700000000), + _make_logs_add(published=1700000001), + id="different-published", + ), + pytest.param( + _make_insights_add(actor="John Doe"), + _make_logs_add(actor="Jane Doe"), + id="different-actor", + ), + pytest.param( + _make_insights_add(auth_id="auth-001"), + _make_logs_add(auth_id="auth-002"), + id="different-auth", + ), + pytest.param( + _make_insights_add(event_object_id="hub-001"), + _make_logs_add(event_object_id="hub-002"), + id="different-hub", + ), + ], +) +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_distinct_access_events_not_suppressed( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, + insights: InsightsAdd, + logs: LogAdd, +) -> None: + """Test access events differing in one key field are both dispatched.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + await handlers["access.logs.insights.add"](insights) + await handlers["access.logs.add"](logs) + await hass.async_block_till_done() + + # Both dispatches reach the entity, advancing its timestamp by one millisecond. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.001+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_same_second_different_doors_not_suppressed( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test two events for different doors in the same second are both dispatched.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + await handlers["access.data.v2.location.update"]( + V2LocationUpdate( + event="access.data.v2.location.update", + data=V2LocationUpdateData( + id="door-002", + location_type="door", + name="Back Door", + device_ids=["hub-device-002"], + ), + ) + ) + + await handlers["access.logs.add"](_make_logs_add()) + await handlers["access.logs.add"](_make_logs_add(device_id="hub-device-002")) + await hass.async_block_till_done() + + # Each door's event entity sees a single dispatch. + front_state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert front_state is not None + assert front_state.state == "2025-01-01T00:00:00.000+00:00" + back_state = hass.states.get(BACK_DOOR_ACCESS_ENTITY) + assert back_state is not None + assert back_state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_unusable_insights_copy_does_not_suppress_logs( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test an insights event without a door does not shadow its logs.add copy.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + doorless_insights = InsightsAdd( + event="access.logs.insights.add", + event_object_id="hub-001", + data=InsightsAddData.model_construct( + event_type="access.door.unlock", + result="ACCESS", + published=1700000000, + metadata=InsightsMetadata.model_construct( + actor=InsightsMetadataEntry(display_name="John Doe"), + authentication=InsightsMetadataEntry( + id="auth-001", display_name="FACE" + ), + ), + ), + ) + + await handlers["access.logs.insights.add"](doorless_insights) + await handlers["access.logs.add"](_make_logs_add()) + await hass.async_block_till_done() + + # Only the logs.add copy dispatches, so the entity sees one trigger. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_unusable_logs_copy_does_not_suppress_insights( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test a logs.add event without a resolvable door does not shadow insights.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + doorless_logs = LogAdd( + event="access.logs.add", + event_object_id="hub-001", + data=LogAddData( + source=LogSource( + target=[ + LogTarget(type="user", id="user-001", display_name="John Doe"), + ], + actor=LogActor(display_name="John Doe"), + event=LogEvent( + type="access.door.unlock", result="ACCESS", published=1700000000 + ), + authentication=LogAuthentication( + credential_provider="FACE", issuer="auth-001" + ), + ), + ), + ) + + await handlers["access.logs.add"](doorless_logs) + await handlers["access.logs.insights.add"](_make_insights_add()) + await hass.async_block_till_done() + + # Only the insights copy dispatches, so the entity sees one trigger. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_null_issuer_still_suppressed( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test a logs.add event without an issuer still matches its insights copy.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + issuerless_logs = LogAdd( + event="access.logs.add", + event_object_id="hub-001", + data=LogAddData( + source=LogSource( + target=[ + LogTarget( + type="device_config", + id="hub-device-001", + display_name="UA Hub Door", + ), + ], + actor=LogActor(display_name="John Doe"), + event=LogEvent( + type="access.door.unlock", result="ACCESS", published=1700000000 + ), + authentication=LogAuthentication(credential_provider="FACE"), + ), + ), + ) + + await handlers["access.logs.insights.add"](_make_insights_add(auth_id="")) + await handlers["access.logs.add"](issuerless_logs) + await hass.async_block_till_done() + + # The empty issuer matches the insights auth id, so only one trigger fires. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_none_insights_auth_id_still_suppressed( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test an insights event with a null auth id still matches its logs copy.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + null_auth_insights = InsightsAdd( + event="access.logs.insights.add", + event_object_id="hub-001", + data=InsightsAddData.model_construct( + event_type="access.door.unlock", + result="ACCESS", + published=1700000000, + metadata=InsightsMetadata.model_construct( + door=[InsightsMetadataEntry(id="door-001", display_name="Front Door")], + actor=InsightsMetadataEntry(display_name="John Doe"), + authentication=InsightsMetadataEntry.model_construct( + id=None, display_name="FACE" + ), + ), + ), + ) + + await handlers["access.logs.insights.add"](null_auth_insights) + await handlers["access.logs.add"](_make_logs_add(auth_id=None)) + await hass.async_block_till_done() + + # Both null auth values normalize to the same key, so only one trigger fires. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.000+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_missing_published_not_suppressed( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test events without a published timestamp are never suppressed.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + await handlers["access.logs.add"](_make_logs_add(published=None)) + await handlers["access.logs.add"](_make_logs_add(published=None)) + await hass.async_block_till_done() + + # Neither event is suppressed, so the entity sees two triggers. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.001+00:00" + + +@pytest.mark.freeze_time("2025-01-01 00:00:00+00:00") +async def test_access_event_redelivered_after_window( + hass: HomeAssistant, + init_integration: MockConfigEntry, + mock_client: MagicMock, +) -> None: + """Test an identical event is dispatched again once the dedup window has passed.""" + handlers = _get_ws_handlers(mock_client) + await _populate_device_mapping(handlers) + + # A negative window expires every recorded event immediately + with patch( + "homeassistant.components.unifi_access.coordinator._ACCESS_EVENT_DEDUP_WINDOW", + -1.0, + ): + for _ in range(2): + await handlers["access.logs.add"](_make_logs_add()) + await hass.async_block_till_done() + + # Both dispatches reach the entity, advancing its timestamp. + state = hass.states.get(FRONT_DOOR_ACCESS_ENTITY) + assert state is not None + assert state.state == "2025-01-01T00:00:00.001+00:00" From 11f9bfc0de979d3f8892ee15191aa470b5386065 Mon Sep 17 00:00:00 2001 From: rubempoli <66323535+rubempoli@users.noreply.github.com> Date: Mon, 19 Oct 2026 02:23:15 -0300 Subject: [PATCH 325/356] Handle missing Omada controller update fields (#185164) --- .../components/tplink_omada/update.py | 15 +- tests/components/tplink_omada/test_update.py | 203 ++++++++++++++++-- 2 files changed, 191 insertions(+), 27 deletions(-) diff --git a/homeassistant/components/tplink_omada/update.py b/homeassistant/components/tplink_omada/update.py index ebb085a4b2a2..10f3b7145d40 100644 --- a/homeassistant/components/tplink_omada/update.py +++ b/homeassistant/components/tplink_omada/update.py @@ -113,22 +113,19 @@ class OmadaControllerUpdate(OmadaControllerEntity, UpdateEntity): def _update_attrs(self) -> None: """Update installed and latest controller versions.""" update = self._update_data - if update is None: + if update is None or (active_update := update.update) is None: self._attr_installed_version = self.coordinator.data.current_version self._attr_latest_version = self._attr_installed_version self._attr_supported_features = UpdateEntityFeature(0) return - active_update = update.update self._attr_installed_version = ( - active_update.current_version - if update.hardware is not None and active_update is not None - else self.coordinator.data.current_version or update.current_version + active_update.current_version or self.coordinator.data.current_version + if update.hardware is not None + else self.coordinator.data.current_version or active_update.current_version ) self._attr_latest_version = ( - active_update.latest_version - if active_update is not None - else self._attr_installed_version + active_update.latest_version or self._attr_installed_version ) self._attr_supported_features = UpdateEntityFeature.RELEASE_NOTES if update.hardware is not None: @@ -169,7 +166,7 @@ class OmadaControllerUpdate(OmadaControllerEntity, UpdateEntity): ) target_version = version or update.latest_version - if target_version is None: + if not target_version: raise HomeAssistantError( translation_domain=DOMAIN, translation_key="firmware_update_rejected", diff --git a/tests/components/tplink_omada/test_update.py b/tests/components/tplink_omada/test_update.py index 8fc42fc97bdd..765a429dae3d 100644 --- a/tests/components/tplink_omada/test_update.py +++ b/tests/components/tplink_omada/test_update.py @@ -19,7 +19,6 @@ from homeassistant.components.update import ( ATTR_IN_PROGRESS, ATTR_INSTALLED_VERSION, ATTR_LATEST_VERSION, - DATA_COMPONENT, DOMAIN as UPDATE_DOMAIN, SERVICE_INSTALL, UpdateEntityFeature, @@ -149,11 +148,26 @@ async def test_install_firmware_success( assert await_args[0].mac == "54-AF-97-00-00-01" +@pytest.mark.parametrize( + ("version_data", "expected_installed_version", "latest_version"), + [ + pytest.param( + {"currentVersion": "1.0.0"}, "1.0.0", "1.0.1", id="version_present" + ), + pytest.param({}, "6.2.10.17", "6.3.0.110", id="version_missing"), + pytest.param( + {"currentVersion": None}, "6.2.10.17", "6.3.0.110", id="version_null" + ), + ], +) async def test_install_controller_firmware_success( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_omada_client: MagicMock, freezer: FrozenDateTimeFactory, + version_data: dict[str, str | None], + expected_installed_version: str, + latest_version: str, ) -> None: """Test successful controller firmware installation.""" entity_id = "update.oc200_test_omada_controller_firmware" @@ -161,8 +175,8 @@ async def test_install_controller_firmware_success( { "hardware": { "upgrade": True, - "currentVersion": "1.0.0", - "latestVersion": "1.0.1", + **version_data, + "latestVersion": latest_version, "fwReleaseLog": "Fixed things.", "releaseUrl": "https://example.com/firmware-release-notes", "downloadLink": "https://example.com/firmware.bin", @@ -178,8 +192,8 @@ async def test_install_controller_firmware_success( entity = hass.states.get(entity_id) assert entity is not None assert entity.state == STATE_ON - assert entity.attributes[ATTR_INSTALLED_VERSION] == "1.0.0" - assert entity.attributes[ATTR_LATEST_VERSION] == "1.0.1" + assert entity.attributes[ATTR_INSTALLED_VERSION] == expected_installed_version + assert entity.attributes[ATTR_LATEST_VERSION] == latest_version assert entity.attributes[ATTR_SUPPORTED_FEATURES] == ( UpdateEntityFeature.RELEASE_NOTES | UpdateEntityFeature.INSTALL ) @@ -197,7 +211,9 @@ async def test_install_controller_firmware_success( async_fire_time_changed(hass) await hass.async_block_till_done() - mock_omada_client.install_controller_firmware.assert_awaited_once_with("1.0.1") + mock_omada_client.install_controller_firmware.assert_awaited_once_with( + latest_version + ) mock_omada_client.check_firmware_updates.assert_awaited_once() @@ -222,10 +238,167 @@ async def test_controller_update_check_failure_does_not_block_setup( assert entity.state == STATE_UNAVAILABLE +@pytest.mark.parametrize("update_type", ["hardware", "software"]) +@pytest.mark.parametrize( + ("update_data", "expected_latest_version", "expected_state"), + [ + pytest.param( + {"upgrade": True, "latestVersion": "6.3.0.110"}, + "6.3.0.110", + STATE_ON, + id="update_available", + ), + pytest.param({"upgrade": False}, "6.2.10.17", STATE_OFF, id="no_update"), + pytest.param({}, "6.2.10.17", STATE_OFF, id="empty_update"), + pytest.param( + {"currentVersion": None, "latestVersion": "6.3.0.110"}, + "6.3.0.110", + STATE_ON, + id="null_current_version", + ), + pytest.param( + { + "currentVersion": None, + "latestVersion": None, + "upgrade": None, + "releaseLog": None, + "fwReleaseLog": None, + "downloadLink": None, + "releaseUrl": None, + }, + "6.2.10.17", + STATE_OFF, + id="null_fields", + ), + ], +) +async def test_controller_update_without_current_version( + hass: HomeAssistant, + hass_ws_client: WebSocketGenerator, + mock_config_entry: MockConfigEntry, + mock_omada_client: MagicMock, + update_type: str, + update_data: dict[str, str | bool | None], + expected_latest_version: str, + expected_state: str, +) -> None: + """Test missing controller update versions do not block update entity setup.""" + mock_omada_client.check_firmware_updates.return_value = OmadaControllerUpdateInfo( + {update_type: update_data} + ) + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.tplink_omada.PLATFORMS", [Platform.UPDATE]): + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entity = hass.states.get("update.oc200_test_omada_controller_firmware") + assert entity is not None + assert entity.state == expected_state + assert entity.attributes[ATTR_INSTALLED_VERSION] == "6.2.10.17" + assert entity.attributes[ATTR_LATEST_VERSION] == expected_latest_version + assert "download_url" not in entity.attributes + + client = await hass_ws_client(hass) + await client.send_json( + {"id": 1, "type": "update/release_notes", "entity_id": entity.entity_id} + ) + result = await client.receive_json() + assert result["success"] + assert result["result"] is None + + device_entity = hass.states.get("update.test_poe_switch_firmware") + assert device_entity is not None + assert device_entity.state == STATE_ON + + +@pytest.mark.parametrize( + "update_data", + [ + pytest.param({}, id="missing_sections"), + pytest.param({"hardware": None}, id="null_hardware"), + pytest.param({"software": None}, id="null_software"), + pytest.param({"hardware": None, "software": None}, id="null_sections"), + ], +) +async def test_controller_update_without_update_sections( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_omada_client: MagicMock, + update_data: dict[str, None], +) -> None: + """Test absent controller update sections do not block device update entities.""" + mock_omada_client.check_firmware_updates.return_value = OmadaControllerUpdateInfo( + update_data + ) + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.tplink_omada.PLATFORMS", [Platform.UPDATE]): + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + entity = hass.states.get("update.oc200_test_omada_controller_firmware") + assert entity is not None + assert entity.state == STATE_OFF + assert entity.attributes[ATTR_INSTALLED_VERSION] == "6.2.10.17" + assert entity.attributes[ATTR_LATEST_VERSION] == "6.2.10.17" + assert entity.attributes[ATTR_SUPPORTED_FEATURES] == 0 + assert "download_url" not in entity.attributes + + mock_omada_client.install_controller_firmware.assert_not_awaited() + + device_entity = hass.states.get("update.test_poe_switch_firmware") + assert device_entity is not None + assert device_entity.state == STATE_ON + + +@pytest.mark.parametrize( + "version_data", + [ + pytest.param({}, id="missing_latest_version"), + pytest.param({"latestVersion": None}, id="null_latest_version"), + pytest.param({"latestVersion": ""}, id="empty_latest_version"), + ], +) +async def test_install_controller_firmware_without_latest_version( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_omada_client: MagicMock, + version_data: dict[str, str | None], +) -> None: + """Test installation is rejected when no target firmware version is known.""" + mock_omada_client.check_firmware_updates.return_value = OmadaControllerUpdateInfo( + {"hardware": version_data} + ) + mock_config_entry.add_to_hass(hass) + + with patch("homeassistant.components.tplink_omada.PLATFORMS", [Platform.UPDATE]): + assert await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + with pytest.raises(HomeAssistantError) as err: + await hass.services.async_call( + UPDATE_DOMAIN, + SERVICE_INSTALL, + {ATTR_ENTITY_ID: "update.oc200_test_omada_controller_firmware"}, + blocking=True, + ) + assert err.value.translation_key == "no_update_available" + mock_omada_client.install_controller_firmware.assert_not_awaited() + + +@pytest.mark.parametrize( + "hardware_data", + [ + pytest.param({}, id="hardware_missing"), + pytest.param({"hardware": None}, id="hardware_null"), + ], +) async def test_controller_software_update_installed_version_prefers_status_coordinator( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_omada_client: MagicMock, + hardware_data: dict[str, None], ) -> None: """Test controller software update installed version prefers controller status.""" entity_id = "update.oc200_test_omada_controller_firmware" @@ -240,11 +413,12 @@ async def test_controller_software_update_installed_version_prefers_status_coord ) mock_omada_client.check_firmware_updates.return_value = OmadaControllerUpdateInfo( { + **hardware_data, "software": { "upgrade": True, "currentVersion": "6.2.10.17", "latestVersion": "6.3.0.45", - } + }, } ) mock_config_entry.add_to_hass(hass) @@ -403,21 +577,14 @@ async def test_install_controller_firmware_exceptions( mock_omada_client.check_firmware_updates.assert_awaited_once() -async def test_install_controller_firmware_rejected_without_hardware( +async def test_controller_update_without_hardware_does_not_support_install( hass: HomeAssistant, init_integration: MockConfigEntry, ) -> None: - """Test controller firmware installation rejects software-only updates.""" - entity = hass.data[DATA_COMPONENT].get_entity( - "update.oc200_test_omada_controller_firmware" - ) + """Test software-only updates do not expose firmware installation.""" + entity = hass.states.get("update.oc200_test_omada_controller_firmware") assert entity is not None - - with pytest.raises(HomeAssistantError) as err: - await entity.async_install(version=None, backup=False) - - assert err.value.translation_key == "firmware_update_rejected" - assert err.value.translation_domain == DOMAIN + assert not entity.attributes[ATTR_SUPPORTED_FEATURES] & UpdateEntityFeature.INSTALL @pytest.mark.parametrize( From 767af3b48590288d7830049e9d5421bb6dad2657 Mon Sep 17 00:00:00 2001 From: Stefan Agner Date: Fri, 9 Oct 2026 12:29:00 +0200 Subject: [PATCH 326/356] Bump wheels and base image to 2026.10.0 (#185227) Co-authored-by: Claude Opus 5.5 --- .github/workflows/builder.yml | 2 +- .github/workflows/wheels.yml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/builder.yml b/.github/workflows/builder.yml index dcae3586e7a0..2ba90244fe43 100644 --- a/.github/workflows/builder.yml +++ b/.github/workflows/builder.yml @@ -14,7 +14,7 @@ env: UV_HTTP_TIMEOUT: 60 UV_SYSTEM_PYTHON: "true" # Base image version from https://github.com/home-assistant/docker - BASE_IMAGE_VERSION: "2026.07.0" + BASE_IMAGE_VERSION: "2026.10.0" ARCHITECTURES: '["amd64", "aarch64"]' MACHINES: >- ["generic-x86-64", "khadas-vim3", "odroid-c2", "odroid-c4", "odroid-m1", diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index c2eb218b954c..942afd3609a8 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -137,7 +137,7 @@ jobs: sed -i "/uv/d" requirements_diff.txt - name: Build wheels - uses: home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716 # 2026.07.0 + uses: home-assistant/wheels@a100f6a076013273baaaf94c908d647d91327364 # 2026.10.0 with: abi: ${{ matrix.abi }} tag: musllinux_1_2 @@ -195,7 +195,7 @@ jobs: sed -i "/uv/d" requirements_diff.txt - name: Build wheels - uses: home-assistant/wheels@9e17ab1ed5c4c79d8b61e29fa63de25ca2710716 # 2026.07.0 + uses: home-assistant/wheels@a100f6a076013273baaaf94c908d647d91327364 # 2026.10.0 with: abi: ${{ matrix.abi }} tag: musllinux_1_2 From 8c543d838780ffa28d4982456ee64b890a0d780a Mon Sep 17 00:00:00 2001 From: Robert Resch Date: Fri, 16 Oct 2026 10:33:17 +0200 Subject: [PATCH 327/356] Upgrade runner to Ubuntu 26.04 (#186424) --- .../actions/restore-or-build-venv/action.yml | 2 +- .github/workflows/builder.yml | 20 +++--- .../check-requirements-deterministic.yml | 2 +- .github/workflows/ci.yaml | 66 +++++++++---------- .github/workflows/e2e-tests.yml | 2 +- .github/workflows/wheels.yml | 10 +-- 6 files changed, 51 insertions(+), 51 deletions(-) diff --git a/.github/actions/restore-or-build-venv/action.yml b/.github/actions/restore-or-build-venv/action.yml index 969bfbcf54bf..9f494960a793 100644 --- a/.github/actions/restore-or-build-venv/action.yml +++ b/.github/actions/restore-or-build-venv/action.yml @@ -78,7 +78,7 @@ runs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libxml2-utils libavcodec-dev libavdevice-dev diff --git a/.github/workflows/builder.yml b/.github/workflows/builder.yml index 2ba90244fe43..3d0ef955da61 100644 --- a/.github/workflows/builder.yml +++ b/.github/workflows/builder.yml @@ -31,7 +31,7 @@ jobs: init: name: Initialize build if: github.repository_owner == 'home-assistant' - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository outputs: @@ -102,9 +102,9 @@ jobs: arch: ${{ fromJson(needs.init.outputs.architectures) }} include: - arch: amd64 - os: ubuntu-24.04 + os: ubuntu-26.04 - arch: aarch64 - os: ubuntu-24.04-arm + os: ubuntu-26.04-arm steps: - name: Checkout the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -227,14 +227,14 @@ jobs: include: # Default: aarch64 on native ARM runner - arch: aarch64 - runs-on: ubuntu-24.04-arm + runs-on: ubuntu-26.04-arm # Overrides for amd64 machines - machine: generic-x86-64 arch: amd64 - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 - machine: qemux86-64 arch: amd64 - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 steps: - name: Checkout the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -297,7 +297,7 @@ jobs: environment: ${{ needs.init.outputs.channel }} if: github.repository_owner == 'home-assistant' needs: ["init", "build_machine", "run_e2e_tests_machine"] - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read steps: @@ -337,7 +337,7 @@ jobs: environment: ${{ needs.init.outputs.channel }} if: github.repository_owner == 'home-assistant' needs: ["init", "build_base", "run_e2e_tests_base"] - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository packages: write # To push to GHCR @@ -472,7 +472,7 @@ jobs: name: Build PyPi package environment: ${{ needs.init.outputs.channel }} needs: ["init", "build_base", "run_e2e_tests_base"] - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository id-token: write # For PyPI trusted publishing @@ -513,7 +513,7 @@ jobs: hassfest-image: name: Build and test hassfest image - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository packages: write # To push to GHCR diff --git a/.github/workflows/check-requirements-deterministic.yml b/.github/workflows/check-requirements-deterministic.yml index 615c872d242b..ae41fd248e87 100644 --- a/.github/workflows/check-requirements-deterministic.yml +++ b/.github/workflows/check-requirements-deterministic.yml @@ -32,7 +32,7 @@ concurrency: jobs: deterministic: name: Run deterministic requirement checks - runs-on: ubuntu-24.04 + runs-on: ubuntu-latest permissions: contents: read pull-requests: read # To fetch the PR diff via gh CLI diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 370797762b5a..6faa6284cdf1 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -37,7 +37,7 @@ on: type: boolean env: - CACHE_VERSION: 4 + CACHE_VERSION: 1 MYPY_CACHE_VERSION: 1 HA_SHORT_VERSION: "2026.10" ADDITIONAL_PYTHON_VERSIONS: "[]" @@ -69,7 +69,7 @@ env: tests/components/recorder tests/components/sensor UV_CACHE_DIR: /tmp/uv-cache - APT_CACHE_VERSION: 1 + APT_CACHE_VERSION: 2 SQLALCHEMY_WARN_20: 1 PYTHONASYNCIODEBUG: 1 HASS_CI: 1 @@ -83,7 +83,7 @@ concurrency: jobs: info: name: Collect information & changes data - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository pull-requests: read # For paths-filter to detect changed files @@ -271,7 +271,7 @@ jobs: prek: name: Run prek checks - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: [info] @@ -298,7 +298,7 @@ jobs: zizmor: name: Check GitHub Actions workflows - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read # To check out the repository needs: [info] @@ -318,7 +318,7 @@ jobs: lint-hadolint: name: Check ${{ matrix.file }} - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: [info] @@ -348,7 +348,7 @@ jobs: base: name: Prepare dependencies - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: [info] @@ -390,7 +390,7 @@ jobs: hassfest: name: Check hassfest - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -409,7 +409,7 @@ jobs: timeout-minutes: 10 uses: $/.github/actions/cache-apt-packages with: - packages: libturbojpeg + packages: libturbojpeg0 version: ${{ env.APT_CACHE_VERSION }} - name: Set up Python and restore venv id: python @@ -427,7 +427,7 @@ jobs: gen-requirements-all: name: Check all requirements - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -458,7 +458,7 @@ jobs: gen-copilot-instructions: name: Check copilot instructions - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -484,7 +484,7 @@ jobs: gen-recorder-db-versions: name: Check recorder database versions - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -510,7 +510,7 @@ jobs: dependency-review: name: Dependency review - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -533,7 +533,7 @@ jobs: audit-licenses: name: Audit licenses - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -582,7 +582,7 @@ jobs: pylint: name: Check pylint - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -628,7 +628,7 @@ jobs: pylint-tests: name: Check pylint on tests - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -675,7 +675,7 @@ jobs: mypy: name: Check mypy - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -737,7 +737,7 @@ jobs: benchmarks: name: Run benchmarks - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read id-token: write # OIDC token CodSpeed mints (no CODSPEED_TOKEN secret) @@ -778,7 +778,7 @@ jobs: prepare-pytest-full: name: Split tests for full run - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read if: | @@ -799,7 +799,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 version: ${{ env.APT_CACHE_VERSION }} execute_install_scripts: true - name: Set up Python and restore venv @@ -864,7 +864,7 @@ jobs: pytest-full: name: Run tests Python ${{ matrix.python-version }} (${{ matrix.group }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -895,7 +895,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libxml2-utils version: ${{ env.APT_CACHE_VERSION }} execute_install_scripts: true @@ -987,7 +987,7 @@ jobs: pytest-mariadb: name: Run ${{ matrix.mariadb-group }} tests Python ${{ matrix.python-version }} - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read services: @@ -1028,7 +1028,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libmariadb-dev-compat libxml2-utils version: ${{ env.APT_CACHE_VERSION }} @@ -1125,7 +1125,7 @@ jobs: pytest-postgres: name: Run ${{ matrix.postgresql-group }} tests Python ${{ matrix.python-version }} - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read services: @@ -1169,7 +1169,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libxml2-utils version: ${{ env.APT_CACHE_VERSION }} execute_install_scripts: true @@ -1273,7 +1273,7 @@ jobs: pytest-sqlite: name: Run SQLite ${{ matrix.sqlite-group.version }} tests Python ${{ matrix.python-version }} - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -1303,7 +1303,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libxml2-utils version: ${{ env.APT_CACHE_VERSION }} execute_install_scripts: true @@ -1386,7 +1386,7 @@ jobs: coverage-full: name: Upload test coverage to Codecov (full suite) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -1415,7 +1415,7 @@ jobs: pytest-partial: name: Run tests Python ${{ matrix.python-version }} (${{ matrix.group }}) - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read needs: @@ -1446,7 +1446,7 @@ jobs: packages: >- bluez ffmpeg - libturbojpeg + libturbojpeg0 libxml2-utils version: ${{ env.APT_CACHE_VERSION }} execute_install_scripts: true @@ -1542,7 +1542,7 @@ jobs: coverage-partial: name: Upload test coverage to Codecov (partial suite) if: needs.info.outputs.skip_coverage != 'true' - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 permissions: contents: read timeout-minutes: 10 @@ -1567,7 +1567,7 @@ jobs: upload-test-results: name: Upload test results to Codecov - runs-on: ubuntu-24.04 + runs-on: ubuntu-26.04 needs: - info - pytest-partial diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index dc7e6b10af92..37c7204954c0 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -38,7 +38,7 @@ jobs: name: Boot check ${{ matrix.image_prefix }} image if: github.repository_owner == 'home-assistant' # amd64 images need an x86 runner; all others are aarch64 - runs-on: ${{ contains(fromJson('["amd64", "generic-x86-64", "qemux86-64"]'), matrix.image_prefix) && 'ubuntu-24.04' || 'ubuntu-24.04-arm' }} + runs-on: ${{ contains(fromJson('["amd64", "generic-x86-64", "qemux86-64"]'), matrix.image_prefix) && 'ubuntu-26.04' || 'ubuntu-26.04-arm' }} timeout-minutes: 20 strategy: fail-fast: false diff --git a/.github/workflows/wheels.yml b/.github/workflows/wheels.yml index 942afd3609a8..d2b8c40d0626 100644 --- a/.github/workflows/wheels.yml +++ b/.github/workflows/wheels.yml @@ -26,7 +26,7 @@ jobs: init: name: Initialize wheels builder if: github.repository_owner == 'home-assistant' - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - name: Checkout the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -111,9 +111,9 @@ jobs: arch: ["amd64", "aarch64"] include: - arch: amd64 - os: ubuntu-latest + os: ubuntu-26.04 - arch: aarch64 - os: ubuntu-24.04-arm + os: ubuntu-26.04-arm steps: - name: Checkout the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -162,9 +162,9 @@ jobs: arch: ["amd64", "aarch64"] include: - arch: amd64 - os: ubuntu-latest + os: ubuntu-26.04 - arch: aarch64 - os: ubuntu-24.04-arm + os: ubuntu-26.04-arm steps: - name: Checkout the repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 From 42a54cd27dfff61eec08fa01934ce4f6d6c71038 Mon Sep 17 00:00:00 2001 From: Robert Resch Date: Wed, 14 Oct 2026 17:50:11 +0200 Subject: [PATCH 328/356] Bump Python to 3.14.8 (#186429) --- .github/workflows/builder.yml | 1 + .python-version | 2 +- script/hassfest/docker/Dockerfile | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/builder.yml b/.github/workflows/builder.yml index 3d0ef955da61..70bb0c1ee411 100644 --- a/.github/workflows/builder.yml +++ b/.github/workflows/builder.yml @@ -14,6 +14,7 @@ env: UV_HTTP_TIMEOUT: 60 UV_SYSTEM_PYTHON: "true" # Base image version from https://github.com/home-assistant/docker + # If python version changes in the base image, update .python-version accordingly to match the new Python version. BASE_IMAGE_VERSION: "2026.10.0" ARCHITECTURES: '["amd64", "aarch64"]' MACHINES: >- diff --git a/.python-version b/.python-version index a6d9ada03ee6..9b8fe2fbb856 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.14.5 +3.14.8 diff --git a/script/hassfest/docker/Dockerfile b/script/hassfest/docker/Dockerfile index 4024b9d1896b..5c5c2246bfad 100644 --- a/script/hassfest/docker/Dockerfile +++ b/script/hassfest/docker/Dockerfile @@ -2,7 +2,7 @@ # Automatically generated by hassfest. # # To update, run python3 -m script.hassfest -p docker -FROM python:3.14.5-alpine +FROM python:3.14.8-alpine ENV \ UV_SYSTEM_PYTHON=true \ From ac33d392667e4a9ad4e20ce2862d0434077b6d24 Mon Sep 17 00:00:00 2001 From: Manu Date: Sat, 17 Oct 2026 06:02:37 +0200 Subject: [PATCH 329/356] Create new SSL context instead of sharing context in SMTP integration (#186812) --- homeassistant/components/smtp/__init__.py | 8 ++++---- homeassistant/components/smtp/config_flow.py | 8 ++++---- tests/components/smtp/conftest.py | 4 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/smtp/__init__.py b/homeassistant/components/smtp/__init__.py index 9e66d0536307..3428931f81d3 100644 --- a/homeassistant/components/smtp/__init__.py +++ b/homeassistant/components/smtp/__init__.py @@ -24,7 +24,7 @@ from homeassistant.helpers import ( entity_registry as er, ) from homeassistant.helpers.typing import ConfigType -from homeassistant.util.ssl import client_context, client_context_no_verify +from homeassistant.util.ssl import create_client_context, create_no_verify_ssl_context from .const import ( CONF_ENCRYPTION, @@ -81,10 +81,10 @@ async def async_setup_entry(hass: HomeAssistant, entry: SmtpConfigEntry) -> bool timeout=entry.options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT), use_tls=entry.data[CONF_ENCRYPTION] == "tls", start_tls=entry.data[CONF_ENCRYPTION] == "starttls", - tls_context=( - client_context() + tls_context=await hass.async_add_executor_job( + create_client_context if entry.data[CONF_VERIFY_SSL] - else client_context_no_verify() + else create_no_verify_ssl_context ), ) try: diff --git a/homeassistant/components/smtp/config_flow.py b/homeassistant/components/smtp/config_flow.py index 73ba306db349..d18ba385beda 100644 --- a/homeassistant/components/smtp/config_flow.py +++ b/homeassistant/components/smtp/config_flow.py @@ -43,7 +43,7 @@ from homeassistant.helpers.selector import ( TextSelectorConfig, TextSelectorType, ) -from homeassistant.util.ssl import client_context, client_context_no_verify +from homeassistant.util.ssl import create_client_context, create_no_verify_ssl_context from . import SmtpConfigEntry from .const import ( @@ -321,10 +321,10 @@ async def validate_input( timeout=options.get(CONF_TIMEOUT, DEFAULT_TIMEOUT), use_tls=user_input[CONF_ENCRYPTION] == "tls", start_tls=user_input[CONF_ENCRYPTION] == "starttls", - tls_context=( - client_context() + tls_context=await hass.async_add_executor_job( + create_client_context if user_input[CONF_VERIFY_SSL] - else client_context_no_verify() + else create_no_verify_ssl_context ), ): pass diff --git a/tests/components/smtp/conftest.py b/tests/components/smtp/conftest.py index b6c41831aa52..d90ebb6340d6 100644 --- a/tests/components/smtp/conftest.py +++ b/tests/components/smtp/conftest.py @@ -113,10 +113,10 @@ def mock_client_context() -> Generator[None]: with ( patch( - "homeassistant.components.smtp.config_flow.client_context" + "homeassistant.components.smtp.config_flow.create_client_context" ) as mock_client, patch( - "homeassistant.components.smtp.client_context", + "homeassistant.components.smtp.create_client_context", new=mock_client, ), ): From 4878492b31b324bb1799d7607329bf3bda55c19f Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 19:21:54 +0200 Subject: [PATCH 330/356] Update uv to 0.12.24 (#186899) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index f3eb4bbd7c86..c7e71de09413 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -72,7 +72,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.23 +uv==0.12.24 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 diff --git a/pyproject.toml b/pyproject.toml index cf1ee4ef4f6c..c8ec4747a266 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ dependencies = [ "typing-extensions>=4.16.0,<5.0", "ulid-transform==2.2.9", "urllib3>=2.0", - "uv==0.12.23", + "uv==0.12.24", "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", diff --git a/requirements.txt b/requirements.txt index 42160d92f3ed..3b166f20700e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,7 +57,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.23 +uv==0.12.24 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 From 8b76eb8553ba768067c8229389b8ec171d96bbe5 Mon Sep 17 00:00:00 2001 From: Klaas Schoute Date: Sat, 17 Oct 2026 12:33:37 +0200 Subject: [PATCH 331/356] Fix missing EnergyZero gas prices before 06:00 (#186917) --- .../components/energyzero/manifest.json | 2 +- .../components/energyzero/services.py | 8 +- requirements_all.txt | 2 +- tests/components/energyzero/test_sensor.py | 148 +++++++++++++++++- tests/components/energyzero/test_services.py | 51 +++++- 5 files changed, 203 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/energyzero/manifest.json b/homeassistant/components/energyzero/manifest.json index 60c553c1e927..97046f98f9c9 100644 --- a/homeassistant/components/energyzero/manifest.json +++ b/homeassistant/components/energyzero/manifest.json @@ -6,6 +6,6 @@ "documentation": "https://www.home-assistant.io/integrations/energyzero", "integration_type": "service", "iot_class": "cloud_polling", - "requirements": ["energyzero==5.1.0"], + "requirements": ["energyzero==5.1.1"], "single_config_entry": true } diff --git a/homeassistant/components/energyzero/services.py b/homeassistant/components/energyzero/services.py index 247395361e80..8a2c26af4840 100644 --- a/homeassistant/components/energyzero/services.py +++ b/homeassistant/components/energyzero/services.py @@ -94,6 +94,11 @@ def __serialize_prices( prices: list[EnergyPrices], start: datetime, end: datetime ) -> ServiceResponse: """Filter and serialize prices to the requested datetime range.""" + unique_prices = { + time_range: price + for price_data in prices + for time_range, price in price_data.prices.items() + } return { "prices": [ { @@ -102,8 +107,7 @@ def __serialize_prices( "start": str(time_range.start_including), "end": str(time_range.end_excluding), } - for price_data in prices - for time_range, price in price_data.prices.items() + for time_range, price in unique_prices.items() if time_range.end_excluding > start and time_range.start_including < end ] } diff --git a/requirements_all.txt b/requirements_all.txt index 3b77f2ed18d9..ba0ec65c3ec8 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -956,7 +956,7 @@ energyflip-api-client==0.3.0 energyid-webhooks==0.0.16 # homeassistant.components.energyzero -energyzero==5.1.0 +energyzero==5.1.1 # homeassistant.components.enocean enocean-async==0.4.2 diff --git a/tests/components/energyzero/test_sensor.py b/tests/components/energyzero/test_sensor.py index cd3f5fc9708d..e7cd588ea4de 100644 --- a/tests/components/energyzero/test_sensor.py +++ b/tests/components/energyzero/test_sensor.py @@ -1,7 +1,8 @@ """Tests for the sensors provided by the EnergyZero integration.""" -from datetime import timedelta +from datetime import datetime, timedelta from unittest.mock import AsyncMock, MagicMock, patch +from zoneinfo import ZoneInfo from energyzero import EnergyZeroNoDataError from freezegun.api import FrozenDateTimeFactory @@ -10,6 +11,7 @@ from syrupy.assertion import SnapshotAssertion from homeassistant.components.energyzero.const import ( CONF_ELECTRICITY_PRICE_INTERVAL, + DOMAIN, SCAN_INTERVAL, ) from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN @@ -19,7 +21,12 @@ from homeassistant.util import dt as dt_util from . import setup_integration -from tests.common import MockConfigEntry, async_fire_time_changed, snapshot_platform +from tests.common import ( + MockConfigEntry, + async_fire_time_changed, + async_load_json_object_fixture, + snapshot_platform, +) pytestmark = [pytest.mark.freeze_time("2026-04-10 20:32:59")] @@ -157,3 +164,140 @@ async def test_existing_market_registry_entries( assert entry.name == original.name assert entry.disabled_by == original.disabled_by assert len(er.async_entries_for_config_entry(entity_registry, "12345")) == 16 + + +@pytest.mark.parametrize( + ("moment", "current", "next_hour"), + [ + pytest.param( + "2026-04-10T00:00:00+02:00", + "0.54345990633176", + "0.54345990633176", + id="midnight", + ), + pytest.param( + "2026-04-10T05:00:00+02:00", + "0.54345990633176", + "0.5468407201224", + id="next-hour-boundary", + ), + pytest.param( + "2026-04-10T05:59:59+02:00", + "0.54345990633176", + "0.5468407201224", + id="before-boundary", + ), + pytest.param( + "2026-04-10T06:00:00+02:00", + "0.5468407201224", + "0.5468407201224", + id="boundary", + ), + ], +) +async def test_gas_prices_after_fresh_start( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, + moment: str, + current: str, + next_hour: str, +) -> None: + """Exercise actual REST parsing without a remembered sensor value.""" + await hass.config.async_set_time_zone("Europe/Amsterdam") + freezer.move_to(moment) + electricity = await async_load_json_object_fixture( + hass, "today_energy.json", DOMAIN + ) + gas = await async_load_json_object_fixture(hass, "today_gas.json", DOMAIN) + mock_config_entry.add_to_hass(hass) + with patch( + "energyzero.api.rest.RESTClient._request", + side_effect=[electricity, gas, electricity], + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + + assert (state := hass.states.get("sensor.energyzero_today_gas_current_hour_price")) + assert state.state == current + assert (state := hass.states.get("sensor.energyzero_today_gas_next_hour_price")) + assert state.state == next_hour + + +@pytest.mark.parametrize( + ("block_count", "expected"), + [ + pytest.param(2, "0.5468407201224", id="new-price"), + pytest.param(1, STATE_UNKNOWN, id="missing-price"), + ], +) +async def test_gas_price_expires_at_boundary( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, + block_count: int, + expected: str, +) -> None: + """A refresh must select the new interval or report an unknown price.""" + await hass.config.async_set_time_zone("Europe/Amsterdam") + freezer.move_to(datetime(2026, 4, 10, 5, 55, tzinfo=ZoneInfo("Europe/Amsterdam"))) + electricity = await async_load_json_object_fixture( + hass, "today_energy.json", DOMAIN + ) + gas = await async_load_json_object_fixture(hass, "today_gas.json", DOMAIN) + gas = { + **gas, + **{ + stream: gas[stream][:block_count] + for stream in ("base", "base_with_vat", "all_in", "all_in_with_vat") + }, + } + mock_config_entry.add_to_hass(hass) + with patch( + "energyzero.api.rest.RESTClient._request", side_effect=[electricity, gas] * 2 + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert ( + state := hass.states.get("sensor.energyzero_today_gas_current_hour_price") + ) + assert state.state == "0.54345990633176" + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=1)) + await hass.async_block_till_done(wait_background_tasks=True) + + assert (state := hass.states.get("sensor.energyzero_today_gas_current_hour_price")) + assert state.state == expected + + +async def test_gas_price_survives_calendar_rollover( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """Refreshing for a new calendar date keeps the still-valid gas interval.""" + await hass.config.async_set_time_zone("Europe/Amsterdam") + freezer.move_to("2026-04-09T23:55:00+02:00") + electricity = await async_load_json_object_fixture( + hass, "today_energy.json", DOMAIN + ) + gas = await async_load_json_object_fixture(hass, "today_gas.json", DOMAIN) + mock_config_entry.add_to_hass(hass) + with patch( + "energyzero.api.rest.RESTClient._request", + side_effect=[electricity, gas, electricity] * 2, + ) as request: + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + assert ( + state := hass.states.get("sensor.energyzero_today_gas_current_hour_price") + ) + assert state.state == "0.54345990633176" + freezer.tick(SCAN_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done(wait_background_tasks=True) + + assert request.await_args_list[1].kwargs["params"]["date"] == "09-04-2026" + assert request.await_args_list[4].kwargs["params"]["date"] == "10-04-2026" + assert (state := hass.states.get("sensor.energyzero_today_gas_current_hour_price")) + assert state.state == "0.54345990633176" diff --git a/tests/components/energyzero/test_services.py b/tests/components/energyzero/test_services.py index 1f62388a68d7..d0e82917be1d 100644 --- a/tests/components/energyzero/test_services.py +++ b/tests/components/energyzero/test_services.py @@ -2,7 +2,7 @@ from datetime import UTC, date, datetime, timedelta import re -from unittest.mock import AsyncMock, call +from unittest.mock import AsyncMock, call, patch from zoneinfo import ZoneInfo from energyzero import ( @@ -12,6 +12,7 @@ from energyzero import ( PriceType, TimeRange, ) +from freezegun.api import FrozenDateTimeFactory import probatio import pytest from syrupy.assertion import SnapshotAssertion @@ -27,8 +28,9 @@ from homeassistant.components.energyzero.services import ( ) from homeassistant.core import HomeAssistant from homeassistant.exceptions import ServiceValidationError +from homeassistant.util import dt as dt_util -from tests.common import MockConfigEntry +from tests.common import MockConfigEntry, async_load_json_object_fixture pytestmark = pytest.mark.freeze_time("2026-04-10 20:32:59") @@ -843,3 +845,48 @@ async def test_energy_service_quarter_invalid_range( return_response=True, ) mock_energyzero.get_electricity_prices.assert_not_awaited() + + +async def test_gas_action_deduplicates_overlapping_days( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + freezer: FrozenDateTimeFactory, +) -> None: + """A multi-day action returns each complete gas interval exactly once.""" + await hass.config.async_set_time_zone("Europe/Amsterdam") + freezer.move_to("2026-04-10T00:00:00+02:00") + electricity = await async_load_json_object_fixture( + hass, "today_energy.json", DOMAIN + ) + gas = await async_load_json_object_fixture(hass, "today_gas.json", DOMAIN) + mock_config_entry.add_to_hass(hass) + with patch( + "energyzero.api.rest.RESTClient._request", + side_effect=[electricity, gas, electricity, gas, gas], + ): + await hass.config_entries.async_setup(mock_config_entry.entry_id) + await hass.async_block_till_done() + response = await hass.services.async_call( + DOMAIN, + GAS_SERVICE_NAME, + { + ATTR_CONFIG_ENTRY: mock_config_entry.entry_id, + "incl_vat": True, + "start": "2026-04-10", + "end": "2026-04-11", + }, + blocking=True, + return_response=True, + ) + + assert response == { + "prices": [ + { + "price": float(block["price"]["value"]), + "timestamp": str(dt_util.parse_datetime(block["start"])), + "start": str(dt_util.parse_datetime(block["start"])), + "end": str(dt_util.parse_datetime(block["end"])), + } + for block in gas["base_with_vat"] + ] + } From 7393c05d2d801bf5b9cfe75db268f10771f0ddf9 Mon Sep 17 00:00:00 2001 From: tronikos Date: Fri, 16 Oct 2026 13:39:47 -0700 Subject: [PATCH 332/356] Bump opower to 0.22.3 (#186928) --- homeassistant/components/opower/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/opower/manifest.json b/homeassistant/components/opower/manifest.json index 8657337df337..588bb71f3ab8 100644 --- a/homeassistant/components/opower/manifest.json +++ b/homeassistant/components/opower/manifest.json @@ -9,5 +9,5 @@ "iot_class": "cloud_polling", "loggers": ["opower"], "quality_scale": "platinum", - "requirements": ["opower==0.22.2"] + "requirements": ["opower==0.22.3"] } diff --git a/requirements_all.txt b/requirements_all.txt index ba0ec65c3ec8..4f81bc0a3ad4 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1851,7 +1851,7 @@ openwrt-luci-rpc==1.1.17 openwrt-ubus-rpc==0.0.3 # homeassistant.components.opower -opower==0.22.2 +opower==0.22.3 # homeassistant.components.oralb oralb-ble==1.1.3 From 63733b522b02231e116885d33b6e103910355a4c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 16 Oct 2026 22:39:14 +0200 Subject: [PATCH 333/356] Update uv to 0.13.0 (#186930) --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index c7e71de09413..bf8fafa439ab 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -72,7 +72,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.24 +uv==0.13.0 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 diff --git a/pyproject.toml b/pyproject.toml index c8ec4747a266..f99d82ce730e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ dependencies = [ "typing-extensions>=4.16.0,<5.0", "ulid-transform==2.2.9", "urllib3>=2.0", - "uv==0.12.24", + "uv==0.13.0", "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", diff --git a/requirements.txt b/requirements.txt index 3b166f20700e..ee3245bf542c 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,7 +57,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.12.24 +uv==0.13.0 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 From 87775d57368dc1d786f25e17792d5b57f55afacb Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Fri, 16 Oct 2026 23:23:24 +0200 Subject: [PATCH 334/356] Handle errors in Synology DSM button press actions (#186931) --- .../components/synology_dsm/button.py | 12 +- .../components/synology_dsm/strings.json | 6 + .../synology_dsm/snapshots/test_button.ambr | 102 +++++++++++ tests/components/synology_dsm/test_button.py | 162 ++++++++++++++++++ 4 files changed, 281 insertions(+), 1 deletion(-) create mode 100644 tests/components/synology_dsm/snapshots/test_button.ambr create mode 100644 tests/components/synology_dsm/test_button.py diff --git a/homeassistant/components/synology_dsm/button.py b/homeassistant/components/synology_dsm/button.py index 3084c027d669..b520cefec39b 100644 --- a/homeassistant/components/synology_dsm/button.py +++ b/homeassistant/components/synology_dsm/button.py @@ -5,6 +5,8 @@ from dataclasses import dataclass import logging from typing import TYPE_CHECKING, Any, Final, override +from synology_dsm.exceptions import SynologyDSMAPIErrorException + from homeassistant.components.button import ( ButtonDeviceClass, ButtonEntity, @@ -12,6 +14,7 @@ from homeassistant.components.button import ( ) from homeassistant.const import EntityCategory from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.device_registry import DeviceInfo from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback @@ -87,4 +90,11 @@ class SynologyDSMButton(ButtonEntity): self.entity_description.key, self.syno_api.network.hostname, ) - await self.entity_description.press_action(self.syno_api)() + try: + await self.entity_description.press_action(self.syno_api)() + except SynologyDSMAPIErrorException as err: + raise HomeAssistantError( + translation_domain=DOMAIN, + translation_key=f"{self.entity_description.key}_failed", + translation_placeholders={"error": str(err)}, + ) from err diff --git a/homeassistant/components/synology_dsm/strings.json b/homeassistant/components/synology_dsm/strings.json index c5b75c6f17ec..312d253efd87 100644 --- a/homeassistant/components/synology_dsm/strings.json +++ b/homeassistant/components/synology_dsm/strings.json @@ -205,8 +205,14 @@ "missing_serial": { "message": "More than one DSM configured, must specify one of serials: {serials}." }, + "reboot_failed": { + "message": "Reboot failed with {error}" + }, "serial_not_found": { "message": "DSM with specified serial {serial} not found." + }, + "shutdown_failed": { + "message": "Shutdown failed with {error}" } }, "issues": { diff --git a/tests/components/synology_dsm/snapshots/test_button.ambr b/tests/components/synology_dsm/snapshots/test_button.ambr new file mode 100644 index 000000000000..98f29177a2b0 --- /dev/null +++ b/tests/components/synology_dsm/snapshots/test_button.ambr @@ -0,0 +1,102 @@ +# serializer version: 1 +# name: test_button[button.nas_meontheinternet_com_restart-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'button', + 'entity_category': , + 'entity_id': 'button.nas_meontheinternet_com_restart', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Restart', + 'options': dict({ + }), + 'original_device_class': , + 'original_icon': None, + 'original_name': 'Restart', + 'platform': 'synology_dsm', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': None, + 'unique_id': 'mySerial_reboot', + 'unit_of_measurement': None, + }) +# --- +# name: test_button[button.nas_meontheinternet_com_restart-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'restart', + : 'nas.meontheinternet.com Restart', + }), + 'context': , + 'entity_id': 'button.nas_meontheinternet_com_restart', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_button[button.nas_meontheinternet_com_shut_down-entry] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': None, + 'config_entry_id': , + 'config_subentry_id': , + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'button', + 'entity_category': , + 'entity_id': 'button.nas_meontheinternet_com_shut_down', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Shut down', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Shut down', + 'platform': 'synology_dsm', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'shutdown', + 'unique_id': 'mySerial_shutdown', + 'unit_of_measurement': None, + }) +# --- +# name: test_button[button.nas_meontheinternet_com_shut_down-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'nas.meontheinternet.com Shut down', + }), + 'context': , + 'entity_id': 'button.nas_meontheinternet_com_shut_down', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- diff --git a/tests/components/synology_dsm/test_button.py b/tests/components/synology_dsm/test_button.py new file mode 100644 index 000000000000..c92b51c11b95 --- /dev/null +++ b/tests/components/synology_dsm/test_button.py @@ -0,0 +1,162 @@ +"""Tests for Synology DSM buttons.""" + +from collections.abc import Generator +from unittest.mock import AsyncMock, MagicMock, Mock, patch + +import pytest +from synology_dsm.exceptions import SynologyDSMAPIErrorException +from syrupy.assertion import SnapshotAssertion + +from homeassistant.components.button import DOMAIN as BUTTON_DOMAIN, SERVICE_PRESS +from homeassistant.components.synology_dsm.button import BUTTONS +from homeassistant.components.synology_dsm.const import DOMAIN +from homeassistant.const import ( + ATTR_ENTITY_ID, + CONF_HOST, + CONF_MAC, + CONF_PASSWORD, + CONF_PORT, + CONF_SSL, + CONF_USERNAME, + Platform, +) +from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers import entity_registry as er +from homeassistant.helpers.translation import LOCALE_EN, async_get_translations + +from .common import mock_dsm_hardware, mock_dsm_information +from .consts import HOST, MACS, PASSWORD, PORT, SERIAL, USE_SSL, USERNAME + +from tests.common import MockConfigEntry, snapshot_platform + + +@pytest.fixture +def mock_dsm() -> Generator[MagicMock]: + """Mock Synology DSM API calls.""" + with patch("homeassistant.components.synology_dsm.common.SynologyDSM") as dsm: + dsm.login = AsyncMock(return_value=True) + dsm.update = AsyncMock(return_value=True) + dsm.system = Mock(reboot=AsyncMock(), shutdown=AsyncMock()) + dsm.network = Mock( + update=AsyncMock(return_value=True), macs=MACS, hostname=HOST + ) + dsm.hardware = mock_dsm_hardware() + dsm.information = mock_dsm_information() + dsm.surveillance_station.update = AsyncMock(return_value=True) + dsm.upgrade.update = AsyncMock(return_value=True) + dsm.file = Mock(get_shared_folders=AsyncMock(return_value=None)) + yield dsm + + +@pytest.fixture +async def setup_button_platform( + hass: HomeAssistant, mock_dsm: MagicMock +) -> MockConfigEntry: + """Set up the Synology DSM button platform.""" + with ( + patch( + "homeassistant.components.synology_dsm.common.SynologyDSM", + return_value=mock_dsm, + ), + patch("homeassistant.components.synology_dsm.PLATFORMS", [Platform.BUTTON]), + ): + entry = MockConfigEntry( + domain=DOMAIN, + data={ + CONF_HOST: HOST, + CONF_PORT: PORT, + CONF_SSL: USE_SSL, + CONF_USERNAME: USERNAME, + CONF_PASSWORD: PASSWORD, + CONF_MAC: MACS[0], + }, + unique_id=SERIAL, + ) + entry.add_to_hass(hass) + await hass.config_entries.async_setup(entry.entry_id) + await hass.async_block_till_done() + + return entry + + +async def test_button( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + snapshot: SnapshotAssertion, + mock_dsm: MagicMock, + setup_button_platform: MockConfigEntry, +) -> None: + """Test Synology DSM button entities.""" + await snapshot_platform( + hass, entity_registry, snapshot, setup_button_platform.entry_id + ) + + +async def test_button_exception_translation(hass: HomeAssistant) -> None: + """Test every button has a translated API error message.""" + translations = await async_get_translations(hass, LOCALE_EN, "exceptions", [DOMAIN]) + + for button in BUTTONS: + translation_key = f"component.{DOMAIN}.exceptions.{button.key}_failed.message" + assert translations.get(translation_key) is not None + + +@pytest.mark.parametrize( + ("button_key", "api_method"), + [("reboot", "reboot"), ("shutdown", "shutdown")], +) +async def test_press_button( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_dsm: MagicMock, + setup_button_platform: MockConfigEntry, + button_key: str, + api_method: str, +) -> None: + """Test pressing each button calls the matching DSM API method.""" + entity_id = entity_registry.async_get_entity_id( + BUTTON_DOMAIN, DOMAIN, f"{SERIAL}_{button_key}" + ) + assert entity_id is not None + + await hass.services.async_call( + BUTTON_DOMAIN, + SERVICE_PRESS, + {ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + getattr(mock_dsm.system, api_method).assert_awaited_once() + + +@pytest.mark.parametrize( + ("button_key", "api_method"), + [("reboot", "reboot"), ("shutdown", "shutdown")], +) +async def test_press_button_api_error( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + mock_dsm: MagicMock, + setup_button_platform: MockConfigEntry, + button_key: str, + api_method: str, +) -> None: + """Test DSM API errors are converted to Home Assistant errors.""" + entity_id = entity_registry.async_get_entity_id( + BUTTON_DOMAIN, DOMAIN, f"{SERIAL}_{button_key}" + ) + assert entity_id is not None + getattr(mock_dsm.system, api_method).side_effect = SynologyDSMAPIErrorException( + "API", 1, {} + ) + + with pytest.raises(HomeAssistantError) as err: + await hass.services.async_call( + BUTTON_DOMAIN, + SERVICE_PRESS, + {ATTR_ENTITY_ID: entity_id}, + blocking=True, + ) + + assert err.value.translation_key == f"{button_key}_failed" From aa5c32ffaa684b7abd972b5b331b3e1c7715558c Mon Sep 17 00:00:00 2001 From: Matthias Alphart Date: Sat, 17 Oct 2026 12:39:59 +0200 Subject: [PATCH 335/356] Hold off the bootstrap timeout while the KNX telegram store initializes (#186980) Co-authored-by: Claude Fable 5.1 --- homeassistant/components/knx/telegrams.py | 12 ++++++--- tests/components/knx/test_telegrams.py | 31 +++++++++++++++++++---- 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/knx/telegrams.py b/homeassistant/components/knx/telegrams.py index d9bfbc62bf0a..656e506c5733 100644 --- a/homeassistant/components/knx/telegrams.py +++ b/homeassistant/components/knx/telegrams.py @@ -30,6 +30,7 @@ from .const import ( CONF_KNX_TELEGRAM_DB_BACKEND, CONF_KNX_TELEGRAM_DB_POSTGRES_DSN, CONF_KNX_TELEGRAM_DB_RETENTION_DAYS, + DOMAIN, KNX_TELEGRAM_BACKEND_POSTGRES, KNX_TELEGRAM_DB_PATH_SQLITE, SIGNAL_KNX_DATA_SECURE_ISSUE_TELEGRAM, @@ -170,19 +171,24 @@ class Telegrams: try: async with self._store_init_timeout(): needs_migration = await self._uninitialized_store.needs_migration() + init_timeout: contextlib.AbstractAsyncContextManager[Any] if needs_migration: _LOGGER.warning( "KNX telegram history database schema upgrade/migration is required. " "This may take some time depending on your database size. Please do not restart Home Assistant" ) - await self._uninitialized_store.initialize() + init_timeout = contextlib.nullcontext() else: _LOGGER.debug( "Initializing KNX telegram storage backend '%s'", self.backend, ) - async with self._store_init_timeout(): - await self._uninitialized_store.initialize() + init_timeout = self._store_init_timeout() + # SQLite initialization is unbounded, so hold off the bootstrap stage + # timeout: a cancelled migration rolls back and starts over on the next + # start, never finishing on a large database. + async with self.hass.timeout.async_freeze(DOMAIN), init_timeout: + await self._uninitialized_store.initialize() _LOGGER.info( "Successfully initialized KNX telegram storage backend '%s'", self.backend, diff --git a/tests/components/knx/test_telegrams.py b/tests/components/knx/test_telegrams.py index 758ce1df7a19..086eb943f507 100644 --- a/tests/components/knx/test_telegrams.py +++ b/tests/components/knx/test_telegrams.py @@ -580,17 +580,38 @@ async def test_telegram_to_dict_dpt_from_project( assert result["dpt_name"] is None -async def test_load_history_needs_migration( +@pytest.mark.parametrize( + "needs_migration", + [ + pytest.param(True, id="needs_migration"), + pytest.param(False, id="no_migration"), + ], +) +async def test_load_history_holds_off_bootstrap_timeout( hass: HomeAssistant, knx: KNXTestKit, + needs_migration: bool, ) -> None: - """Test the schema-migration branch of store initialization.""" - with patch( - "knx_telegram_store.BufferedSqliteStore.needs_migration", - return_value=True, + """Store initialization runs under a timeout freeze so bootstrap waits for it.""" + original_initialize = BufferedSqliteStore.initialize + timeout_frozen: list[bool] = [] + + async def initialize(self: BufferedSqliteStore) -> None: + # The bootstrap stage timeout must wait for a migration to finish + timeout_frozen.append(DOMAIN in hass.timeout.zones) + await original_initialize(self) + + with ( + patch( + "knx_telegram_store.BufferedSqliteStore.needs_migration", + return_value=needs_migration, + ), + patch.object(BufferedSqliteStore, "initialize", initialize), ): await knx.setup_integration(real_telegram_store=True) + assert timeout_frozen == [True] + assert DOMAIN not in hass.timeout.zones telegrams_module = hass.data[KNX_MODULE_KEY].telegrams assert telegrams_module.store is not None From c4380e48df56a1edb5ac26f9ae9bd91c1fd6a76c Mon Sep 17 00:00:00 2001 From: SchmidSP <75223947+SchmidSP@users.noreply.github.com> Date: Sat, 17 Oct 2026 12:32:06 +0200 Subject: [PATCH 336/356] Constrain bitstring<5 to fix edl21 (pysml incompatibility) (#186985) --- homeassistant/package_constraints.txt | 6 ++++++ script/gen_requirements_all.py | 6 ++++++ 2 files changed, 12 insertions(+) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index bf8fafa439ab..f648cc1c6ef4 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -258,6 +258,12 @@ auth0-python<5.0 backoff==2.2.1 python-backoff<2.4.0 +# bitstring 5.0.0 removed ConstBitStream, which pysml (used by edl21) still imports +# https://github.com/home-assistant/core/issues/185883 +# https://codeberg.org/obi/pysml/issues/33 +# Remove once pysml supports bitstring>=5 +bitstring<5 + # graphql-core 3.3 removed graphql_input_types, which apischema 0.19.0 # (used by pydrawise) still imports # https://github.com/home-assistant/core/issues/184918 diff --git a/script/gen_requirements_all.py b/script/gen_requirements_all.py index 2c817fd29c5b..36df4a5b7e2c 100755 --- a/script/gen_requirements_all.py +++ b/script/gen_requirements_all.py @@ -242,6 +242,12 @@ auth0-python<5.0 backoff==2.2.1 python-backoff<2.4.0 +# bitstring 5.0.0 removed ConstBitStream, which pysml (used by edl21) still imports +# https://github.com/home-assistant/core/issues/185883 +# https://codeberg.org/obi/pysml/issues/33 +# Remove once pysml supports bitstring>=5 +bitstring<5 + # graphql-core 3.3 removed graphql_input_types, which apischema 0.19.0 # (used by pydrawise) still imports # https://github.com/home-assistant/core/issues/184918 From ff3fed6913337a0c12e0b63ee08cc3ea339804de Mon Sep 17 00:00:00 2001 From: DeviousCardi <115358213+DeviousCardi@users.noreply.github.com> Date: Mon, 19 Oct 2026 14:51:57 +0530 Subject: [PATCH 337/356] Fix Sensibo full_state action modifying the coordinator data (#187014) Co-authored-by: Claude Opus 5.5 (1M context) --- homeassistant/components/sensibo/climate.py | 7 ++- tests/components/sensibo/test_climate.py | 47 +++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/sensibo/climate.py b/homeassistant/components/sensibo/climate.py index 718f4006710f..ab90b3ddbdbd 100644 --- a/homeassistant/components/sensibo/climate.py +++ b/homeassistant/components/sensibo/climate.py @@ -419,8 +419,11 @@ class SensiboClimate(SensiboDeviceBaseEntity, ClimateEntity): light: str | None = None, ) -> None: """Set full AC state.""" - new_ac_state = self.device_data.ac_states - new_ac_state.pop("timestamp") + new_ac_state = { + key: value + for key, value in self.device_data.ac_states.items() + if key != "timestamp" + } new_ac_state["on"] = False if mode != "off": new_ac_state["on"] = True diff --git a/tests/components/sensibo/test_climate.py b/tests/components/sensibo/test_climate.py index 3505e431e145..712a2aae46f9 100644 --- a/tests/components/sensibo/test_climate.py +++ b/tests/components/sensibo/test_climate.py @@ -1263,6 +1263,53 @@ async def test_climate_full_ac_state( assert state.attributes["temperature"] == 22 +async def test_climate_full_ac_state_keeps_device_data( + hass: HomeAssistant, + load_int: ConfigEntry, + mock_client: MagicMock, +) -> None: + """Test the Full AC state service does not modify the coordinator data.""" + ac_states = load_int.runtime_data.data.parsed["ABC999111"].ac_states + original_ac_states = ac_states.copy() + service_data = { + ATTR_ENTITY_ID: "climate.hallway_hallway", + ATTR_MODE: "cool", + ATTR_TARGET_TEMPERATURE: 22, + } + expected_payload = { + "on": True, + "mode": "cool", + "fanLevel": "high", + "targetTemperature": 22, + "swing": "stopped", + "horizontalSwing": "stopped", + "light": "on", + } + + # A failed call does not refresh the coordinator, so the next call + # works on the same device data. + mock_client.async_set_ac_states.return_value = {"result": {"status": "Failed"}} + with pytest.raises(HomeAssistantError): + await hass.services.async_call( + DOMAIN, SERVICE_FULL_STATE, service_data, blocking=True + ) + + assert ac_states == original_ac_states + mock_client.async_set_ac_states.assert_called_once_with( + "ABC999111", expected_payload + ) + + mock_client.async_set_ac_states.reset_mock() + mock_client.async_set_ac_states.return_value = {"result": {"status": "Success"}} + await hass.services.async_call( + DOMAIN, SERVICE_FULL_STATE, service_data, blocking=True + ) + + mock_client.async_set_ac_states.assert_called_once_with( + "ABC999111", expected_payload + ) + + async def test_climate_fan_mode_and_swing_mode_not_supported( hass: HomeAssistant, load_int: ConfigEntry, From 8789c80ce4fb7df9fa1fe68cf44edf6977569a0e Mon Sep 17 00:00:00 2001 From: Michael <35783820+mib1185@users.noreply.github.com> Date: Sun, 18 Oct 2026 12:25:39 +0200 Subject: [PATCH 338/356] Correct the mix-ed up lock and device lock FRITZ!SmartHome sensors (#187119) --- homeassistant/components/fritzbox/strings.json | 4 ++-- .../components/fritzbox/snapshots/test_binary_sensor.ambr | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/homeassistant/components/fritzbox/strings.json b/homeassistant/components/fritzbox/strings.json index 99ed3317dccf..4988e4d9de08 100644 --- a/homeassistant/components/fritzbox/strings.json +++ b/homeassistant/components/fritzbox/strings.json @@ -71,9 +71,9 @@ "entity": { "binary_sensor": { "alarm": { "name": "Alarm" }, - "device_lock": { "name": "Button lock via UI" }, + "device_lock": { "name": "Button lock on device" }, "holiday_active": { "name": "Holiday mode" }, - "lock": { "name": "Button lock on device" }, + "lock": { "name": "Button lock via UI" }, "summer_active": { "name": "Summer mode" }, "window_open": { "name": "Open window detected" } }, diff --git a/tests/components/fritzbox/snapshots/test_binary_sensor.ambr b/tests/components/fritzbox/snapshots/test_binary_sensor.ambr index 7f41a3bc2646..defa00dfd7e7 100644 --- a/tests/components/fritzbox/snapshots/test_binary_sensor.ambr +++ b/tests/components/fritzbox/snapshots/test_binary_sensor.ambr @@ -133,8 +133,8 @@ 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'lock', - 'unique_id': '12345 1234567_lock', + 'translation_key': 'device_lock', + 'unique_id': '12345 1234567_device_lock', 'unit_of_measurement': None, }) # --- @@ -184,8 +184,8 @@ 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'device_lock', - 'unique_id': '12345 1234567_device_lock', + 'translation_key': 'lock', + 'unique_id': '12345 1234567_lock', 'unit_of_measurement': None, }) # --- From 68fc9d2065f8ce258bde88fb51b1139fe6d8f397 Mon Sep 17 00:00:00 2001 From: nikslim Date: Mon, 19 Oct 2026 18:29:26 +0400 Subject: [PATCH 339/356] Fix Home Connect event listener stopping on token refresh errors (#187207) Co-authored-by: Claude Opus 5.5 --- .../components/home_connect/coordinator.py | 27 ++- tests/components/home_connect/conftest.py | 6 +- .../home_connect/test_coordinator.py | 161 +++++++++++++++++- 3 files changed, 183 insertions(+), 11 deletions(-) diff --git a/homeassistant/components/home_connect/coordinator.py b/homeassistant/components/home_connect/coordinator.py index 7e85e2957db7..d069079eeb79 100644 --- a/homeassistant/components/home_connect/coordinator.py +++ b/homeassistant/components/home_connect/coordinator.py @@ -33,7 +33,12 @@ from aiohomeconnect.model.program import EnumerateProgram, ProgramDefinitionOpti from homeassistant.config_entries import ConfigEntry from homeassistant.core import CALLBACK_TYPE, HomeAssistant, callback -from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady +from homeassistant.exceptions import ( + ConfigEntryAuthFailed, + ConfigEntryNotReady, + OAuth2TokenRequestBaseError, + OAuth2TokenRequestReauthError, +) from homeassistant.helpers import device_registry as dr from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed @@ -167,7 +172,19 @@ class HomeConnectRuntimeData: assert appliance_coordinator await appliance_coordinator.event_listener(event_message) - except (EventStreamInterruptedError, HomeConnectRequestError) as error: + except (HomeConnectApiError, OAuth2TokenRequestReauthError) as error: + _LOGGER.error("Error while listening for events: %s", error) + self.hass.config_entries.async_schedule_reload( + self.config_entry.entry_id + ) + break + except ( + EventStreamInterruptedError, + HomeConnectRequestError, + OAuth2TokenRequestBaseError, + # The token request leaves a bare TimeoutError unmapped + TimeoutError, + ) as error: _LOGGER.debug( "Non-breaking error (%s) while listening for events," " continuing in %s seconds", @@ -176,12 +193,6 @@ class HomeConnectRuntimeData: ) await asyncio_sleep(retry_time) retry_time = min(retry_time * 2, 3600) - except HomeConnectApiError as error: - _LOGGER.error("Error while listening for events: %s", error) - self.hass.config_entries.async_schedule_reload( - self.config_entry.entry_id - ) - break @callback def async_add_global_listener( diff --git a/tests/components/home_connect/conftest.py b/tests/components/home_connect/conftest.py index 97b71d205adb..3c185336546e 100644 --- a/tests/components/home_connect/conftest.py +++ b/tests/components/home_connect/conftest.py @@ -149,6 +149,10 @@ async def mock_integration_setup( config_entry.add_to_hass(hass) async def run(client: MagicMock) -> bool: + def init_side_effect(auth) -> MagicMock: + client._auth = auth + return client + assert config_entry.state is ConfigEntryState.NOT_LOADED with ( patch("homeassistant.components.home_connect.PLATFORMS", platforms), @@ -156,7 +160,7 @@ async def mock_integration_setup( "homeassistant.components.home_connect.HomeConnectClient" ) as client_mock, ): - client_mock.return_value = client + client_mock.side_effect = init_side_effect result = await hass.config_entries.async_setup(config_entry.entry_id) await hass.async_block_till_done() return result diff --git a/tests/components/home_connect/test_coordinator.py b/tests/components/home_connect/test_coordinator.py index e57ab2239290..a03b191bc48f 100644 --- a/tests/components/home_connect/test_coordinator.py +++ b/tests/components/home_connect/test_coordinator.py @@ -1,11 +1,13 @@ """Test for Home Connect coordinator.""" -from collections.abc import Awaitable, Callable +from collections.abc import AsyncGenerator, Awaitable, Callable from datetime import timedelta +from http import HTTPStatus import re from typing import Any, cast from unittest.mock import AsyncMock, MagicMock, patch +from aiohomeconnect.const import OAUTH2_TOKEN from aiohomeconnect.model import ( ArrayOfEvents, ArrayOfHomeAppliances, @@ -37,6 +39,7 @@ from aiohomeconnect.model.program import ( ProgramDefinitionOption, ProgramKey, ) +from aiohttp import ConnectionTimeoutError from freezegun.api import FrozenDateTimeFactory import pytest @@ -50,7 +53,7 @@ from homeassistant.components.homeassistant import ( DOMAIN as HA_DOMAIN, SERVICE_UPDATE_ENTITY, ) -from homeassistant.config_entries import ConfigEntries, ConfigEntryState +from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntries, ConfigEntryState from homeassistant.const import ( ATTR_ENTITY_ID, EVENT_STATE_REPORTED, @@ -69,7 +72,10 @@ 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 .conftest import SERVER_ACCESS_TOKEN + from tests.common import MockConfigEntry, async_fire_time_changed +from tests.test_util.aiohttp import AiohttpClientMocker INITIAL_FETCH_CLIENT_METHODS = [ "get_settings", @@ -417,6 +423,157 @@ async def test_event_listener_error( assert not config_entry._background_tasks +async def _setup_with_token_refresh_on_connect( + client: MagicMock, + config_entry: MockConfigEntry, + integration_setup: Callable[[MagicMock], Awaitable[bool]], +) -> MagicMock: + """Set up the integration with an event stream that gets a token first. + + Like aiohomeconnect, the stream gets the access token from the real + OAuth2 session before connecting. + """ + queue_stream = client.stream_all_events + + async def stream_all_events() -> AsyncGenerator[EventMessage]: + await client._auth.async_get_access_token() + async for event in queue_stream(): + yield event + + client.stream_all_events = MagicMock(side_effect=stream_all_events) + + assert await integration_setup(client) + assert config_entry.state is ConfigEntryState.LOADED + assert client.stream_all_events.call_count == 1 + return client.stream_all_events + + +@pytest.mark.parametrize("platforms", [("sensor",)]) +@pytest.mark.parametrize("appliance", ["Washer"], indirect=True) +@pytest.mark.parametrize( + "token_request_failure", + [ + pytest.param({"exc": ConnectionTimeoutError()}, id="connection_timeout"), + pytest.param({"exc": TimeoutError()}, id="total_timeout"), + pytest.param({"status": HTTPStatus.SERVICE_UNAVAILABLE}, id="server_error"), + ], +) +async def test_event_listener_token_refresh_error( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + token_expiration_time: float, + aioclient_mock: AiohttpClientMocker, + client: MagicMock, + config_entry: MockConfigEntry, + integration_setup: Callable[[MagicMock], Awaitable[bool]], + appliance: HomeAppliance, + token_request_failure: dict[str, Any], +) -> None: + """Test the event listener reconnects after a failed token refresh.""" + stream_all_events = await _setup_with_token_refresh_on_connect( + client, config_entry, integration_setup + ) + assert hass.states.get("sensor.washer_door").state == "closed" + # Setup kept the fixture token, so it expires at token_expiration_time + assert config_entry.data["token"]["expires_at"] == token_expiration_time + + aioclient_mock.post(OAUTH2_TOKEN, **token_request_failure) + await client.add_events([EventStreamInterruptedError()]) + await hass.async_block_till_done() + # Jump to 1 s after the token expires; this also fires the 10 s retry + freezer.move_to(dt_util.utc_from_timestamp(token_expiration_time + 1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + + assert stream_all_events.call_count == 2 + assert aioclient_mock.call_count == 1 + + aioclient_mock.clear_requests() + aioclient_mock.post(OAUTH2_TOKEN, json=SERVER_ACCESS_TOKEN) + # Fire the next retry (20 s backoff) without moving the clock again + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=60)) + await hass.async_block_till_done() + + assert stream_all_events.call_count == 3 + assert aioclient_mock.call_count == 1 + assert ( + config_entry.data["token"]["access_token"] + == SERVER_ACCESS_TOKEN["access_token"] + ) + + await client.add_events( + [ + EventMessage( + appliance.ha_id, + EventType.STATUS, + ArrayOfEvents( + [ + Event( + key=EventKey.BSH_COMMON_STATUS_DOOR_STATE, + raw_key=EventKey.BSH_COMMON_STATUS_DOOR_STATE.value, + timestamp=0, + level="", + handling="", + value=BSH_DOOR_STATE_OPEN, + ) + ], + ), + ), + ] + ) + await hass.async_block_till_done() + + assert hass.states.get("sensor.washer_door").state == "open" + + +@pytest.mark.parametrize("platforms", [("sensor",)]) +@pytest.mark.parametrize("appliance", ["Washer"], indirect=True) +async def test_event_listener_token_refresh_reauth_error( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + token_expiration_time: float, + aioclient_mock: AiohttpClientMocker, + client: MagicMock, + config_entry: MockConfigEntry, + integration_setup: Callable[[MagicMock], Awaitable[bool]], +) -> None: + """Test config entry reloads when the token refresh needs reauth.""" + stream_all_events = await _setup_with_token_refresh_on_connect( + client, config_entry, integration_setup + ) + # Setup kept the fixture token, so it expires at token_expiration_time + assert config_entry.data["token"]["expires_at"] == token_expiration_time + + aioclient_mock.post( + OAUTH2_TOKEN, + status=HTTPStatus.BAD_REQUEST, + json={"error": "invalid_grant"}, + ) + with patch.object( + ConfigEntries, + "async_schedule_reload", + ) as mock_schedule_reload: + await client.add_events([EventStreamInterruptedError()]) + await hass.async_block_till_done() + # Jump to 1 s after the token expires; this also fires the 10 s retry + freezer.move_to(dt_util.utc_from_timestamp(token_expiration_time + 1)) + async_fire_time_changed(hass) + await hass.async_block_till_done() + # Long past any retry delay: the stopped listener must not reconnect + async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1)) + await hass.async_block_till_done() + + assert stream_all_events.call_count == 2 + assert aioclient_mock.call_count == 1 + mock_schedule_reload.assert_called_once_with(config_entry.entry_id) + assert not config_entry._background_tasks + + flows_in_progress = hass.config_entries.flow.async_progress() + assert len(flows_in_progress) == 1 + assert flows_in_progress[0]["context"]["source"] == SOURCE_REAUTH + assert flows_in_progress[0]["context"]["entry_id"] == config_entry.entry_id + + @pytest.mark.parametrize("platforms", [("sensor",)]) @pytest.mark.parametrize("appliance", ["Washer"], indirect=True) @pytest.mark.parametrize( From 9cccaf6ef655102e7bd7a667cd529b4bc057e791 Mon Sep 17 00:00:00 2001 From: bkobus-bbx Date: Fri, 2 Oct 2026 09:23:21 +0200 Subject: [PATCH 340/356] Bump blebox-uniapi to v2.5.8 (#183968) Co-authored-by: Erwin Douna --- homeassistant/components/blebox/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/blebox/manifest.json b/homeassistant/components/blebox/manifest.json index 66198c59d7b4..c08543a31b1e 100644 --- a/homeassistant/components/blebox/manifest.json +++ b/homeassistant/components/blebox/manifest.json @@ -47,6 +47,6 @@ "iot_class": "local_polling", "loggers": ["blebox_uniapi"], "quality_scale": "gold", - "requirements": ["blebox-uniapi==2.5.7"], + "requirements": ["blebox-uniapi==2.5.8"], "zeroconf": ["_bbxsrv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 4f81bc0a3ad4..943a0119d740 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -691,7 +691,7 @@ bleak-smlight==1.1.0 bleak==3.0.2 # homeassistant.components.blebox -blebox-uniapi==2.5.7 +blebox-uniapi==2.5.8 # homeassistant.components.blink blinkpy==0.25.9 From 989c7a64a8f2ea7ac9a9e5c942ada2812b84417a Mon Sep 17 00:00:00 2001 From: bkobus-bbx Date: Mon, 19 Oct 2026 10:47:27 +0200 Subject: [PATCH 341/356] Bump blebox-uniapi to v2.5.9 (#187300) --- homeassistant/components/blebox/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/blebox/manifest.json b/homeassistant/components/blebox/manifest.json index c08543a31b1e..b468b0a6560d 100644 --- a/homeassistant/components/blebox/manifest.json +++ b/homeassistant/components/blebox/manifest.json @@ -47,6 +47,6 @@ "iot_class": "local_polling", "loggers": ["blebox_uniapi"], "quality_scale": "gold", - "requirements": ["blebox-uniapi==2.5.8"], + "requirements": ["blebox-uniapi==2.5.9"], "zeroconf": ["_bbxsrv._tcp.local."] } diff --git a/requirements_all.txt b/requirements_all.txt index 943a0119d740..5864c51dc6e6 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -691,7 +691,7 @@ bleak-smlight==1.1.0 bleak==3.0.2 # homeassistant.components.blebox -blebox-uniapi==2.5.8 +blebox-uniapi==2.5.9 # homeassistant.components.blink blinkpy==0.25.9 From eee16c70ef2b3452c6ef61846649f6cd18aa451e Mon Sep 17 00:00:00 2001 From: jameson_uk <1040621+jamesonuk@users.noreply.github.com> Date: Mon, 19 Oct 2026 18:40:56 +0100 Subject: [PATCH 342/356] Bump aioamazondevices to 16.8.1 (#187332) --- .../components/alexa_devices/binary_sensor.py | 2 +- .../components/alexa_devices/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/alexa_devices/const.py | 30 +++++++++++++++++++ .../snapshots/test_diagnostics.ambr | 12 ++++++++ .../snapshots/test_services.ambr | 24 +++++++++++++++ tests/components/alexa_devices/test_sensor.py | 6 ++++ 7 files changed, 75 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/alexa_devices/binary_sensor.py b/homeassistant/components/alexa_devices/binary_sensor.py index bd7b41c6d5d2..3675500d60f6 100644 --- a/homeassistant/components/alexa_devices/binary_sensor.py +++ b/homeassistant/components/alexa_devices/binary_sensor.py @@ -4,7 +4,7 @@ from collections.abc import Callable from dataclasses import dataclass from typing import Final, override -from aioamazondevices.const.metadata import SENSOR_STATE_OFF +from aioamazondevices.const.sensors import SENSOR_STATE_OFF from aioamazondevices.structures import AmazonDevice from homeassistant.components.binary_sensor import ( diff --git a/homeassistant/components/alexa_devices/manifest.json b/homeassistant/components/alexa_devices/manifest.json index f653fa1623c9..e0a430f839b2 100644 --- a/homeassistant/components/alexa_devices/manifest.json +++ b/homeassistant/components/alexa_devices/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aioamazondevices"], "quality_scale": "platinum", - "requirements": ["aioamazondevices==16.3.2"] + "requirements": ["aioamazondevices==16.8.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 5864c51dc6e6..23a3e5773020 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -190,7 +190,7 @@ aioairzone-cloud==0.7.2 aioairzone==1.0.5 # homeassistant.components.alexa_devices -aioamazondevices==16.3.2 +aioamazondevices==16.8.1 # homeassistant.components.ambient_network # homeassistant.components.ambient_station diff --git a/tests/components/alexa_devices/const.py b/tests/components/alexa_devices/const.py index c312419d7ca2..d0b36c244667 100644 --- a/tests/components/alexa_devices/const.py +++ b/tests/components/alexa_devices/const.py @@ -47,6 +47,9 @@ TEST_DEVICE_1 = AmazonDevice( error_msg=None, error_type=None, scale=None, + feature_name="dnd", + property_name="dnd", + instance="", ), "temperature": AmazonDeviceSensor( name="temperature", @@ -55,6 +58,9 @@ TEST_DEVICE_1 = AmazonDevice( error_msg=None, error_type=None, scale="CELSIUS", + feature_name="temperatureSensor", + property_name="temperature", + instance="1", ), }, notifications_supported=True, @@ -85,6 +91,7 @@ TEST_DEVICE_1 = AmazonDevice( "dropin": "All", }, voice_control_supported=True, + features={}, ) TEST_DEVICE_2_SN = "echo_test_2_serial_number" @@ -113,6 +120,9 @@ TEST_DEVICE_2 = AmazonDevice( error_msg=None, error_type=None, scale="CELSIUS", + feature_name="temperatureSensor", + property_name="temperature", + instance="1", ) }, notifications_supported=False, @@ -120,6 +130,7 @@ TEST_DEVICE_2 = AmazonDevice( media_player_supported=False, communication_settings={}, voice_control_supported=True, + features={}, ) TEST_DEVICE_AQM_SN = "aqm_test_serial_number" @@ -150,6 +161,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="%", + feature_name="range", + property_name="rangeValue", + instance="4", ), "VOC": AmazonDeviceSensor( name="VOC", @@ -158,6 +172,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale=None, + feature_name="range", + property_name="rangeValue", + instance="5", ), "PM25": AmazonDeviceSensor( name="PM25", @@ -166,6 +183,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="MicroGramsPerCubicMeter", + feature_name="range", + property_name="rangeValue", + instance="6", ), "PM10": AmazonDeviceSensor( name="PM10", @@ -174,6 +194,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="MicroGramsPerCubicMeter", + feature_name="range", + property_name="rangeValue", + instance="7", ), "CO": AmazonDeviceSensor( name="CO", @@ -182,6 +205,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="ppm", + feature_name="range", + property_name="rangeValue", + instance="8", ), "Air Quality": AmazonDeviceSensor( name="Air Quality", @@ -190,6 +216,9 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale=None, + feature_name="range", + property_name="rangeValue", + instance="9", ), }, notifications_supported=False, @@ -197,6 +226,7 @@ TEST_DEVICE_AQM = AmazonDevice( media_player_supported=False, communication_settings={}, voice_control_supported=False, + features={}, ) TEST_VOCAL_RECORD_INITIAL = AmazonVocalRecord( diff --git a/tests/components/alexa_devices/snapshots/test_diagnostics.ambr b/tests/components/alexa_devices/snapshots/test_diagnostics.ambr index ee115d6e6075..50dc655950a6 100644 --- a/tests/components/alexa_devices/snapshots/test_diagnostics.ambr +++ b/tests/components/alexa_devices/snapshots/test_diagnostics.ambr @@ -18,7 +18,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'dnd', + 'instance': '', 'name': 'dnd', + 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -27,7 +30,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'temperatureSensor', + 'instance': '1', 'name': 'temperature', + 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -59,7 +65,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'dnd', + 'instance': '', 'name': 'dnd', + 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -68,7 +77,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'temperatureSensor', + 'instance': '1', 'name': 'temperature', + 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', diff --git a/tests/components/alexa_devices/snapshots/test_services.ambr b/tests/components/alexa_devices/snapshots/test_services.ambr index c677a1acf424..bfd73776cdf4 100644 --- a/tests/components/alexa_devices/snapshots/test_services.ambr +++ b/tests/components/alexa_devices/snapshots/test_services.ambr @@ -22,6 +22,8 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', + 'features': dict({ + }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -56,7 +58,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'dnd', + 'instance': '', 'name': 'dnd', + 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -65,7 +70,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'temperatureSensor', + 'instance': '1', 'name': 'temperature', + 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -104,6 +112,8 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', + 'features': dict({ + }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -138,7 +148,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'dnd', + 'instance': '', 'name': 'dnd', + 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -147,7 +160,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'temperatureSensor', + 'instance': '1', 'name': 'temperature', + 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -186,6 +202,8 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', + 'features': dict({ + }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -220,7 +238,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'dnd', + 'instance': '', 'name': 'dnd', + 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -229,7 +250,10 @@ 'error': False, 'error_msg': None, 'error_type': None, + 'feature_name': 'temperatureSensor', + 'instance': '1', 'name': 'temperature', + 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', diff --git a/tests/components/alexa_devices/test_sensor.py b/tests/components/alexa_devices/test_sensor.py index 8171f4ae591d..03607b055a7e 100644 --- a/tests/components/alexa_devices/test_sensor.py +++ b/tests/components/alexa_devices/test_sensor.py @@ -178,6 +178,9 @@ async def test_unit_of_measurement( error_msg=None, error_type=None, scale=scale, + feature_name="sensor", + property_name="sensor", + instance="1", ) } @@ -208,6 +211,9 @@ async def test_sensor_unavailable( error_msg=None, error_type=None, scale=None, + feature_name="lightSensor", + property_name="illuminance", + instance="1", ) } From e7efed2449b5a6ad7b9d27f5d23c9f65404bc2dc Mon Sep 17 00:00:00 2001 From: G Johansson Date: Tue, 20 Oct 2026 21:08:40 +0200 Subject: [PATCH 343/356] Fix holiday category selector translations (#187606) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/holiday/strings.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/holiday/strings.json b/homeassistant/components/holiday/strings.json index a2c29e27ffeb..334e4c29c9b7 100644 --- a/homeassistant/components/holiday/strings.json +++ b/homeassistant/components/holiday/strings.json @@ -48,7 +48,7 @@ } }, "selector": { - "device_class": { + "categories": { "options": { "albanian": "Albanian", "armed_forces": "Armed forces", @@ -65,6 +65,7 @@ "hindu": "Hindu", "islamic": "Islamic", "optional": "Optional", + "optional_women": "Optional for women", "orthodox": "Orthodox", "protestant": "Protestant", "public": "Public", From 8ad8ff2c4afe697ab2aa334e977c5fa228ab16d8 Mon Sep 17 00:00:00 2001 From: Khole <29937485+KJonline@users.noreply.github.com> Date: Wed, 21 Oct 2026 06:42:54 +0100 Subject: [PATCH 344/356] Bump pyhive-integration to 1.0.10 (#187610) --- homeassistant/components/hive/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/hive/manifest.json b/homeassistant/components/hive/manifest.json index 5ebe678e73b2..7c9314d150d9 100644 --- a/homeassistant/components/hive/manifest.json +++ b/homeassistant/components/hive/manifest.json @@ -10,5 +10,5 @@ "integration_type": "hub", "iot_class": "cloud_polling", "loggers": ["apyhiveapi"], - "requirements": ["pyhive-integration==1.0.9"] + "requirements": ["pyhive-integration==1.0.10"] } diff --git a/requirements_all.txt b/requirements_all.txt index 23a3e5773020..6dcca576e000 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2292,7 +2292,7 @@ pyhelty==0.2.0 pyheos==1.0.6 # homeassistant.components.hive -pyhive-integration==1.0.9 +pyhive-integration==1.0.10 # homeassistant.components.homematic pyhomematic==0.1.78 From ee733f6c120ef06b5df2ccdb8d6ad10178660caf Mon Sep 17 00:00:00 2001 From: Robert Resch Date: Wed, 21 Oct 2026 16:29:56 +0200 Subject: [PATCH 345/356] Update uv to 0.13.4 (#187742) --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index f648cc1c6ef4..addba726fccf 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -72,7 +72,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.13.0 +uv==0.13.4 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 diff --git a/pyproject.toml b/pyproject.toml index f99d82ce730e..543049313576 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ dependencies = [ "typing-extensions>=4.16.0,<5.0", "ulid-transform==2.2.9", "urllib3>=2.0", - "uv==0.13.0", + "uv==0.13.4", "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", diff --git a/requirements.txt b/requirements.txt index ee3245bf542c..a64180483543 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,7 +57,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.13.0 +uv==0.13.4 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 From e207dc9be96f289a3d032c5f0ddd3d9989491538 Mon Sep 17 00:00:00 2001 From: Maximilian <43999966+DeerMaximum@users.noreply.github.com> Date: Thu, 22 Oct 2026 00:50:03 +0200 Subject: [PATCH 346/356] Bump pynina to 1.0.4 (#187868) --- homeassistant/components/nina/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/nina/manifest.json b/homeassistant/components/nina/manifest.json index 8792570c62b9..3558bbeb02b8 100644 --- a/homeassistant/components/nina/manifest.json +++ b/homeassistant/components/nina/manifest.json @@ -8,6 +8,6 @@ "iot_class": "cloud_polling", "loggers": ["pynina"], "quality_scale": "silver", - "requirements": ["pynina==1.0.3"], + "requirements": ["pynina==1.0.4"], "single_config_entry": true } diff --git a/requirements_all.txt b/requirements_all.txt index 6dcca576e000..85e4f905a7fc 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2445,7 +2445,7 @@ pynetgear==0.10.10 pynetio==0.1.9.1 # homeassistant.components.nina -pynina==1.0.3 +pynina==1.0.4 # homeassistant.components.nintendo_parental_controls pynintendoauth==1.0.3 From cceaf22a0177e7b923dfa0721807a9086f6deb70 Mon Sep 17 00:00:00 2001 From: jameson_uk <1040621+jamesonuk@users.noreply.github.com> Date: Thu, 22 Oct 2026 10:28:03 +0100 Subject: [PATCH 347/356] bump aioamazondevices to 16.9.1 (#187985) --- homeassistant/components/alexa_devices/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/alexa_devices/const.py | 3 +++ tests/components/alexa_devices/snapshots/test_services.ambr | 6 ++++++ 4 files changed, 11 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/alexa_devices/manifest.json b/homeassistant/components/alexa_devices/manifest.json index e0a430f839b2..fe89fa4a1c4b 100644 --- a/homeassistant/components/alexa_devices/manifest.json +++ b/homeassistant/components/alexa_devices/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aioamazondevices"], "quality_scale": "platinum", - "requirements": ["aioamazondevices==16.8.1"] + "requirements": ["aioamazondevices==16.9.1"] } diff --git a/requirements_all.txt b/requirements_all.txt index 85e4f905a7fc..5da2263dd7aa 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -190,7 +190,7 @@ aioairzone-cloud==0.7.2 aioairzone==1.0.5 # homeassistant.components.alexa_devices -aioamazondevices==16.8.1 +aioamazondevices==16.9.1 # homeassistant.components.ambient_network # homeassistant.components.ambient_station diff --git a/tests/components/alexa_devices/const.py b/tests/components/alexa_devices/const.py index d0b36c244667..f524b68c69bb 100644 --- a/tests/components/alexa_devices/const.py +++ b/tests/components/alexa_devices/const.py @@ -92,6 +92,7 @@ TEST_DEVICE_1 = AmazonDevice( }, voice_control_supported=True, features={}, + unsupported_features={}, ) TEST_DEVICE_2_SN = "echo_test_2_serial_number" @@ -131,6 +132,7 @@ TEST_DEVICE_2 = AmazonDevice( communication_settings={}, voice_control_supported=True, features={}, + unsupported_features={}, ) TEST_DEVICE_AQM_SN = "aqm_test_serial_number" @@ -227,6 +229,7 @@ TEST_DEVICE_AQM = AmazonDevice( communication_settings={}, voice_control_supported=False, features={}, + unsupported_features={}, ) TEST_VOCAL_RECORD_INITIAL = AmazonVocalRecord( diff --git a/tests/components/alexa_devices/snapshots/test_services.ambr b/tests/components/alexa_devices/snapshots/test_services.ambr index bfd73776cdf4..7fd552a8277a 100644 --- a/tests/components/alexa_devices/snapshots/test_services.ambr +++ b/tests/components/alexa_devices/snapshots/test_services.ambr @@ -81,6 +81,8 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', + 'unsupported_features': dict({ + }), 'voice_control_supported': True, }), 'Alexa.Joke.Play', @@ -171,6 +173,8 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', + 'unsupported_features': dict({ + }), 'voice_control_supported': True, }), 'bell_02', @@ -261,6 +265,8 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', + 'unsupported_features': dict({ + }), 'voice_control_supported': True, }), 'Play B.B.C. radio on TuneIn', From 3debc8ae6656933b5163ab465b708173c3c7d840 Mon Sep 17 00:00:00 2001 From: NANI <9637751+AndyTempel@users.noreply.github.com> Date: Fri, 23 Oct 2026 01:15:27 +0200 Subject: [PATCH 348/356] Bump victron-vrm to 0.1.14 (#188016) --- .../components/victron_remote_monitoring/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/victron_remote_monitoring/manifest.json b/homeassistant/components/victron_remote_monitoring/manifest.json index bacc2c499e8c..a88c20c5fdb2 100644 --- a/homeassistant/components/victron_remote_monitoring/manifest.json +++ b/homeassistant/components/victron_remote_monitoring/manifest.json @@ -7,5 +7,5 @@ "integration_type": "service", "iot_class": "cloud_polling", "quality_scale": "bronze", - "requirements": ["victron-vrm==0.1.13"] + "requirements": ["victron-vrm==0.1.14"] } diff --git a/requirements_all.txt b/requirements_all.txt index 5da2263dd7aa..38a4c0335e47 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -3382,7 +3382,7 @@ victron-ble-ha-parser==0.8.0 victron-mqtt==2026.9.5 # homeassistant.components.victron_remote_monitoring -victron-vrm==0.1.13 +victron-vrm==0.1.14 # homeassistant.components.vilfo vilfo-api-client==0.5.0 From 2ffb7996374257aebfb24988b8feb2a29882c9b7 Mon Sep 17 00:00:00 2001 From: Robert Resch Date: Fri, 23 Oct 2026 16:53:48 +0200 Subject: [PATCH 349/356] Bump base image to 2026.10.1 (#188204) --- .github/workflows/builder.yml | 2 +- .python-version | 2 +- script/hassfest/docker/Dockerfile | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/builder.yml b/.github/workflows/builder.yml index 70bb0c1ee411..78f6a237d035 100644 --- a/.github/workflows/builder.yml +++ b/.github/workflows/builder.yml @@ -15,7 +15,7 @@ env: UV_SYSTEM_PYTHON: "true" # Base image version from https://github.com/home-assistant/docker # If python version changes in the base image, update .python-version accordingly to match the new Python version. - BASE_IMAGE_VERSION: "2026.10.0" + BASE_IMAGE_VERSION: "2026.10.1" ARCHITECTURES: '["amd64", "aarch64"]' MACHINES: >- ["generic-x86-64", "khadas-vim3", "odroid-c2", "odroid-c4", "odroid-m1", diff --git a/.python-version b/.python-version index 9b8fe2fbb856..70c445ec1564 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.14.8 +3.14.9 diff --git a/script/hassfest/docker/Dockerfile b/script/hassfest/docker/Dockerfile index 5c5c2246bfad..6efaf320c130 100644 --- a/script/hassfest/docker/Dockerfile +++ b/script/hassfest/docker/Dockerfile @@ -2,7 +2,7 @@ # Automatically generated by hassfest. # # To update, run python3 -m script.hassfest -p docker -FROM python:3.14.8-alpine +FROM python:3.14.9-alpine ENV \ UV_SYSTEM_PYTHON=true \ From ca9f1fd81139212c226d102538fd50df9ce6e402 Mon Sep 17 00:00:00 2001 From: Bram Kragten Date: Fri, 23 Oct 2026 16:41:57 +0200 Subject: [PATCH 350/356] Update frontend to 20260930.5 (#188206) --- homeassistant/components/frontend/manifest.json | 2 +- homeassistant/package_constraints.txt | 2 +- pylint/plugins/pylint_home_assistant/generated/mdi_icons.py | 2 +- requirements_all.txt | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/frontend/manifest.json b/homeassistant/components/frontend/manifest.json index 873ade3dd9cd..2d6c7a90e113 100644 --- a/homeassistant/components/frontend/manifest.json +++ b/homeassistant/components/frontend/manifest.json @@ -22,5 +22,5 @@ "integration_type": "system", "preview_features": { "winter_mode": {} }, "quality_scale": "internal", - "requirements": ["home-assistant-frontend==20260930.4"] + "requirements": ["home-assistant-frontend==20260930.5"] } diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index addba726fccf..f4d7d5c01497 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -40,7 +40,7 @@ habluetooth==7.1.2 hass-nabucasa==2.7.0 hassil==3.12.1 home-assistant-bluetooth==2.0.0 -home-assistant-frontend==20260930.4 +home-assistant-frontend==20260930.5 home-assistant-intents==2026.10.6 httpx==0.28.1 ifaddr==0.2.0 diff --git a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py index 387e1de7f35e..5a8db09d1969 100644 --- a/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py +++ b/pylint/plugins/pylint_home_assistant/generated/mdi_icons.py @@ -5,7 +5,7 @@ To update, run python3 -m script.hassfest from typing import Final -FRONTEND_VERSION: Final[str] = "20260930.4" +FRONTEND_VERSION: Final[str] = "20260930.5" MDI_ICONS: Final[set[str]] = { "ab-testing", diff --git a/requirements_all.txt b/requirements_all.txt index 38a4c0335e47..ce3952d85477 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -1315,7 +1315,7 @@ hole==0.9.2 holidays==0.106 # homeassistant.components.frontend -home-assistant-frontend==20260930.4 +home-assistant-frontend==20260930.5 # homeassistant.components.conversation home-assistant-intents==2026.10.6 From a78f627dba73de9876e05a587c4de2361cc3428c Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Fri, 23 Oct 2026 16:32:44 +0200 Subject: [PATCH 351/356] Update uv to 0.13.5 (#188208) Co-authored-by: Robert Resch --- homeassistant/package_constraints.txt | 2 +- pyproject.toml | 2 +- requirements.txt | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/homeassistant/package_constraints.txt b/homeassistant/package_constraints.txt index f4d7d5c01497..c217ab3fd4f4 100644 --- a/homeassistant/package_constraints.txt +++ b/homeassistant/package_constraints.txt @@ -72,7 +72,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.13.4 +uv==0.13.5 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 diff --git a/pyproject.toml b/pyproject.toml index 543049313576..2b555ea06e0a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -77,7 +77,7 @@ dependencies = [ "typing-extensions>=4.16.0,<5.0", "ulid-transform==2.2.9", "urllib3>=2.0", - "uv==0.13.4", + "uv==0.13.5", "probatio==0.13.0", "yarl==1.25.1", "webrtc-models==0.3.0", diff --git a/requirements.txt b/requirements.txt index a64180483543..6dbd2efbd0b0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -57,7 +57,7 @@ standard-telnetlib==3.13.0 typing-extensions>=4.16.0,<5.0 ulid-transform==2.2.9 urllib3>=2.0 -uv==0.13.4 +uv==0.13.5 webrtc-models==0.3.0 yarl==1.25.1 zeroconf==0.151.5 From 9d248190a7ba7e569db9a53dbc82146977b08c36 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 23 Oct 2026 18:04:02 +0000 Subject: [PATCH 352/356] Bump version to 2026.10.3 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index e65cc0f31e60..bd6b29a28f58 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "2" +PATCH_VERSION: Final = "3" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 2b555ea06e0a..4270bc455990 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.2" +version = "2026.10.3" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 0ae3fd87efea197fa158c99d646d4e1ec0475941 Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Fri, 23 Oct 2026 18:15:09 +0000 Subject: [PATCH 353/356] Revert aioamazondevices bumps to 16.8.1 and 16.9.1 This reverts #187332 and #187985 from the 2026.10 release branch. Since 16.4.0, aioamazondevices requires orjson>=3.13.0, which conflicts with the orjson==3.11.9 pin on this branch. --- .../components/alexa_devices/binary_sensor.py | 2 +- .../components/alexa_devices/manifest.json | 2 +- requirements_all.txt | 2 +- tests/components/alexa_devices/const.py | 33 ------------------- .../snapshots/test_diagnostics.ambr | 12 ------- .../snapshots/test_services.ambr | 30 ----------------- tests/components/alexa_devices/test_sensor.py | 6 ---- 7 files changed, 3 insertions(+), 84 deletions(-) diff --git a/homeassistant/components/alexa_devices/binary_sensor.py b/homeassistant/components/alexa_devices/binary_sensor.py index 3675500d60f6..bd7b41c6d5d2 100644 --- a/homeassistant/components/alexa_devices/binary_sensor.py +++ b/homeassistant/components/alexa_devices/binary_sensor.py @@ -4,7 +4,7 @@ from collections.abc import Callable from dataclasses import dataclass from typing import Final, override -from aioamazondevices.const.sensors import SENSOR_STATE_OFF +from aioamazondevices.const.metadata import SENSOR_STATE_OFF from aioamazondevices.structures import AmazonDevice from homeassistant.components.binary_sensor import ( diff --git a/homeassistant/components/alexa_devices/manifest.json b/homeassistant/components/alexa_devices/manifest.json index fe89fa4a1c4b..f653fa1623c9 100644 --- a/homeassistant/components/alexa_devices/manifest.json +++ b/homeassistant/components/alexa_devices/manifest.json @@ -8,5 +8,5 @@ "iot_class": "cloud_polling", "loggers": ["aioamazondevices"], "quality_scale": "platinum", - "requirements": ["aioamazondevices==16.9.1"] + "requirements": ["aioamazondevices==16.3.2"] } diff --git a/requirements_all.txt b/requirements_all.txt index ce3952d85477..14379fccafae 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -190,7 +190,7 @@ aioairzone-cloud==0.7.2 aioairzone==1.0.5 # homeassistant.components.alexa_devices -aioamazondevices==16.9.1 +aioamazondevices==16.3.2 # homeassistant.components.ambient_network # homeassistant.components.ambient_station diff --git a/tests/components/alexa_devices/const.py b/tests/components/alexa_devices/const.py index f524b68c69bb..c312419d7ca2 100644 --- a/tests/components/alexa_devices/const.py +++ b/tests/components/alexa_devices/const.py @@ -47,9 +47,6 @@ TEST_DEVICE_1 = AmazonDevice( error_msg=None, error_type=None, scale=None, - feature_name="dnd", - property_name="dnd", - instance="", ), "temperature": AmazonDeviceSensor( name="temperature", @@ -58,9 +55,6 @@ TEST_DEVICE_1 = AmazonDevice( error_msg=None, error_type=None, scale="CELSIUS", - feature_name="temperatureSensor", - property_name="temperature", - instance="1", ), }, notifications_supported=True, @@ -91,8 +85,6 @@ TEST_DEVICE_1 = AmazonDevice( "dropin": "All", }, voice_control_supported=True, - features={}, - unsupported_features={}, ) TEST_DEVICE_2_SN = "echo_test_2_serial_number" @@ -121,9 +113,6 @@ TEST_DEVICE_2 = AmazonDevice( error_msg=None, error_type=None, scale="CELSIUS", - feature_name="temperatureSensor", - property_name="temperature", - instance="1", ) }, notifications_supported=False, @@ -131,8 +120,6 @@ TEST_DEVICE_2 = AmazonDevice( media_player_supported=False, communication_settings={}, voice_control_supported=True, - features={}, - unsupported_features={}, ) TEST_DEVICE_AQM_SN = "aqm_test_serial_number" @@ -163,9 +150,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="%", - feature_name="range", - property_name="rangeValue", - instance="4", ), "VOC": AmazonDeviceSensor( name="VOC", @@ -174,9 +158,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale=None, - feature_name="range", - property_name="rangeValue", - instance="5", ), "PM25": AmazonDeviceSensor( name="PM25", @@ -185,9 +166,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="MicroGramsPerCubicMeter", - feature_name="range", - property_name="rangeValue", - instance="6", ), "PM10": AmazonDeviceSensor( name="PM10", @@ -196,9 +174,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="MicroGramsPerCubicMeter", - feature_name="range", - property_name="rangeValue", - instance="7", ), "CO": AmazonDeviceSensor( name="CO", @@ -207,9 +182,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale="ppm", - feature_name="range", - property_name="rangeValue", - instance="8", ), "Air Quality": AmazonDeviceSensor( name="Air Quality", @@ -218,9 +190,6 @@ TEST_DEVICE_AQM = AmazonDevice( error_msg=None, error_type=None, scale=None, - feature_name="range", - property_name="rangeValue", - instance="9", ), }, notifications_supported=False, @@ -228,8 +197,6 @@ TEST_DEVICE_AQM = AmazonDevice( media_player_supported=False, communication_settings={}, voice_control_supported=False, - features={}, - unsupported_features={}, ) TEST_VOCAL_RECORD_INITIAL = AmazonVocalRecord( diff --git a/tests/components/alexa_devices/snapshots/test_diagnostics.ambr b/tests/components/alexa_devices/snapshots/test_diagnostics.ambr index 50dc655950a6..ee115d6e6075 100644 --- a/tests/components/alexa_devices/snapshots/test_diagnostics.ambr +++ b/tests/components/alexa_devices/snapshots/test_diagnostics.ambr @@ -18,10 +18,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'dnd', - 'instance': '', 'name': 'dnd', - 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -30,10 +27,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'temperatureSensor', - 'instance': '1', 'name': 'temperature', - 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -65,10 +59,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'dnd', - 'instance': '', 'name': 'dnd', - 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -77,10 +68,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'temperatureSensor', - 'instance': '1', 'name': 'temperature', - 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', diff --git a/tests/components/alexa_devices/snapshots/test_services.ambr b/tests/components/alexa_devices/snapshots/test_services.ambr index 7fd552a8277a..c677a1acf424 100644 --- a/tests/components/alexa_devices/snapshots/test_services.ambr +++ b/tests/components/alexa_devices/snapshots/test_services.ambr @@ -22,8 +22,6 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', - 'features': dict({ - }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -58,10 +56,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'dnd', - 'instance': '', 'name': 'dnd', - 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -70,10 +65,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'temperatureSensor', - 'instance': '1', 'name': 'temperature', - 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -81,8 +73,6 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', - 'unsupported_features': dict({ - }), 'voice_control_supported': True, }), 'Alexa.Joke.Play', @@ -114,8 +104,6 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', - 'features': dict({ - }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -150,10 +138,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'dnd', - 'instance': '', 'name': 'dnd', - 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -162,10 +147,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'temperatureSensor', - 'instance': '1', 'name': 'temperature', - 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -173,8 +155,6 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', - 'unsupported_features': dict({ - }), 'voice_control_supported': True, }), 'bell_02', @@ -206,8 +186,6 @@ 'device_type': 'echo', 'endpoint_id': 'G1234567890123456789012345678A', 'entity_id': '11111111-2222-3333-4444-555555555555', - 'features': dict({ - }), 'hardware_version': '1.0', 'household_device': False, 'manufacturer': 'Test manufacturer', @@ -242,10 +220,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'dnd', - 'instance': '', 'name': 'dnd', - 'property_name': 'dnd', 'scale': None, 'time_of_sample': None, 'value': False, @@ -254,10 +229,7 @@ 'error': False, 'error_msg': None, 'error_type': None, - 'feature_name': 'temperatureSensor', - 'instance': '1', 'name': 'temperature', - 'property_name': 'temperature', 'scale': 'CELSIUS', 'time_of_sample': None, 'value': '22.5', @@ -265,8 +237,6 @@ }), 'serial_number': 'echo_test_serial_number', 'software_version': 'echo_test_software_version', - 'unsupported_features': dict({ - }), 'voice_control_supported': True, }), 'Play B.B.C. radio on TuneIn', diff --git a/tests/components/alexa_devices/test_sensor.py b/tests/components/alexa_devices/test_sensor.py index 03607b055a7e..8171f4ae591d 100644 --- a/tests/components/alexa_devices/test_sensor.py +++ b/tests/components/alexa_devices/test_sensor.py @@ -178,9 +178,6 @@ async def test_unit_of_measurement( error_msg=None, error_type=None, scale=scale, - feature_name="sensor", - property_name="sensor", - instance="1", ) } @@ -211,9 +208,6 @@ async def test_sensor_unavailable( error_msg=None, error_type=None, scale=None, - feature_name="lightSensor", - property_name="illuminance", - instance="1", ) } From 835c742460b2acb4b6c666c50fe8f44371eaae4d Mon Sep 17 00:00:00 2001 From: MichaelMKKelly <100048727+MichaelMKKelly@users.noreply.github.com> Date: Sat, 24 Oct 2026 18:20:25 +0100 Subject: [PATCH 354/356] Raise aiohttp client header limits to 64 KiB (#188329) --- homeassistant/helpers/aiohttp_client.py | 7 +++++++ tests/helpers/test_aiohttp_client.py | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/homeassistant/helpers/aiohttp_client.py b/homeassistant/helpers/aiohttp_client.py index 2529005c293a..f2aa3a335c1f 100644 --- a/homeassistant/helpers/aiohttp_client.py +++ b/homeassistant/helpers/aiohttp_client.py @@ -157,6 +157,10 @@ async def _async_is_blocked_host( MAXIMUM_CONNECTIONS = 4096 MAXIMUM_CONNECTIONS_PER_HOST = 100 +# aiohttp's 8190 byte default is too small for some servers, e.g. GitHub's +# release download redirects carry a ~9 KiB Content-Security-Policy header. +MAXIMUM_HEADER_SIZE = 65536 + class HassAsyncDNSResolver(AsyncDualMDNSResolver): """Home Assistant AsyncDNSResolver. @@ -290,6 +294,9 @@ def _async_create_clientsession( *kwargs.pop("middlewares", ()), ) + kwargs.setdefault("max_line_size", MAXIMUM_HEADER_SIZE) + kwargs.setdefault("max_field_size", MAXIMUM_HEADER_SIZE) + clientsession = aiohttp.ClientSession( connector=_async_get_connector(hass, verify_ssl, family, ssl_cipher), json_serialize=json_dumps, diff --git a/tests/helpers/test_aiohttp_client.py b/tests/helpers/test_aiohttp_client.py index e763ad208c4e..3b343db7204c 100644 --- a/tests/helpers/test_aiohttp_client.py +++ b/tests/helpers/test_aiohttp_client.py @@ -690,3 +690,22 @@ async def test_redirect_to_blocked_address( pytest.raises(client.SSRFRedirectError), ): await session.get(redirect_url) + + +@pytest.mark.usefixtures("socket_enabled") +async def test_clientsession_accepts_large_headers(hass: HomeAssistant) -> None: + """Test the clientsession reads header fields larger than aiohttp's default limit.""" + large_value = "x" * 9300 + + async def handler(request: web.Request) -> web.Response: + """Return a response with a header field larger than 8190 bytes.""" + return web.Response(text="ok", headers={"Content-Security-Policy": large_value}) + + app = web.Application() + app.router.add_get("/", handler) + + async with TestServer(app) as server: + session = client.async_get_clientsession(hass) + async with session.get(server.make_url("/")) as resp: + assert resp.status == 200 + assert resp.headers["Content-Security-Policy"] == large_value From 2319fcf0dbe1f5bd8a2e411f666a7acd09edba5a Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sat, 24 Oct 2026 17:48:17 +0000 Subject: [PATCH 355/356] Bump version to 2026.10.4 --- homeassistant/const.py | 2 +- pyproject.toml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/const.py b/homeassistant/const.py index bd6b29a28f58..6c40cc8d464b 100644 --- a/homeassistant/const.py +++ b/homeassistant/const.py @@ -23,7 +23,7 @@ if TYPE_CHECKING: APPLICATION_NAME: Final = "HomeAssistant" MAJOR_VERSION: Final = 2026 MINOR_VERSION: Final = 10 -PATCH_VERSION: Final = "3" +PATCH_VERSION: Final = "4" __short_version__: Final = f"{MAJOR_VERSION}.{MINOR_VERSION}" __version__: Final = f"{__short_version__}.{PATCH_VERSION}" REQUIRED_PYTHON_VER: Final[tuple[int, int, int]] = (3, 14, 2) diff --git a/pyproject.toml b/pyproject.toml index 4270bc455990..e205844f9dbe 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "homeassistant" -version = "2026.10.3" +version = "2026.10.4" license = "Apache-2.0" license-files = ["LICENSE*", "homeassistant/backports/LICENSE*"] description = "Open-source home automation platform running on Python 3." From 4649568158a14d8acced1ed44e3b61bf15b769b1 Mon Sep 17 00:00:00 2001 From: TheJulianJES Date: Sat, 24 Oct 2026 21:03:24 +0200 Subject: [PATCH 356/356] Bump pylutron-caseta to 0.30.0 (#188388) --- homeassistant/components/lutron_caseta/manifest.json | 2 +- requirements_all.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/lutron_caseta/manifest.json b/homeassistant/components/lutron_caseta/manifest.json index f6bba1ab2a34..d0c203cccb4b 100644 --- a/homeassistant/components/lutron_caseta/manifest.json +++ b/homeassistant/components/lutron_caseta/manifest.json @@ -10,7 +10,7 @@ "integration_type": "hub", "iot_class": "local_push", "loggers": ["pylutron_caseta"], - "requirements": ["pylutron-caseta==0.29.0"], + "requirements": ["pylutron-caseta==0.30.0"], "zeroconf": [ { "properties": { diff --git a/requirements_all.txt b/requirements_all.txt index 14379fccafae..5c0da0127012 100644 --- a/requirements_all.txt +++ b/requirements_all.txt @@ -2397,7 +2397,7 @@ pylitejet==0.6.3 pylitterbot==2025.6.5 # homeassistant.components.lutron_caseta -pylutron-caseta==0.29.0 +pylutron-caseta==0.30.0 # homeassistant.components.lutron pylutron==0.4.4