mirror of
https://github.com/home-assistant/core.git
synced 2026-12-04 12:50:45 -04:00
Add KNX project data from other sources (#192341)
This commit is contained in:
@@ -41,7 +41,10 @@ from .const import (
|
||||
from .expose import create_combined_knx_exposure
|
||||
from .knx_module import KNXModule
|
||||
from .llm_api import async_register_llm_api
|
||||
from .project import STORAGE_KEY as PROJECT_STORAGE_KEY
|
||||
from .project import (
|
||||
STORAGE_KEY as PROJECT_STORAGE_KEY,
|
||||
async_set_project as async_set_project, # for other integrations
|
||||
)
|
||||
from .schema import (
|
||||
BinarySensorSchema,
|
||||
ButtonSchema,
|
||||
|
||||
@@ -1,14 +1,19 @@
|
||||
"""Handle KNX project data."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Mapping
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from typing import Final
|
||||
from typing import Any, Final
|
||||
|
||||
from awesomeversion import AwesomeVersion, AwesomeVersionException
|
||||
import probatio
|
||||
from xknx import XKNX
|
||||
from xknx.dpt import DPTBase
|
||||
from xknx.exceptions import CouldNotParseAddress
|
||||
from xknx.telegram.address import DeviceAddressableType, GroupAddress, GroupAddressType
|
||||
from xknxproject import XKNXProj
|
||||
from xknxproject.__version__ import __version__ as XKNXPROJECT_VERSION
|
||||
from xknxproject.models import (
|
||||
Device,
|
||||
DPTType,
|
||||
@@ -21,9 +26,11 @@ from xknxproject.models import (
|
||||
from homeassistant.components.file_upload import process_uploaded_file
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers.storage import Store
|
||||
|
||||
from .const import DOMAIN
|
||||
from .services import get_knx_module
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
@@ -31,6 +38,102 @@ STORAGE_VERSION: Final = 1
|
||||
STORAGE_KEY: Final = f"{DOMAIN}/knx_project.json"
|
||||
|
||||
|
||||
def _group_addresses(value: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Validate group addresses beyond their types."""
|
||||
for key, group_address in value.items():
|
||||
address = group_address["address"]
|
||||
try:
|
||||
GroupAddress(address)
|
||||
except CouldNotParseAddress as err:
|
||||
raise probatio.Invalid(f"invalid group address `{address}`") from err
|
||||
if key != address:
|
||||
raise probatio.Invalid(f"group address `{address}` is keyed as `{key}`")
|
||||
return value
|
||||
|
||||
|
||||
def _info(value: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Validate the project info beyond its types."""
|
||||
probatio.In([style.value for style in XknxProjectGroupAddressStyle])(
|
||||
value["group_address_style"]
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
# Project data in the format of the installed xknxproject, built from its types.
|
||||
PROJECT_DATA_SCHEMA: Final = probatio.TypedDictSchema(
|
||||
KNXProjectModel,
|
||||
{"group_addresses": _group_addresses, "info": _info},
|
||||
extra=probatio.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
|
||||
def _check_parser_version(project: Any) -> None:
|
||||
"""Refuse data of a minor version of xknxproject other than the installed one.
|
||||
|
||||
A minor version can add required keys, which the schema would only report
|
||||
as missing. Data without a version is left to the schema to report.
|
||||
"""
|
||||
info = project.get("info") if isinstance(project, Mapping) else None
|
||||
version = info.get("xknxproject_version") if isinstance(info, Mapping) else None
|
||||
if not isinstance(version, str):
|
||||
return
|
||||
try:
|
||||
data_version = AwesomeVersion(version)
|
||||
installed_version = AwesomeVersion(XKNXPROJECT_VERSION)
|
||||
compatible = (data_version.major, data_version.minor) == (
|
||||
installed_version.major,
|
||||
installed_version.minor,
|
||||
)
|
||||
except AwesomeVersionException:
|
||||
compatible = False
|
||||
if not compatible:
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="project_data_incompatible",
|
||||
translation_placeholders={
|
||||
"version": version,
|
||||
"installed_version": XKNXPROJECT_VERSION,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def validate_project_data(project: Any) -> KNXProjectModel:
|
||||
"""Validate project data in the format of the installed xknxproject.
|
||||
|
||||
Raises HomeAssistantError when the data was created for another minor
|
||||
version of xknxproject, or doesn't have its format.
|
||||
"""
|
||||
_check_parser_version(project)
|
||||
try:
|
||||
data = PROJECT_DATA_SCHEMA(project)
|
||||
except probatio.Invalid as err:
|
||||
raise HomeAssistantError(
|
||||
translation_domain=DOMAIN,
|
||||
translation_key="project_data_invalid",
|
||||
translation_placeholders={"error": str(err)},
|
||||
) from err
|
||||
return data
|
||||
|
||||
|
||||
async def async_set_project(hass: HomeAssistant, project: Mapping[str, Any]) -> None:
|
||||
"""Replace the KNX project with project data in the format of xknxproject.
|
||||
|
||||
For integrations and tools that provide project data from another source
|
||||
than a project file, eg. a project editor keeping it up to date while it is
|
||||
edited. The data is validated first; it is stored and loaded as an uploaded
|
||||
project file is.
|
||||
|
||||
Each call writes the whole project to storage and reloads its group
|
||||
addresses. Debouncing frequent updates is left to the caller.
|
||||
|
||||
Raises HomeAssistantError when the KNX integration is not loaded, or the
|
||||
data is invalid or incompatible. The current project is kept then.
|
||||
"""
|
||||
knx_module = get_knx_module(hass)
|
||||
data = validate_project_data(project)
|
||||
await knx_module.project.async_store_project(knx_module.xknx, data)
|
||||
|
||||
|
||||
@dataclass
|
||||
class GroupAddressInfo:
|
||||
"""Group address info for runtime usage."""
|
||||
@@ -131,6 +234,10 @@ class KNXProject:
|
||||
return xknxproj.parse()
|
||||
|
||||
project = await self.hass.async_add_executor_job(_parse_project)
|
||||
await self.async_store_project(xknx, project)
|
||||
|
||||
async def async_store_project(self, xknx: XKNX, project: KNXProjectModel) -> None:
|
||||
"""Store and load parsed project data, replacing the current project."""
|
||||
async with self._project_lock:
|
||||
await self._store.async_save(project)
|
||||
# Invalidate rather than populate: whether the full project is held
|
||||
|
||||
@@ -1645,6 +1645,12 @@
|
||||
"llm_tool_failed": {
|
||||
"message": "KNX tool call failed: {error}"
|
||||
},
|
||||
"project_data_incompatible": {
|
||||
"message": "The KNX project data is for xknxproject {version}, which is not compatible with the installed xknxproject {installed_version}."
|
||||
},
|
||||
"project_data_invalid": {
|
||||
"message": "Invalid KNX project data: {error}"
|
||||
},
|
||||
"service_event_register_ga_not_found": {
|
||||
"message": "Could not find registered event for `{group_addresses}` to remove."
|
||||
},
|
||||
|
||||
@@ -39,6 +39,7 @@ from .const import (
|
||||
UI_DEVICE_ID_PREFIX,
|
||||
)
|
||||
from .dpt import get_supported_dpts
|
||||
from .project import async_set_project
|
||||
from .storage.config_store import ConfigStoreException
|
||||
from .storage.const import CONF_DATA
|
||||
from .storage.entity_store_schema import (
|
||||
@@ -76,6 +77,7 @@ async def register_panel(hass: HomeAssistant) -> None:
|
||||
websocket_api.async_register_command(hass, ws_query_telegrams)
|
||||
websocket_api.async_register_command(hass, ws_subscribe_telegram)
|
||||
websocket_api.async_register_command(hass, ws_get_knx_project)
|
||||
websocket_api.async_register_command(hass, ws_set_knx_project)
|
||||
websocket_api.async_register_command(hass, ws_get_entity_suggestions)
|
||||
websocket_api.async_register_command(hass, ws_validate_entity)
|
||||
websocket_api.async_register_command(hass, ws_create_entity)
|
||||
@@ -260,6 +262,29 @@ async def ws_get_knx_project(
|
||||
)
|
||||
|
||||
|
||||
@websocket_api.require_admin
|
||||
@websocket_api.websocket_command(
|
||||
{
|
||||
probatio.Required("type"): "knx/set_knx_project",
|
||||
probatio.Required("project"): dict,
|
||||
}
|
||||
)
|
||||
@websocket_api.async_response
|
||||
async def ws_set_knx_project(
|
||||
hass: HomeAssistant,
|
||||
connection: websocket_api.ActiveConnection,
|
||||
msg: dict,
|
||||
) -> None:
|
||||
"""Replace the KNX project with project data in the format of xknxproject.
|
||||
|
||||
The whole project is one message, so it is limited by the maximum message
|
||||
size of the WebSocket API (4 MiB): a larger message closes the connection.
|
||||
Larger project data can be set with `async_set_project` from Python.
|
||||
"""
|
||||
await async_set_project(hass, msg["project"])
|
||||
connection.send_result(msg["id"])
|
||||
|
||||
|
||||
@websocket_api.require_admin
|
||||
@websocket_api.websocket_command(
|
||||
{
|
||||
|
||||
@@ -463,6 +463,12 @@ async def project_data(hass: HomeAssistant) -> dict[str, Any]:
|
||||
return await async_load_json_object_fixture(hass, "project.json", DOMAIN)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def current_project_data(hass: HomeAssistant) -> dict[str, Any]:
|
||||
"""Return project data in the format of the installed xknxproject."""
|
||||
return await async_load_json_object_fixture(hass, "project_current.json", DOMAIN)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def load_knxproj(
|
||||
project_data: dict[str, Any], hass_storage: dict[str, Any]
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,7 @@ left to whoever asks for it, so setup does not populate the cache.
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from typing import Any
|
||||
from unittest.mock import patch
|
||||
|
||||
@@ -16,8 +17,11 @@ import pytest
|
||||
from pytest_homeassistant.typing import WebSocketGenerator
|
||||
from xknx.telegram.address import GroupAddress
|
||||
|
||||
from homeassistant.components.knx import async_set_project
|
||||
from homeassistant.components.knx.const import KNX_MODULE_KEY
|
||||
from homeassistant.components.knx.project import STORAGE_KEY as KNX_PROJECT_STORAGE_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
|
||||
from .conftest import KNXTestKit
|
||||
|
||||
@@ -141,3 +145,223 @@ async def test_new_project_replaces_group_addresses(
|
||||
assert "0/0/2" in project.group_addresses
|
||||
assert xknx.group_address_dpt.get(GroupAddress("0/0/1")) is None
|
||||
assert xknx.group_address_dpt.get(GroupAddress("0/0/2")) is not None
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("load_knxproj")
|
||||
async def test_set_project(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
current_project_data: dict[str, Any],
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Project data from another source is stored and loaded like an upload."""
|
||||
await knx.setup_integration()
|
||||
project = hass.data[KNX_MODULE_KEY].project
|
||||
xknx = hass.data[KNX_MODULE_KEY].xknx
|
||||
assert await project.get_knxproject() is not None
|
||||
assert "0/0/3" in project.group_addresses
|
||||
|
||||
group_addresses = current_project_data["group_addresses"]
|
||||
new_data = {
|
||||
**current_project_data,
|
||||
"group_addresses": {
|
||||
address: ga for address, ga in group_addresses.items() if address != "1/0/0"
|
||||
},
|
||||
}
|
||||
await async_set_project(hass, new_data)
|
||||
|
||||
assert project.info is not None
|
||||
assert project.info["name"] == "xknx test project"
|
||||
assert set(project.group_addresses) == set(group_addresses) - {"1/0/0"}
|
||||
assert xknx.group_address_dpt.get(GroupAddress("0/0/3")) is None
|
||||
assert xknx.group_address_dpt.get(GroupAddress("2/0/1")) is not None
|
||||
assert hass_storage[KNX_PROJECT_STORAGE_KEY]["data"] == new_data
|
||||
knxproject = await project.get_knxproject()
|
||||
assert knxproject is not None
|
||||
assert knxproject["info"]["name"] == "xknx test project"
|
||||
|
||||
|
||||
async def test_set_project_keeps_unknown_data(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
current_project_data: dict[str, Any],
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Data the installed xknxproject doesn't know is stored as it is."""
|
||||
await knx.setup_integration()
|
||||
new_data = {
|
||||
**current_project_data,
|
||||
"new_section": {},
|
||||
"group_addresses": {
|
||||
address: {**ga, "new_key": "kept"}
|
||||
for address, ga in current_project_data["group_addresses"].items()
|
||||
},
|
||||
}
|
||||
|
||||
await async_set_project(hass, new_data)
|
||||
|
||||
assert hass.data[KNX_MODULE_KEY].project.loaded
|
||||
assert hass_storage[KNX_PROJECT_STORAGE_KEY]["data"] == new_data
|
||||
|
||||
|
||||
def _without(data: dict[str, Any], key: str) -> dict[str, Any]:
|
||||
return {k: v for k, v in data.items() if k != key}
|
||||
|
||||
|
||||
# a device of the test project with channels
|
||||
DEVICE = "1.1.7"
|
||||
CHANNEL = "MD-2_M-20_MI-1_CH-81"
|
||||
|
||||
|
||||
def _with_group_address(data: dict[str, Any], **changes: Any) -> dict[str, Any]:
|
||||
group_address = data["group_addresses"]["1/0/0"]
|
||||
return {
|
||||
**data,
|
||||
"group_addresses": {
|
||||
**data["group_addresses"],
|
||||
"1/0/0": {**group_address, **changes},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _with_device(data: dict[str, Any], device: dict[str, Any]) -> dict[str, Any]:
|
||||
return {**data, "devices": {**data["devices"], DEVICE: device}}
|
||||
|
||||
|
||||
def _with_channel(data: dict[str, Any], **changes: Any) -> dict[str, Any]:
|
||||
device = data["devices"][DEVICE]
|
||||
channel = device["channels"][CHANNEL]
|
||||
return _with_device(
|
||||
data,
|
||||
{**device, "channels": {**device["channels"], CHANNEL: {**channel, **changes}}},
|
||||
)
|
||||
|
||||
|
||||
def _with_info(data: dict[str, Any], **changes: Any) -> dict[str, Any]:
|
||||
return {**data, "info": {**data["info"], **changes}}
|
||||
|
||||
|
||||
async def test_set_project_two_level(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
current_project_data: dict[str, Any],
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""The group addresses of a two level project are taken."""
|
||||
# loading sets the address format of xknx for the whole process: setting
|
||||
# the attribute to its own value restores it on teardown
|
||||
monkeypatch.setattr(GroupAddress, "address_format", GroupAddress.address_format)
|
||||
await knx.setup_integration()
|
||||
group_address = current_project_data["group_addresses"]["1/0/0"]
|
||||
new_data = {
|
||||
**_with_info(current_project_data, group_address_style="TwoLevel"),
|
||||
"group_addresses": {"0/1": {**group_address, "address": "0/1"}},
|
||||
}
|
||||
|
||||
await async_set_project(hass, new_data)
|
||||
|
||||
assert set(hass.data[KNX_MODULE_KEY].project.group_addresses) == {"0/1"}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("change", "translation_key"),
|
||||
[
|
||||
(lambda data: _without(data, "devices"), "project_data_invalid"),
|
||||
(lambda data: _without(data, "functions"), "project_data_invalid"),
|
||||
(
|
||||
lambda data: {**data, "info": _without(data["info"], "name")},
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: _with_info(data, group_address_style="FourLevel"),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(lambda data: _with_group_address(data, address="x/y"), "project_data_invalid"),
|
||||
(
|
||||
# the address is read from the field, but links refer to the key
|
||||
lambda data: _with_group_address(data, address="1/0/1"),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: _with_group_address(data, dpt={"main": "1", "sub": None}),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: _with_device(data, _without(data["devices"][DEVICE], "name")),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
# the semantics entity suggestions read
|
||||
lambda data: _with_device(
|
||||
data, _without(data["devices"][DEVICE], "channels")
|
||||
),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: _with_channel(data, functional_blocks="FB-1"),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: {
|
||||
**data,
|
||||
"communication_objects": {
|
||||
object_id: _without(com_object, "dpas")
|
||||
for object_id, com_object in data["communication_objects"].items()
|
||||
},
|
||||
},
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: {
|
||||
**_without(data, "trades"),
|
||||
"info": {**data["info"], "xknxproject_version": "3.10.0"},
|
||||
},
|
||||
"project_data_incompatible",
|
||||
),
|
||||
(
|
||||
# a required key of the installed version
|
||||
lambda data: _without(data, "trades"),
|
||||
"project_data_invalid",
|
||||
),
|
||||
(
|
||||
lambda data: _with_info(data, xknxproject_version="99.0.0"),
|
||||
"project_data_incompatible",
|
||||
),
|
||||
(
|
||||
lambda data: _with_info(data, xknxproject_version="unknown"),
|
||||
"project_data_incompatible",
|
||||
),
|
||||
],
|
||||
)
|
||||
@pytest.mark.usefixtures("load_knxproj")
|
||||
async def test_set_project_invalid_data(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
project_data: dict[str, Any],
|
||||
current_project_data: dict[str, Any],
|
||||
hass_storage: dict[str, Any],
|
||||
change: Callable[[dict[str, Any]], dict[str, Any]],
|
||||
translation_key: str,
|
||||
) -> None:
|
||||
"""Invalid or incompatible data is refused and the project is kept."""
|
||||
await knx.setup_integration()
|
||||
project = hass.data[KNX_MODULE_KEY].project
|
||||
stored = hass_storage[KNX_PROJECT_STORAGE_KEY]
|
||||
|
||||
with pytest.raises(HomeAssistantError) as exc_info:
|
||||
await async_set_project(hass, change(current_project_data))
|
||||
|
||||
assert exc_info.value.translation_key == translation_key
|
||||
assert hass_storage[KNX_PROJECT_STORAGE_KEY] is stored
|
||||
assert project.info == project_data["info"]
|
||||
assert "0/0/3" in project.group_addresses
|
||||
|
||||
|
||||
async def test_set_project_not_loaded(
|
||||
hass: HomeAssistant, current_project_data: dict[str, Any]
|
||||
) -> None:
|
||||
"""Project data needs a loaded KNX integration."""
|
||||
with pytest.raises(HomeAssistantError) as exc_info:
|
||||
await async_set_project(hass, current_project_data)
|
||||
|
||||
assert exc_info.value.translation_key == "integration_not_loaded"
|
||||
|
||||
@@ -176,6 +176,75 @@ async def test_knx_project_file_process_error(
|
||||
assert not hass.data[KNX_MODULE_KEY].project.loaded
|
||||
|
||||
|
||||
async def test_knx_set_project(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_storage: dict[str, Any],
|
||||
current_project_data: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test knx/set_knx_project command for storing and loading project data."""
|
||||
await knx.setup_integration()
|
||||
client = await hass_ws_client(hass)
|
||||
assert not hass.data[KNX_MODULE_KEY].project.loaded
|
||||
|
||||
await client.send_json_auto_id(
|
||||
{"type": "knx/set_knx_project", "project": current_project_data}
|
||||
)
|
||||
res = await client.receive_json()
|
||||
|
||||
assert res["success"], res
|
||||
assert hass.data[KNX_MODULE_KEY].project.loaded
|
||||
assert hass_storage[KNX_PROJECT_STORAGE_KEY]["data"] == current_project_data
|
||||
|
||||
|
||||
async def test_knx_set_project_invalid(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
hass_storage: dict[str, Any],
|
||||
current_project_data: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test knx/set_knx_project refuses invalid project data."""
|
||||
await knx.setup_integration()
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
await client.send_json_auto_id(
|
||||
{
|
||||
"type": "knx/set_knx_project",
|
||||
"project": {**current_project_data, "group_addresses": None},
|
||||
}
|
||||
)
|
||||
res = await client.receive_json()
|
||||
|
||||
assert not res["success"]
|
||||
assert res["error"]["code"] == "home_assistant_error"
|
||||
assert res["error"]["translation_key"] == "project_data_invalid"
|
||||
assert not hass.data[KNX_MODULE_KEY].project.loaded
|
||||
assert KNX_PROJECT_STORAGE_KEY not in hass_storage
|
||||
|
||||
|
||||
async def test_knx_set_project_not_loaded(
|
||||
hass: HomeAssistant,
|
||||
knx: KNXTestKit,
|
||||
hass_ws_client: WebSocketGenerator,
|
||||
current_project_data: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test knx/set_knx_project when the config entry is unloaded."""
|
||||
await knx.setup_integration()
|
||||
await hass.config_entries.async_unload(knx.mock_config_entry.entry_id)
|
||||
client = await hass_ws_client(hass)
|
||||
|
||||
await client.send_json_auto_id(
|
||||
{"type": "knx/set_knx_project", "project": current_project_data}
|
||||
)
|
||||
res = await client.receive_json()
|
||||
|
||||
assert not res["success"]
|
||||
assert res["error"]["code"] == "home_assistant_error"
|
||||
assert res["error"]["translation_key"] == "integration_not_loaded"
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("load_knxproj")
|
||||
async def test_knx_project_file_remove(
|
||||
hass: HomeAssistant,
|
||||
|
||||
Reference in New Issue
Block a user