mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add reconfigure flow to Bravia TV (#189092)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
c69b65287d
commit
f59f17d3e1
@@ -1,7 +1,7 @@
|
||||
"""Config flow to configure the Bravia TV integration."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from typing import Any, cast, override
|
||||
from typing import TYPE_CHECKING, Any, cast, override
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from aiohttp import CookieJar
|
||||
@@ -29,6 +29,7 @@ from .const import (
|
||||
CONF_USE_PSK,
|
||||
CONF_USE_SSL,
|
||||
DOMAIN,
|
||||
LEGACY_CLIENT_ID,
|
||||
NICKNAME_PREFIX,
|
||||
)
|
||||
|
||||
@@ -60,7 +61,13 @@ class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
return uuid, f"{NICKNAME_PREFIX} {uuid[:6]}"
|
||||
|
||||
async def async_connect_device(self) -> None:
|
||||
"""Connect to Bravia TV device from config."""
|
||||
"""Connect to Bravia TV device from config and enable Wake-on-LAN."""
|
||||
assert self.client
|
||||
await self._async_authenticate()
|
||||
await self.client.set_wol_mode(True)
|
||||
|
||||
async def _async_authenticate(self) -> None:
|
||||
"""Authenticate with the Bravia TV without changing its settings."""
|
||||
assert self.client
|
||||
|
||||
pin = self.device_config[CONF_PIN]
|
||||
@@ -72,7 +79,6 @@ class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
client_id = self.device_config[CONF_CLIENT_ID]
|
||||
nickname = self.device_config[CONF_NICKNAME]
|
||||
await self.client.connect(pin=pin, clientid=client_id, nickname=nickname)
|
||||
await self.client.set_wol_mode(True)
|
||||
|
||||
async def async_create_device(self) -> ConfigFlowResult:
|
||||
"""Create Bravia TV device from config."""
|
||||
@@ -288,3 +294,69 @@ class BraviaTVConfigFlow(ConfigFlow, domain=DOMAIN):
|
||||
"""Handle configuration by re-auth."""
|
||||
self.device_config = {**entry_data}
|
||||
return await self.async_step_authorize()
|
||||
|
||||
async def async_step_reconfigure(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
) -> ConfigFlowResult:
|
||||
"""Handle reconfiguration of the host of a Bravia TV."""
|
||||
reconfigure_entry = self._get_reconfigure_entry()
|
||||
errors: dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
host = user_input[CONF_HOST]
|
||||
if not is_host_valid(host):
|
||||
errors[CONF_HOST] = "invalid_host"
|
||||
else:
|
||||
# Defaults match the coordinator for entries created before these keys
|
||||
self.device_config = {
|
||||
CONF_USE_PSK: False,
|
||||
CONF_USE_SSL: False,
|
||||
CONF_CLIENT_ID: LEGACY_CLIENT_ID,
|
||||
CONF_NICKNAME: NICKNAME_PREFIX,
|
||||
**reconfigure_entry.data,
|
||||
CONF_HOST: host,
|
||||
}
|
||||
self.create_client()
|
||||
if TYPE_CHECKING:
|
||||
assert self.client
|
||||
try:
|
||||
# Wake-on-LAN was enabled when the entry was created
|
||||
await self._async_authenticate()
|
||||
system_info = await self.client.get_system_info()
|
||||
except BraviaAuthError:
|
||||
errors["base"] = "invalid_auth"
|
||||
except BraviaNotSupported:
|
||||
errors["base"] = "unsupported_model"
|
||||
except BraviaError:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
formatted_mac = format_mac(system_info[ATTR_MAC])
|
||||
if reconfigure_entry.unique_id:
|
||||
await self.async_set_unique_id(
|
||||
system_info[ATTR_CID].lower() or formatted_mac
|
||||
)
|
||||
self._abort_if_unique_id_mismatch()
|
||||
# Entries without a CID keep an empty unique ID until the
|
||||
# migration sets the MAC, and without a MAC can't be verified
|
||||
elif (
|
||||
not formatted_mac
|
||||
or format_mac(reconfigure_entry.data[CONF_MAC]) != formatted_mac
|
||||
):
|
||||
return self.async_abort(reason="unique_id_mismatch")
|
||||
# A loaded entry is reloaded by its update listener
|
||||
if reconfigure_entry.update_listeners:
|
||||
return self.async_update_and_abort(
|
||||
reconfigure_entry, data_updates={CONF_HOST: host}
|
||||
)
|
||||
return self.async_update_reload_and_abort(
|
||||
reconfigure_entry, data_updates={CONF_HOST: host}
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="reconfigure",
|
||||
data_schema=self.add_suggested_values_to_schema(
|
||||
probatio.Schema({probatio.Required(CONF_HOST): str}),
|
||||
user_input or reconfigure_entry.data,
|
||||
),
|
||||
errors=errors,
|
||||
)
|
||||
|
||||
@@ -74,7 +74,7 @@ rules:
|
||||
icon-translations:
|
||||
status: exempt
|
||||
comment: The integration does not provide any custom icons.
|
||||
reconfiguration-flow: todo
|
||||
reconfiguration-flow: done
|
||||
repair-issues:
|
||||
status: exempt
|
||||
comment: The integration does not have anything to repair.
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
|
||||
"no_devices_found": "[%key:common::config_flow::abort::no_devices_found%]",
|
||||
"no_ip_control": "IP Control is disabled on your TV or the TV is not supported.",
|
||||
"not_bravia_device": "The device is not a Bravia TV."
|
||||
"not_bravia_device": "The device is not a Bravia TV.",
|
||||
"unique_id_mismatch": "The host you entered belongs to a different Bravia TV."
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
@@ -48,6 +49,15 @@
|
||||
"description": "To set up PSK on your TV, go to: Settings -> Network -> Home Network Setup -> IP Control. Set «Authentication» to «Normal and Pre-Shared Key» or «Pre-Shared Key» and define your Pre-Shared-Key string (e.g. sony). \n\nThen enter your PSK here.",
|
||||
"title": "[%key:component::braviatv::config::step::authorize::title%]"
|
||||
},
|
||||
"reconfigure": {
|
||||
"data": {
|
||||
"host": "[%key:common::config_flow::data::host%]"
|
||||
},
|
||||
"data_description": {
|
||||
"host": "[%key:component::braviatv::config::step::user::data_description::host%]"
|
||||
},
|
||||
"description": "Update the hostname or IP address of your Sony Bravia TV. The existing authorization is kept, so make sure the TV is turned on."
|
||||
},
|
||||
"user": {
|
||||
"data": {
|
||||
"host": "[%key:common::config_flow::data::host%]"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Define tests for the Bravia TV config flow."""
|
||||
|
||||
from typing import Any
|
||||
from unittest.mock import ANY, AsyncMock
|
||||
|
||||
from pybravia import (
|
||||
@@ -629,3 +630,216 @@ async def test_user_flow_with_empty_cid(
|
||||
sorted(entry.unique_id for entry in hass.config_entries.async_entries(DOMAIN))
|
||||
== expected_unique_ids
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def reconfigure_entry(hass: HomeAssistant) -> MockConfigEntry:
|
||||
"""Add a config entry to reconfigure."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="very_unique_string",
|
||||
data={
|
||||
CONF_HOST: "bravia-host",
|
||||
CONF_PIN: "1234",
|
||||
CONF_MAC: "AA:BB:CC:DD:EE:FF",
|
||||
CONF_USE_PSK: True,
|
||||
CONF_USE_SSL: False,
|
||||
},
|
||||
title="TV-Model",
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
return config_entry
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry_data", "connect_kwargs"),
|
||||
[
|
||||
pytest.param({CONF_USE_PSK: True}, {"psk": "1234"}, id="psk"),
|
||||
pytest.param(
|
||||
{CONF_USE_PSK: False, CONF_CLIENT_ID: "client", CONF_NICKNAME: "nick"},
|
||||
{"pin": "1234", "clientid": "client", "nickname": "nick"},
|
||||
id="pin",
|
||||
),
|
||||
pytest.param(
|
||||
{},
|
||||
{"pin": "1234", "clientid": "HomeAssistant", "nickname": NICKNAME_PREFIX},
|
||||
id="legacy",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_reconfigure(
|
||||
hass: HomeAssistant,
|
||||
mock_braviatv_client: AsyncMock,
|
||||
entry_data: dict[str, Any],
|
||||
connect_kwargs: dict[str, str],
|
||||
) -> None:
|
||||
"""Test reconfiguring the host keeps the existing authorization."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="very_unique_string",
|
||||
data={
|
||||
CONF_HOST: "bravia-host",
|
||||
CONF_PIN: "1234",
|
||||
CONF_MAC: "AA:BB:CC:DD:EE:FF",
|
||||
**entry_data,
|
||||
},
|
||||
title="TV-Model",
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
result = await config_entry.start_reconfigure_flow(hass)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reconfigure"
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
mock_braviatv_client.connect.assert_called_once_with(**connect_kwargs)
|
||||
assert config_entry.data == {
|
||||
CONF_HOST: "10.0.0.2",
|
||||
CONF_PIN: "1234",
|
||||
CONF_MAC: "AA:BB:CC:DD:EE:FF",
|
||||
**entry_data,
|
||||
}
|
||||
|
||||
|
||||
async def test_reconfigure_invalid_host(
|
||||
hass: HomeAssistant, reconfigure_entry: MockConfigEntry
|
||||
) -> None:
|
||||
"""Test reconfiguring with an invalid host shows an error and recovers."""
|
||||
result = await reconfigure_entry.start_reconfigure_flow(hass)
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "invalid/host"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {CONF_HOST: "invalid_host"}
|
||||
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
assert reconfigure_entry.data[CONF_HOST] == "10.0.0.2"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "error_message"),
|
||||
[
|
||||
pytest.param(BraviaAuthError, "invalid_auth", id="invalid_auth"),
|
||||
pytest.param(BraviaNotSupported, "unsupported_model", id="unsupported_model"),
|
||||
pytest.param(BraviaConnectionError, "cannot_connect", id="cannot_connect"),
|
||||
],
|
||||
)
|
||||
async def test_reconfigure_errors(
|
||||
hass: HomeAssistant,
|
||||
reconfigure_entry: MockConfigEntry,
|
||||
mock_braviatv_client: AsyncMock,
|
||||
side_effect: type[Exception],
|
||||
error_message: str,
|
||||
) -> None:
|
||||
"""Test reconfiguring shows errors and recovers from them."""
|
||||
result = await reconfigure_entry.start_reconfigure_flow(hass)
|
||||
|
||||
mock_braviatv_client.connect.side_effect = side_effect
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "reconfigure"
|
||||
assert result["errors"] == {"base": error_message}
|
||||
|
||||
mock_braviatv_client.connect.side_effect = None
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
assert reconfigure_entry.data[CONF_HOST] == "10.0.0.2"
|
||||
|
||||
|
||||
async def test_reconfigure_unique_id_mismatch(
|
||||
hass: HomeAssistant,
|
||||
reconfigure_entry: MockConfigEntry,
|
||||
mock_braviatv_client: AsyncMock,
|
||||
) -> None:
|
||||
"""Test reconfiguring to a different TV aborts without changing its settings."""
|
||||
result = await reconfigure_entry.start_reconfigure_flow(hass)
|
||||
|
||||
mock_braviatv_client.get_system_info.return_value = BRAVIA_SYSTEM_INFO | {
|
||||
"cid": "other_tv"
|
||||
}
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "unique_id_mismatch"
|
||||
assert reconfigure_entry.data[CONF_HOST] == "bravia-host"
|
||||
mock_braviatv_client.set_wol_mode.assert_not_called()
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("entry_mac", "mac", "reason", "host"),
|
||||
[
|
||||
pytest.param(
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
"reconfigure_successful",
|
||||
"10.0.0.2",
|
||||
id="same_tv",
|
||||
),
|
||||
pytest.param(
|
||||
"AA:BB:CC:DD:EE:FF",
|
||||
"11:22:33:44:55:66",
|
||||
"unique_id_mismatch",
|
||||
"bravia-host",
|
||||
id="other_tv",
|
||||
),
|
||||
pytest.param("", "", "unique_id_mismatch", "bravia-host", id="no_mac"),
|
||||
],
|
||||
)
|
||||
async def test_reconfigure_entry_without_unique_id(
|
||||
hass: HomeAssistant,
|
||||
mock_braviatv_client: AsyncMock,
|
||||
entry_mac: str,
|
||||
mac: str,
|
||||
reason: str,
|
||||
host: str,
|
||||
) -> None:
|
||||
"""Test reconfiguring a legacy entry without unique ID compares the MAC address."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
unique_id="",
|
||||
data={
|
||||
CONF_HOST: "bravia-host",
|
||||
CONF_PIN: "1234",
|
||||
CONF_MAC: entry_mac,
|
||||
CONF_USE_PSK: True,
|
||||
},
|
||||
disabled_by=ConfigEntryDisabler.USER,
|
||||
minor_version=1,
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
result = await config_entry.start_reconfigure_flow(hass)
|
||||
mock_braviatv_client.get_system_info.return_value = BRAVIA_SYSTEM_INFO | {
|
||||
"cid": "",
|
||||
"macAddr": mac,
|
||||
}
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == reason
|
||||
assert config_entry.data[CONF_HOST] == host
|
||||
# The migration sets the unique ID once the entry is enabled
|
||||
assert config_entry.unique_id == ""
|
||||
|
||||
@@ -35,6 +35,7 @@ from homeassistant.const import (
|
||||
STATE_UNAVAILABLE,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.helpers.service_info.ssdp import SsdpServiceInfo
|
||||
from homeassistant.helpers.update_coordinator import UpdateFailed
|
||||
@@ -324,3 +325,47 @@ async def test_update_failed(
|
||||
assert isinstance(error, UpdateFailed)
|
||||
assert error.translation_key == translation_key
|
||||
assert error.translation_placeholders == placeholders
|
||||
|
||||
|
||||
async def test_reconfigure_loaded_entry(hass: HomeAssistant) -> None:
|
||||
"""Test reconfiguring a loaded entry reloads it once with the new host."""
|
||||
config_entry = MockConfigEntry(
|
||||
domain=DOMAIN, unique_id="very_unique_string", data=ENTRY_DATA
|
||||
)
|
||||
config_entry.add_to_hass(hass)
|
||||
|
||||
with (
|
||||
patch("homeassistant.components.braviatv.PLATFORMS", []),
|
||||
patch(
|
||||
"homeassistant.components.braviatv.BraviaClient", autospec=True
|
||||
) as mock_client,
|
||||
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()
|
||||
|
||||
result = await config_entry.start_reconfigure_flow(hass)
|
||||
with (
|
||||
patch("pybravia.BraviaClient.connect"),
|
||||
patch(
|
||||
"pybravia.BraviaClient.get_system_info",
|
||||
return_value={
|
||||
"cid": "very_unique_string",
|
||||
"macAddr": "AA:BB:CC:DD:EE:FF",
|
||||
},
|
||||
),
|
||||
):
|
||||
result = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"], user_input={CONF_HOST: "10.0.0.2"}
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.ABORT
|
||||
assert result["reason"] == "reconfigure_successful"
|
||||
assert config_entry.state is ConfigEntryState.LOADED
|
||||
# Initial setup plus a single reload by the update listener
|
||||
assert mock_client.call_count == 2
|
||||
assert mock_client.call_args.args[0] == "10.0.0.2"
|
||||
|
||||
Reference in New Issue
Block a user