Create or import thread active dataset when setting up OTBR (#87186)

* Create a thread active dataset when discovering OTBR

* Align with lib changes

* Use thread preferred dataset if set

* Create a dataset also from the user flow
This commit is contained in:
Erik Montnemery 2023-02-08 19:32:19 +01:00 committed by GitHub
parent 278050a73f
commit 2246255e90
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 225 additions and 7 deletions

View File

@ -1,10 +1,13 @@
"""Config flow for the Open Thread Border Router integration."""
from __future__ import annotations
import logging
import python_otbr_api
import voluptuous as vol
from homeassistant.components.hassio import HassioServiceInfo
from homeassistant.components.thread import async_get_preferred_dataset
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_URL
from homeassistant.data_entry_flow import FlowResult
@ -12,12 +15,26 @@ from homeassistant.helpers.aiohttp_client import async_get_clientsession
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
class OTBRConfigFlow(ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Open Thread Border Router."""
VERSION = 1
async def _connect_and_create_dataset(self, url: str) -> None:
"""Connect to the OTBR and create a dataset if it doesn't have one."""
api = python_otbr_api.OTBR(url, async_get_clientsession(self.hass), 10)
if await api.get_active_dataset_tlvs() is None:
if dataset := await async_get_preferred_dataset(self.hass):
await api.set_active_dataset_tlvs(bytes.fromhex(dataset))
else:
await api.create_active_dataset(
python_otbr_api.OperationalDataSet(network_name="home-assistant")
)
await api.set_enabled(True)
async def async_step_user(
self, user_input: dict[str, str] | None = None
) -> FlowResult:
@ -29,9 +46,8 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN):
if user_input is not None:
url = user_input[CONF_URL]
api = python_otbr_api.OTBR(url, async_get_clientsession(self.hass), 10)
try:
await api.get_active_dataset_tlvs()
await self._connect_and_create_dataset(url)
except python_otbr_api.OTBRError:
errors["base"] = "cannot_connect"
else:
@ -53,6 +69,13 @@ class OTBRConfigFlow(ConfigFlow, domain=DOMAIN):
config = discovery_info.config
url = f"http://{config['host']}:{config['port']}"
try:
await self._connect_and_create_dataset(url)
except python_otbr_api.OTBRError as exc:
_LOGGER.warning("Failed to communicate with OTBR@%s: %s", url, exc)
return self.async_abort(reason="unknown")
await self.async_set_unique_id(DOMAIN)
return self.async_create_entry(
title="Open Thread Border Router",

View File

@ -6,13 +6,14 @@ from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN
from .dataset_store import DatasetEntry, async_add_dataset
from .dataset_store import DatasetEntry, async_add_dataset, async_get_preferred_dataset
from .websocket_api import async_setup as async_setup_ws_api
__all__ = [
"DOMAIN",
"DatasetEntry",
"async_add_dataset",
"async_get_preferred_dataset",
]

View File

@ -144,3 +144,13 @@ async def async_add_dataset(hass: HomeAssistant, source: str, tlv: str) -> None:
"""Add a dataset."""
store = await async_get_store(hass)
store.async_add(source, tlv)
async def async_get_preferred_dataset(hass: HomeAssistant) -> str | None:
"""Get the preferred dataset."""
store = await async_get_store(hass)
if (preferred_dataset := store.preferred_dataset) is None or (
entry := store.async_get(preferred_dataset)
) is None:
return None
return entry.tlv

View File

@ -12,9 +12,9 @@ from tests.common import MockConfigEntry, MockModule, mock_integration
from tests.test_util.aiohttp import AiohttpClientMocker
HASSIO_DATA = hassio.HassioServiceInfo(
config={"host": "blah", "port": "bluh"},
name="blah",
slug="blah",
config={"host": "core-silabs-multiprotocol", "port": 8081},
name="Silicon Labs Multiprotocol",
slug="otbr",
)
@ -56,6 +56,64 @@ async def test_user_flow(
assert config_entry.unique_id == otbr.DOMAIN
async def test_user_flow_router_not_setup(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the user flow when the border router has no dataset.
This tests the behavior when the thread integration has no preferred dataset.
"""
url = "http://custom_url:1234"
aioclient_mock.get(f"{url}/node/dataset/active", status=HTTPStatus.NO_CONTENT)
aioclient_mock.post(f"{url}/node/dataset/active", status=HTTPStatus.ACCEPTED)
aioclient_mock.post(f"{url}/node/state", status=HTTPStatus.OK)
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "user"}
)
assert result["type"] == FlowResultType.FORM
assert result["errors"] == {}
with patch(
"homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
return_value=None,
), patch(
"homeassistant.components.otbr.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
"url": url,
},
)
# Check we create a dataset and enable the router
assert aioclient_mock.mock_calls[-2][0] == "POST"
assert aioclient_mock.mock_calls[-2][1].path == "/node/dataset/active"
assert aioclient_mock.mock_calls[-2][2] == {"NetworkName": "home-assistant"}
assert aioclient_mock.mock_calls[-1][0] == "POST"
assert aioclient_mock.mock_calls[-1][1].path == "/node/state"
assert aioclient_mock.mock_calls[-1][2] == "enabled"
expected_data = {
"url": "http://custom_url:1234",
}
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Open Thread Border Router"
assert result["data"] == expected_data
assert result["options"] == {}
assert len(mock_setup_entry.mock_calls) == 1
config_entry = hass.config_entries.async_entries(otbr.DOMAIN)[0]
assert config_entry.data == expected_data
assert config_entry.options == {}
assert config_entry.title == "Open Thread Border Router"
assert config_entry.unique_id == otbr.DOMAIN
async def test_user_flow_404(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
@ -79,8 +137,13 @@ async def test_user_flow_404(
assert result["errors"] == {"base": "cannot_connect"}
async def test_hassio_discovery_flow(hass: HomeAssistant) -> None:
async def test_hassio_discovery_flow(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the hassio discovery flow."""
url = "http://core-silabs-multiprotocol:8081"
aioclient_mock.get(f"{url}/node/dataset/active", text="aa")
with patch(
"homeassistant.components.otbr.async_setup_entry",
return_value=True,
@ -106,6 +169,118 @@ async def test_hassio_discovery_flow(hass: HomeAssistant) -> None:
assert config_entry.unique_id == otbr.DOMAIN
async def test_hassio_discovery_flow_router_not_setup(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the hassio discovery flow when the border router has no dataset.
This tests the behavior when the thread integration has no preferred dataset.
"""
url = "http://core-silabs-multiprotocol:8081"
aioclient_mock.get(f"{url}/node/dataset/active", status=HTTPStatus.NO_CONTENT)
aioclient_mock.post(f"{url}/node/dataset/active", status=HTTPStatus.ACCEPTED)
aioclient_mock.post(f"{url}/node/state", status=HTTPStatus.OK)
with patch(
"homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
return_value=None,
), patch(
"homeassistant.components.otbr.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
# Check we create a dataset and enable the router
assert aioclient_mock.mock_calls[-2][0] == "POST"
assert aioclient_mock.mock_calls[-2][1].path == "/node/dataset/active"
assert aioclient_mock.mock_calls[-2][2] == {"NetworkName": "home-assistant"}
assert aioclient_mock.mock_calls[-1][0] == "POST"
assert aioclient_mock.mock_calls[-1][1].path == "/node/state"
assert aioclient_mock.mock_calls[-1][2] == "enabled"
expected_data = {
"url": f"http://{HASSIO_DATA.config['host']}:{HASSIO_DATA.config['port']}",
}
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Open Thread Border Router"
assert result["data"] == expected_data
assert result["options"] == {}
assert len(mock_setup_entry.mock_calls) == 1
config_entry = hass.config_entries.async_entries(otbr.DOMAIN)[0]
assert config_entry.data == expected_data
assert config_entry.options == {}
assert config_entry.title == "Open Thread Border Router"
assert config_entry.unique_id == otbr.DOMAIN
async def test_hassio_discovery_flow_router_not_setup_has_preferred(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the hassio discovery flow when the border router has no dataset.
This tests the behavior when the thread integration has a preferred dataset.
"""
url = "http://core-silabs-multiprotocol:8081"
aioclient_mock.get(f"{url}/node/dataset/active", status=HTTPStatus.NO_CONTENT)
aioclient_mock.put(f"{url}/node/dataset/active", status=HTTPStatus.ACCEPTED)
aioclient_mock.post(f"{url}/node/state", status=HTTPStatus.OK)
with patch(
"homeassistant.components.otbr.config_flow.async_get_preferred_dataset",
return_value="aa",
), patch(
"homeassistant.components.otbr.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
# Check we create a dataset and enable the router
assert aioclient_mock.mock_calls[-2][0] == "PUT"
assert aioclient_mock.mock_calls[-2][1].path == "/node/dataset/active"
assert aioclient_mock.mock_calls[-2][2] == "aa"
assert aioclient_mock.mock_calls[-1][0] == "POST"
assert aioclient_mock.mock_calls[-1][1].path == "/node/state"
assert aioclient_mock.mock_calls[-1][2] == "enabled"
expected_data = {
"url": f"http://{HASSIO_DATA.config['host']}:{HASSIO_DATA.config['port']}",
}
assert result["type"] == FlowResultType.CREATE_ENTRY
assert result["title"] == "Open Thread Border Router"
assert result["data"] == expected_data
assert result["options"] == {}
assert len(mock_setup_entry.mock_calls) == 1
config_entry = hass.config_entries.async_entries(otbr.DOMAIN)[0]
assert config_entry.data == expected_data
assert config_entry.options == {}
assert config_entry.title == "Open Thread Border Router"
assert config_entry.unique_id == otbr.DOMAIN
async def test_hassio_discovery_flow_404(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
) -> None:
"""Test the user and discovery flows."""
url = "http://core-silabs-multiprotocol:8081"
aioclient_mock.get(f"{url}/node/dataset/active", status=HTTPStatus.NOT_FOUND)
result = await hass.config_entries.flow.async_init(
otbr.DOMAIN, context={"source": "hassio"}, data=HASSIO_DATA
)
assert result["type"] == FlowResultType.ABORT
assert result["reason"] == "unknown"
@pytest.mark.parametrize("source", ("hassio", "user"))
async def test_config_flow_single_entry(hass: HomeAssistant, source: str) -> None:
"""Test only a single entry is allowed."""

View File

@ -52,6 +52,15 @@ async def test_add_dataset_reordered(hass: HomeAssistant) -> None:
assert list(store.datasets.values())[0].created == created
async def test_get_preferred_dataset(hass: HomeAssistant) -> None:
"""Test get the preferred dataset."""
assert await dataset_store.async_get_preferred_dataset(hass) is None
await dataset_store.async_add_dataset(hass, "source", DATASET_1)
assert (await dataset_store.async_get_preferred_dataset(hass)) == DATASET_1
async def test_dataset_properties(hass: HomeAssistant) -> None:
"""Test dataset entry properties."""
datasets = [