Convert Vallox integration to config flow (#62780)

This commit is contained in:
Sebastian Lövdahl 2021-12-28 22:06:29 +02:00 committed by GitHub
parent 28faf9eafc
commit b5fd2e0d58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 546 additions and 74 deletions

View File

@ -1206,7 +1206,10 @@ omit =
homeassistant/components/upnp/*
homeassistant/components/upc_connect/*
homeassistant/components/uscis/sensor.py
homeassistant/components/vallox/*
homeassistant/components/vallox/__init__.py
homeassistant/components/vallox/const.py
homeassistant/components/vallox/fan.py
homeassistant/components/vallox/sensor.py
homeassistant/components/vasttrafik/sensor.py
homeassistant/components/velbus/__init__.py
homeassistant/components/velbus/binary_sensor.py

View File

@ -986,7 +986,8 @@ homeassistant/components/usgs_earthquakes_feed/* @exxamalte
tests/components/usgs_earthquakes_feed/* @exxamalte
homeassistant/components/utility_meter/* @dgomes
tests/components/utility_meter/* @dgomes
homeassistant/components/vallox/* @andre-richter
homeassistant/components/vallox/* @andre-richter @slovdahl
tests/components/vallox/* @andre-richter @slovdahl
homeassistant/components/velbus/* @Cereal2nd @brefra
tests/components/velbus/* @Cereal2nd @brefra
homeassistant/components/velux/* @Julius2342

View File

@ -1,7 +1,6 @@
"""Support for Vallox ventilation units."""
from __future__ import annotations
import asyncio
from dataclasses import dataclass, field
import ipaddress
import logging
@ -13,10 +12,10 @@ from vallox_websocket_api.exceptions import ValloxApiException
from vallox_websocket_api.vallox import get_uuid as calculate_uuid
import voluptuous as vol
from homeassistant.const import CONF_HOST, CONF_NAME, EVENT_HOMEASSISTANT_STARTED
from homeassistant.core import CoreState, HomeAssistant, ServiceCall
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_HOST, CONF_NAME, Platform
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import config_validation as cv
from homeassistant.helpers.discovery import async_load_platform
from homeassistant.helpers.typing import ConfigType, StateType
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
@ -26,7 +25,6 @@ from .const import (
DEFAULT_FAN_SPEED_HOME,
DEFAULT_NAME,
DOMAIN,
INITIAL_COORDINATOR_UPDATE_RETRY_INTERVAL_SECONDS,
METRIC_KEY_PROFILE_FAN_SPEED_AWAY,
METRIC_KEY_PROFILE_FAN_SPEED_BOOST,
METRIC_KEY_PROFILE_FAN_SPEED_HOME,
@ -37,17 +35,25 @@ from .const import (
_LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_HOST): vol.All(ipaddress.ip_address, cv.string),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
},
vol.All(
cv.deprecated(DOMAIN),
{
DOMAIN: vol.Schema(
{
vol.Required(CONF_HOST): vol.All(ipaddress.ip_address, cv.string),
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
}
)
},
),
extra=vol.ALLOW_EXTRA,
)
PLATFORMS: list[str] = [
Platform.SENSOR,
Platform.FAN,
]
ATTR_PROFILE = "profile"
ATTR_PROFILE_FAN_SPEED = "fan_speed"
@ -133,10 +139,25 @@ class ValloxDataUpdateCoordinator(DataUpdateCoordinator):
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the integration from configuration.yaml (DEPRECATED)."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data=config[DOMAIN],
)
)
return True
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up the client and boot the platforms."""
conf = config[DOMAIN]
host = conf[CONF_HOST]
name = conf[CONF_NAME]
host = entry.data[CONF_HOST]
name = entry.data[CONF_NAME]
client = Vallox(host)
@ -161,6 +182,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
update_method=async_update_data,
)
await coordinator.async_config_entry_first_refresh()
service_handler = ValloxServiceHandler(client, coordinator)
for vallox_service, service_details in SERVICE_TO_METHOD.items():
hass.services.async_register(
@ -170,44 +193,31 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
schema=service_details.schema,
)
hass.data[DOMAIN] = {"client": client, "coordinator": coordinator, "name": name}
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = {
"client": client,
"coordinator": coordinator,
"name": name,
}
async def _async_load_platform_delayed(*_: Any) -> None:
# We need a successful update before loading the platforms, because platform init code
# derives the UUIDs from the data the coordinator fetches.
warned_once = False
while hass.state == CoreState.running:
await coordinator.async_refresh()
if coordinator.last_update_success:
break
if not warned_once:
_LOGGER.warning(
"Vallox integration not ready yet; Retrying in background"
)
warned_once = True
await asyncio.sleep(INITIAL_COORDINATOR_UPDATE_RETRY_INTERVAL_SECONDS)
else:
return
hass.async_create_task(async_load_platform(hass, "sensor", DOMAIN, {}, config))
hass.async_create_task(async_load_platform(hass, "fan", DOMAIN, {}, config))
# The Vallox hardware expects quite strict timings for websocket requests. Timings that machines
# with less processing power, like a Raspberry Pi, cannot live up to during the busy start phase
# of Home Asssistant.
#
# Hence, wait for the started event before doing a first data refresh and loading the platforms,
# because it usually means the system is less busy after the event and can now meet the
# websocket timing requirements.
hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_STARTED, _async_load_platform_delayed
)
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
if hass.data[DOMAIN]:
return unload_ok
for service in SERVICE_TO_METHOD:
hass.services.async_remove(DOMAIN, service)
return unload_ok
class ValloxServiceHandler:
"""Services implementation."""

View File

@ -0,0 +1,120 @@
"""Config flow for the Vallox integration."""
from __future__ import annotations
import logging
from typing import Any
from vallox_websocket_api import Vallox
from vallox_websocket_api.exceptions import ValloxApiException
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResult
from homeassistant.exceptions import HomeAssistantError
from homeassistant.util.network import is_ip_address
from .const import DEFAULT_NAME, DOMAIN
_LOGGER = logging.getLogger(__name__)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_HOST): str,
}
)
VALLOX_CONNECTION_EXCEPTIONS = (
OSError,
ValloxApiException,
)
async def validate_host(hass: HomeAssistant, host: str) -> None:
"""Validate that the user input allows us to connect."""
if not is_ip_address(host):
raise InvalidHost(f"Invalid IP address: {host}")
client = Vallox(host)
await client.get_info()
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for the Vallox integration."""
VERSION = 1
async def async_step_import(self, data: dict[str, Any]) -> FlowResult:
"""Handle import from YAML."""
# We need to use the name from the YAML configuration to avoid
# breaking existing entity IDs.
name = data.get(CONF_NAME, DEFAULT_NAME)
host = data[CONF_HOST]
self._async_abort_entries_match({CONF_HOST: host})
reason = None
try:
await validate_host(self.hass, host)
except InvalidHost:
_LOGGER.exception("An invalid host is configured for Vallox")
reason = "invalid_host"
except VALLOX_CONNECTION_EXCEPTIONS:
_LOGGER.exception("Cannot connect to Vallox")
reason = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
reason = "unknown"
else:
return self.async_create_entry(
title=name,
data={
**data,
CONF_NAME: name,
},
)
return self.async_abort(reason=reason)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
if user_input is None or user_input[CONF_HOST] is None:
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)
errors = {}
host = user_input[CONF_HOST]
self._async_abort_entries_match({CONF_HOST: host})
try:
await validate_host(self.hass, host)
except InvalidHost:
errors[CONF_HOST] = "invalid_host"
except VALLOX_CONNECTION_EXCEPTIONS:
errors[CONF_HOST] = "cannot_connect"
except Exception: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
errors[CONF_HOST] = "unknown"
else:
return self.async_create_entry(
title=DEFAULT_NAME,
data={
**user_input,
CONF_NAME: DEFAULT_NAME,
},
)
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA, errors=errors
)
class InvalidHost(HomeAssistantError):
"""Error to indicate an invalid host was input."""

View File

@ -7,7 +7,6 @@ from vallox_websocket_api import PROFILE as VALLOX_PROFILE
DOMAIN = "vallox"
DEFAULT_NAME = "Vallox"
INITIAL_COORDINATOR_UPDATE_RETRY_INTERVAL_SECONDS = 5
STATE_SCAN_INTERVAL = timedelta(seconds=60)
# Common metric keys and (default) values.

View File

@ -13,9 +13,10 @@ from homeassistant.components.fan import (
FanEntity,
NotValidPresetModeError,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from . import ValloxDataUpdateCoordinator
@ -61,21 +62,19 @@ def _convert_fan_speed_value(value: StateType) -> int | None:
return None
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the fan device."""
if discovery_info is None:
return
data = hass.data[DOMAIN][entry.entry_id]
client = hass.data[DOMAIN]["client"]
client = data["client"]
client.set_settable_address(METRIC_KEY_MODE, int)
device = ValloxFan(
hass.data[DOMAIN]["name"], client, hass.data[DOMAIN]["coordinator"]
data["name"],
client,
data["coordinator"],
)
async_add_entities([device])

View File

@ -3,6 +3,7 @@
"name": "Vallox",
"documentation": "https://www.home-assistant.io/integrations/vallox",
"requirements": ["vallox-websocket-api==2.8.1"],
"codeowners": ["@andre-richter"],
"codeowners": ["@andre-richter", "@slovdahl"],
"config_flow": true,
"iot_class": "local_polling"
}

View File

@ -10,6 +10,7 @@ from homeassistant.components.sensor import (
SensorEntityDescription,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
CONCENTRATION_PARTS_PER_MILLION,
PERCENTAGE,
@ -17,7 +18,7 @@ from homeassistant.const import (
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType, StateType
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import CoordinatorEntity
from homeassistant.util import dt as dt_util
@ -219,18 +220,12 @@ SENSORS: tuple[ValloxSensorEntityDescription, ...] = (
)
async def async_setup_platform(
hass: HomeAssistant,
config: ConfigType,
async_add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up the sensors."""
if discovery_info is None:
return
name = hass.data[DOMAIN]["name"]
coordinator = hass.data[DOMAIN]["coordinator"]
name = hass.data[DOMAIN][entry.entry_id]["name"]
coordinator = hass.data[DOMAIN][entry.entry_id]["coordinator"]
async_add_entities(
[

View File

@ -0,0 +1,21 @@
{
"config": {
"step": {
"user": {
"title": "Vallox",
"description": "Set up the Vallox integration. If you have problems with configuration go to https://www.home-assistant.io/integrations/vallox.",
"data": {
"host": "[%key:common::config_flow::data::host%]",
"name": "[%key:common::config_flow::data::name%]"
}
}
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_service%]"
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
"invalid_host": "[%key:common::config_flow::error::invalid_host%]"
}
}
}

View File

@ -0,0 +1,20 @@
{
"config": {
"abort": {
"already_configured": "Device is already configured"
},
"error": {
"cannot_connect": "Failed to connect to Vallox",
"invalid_host": "Invalid host",
"unknown": "Unexpected error"
},
"step": {
"user": {
"data": {
"host": "Host",
"name": "Name"
}
}
}
}
}

View File

@ -329,6 +329,7 @@ FLOWS = [
"upcloud",
"upnp",
"uptimerobot",
"vallox",
"velbus",
"venstar",
"vera",

View File

@ -1428,6 +1428,9 @@ url-normalize==1.4.1
# homeassistant.components.uvc
uvcclient==0.11.0
# homeassistant.components.vallox
vallox-websocket-api==2.8.1
# homeassistant.components.rdw
vehicle==0.3.1

View File

@ -0,0 +1 @@
"""Tests for the Vallox integration."""

View File

@ -0,0 +1,298 @@
"""Test the Vallox integration config flow."""
from unittest.mock import patch
from vallox_websocket_api.exceptions import ValloxApiException
from homeassistant.components.vallox.const import DOMAIN
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
from homeassistant.const import CONF_HOST, CONF_NAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from tests.common import MockConfigEntry
async def test_form_no_input(hass: HomeAssistant) -> None:
"""Test that the form is returned with no input."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] is None
async def test_form_create_entry(hass: HomeAssistant) -> None:
"""Test that an entry is created with valid input."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
assert init["type"] == RESULT_TYPE_FORM
assert init["errors"] is None
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
return_value=None,
), patch(
"homeassistant.components.vallox.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "1.2.3.4"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "Vallox"
assert result["data"] == {"host": "1.2.3.4", "name": "Vallox"}
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_invalid_ip(hass: HomeAssistant) -> None:
"""Test that invalid IP error is handled."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "test.host.com"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"host": "invalid_host"}
async def test_form_vallox_api_exception_cannot_connect(hass: HomeAssistant) -> None:
"""Test that cannot connect error is handled."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=ValloxApiException,
):
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "4.3.2.1"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"host": "cannot_connect"}
async def test_form_os_error_cannot_connect(hass: HomeAssistant) -> None:
"""Test that cannot connect error is handled."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=OSError,
):
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "5.6.7.8"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"host": "cannot_connect"}
async def test_form_unknown_exception(hass: HomeAssistant) -> None:
"""Test that unknown exceptions are handled."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "54.12.31.41"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"host": "unknown"}
async def test_form_already_configured(hass: HomeAssistant) -> None:
"""Test that already configured error is handled."""
init = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_USER}
)
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "20.40.10.30",
CONF_NAME: "Vallox 110 MV",
},
)
mock_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_configure(
init["flow_id"],
{"host": "20.40.10.30"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
async def test_import_with_custom_name(hass: HomeAssistant) -> None:
"""Test that import is handled."""
name = "Vallox 90 MV"
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
return_value=None,
), patch(
"homeassistant.components.vallox.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "1.2.3.4", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == name
assert result["data"] == {"host": "1.2.3.4", "name": "Vallox 90 MV"}
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_without_custom_name(hass: HomeAssistant) -> None:
"""Test that import is handled."""
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
return_value=None,
), patch(
"homeassistant.components.vallox.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "1.2.3.4"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
assert result["title"] == "Vallox"
assert result["data"] == {"host": "1.2.3.4", "name": "Vallox"}
assert len(mock_setup_entry.mock_calls) == 1
async def test_import_invalid_ip(hass: HomeAssistant) -> None:
"""Test that invalid IP error is handled during import."""
name = "Vallox 90 MV"
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "vallox90mv.host.name", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "invalid_host"
async def test_import_already_configured(hass: HomeAssistant) -> None:
"""Test that an already configured Vallox device is handled during import."""
name = "Vallox 145 MV"
mock_entry = MockConfigEntry(
domain=DOMAIN,
data={
CONF_HOST: "40.10.20.30",
CONF_NAME: "Vallox 145 MV",
},
)
mock_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "40.10.20.30", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
async def test_import_cannot_connect_OSError(hass: HomeAssistant) -> None:
"""Test that cannot connect error is handled."""
name = "Vallox 90 MV"
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=OSError,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "1.2.3.4", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "cannot_connect"
async def test_import_cannot_connect_ValloxApiException(hass: HomeAssistant) -> None:
"""Test that cannot connect error is handled."""
name = "Vallox 90 MV"
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=ValloxApiException,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "5.6.3.1", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "cannot_connect"
async def test_import_unknown_exception(hass: HomeAssistant) -> None:
"""Test that unknown exceptions are handled."""
name = "Vallox 245 MV"
with patch(
"homeassistant.components.vallox.config_flow.Vallox.get_info",
side_effect=Exception,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": SOURCE_IMPORT},
data={"host": "1.2.3.4", "name": name},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "unknown"