mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Refuse LibreSync hubs built on the LS10 module (#191309)
This commit is contained in:
@@ -1,34 +1,76 @@
|
||||
"""The LibreSync integration."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
|
||||
from aiolibresync import DeviceState, LibreSyncClient, NotConnectedError
|
||||
from aiolibresync import (
|
||||
DeviceState,
|
||||
LibreSyncClient,
|
||||
LssdpInfo,
|
||||
NotConnectedError,
|
||||
async_query_lssdp,
|
||||
)
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_HOST, Platform
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.exceptions import ConfigEntryError, ConfigEntryNotReady
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
|
||||
from .const import CONNECT_TIMEOUT, DOMAIN, MANUFACTURER
|
||||
from .const import CONNECT_TIMEOUT, DOMAIN, MANUFACTURER, UNSUPPORTED_MODULES
|
||||
|
||||
PLATFORMS: list[Platform] = [Platform.MEDIA_PLAYER]
|
||||
|
||||
type LibreSyncConfigEntry = ConfigEntry[LibreSyncClient]
|
||||
|
||||
|
||||
def unsupported_module(info: LssdpInfo | None) -> str | None:
|
||||
"""Return the module LSSDP named if this integration cannot drive it.
|
||||
|
||||
A hub that did not answer on LSSDP is not refused: None means unknown.
|
||||
"""
|
||||
if info is not None and info.module in UNSUPPORTED_MODULES:
|
||||
return info.module
|
||||
return None
|
||||
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: LibreSyncConfigEntry) -> None:
|
||||
"""Set up LibreSync from a config entry."""
|
||||
client = LibreSyncClient(entry.data[CONF_HOST])
|
||||
host = entry.data[CONF_HOST]
|
||||
client = LibreSyncClient(host)
|
||||
# The module is asked alongside the connection, so a hub that is down waits
|
||||
# no longer, and an entry added before the config flow refused these hubs
|
||||
# stops retrying.
|
||||
try:
|
||||
# Disconnects again on failure, so a retry leaves nothing running.
|
||||
await client.async_connect(timeout=CONNECT_TIMEOUT)
|
||||
except NotConnectedError as err:
|
||||
connected, info = await asyncio.gather(
|
||||
client.async_connect(timeout=CONNECT_TIMEOUT),
|
||||
async_query_lssdp(host),
|
||||
return_exceptions=True,
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
# The connection may have opened while the query was still pending.
|
||||
await client.async_disconnect()
|
||||
raise
|
||||
if isinstance(info, BaseException):
|
||||
await client.async_disconnect()
|
||||
raise info
|
||||
if (module := unsupported_module(info)) is not None:
|
||||
await client.async_disconnect()
|
||||
raise ConfigEntryError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="unsupported_hub",
|
||||
translation_placeholders={"host": host, "module": module},
|
||||
)
|
||||
if isinstance(connected, NotConnectedError):
|
||||
# The client disconnects again on failure, so a retry leaves nothing
|
||||
# running.
|
||||
raise ConfigEntryNotReady(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="cannot_connect",
|
||||
translation_placeholders={"host": entry.data[CONF_HOST]},
|
||||
) from err
|
||||
translation_placeholders={"host": host},
|
||||
) from connected
|
||||
if isinstance(connected, BaseException):
|
||||
raise connected
|
||||
|
||||
entry.async_on_unload(client.async_disconnect)
|
||||
entry.runtime_data = client
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
"""Config flow for the LibreSync integration."""
|
||||
|
||||
import asyncio
|
||||
from typing import Any, override
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from aiolibresync import DiscoveredDevice, async_probe, async_probe_control
|
||||
from aiolibresync import (
|
||||
DiscoveredDevice,
|
||||
async_probe,
|
||||
async_probe_control,
|
||||
async_query_lssdp,
|
||||
)
|
||||
import probatio
|
||||
|
||||
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
|
||||
@@ -15,6 +21,7 @@ from homeassistant.helpers.service_info.ssdp import (
|
||||
SsdpServiceInfo,
|
||||
)
|
||||
|
||||
from . import unsupported_module
|
||||
from .const import DEFAULT_NAME, DOMAIN
|
||||
|
||||
STEP_USER_SCHEMA = probatio.Schema({probatio.Required(CONF_HOST): TextSelector()})
|
||||
@@ -37,7 +44,14 @@ class LibreSyncConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
errors: dict[str, str] = {}
|
||||
if user_input is not None:
|
||||
host = user_input[CONF_HOST]
|
||||
device = await async_probe(host)
|
||||
device, info = await asyncio.gather(
|
||||
async_probe(host), async_query_lssdp(host)
|
||||
)
|
||||
if (module := unsupported_module(info)) is not None:
|
||||
return self.async_abort(
|
||||
reason="unsupported_hub",
|
||||
description_placeholders={"module": module},
|
||||
)
|
||||
if device is None:
|
||||
errors["base"] = "cannot_connect"
|
||||
elif not device.udn:
|
||||
@@ -66,7 +80,14 @@ class LibreSyncConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
await self.async_set_unique_id(udn)
|
||||
self._abort_if_unique_id_configured(updates={CONF_HOST: host})
|
||||
|
||||
if not await async_probe_control(host):
|
||||
reachable, info = await asyncio.gather(
|
||||
async_probe_control(host), async_query_lssdp(host)
|
||||
)
|
||||
if (module := unsupported_module(info)) is not None:
|
||||
return self.async_abort(
|
||||
reason="unsupported_hub", description_placeholders={"module": module}
|
||||
)
|
||||
if not reachable:
|
||||
return self.async_abort(reason="cannot_connect")
|
||||
|
||||
self._discovered = DiscoveredDevice(
|
||||
|
||||
@@ -9,3 +9,8 @@ DEFAULT_NAME: Final = "LibreSync hub"
|
||||
|
||||
# Both ports are up in about 0.05 s on a LAN.
|
||||
CONNECT_TIMEOUT: Final = 10.0
|
||||
|
||||
# Libre modules whose port 7777 the library cannot open: the Surround Hub wraps
|
||||
# it in mutual TLS, the Stereo Hub HT resets a plaintext session. LSSDP names
|
||||
# the module.
|
||||
UNSUPPORTED_MODULES: Final = frozenset({"LS10"})
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
"iot_class": "local_push",
|
||||
"loggers": ["aiolibresync"],
|
||||
"quality_scale": "bronze",
|
||||
"requirements": ["aiolibresync==0.5.1"],
|
||||
"requirements": ["aiolibresync==0.5.3"],
|
||||
"ssdp": [
|
||||
{
|
||||
"deviceType": "urn:schemas-upnp-org:device:MediaRenderer:1",
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
"config": {
|
||||
"abort": {
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]"
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"unsupported_hub": "This hub is built on Libre's newer {module} module, like the Stereo Hub HT and the Surround Hub, which this integration does not support yet."
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
@@ -58,6 +59,9 @@
|
||||
},
|
||||
"not_connected": {
|
||||
"message": "The hub is not connected, so the command was not sent."
|
||||
},
|
||||
"unsupported_hub": {
|
||||
"message": "The hub at {host} is built on Libre's newer {module} module, which this integration does not support yet."
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Generated
+1
-1
@@ -353,7 +353,7 @@ aiokem==1.0.1
|
||||
aiolibrenms==0.0.4
|
||||
|
||||
# homeassistant.components.libresync
|
||||
aiolibresync==0.5.1
|
||||
aiolibresync==0.5.3
|
||||
|
||||
# homeassistant.components.lichess
|
||||
aiolichess==1.3.0
|
||||
|
||||
@@ -7,6 +7,7 @@ from aiolibresync import (
|
||||
DeviceState,
|
||||
DiscoveredDevice,
|
||||
LibreSyncClient,
|
||||
LssdpInfo,
|
||||
NowPlaying,
|
||||
PlayState,
|
||||
Source,
|
||||
@@ -56,6 +57,24 @@ FOUND = DiscoveredDevice(
|
||||
)
|
||||
|
||||
|
||||
LS9 = LssdpInfo(
|
||||
module="LS9", model="Stereo Hub", firmware="p15262.515.0", media_port=7777
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def mock_lssdp() -> Generator[AsyncMock]:
|
||||
"""Mock the LSSDP query, answered by the original Stereo Hub."""
|
||||
lssdp = AsyncMock(return_value=LS9)
|
||||
with (
|
||||
patch("homeassistant.components.libresync.async_query_lssdp", lssdp),
|
||||
patch(
|
||||
"homeassistant.components.libresync.config_flow.async_query_lssdp", lssdp
|
||||
),
|
||||
):
|
||||
yield lssdp
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_setup_entry() -> Generator[AsyncMock]:
|
||||
"""Mock setting up a config entry."""
|
||||
|
||||
@@ -19,7 +19,7 @@ from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo
|
||||
|
||||
from .conftest import FOUND, HOST, UDN
|
||||
from .conftest import FOUND, HOST, LS9, UDN
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
|
||||
|
||||
@@ -277,3 +277,43 @@ async def test_ssdp_dropped_after_manual_add(hass: HomeAssistant) -> None:
|
||||
assert manual["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert manual["result"].unique_id == UDN
|
||||
assert hass.config_entries.flow.async_progress() == []
|
||||
|
||||
|
||||
async def test_user_flow_unsupported_hub(
|
||||
hass: HomeAssistant, mock_probe: AsyncMock, mock_lssdp: AsyncMock
|
||||
) -> None:
|
||||
"""Test a hub on the LS10 module is refused."""
|
||||
mock_lssdp.return_value = replace(LS9, module="LS10")
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_USER}
|
||||
)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], {CONF_HOST: HOST}
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "unsupported_hub"
|
||||
assert result["description_placeholders"] == {"module": "LS10"}
|
||||
mock_lssdp.assert_awaited_once_with(HOST)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_probe_control")
|
||||
async def test_ssdp_unsupported_hub(hass: HomeAssistant, mock_lssdp: AsyncMock) -> None:
|
||||
"""Test a discovered hub on the LS10 module is refused."""
|
||||
mock_lssdp.return_value = replace(LS9, module="LS10")
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_INFO
|
||||
)
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "unsupported_hub"
|
||||
mock_lssdp.assert_awaited_once_with(HOST)
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("mock_probe_control")
|
||||
async def test_ssdp_no_lssdp_answer(hass: HomeAssistant, mock_lssdp: AsyncMock) -> None:
|
||||
"""Test a hub that does not answer on LSSDP is still offered."""
|
||||
mock_lssdp.return_value = None
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_INFO
|
||||
)
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "discovery_confirm"
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
"""Tests for the LibreSync integration setup."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
import asyncio
|
||||
from dataclasses import replace
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
from aiolibresync import NotConnectedError
|
||||
from aiolibresync import LssdpInfo, NotConnectedError
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
from homeassistant.components.libresync.const import CONNECT_TIMEOUT
|
||||
@@ -11,7 +14,7 @@ from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers import device_registry as dr
|
||||
|
||||
from . import setup_integration
|
||||
from .conftest import HOST, STATE, push
|
||||
from .conftest import HOST, LS9, STATE, push
|
||||
|
||||
|
||||
async def test_load_unload(
|
||||
@@ -28,10 +31,16 @@ async def test_load_unload(
|
||||
mock_client.async_disconnect.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lssdp", [LS9, None], ids=["ls9", "no_lssdp"])
|
||||
async def test_not_ready(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
mock_lssdp: AsyncMock,
|
||||
lssdp: LssdpInfo | None,
|
||||
) -> None:
|
||||
"""Test a hub that does not answer in time is retried."""
|
||||
mock_lssdp.return_value = lssdp
|
||||
mock_client.async_connect.side_effect = NotConnectedError("no answer")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
@@ -41,6 +50,29 @@ async def test_not_ready(
|
||||
assert mock_client.subscribers == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"connect_error", [NotConnectedError("no answer"), None], ids=["fails", "connects"]
|
||||
)
|
||||
async def test_unsupported_hub_not_retried(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
mock_lssdp: AsyncMock,
|
||||
connect_error: Exception | None,
|
||||
) -> None:
|
||||
"""Test an entry on an LS10 hub fails setup instead of retrying for ever."""
|
||||
mock_lssdp.return_value = replace(LS9, module="LS10")
|
||||
mock_client.async_connect.side_effect = connect_error
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
mock_client.async_disconnect.assert_awaited_once()
|
||||
assert mock_config_entry.reason == (
|
||||
f"The hub at {HOST} is built on Libre's newer LS10 module, which this "
|
||||
"integration does not support yet"
|
||||
)
|
||||
mock_lssdp.assert_awaited_once_with(HOST)
|
||||
|
||||
|
||||
async def test_device_updated(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
@@ -81,3 +113,51 @@ async def test_device_keeps_identity_across_reload(
|
||||
device_registry, mock_config_entry.entry_id
|
||||
)
|
||||
assert device.model == "Stereo Hub"
|
||||
|
||||
|
||||
async def test_lssdp_error_propagates(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
mock_lssdp: AsyncMock,
|
||||
) -> None:
|
||||
"""Test an unexpected LSSDP error disconnects the client and fails setup."""
|
||||
mock_lssdp.side_effect = RuntimeError("boom")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
mock_client.async_disconnect.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_connect_error_propagates(
|
||||
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_client: MagicMock
|
||||
) -> None:
|
||||
"""Test an unexpected connect error fails setup."""
|
||||
mock_client.async_connect.side_effect = RuntimeError("boom")
|
||||
await setup_integration(hass, mock_config_entry)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
|
||||
|
||||
|
||||
async def test_cancelled_setup_disconnects(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_client: MagicMock,
|
||||
mock_lssdp: AsyncMock,
|
||||
) -> None:
|
||||
"""Test a setup cancelled after the connection opened disconnects it."""
|
||||
pending = asyncio.Event()
|
||||
|
||||
async def never_answers(host: str) -> None:
|
||||
pending.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
mock_lssdp.side_effect = never_answers
|
||||
mock_config_entry.add_to_hass(hass)
|
||||
setup = hass.async_create_task(
|
||||
hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
)
|
||||
await pending.wait()
|
||||
mock_client.async_connect.assert_awaited_once()
|
||||
setup.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await setup
|
||||
mock_client.async_disconnect.assert_awaited_once()
|
||||
|
||||
Reference in New Issue
Block a user