From 79c7920475eafac150d28a7433fb7613451e2f0b Mon Sep 17 00:00:00 2001 From: Shay Levy <1858925+thecode@users.noreply.github.com> Date: Wed, 2 Dec 2026 01:36:06 +0200 Subject: [PATCH] Track webOS TV host changes from SSDP announcements (#195896) Co-authored-by: Claude Opus 5.5 --- homeassistant/components/webostv/__init__.py | 36 +++++- .../components/webostv/manifest.json | 1 + tests/components/webostv/conftest.py | 17 +++ tests/components/webostv/test_init.py | 117 +++++++++++++++++- 4 files changed, 168 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/webostv/__init__.py b/homeassistant/components/webostv/__init__.py index 4ca18e80a698..985c2220a30b 100644 --- a/homeassistant/components/webostv/__init__.py +++ b/homeassistant/components/webostv/__init__.py @@ -1,8 +1,10 @@ """The LG webOS TV integration.""" +from urllib.parse import urlparse + from aiowebostv import WebOsClient -from homeassistant.components import notify as hass_notify +from homeassistant.components import notify as hass_notify, ssdp from homeassistant.const import ( ATTR_CONFIG_ENTRY_ID, CONF_CLIENT_SECRET, @@ -14,6 +16,7 @@ from homeassistant.const import ( from homeassistant.core import Event, HomeAssistant from homeassistant.helpers import config_validation as cv, discovery from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo from homeassistant.helpers.typing import ConfigType from .const import DOMAIN, PLATFORMS @@ -40,6 +43,37 @@ async def async_setup_entry(hass: HomeAssistant, entry: WebOsTvConfigEntry) -> N await coordinator.async_config_entry_first_refresh() await client.register_state_update_callback(coordinator.async_handle_update) + udn = f"uuid:{entry.unique_id}" + + async def _async_ssdp_update( + _discovery_info: SsdpServiceInfo, change: ssdp.SsdpChange + ) -> None: + """Update the host when the TV announces a new address.""" + if change is ssdp.SsdpChange.BYEBYE: + return + # Headers are cached per service type and may hold an old location, + # so use the most recently received one. + latest = max( + await ssdp.async_get_discovery_info_by_udn(hass, udn), + key=lambda info: info.ssdp_headers["_timestamp"], + default=None, + ) + if latest is None or not latest.ssdp_location: + return + host = urlparse(latest.ssdp_location).hostname + if not host or host == entry.data[CONF_HOST]: + return + hass.config_entries.async_update_entry( + entry, data={**entry.data, CONF_HOST: host} + ) + hass.config_entries.async_schedule_reload(entry.entry_id) + + # Match on the UDN, as the discovery flow only sees the location change + # if the TV first announces it for the webOS service type. + entry.async_on_unload( + await ssdp.async_register_callback(hass, _async_ssdp_update, {"_udn": udn}) + ) + await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) # set up notify platform, no entry support for notify component yet, diff --git a/homeassistant/components/webostv/manifest.json b/homeassistant/components/webostv/manifest.json index 1cd6efecab87..17fb21443430 100644 --- a/homeassistant/components/webostv/manifest.json +++ b/homeassistant/components/webostv/manifest.json @@ -5,6 +5,7 @@ "codeowners": ["@thecode"], "config_flow": true, "connectivity": ["network"], + "dependencies": ["ssdp"], "documentation": "https://www.home-assistant.io/integrations/webostv", "integration_type": "device", "iot_class": "local_push", diff --git a/tests/components/webostv/conftest.py b/tests/components/webostv/conftest.py index eb2391d928dd..dca3bdb03450 100644 --- a/tests/components/webostv/conftest.py +++ b/tests/components/webostv/conftest.py @@ -19,6 +19,23 @@ from .const import ( ) +@pytest.fixture(autouse=True) +def ssdp_scanner_mock() -> Generator[MagicMock]: + """Mock the SSDP scanner.""" + with patch("homeassistant.components.ssdp.Scanner", autospec=True) as mock_scanner: + mock_scanner.return_value.async_register_callback.return_value = Mock( + return_value=None + ) + yield mock_scanner.return_value + + +@pytest.fixture(autouse=True) +def ssdp_server_mock() -> Generator[None]: + """Mock the SSDP server.""" + with patch("homeassistant.components.ssdp.Server", autospec=True): + yield + + @pytest.fixture def mock_setup_entry() -> Generator[AsyncMock]: """Override async_setup_entry.""" diff --git a/tests/components/webostv/test_init.py b/tests/components/webostv/test_init.py index ed93047d0612..8102d9753dad 100644 --- a/tests/components/webostv/test_init.py +++ b/tests/components/webostv/test_init.py @@ -1,15 +1,39 @@ """The tests for the LG webOS TV platform.""" +from datetime import datetime +from unittest.mock import MagicMock + from aiowebostv import WebOsTvPairError +import pytest from homeassistant.components.media_player import ATTR_INPUT_SOURCE_LIST +from homeassistant.components.ssdp import SsdpChange from homeassistant.components.webostv.const import CONF_SOURCES, DOMAIN from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState -from homeassistant.const import CONF_CLIENT_SECRET, EVENT_HOMEASSISTANT_STOP +from homeassistant.const import CONF_CLIENT_SECRET, CONF_HOST, EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant +from homeassistant.helpers.service_info.ssdp import ATTR_UPNP_UDN, SsdpServiceInfo from . import setup_webostv -from .const import ENTITY_ID +from .const import ENTITY_ID, FAKE_UUID, HOST + +NEW_HOST = "1.2.3.5" +WEBOS_ST = "urn:lge-com:service:webos-second-screen:1" +OLD_TIME = datetime(2026, 12, 1, 10, 0, 0) +NEW_TIME = datetime(2026, 12, 1, 10, 5, 0) + + +def _ssdp_info( + location: str | None, timestamp: datetime = NEW_TIME, st: str = "upnp:rootdevice" +) -> SsdpServiceInfo: + """Return SSDP discovery info for the TV.""" + return SsdpServiceInfo( + ssdp_usn=f"uuid:{FAKE_UUID}::{st}", + ssdp_st=st, + ssdp_location=location, + ssdp_headers={"_timestamp": timestamp}, + upnp={ATTR_UPNP_UDN: f"uuid:{FAKE_UUID}"}, + ) async def test_reauth_setup_entry(hass: HomeAssistant, client) -> None: @@ -77,3 +101,92 @@ async def test_disconnect_on_stop(hass: HomeAssistant, client) -> None: assert client.disconnect.call_count == 1 assert client.clear_state_update_callbacks.call_count == 1 assert config_entry.state is ConfigEntryState.LOADED + + +@pytest.mark.parametrize("change", [SsdpChange.ALIVE, SsdpChange.UPDATE]) +async def test_ssdp_host_update( + hass: HomeAssistant, + client: MagicMock, + ssdp_scanner_mock: MagicMock, + change: SsdpChange, +) -> None: + """Test the host is updated from the most recent SSDP location.""" + # Service types not yet seen at the new address keep the old location + ssdp_scanner_mock.async_get_discovery_info_by_udn.return_value = [ + _ssdp_info(f"http://{HOST}:1026/", OLD_TIME, WEBOS_ST), + _ssdp_info(f"http://{NEW_HOST}:1026/", NEW_TIME), + _ssdp_info(f"http://{HOST}:1026/", OLD_TIME), + ] + entry = await setup_webostv(hass) + + register_callback = ssdp_scanner_mock.async_register_callback + register_callback.assert_awaited_once() + assert register_callback.call_args.args[1] == {"_udn": f"uuid:{FAKE_UUID}"} + + await register_callback.call_args.args[0].target( + _ssdp_info(f"http://{HOST}:1026/", OLD_TIME, WEBOS_ST), change + ) + await hass.async_block_till_done() + + assert entry.state is ConfigEntryState.LOADED + assert entry.data[CONF_HOST] == NEW_HOST + assert client.disconnect.call_count == 1 + ssdp_scanner_mock.async_get_discovery_info_by_udn.assert_awaited_with( + f"uuid:{FAKE_UUID}" + ) + # Reload registered a new callback and unregistered the old one + assert register_callback.await_count == 2 + assert register_callback.return_value.call_count == 1 + + # Replaying the stale cached location after the reload keeps the new host + await register_callback.call_args.args[0].target( + _ssdp_info(f"http://{HOST}:1026/", OLD_TIME, WEBOS_ST), SsdpChange.ALIVE + ) + await hass.async_block_till_done() + + assert entry.data[CONF_HOST] == NEW_HOST + assert client.disconnect.call_count == 1 + assert register_callback.await_count == 2 + + +@pytest.mark.parametrize( + ("cached", "change"), + [ + pytest.param( + [ + _ssdp_info(f"http://{NEW_HOST}:1026/", OLD_TIME), + _ssdp_info(f"http://{HOST}:1026/", NEW_TIME, WEBOS_ST), + ], + SsdpChange.ALIVE, + id="latest_is_same_host", + ), + pytest.param( + [_ssdp_info(f"http://{NEW_HOST}:1026/")], + SsdpChange.BYEBYE, + id="byebye", + ), + pytest.param([_ssdp_info(None)], SsdpChange.ALIVE, id="no_location"), + pytest.param([], SsdpChange.ALIVE, id="not_cached"), + ], +) +async def test_ssdp_host_not_updated( + hass: HomeAssistant, + client: MagicMock, + ssdp_scanner_mock: MagicMock, + cached: list[SsdpServiceInfo], + change: SsdpChange, +) -> None: + """Test SSDP messages that must not update the host.""" + ssdp_scanner_mock.async_get_discovery_info_by_udn.return_value = cached + entry = await setup_webostv(hass) + + register_callback = ssdp_scanner_mock.async_register_callback + await register_callback.call_args.args[0].target( + _ssdp_info(f"http://{NEW_HOST}:1026/"), change + ) + await hass.async_block_till_done() + + assert entry.data[CONF_HOST] == HOST + assert client.disconnect.call_count == 0 + assert register_callback.await_count == 1 + assert register_callback.return_value.call_count == 0