Add config flow for nuki (#45664)
* implemented config_flow for nuki component * warn -> warning * exception handling & config_flow tests * gen_requirements_all * Update config_flow.py Co-authored-by: Pascal Vizeli <pascal.vizeli@syshack.ch>
This commit is contained in:
parent
b74cbb2a59
commit
ba55f1ff4b
13 changed files with 319 additions and 11 deletions
|
@ -621,6 +621,8 @@ omit =
|
|||
homeassistant/components/notify_events/notify.py
|
||||
homeassistant/components/nsw_fuel_station/sensor.py
|
||||
homeassistant/components/nuimo_controller/*
|
||||
homeassistant/components/nuki/__init__.py
|
||||
homeassistant/components/nuki/const.py
|
||||
homeassistant/components/nuki/lock.py
|
||||
homeassistant/components/nut/sensor.py
|
||||
homeassistant/components/nx584/alarm_control_panel.py
|
||||
|
|
|
@ -310,7 +310,7 @@ homeassistant/components/notion/* @bachya
|
|||
homeassistant/components/nsw_fuel_station/* @nickw444
|
||||
homeassistant/components/nsw_rural_fire_service_feed/* @exxamalte
|
||||
homeassistant/components/nuheat/* @bdraco
|
||||
homeassistant/components/nuki/* @pschmitt @pvizeli
|
||||
homeassistant/components/nuki/* @pschmitt @pvizeli @pree
|
||||
homeassistant/components/numato/* @clssn
|
||||
homeassistant/components/number/* @home-assistant/core @Shulyaka
|
||||
homeassistant/components/nut/* @bdraco
|
||||
|
|
|
@ -1,3 +1,63 @@
|
|||
"""The nuki component."""
|
||||
|
||||
DOMAIN = "nuki"
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.lock import DOMAIN as LOCK_DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_IMPORT
|
||||
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from .const import DEFAULT_PORT, DOMAIN
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
NUKI_PLATFORMS = ["lock"]
|
||||
UPDATE_INTERVAL = timedelta(seconds=30)
|
||||
|
||||
NUKI_SCHEMA = vol.Schema(
|
||||
vol.All(
|
||||
{
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
|
||||
vol.Required(CONF_TOKEN): cv.string,
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
CONFIG_SCHEMA = vol.Schema(
|
||||
{DOMAIN: vol.Schema(NUKI_SCHEMA)},
|
||||
extra=vol.ALLOW_EXTRA,
|
||||
)
|
||||
|
||||
|
||||
async def async_setup(hass, config):
|
||||
"""Set up the Nuki component."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
_LOGGER.debug("Config: %s", config)
|
||||
|
||||
for platform in NUKI_PLATFORMS:
|
||||
confs = config.get(platform)
|
||||
if confs is None:
|
||||
continue
|
||||
|
||||
for conf in confs:
|
||||
_LOGGER.debug("Conf: %s", conf)
|
||||
hass.async_create_task(
|
||||
hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": SOURCE_IMPORT}, data=conf
|
||||
)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
async def async_setup_entry(hass, entry):
|
||||
"""Set up the Nuki entry."""
|
||||
hass.async_create_task(
|
||||
hass.config_entries.async_forward_entry_setup(entry, LOCK_DOMAIN)
|
||||
)
|
||||
|
||||
return True
|
||||
|
|
97
homeassistant/components/nuki/config_flow.py
Normal file
97
homeassistant/components/nuki/config_flow.py
Normal file
|
@ -0,0 +1,97 @@
|
|||
"""Config flow to configure the Nuki integration."""
|
||||
import logging
|
||||
|
||||
from pynuki import NukiBridge
|
||||
from pynuki.bridge import InvalidCredentialsException
|
||||
from requests.exceptions import RequestException
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant import config_entries, exceptions
|
||||
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
|
||||
|
||||
from .const import ( # pylint: disable=unused-import
|
||||
DEFAULT_PORT,
|
||||
DEFAULT_TIMEOUT,
|
||||
DOMAIN,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
USER_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Required(CONF_HOST): str,
|
||||
vol.Optional(CONF_PORT, default=DEFAULT_PORT): vol.Coerce(int),
|
||||
vol.Required(CONF_TOKEN): str,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def validate_input(hass, data):
|
||||
"""Validate the user input allows us to connect.
|
||||
|
||||
Data has the keys from USER_SCHEMA with values provided by the user.
|
||||
"""
|
||||
|
||||
try:
|
||||
bridge = await hass.async_add_executor_job(
|
||||
NukiBridge,
|
||||
data[CONF_HOST],
|
||||
data[CONF_TOKEN],
|
||||
data[CONF_PORT],
|
||||
True,
|
||||
DEFAULT_TIMEOUT,
|
||||
)
|
||||
|
||||
info = bridge.info()
|
||||
except InvalidCredentialsException as err:
|
||||
raise InvalidAuth from err
|
||||
except RequestException as err:
|
||||
raise CannotConnect from err
|
||||
|
||||
return info
|
||||
|
||||
|
||||
class NukiConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Nuki config flow."""
|
||||
|
||||
async def async_step_import(self, user_input=None):
|
||||
"""Handle a flow initiated by import."""
|
||||
return await self.async_step_validate(user_input)
|
||||
|
||||
async def async_step_user(self, user_input=None):
|
||||
"""Handle a flow initiated by the user."""
|
||||
return await self.async_step_validate(user_input)
|
||||
|
||||
async def async_step_validate(self, user_input):
|
||||
"""Handle init step of a flow."""
|
||||
|
||||
errors = {}
|
||||
if user_input is not None:
|
||||
try:
|
||||
info = await validate_input(self.hass, user_input)
|
||||
except CannotConnect:
|
||||
errors["base"] = "cannot_connect"
|
||||
except InvalidAuth:
|
||||
errors["base"] = "invalid_auth"
|
||||
except Exception: # pylint: disable=broad-except
|
||||
_LOGGER.exception("Unexpected exception")
|
||||
errors["base"] = "unknown"
|
||||
|
||||
if "base" not in errors:
|
||||
await self.async_set_unique_id(info["ids"]["hardwareId"])
|
||||
self._abort_if_unique_id_configured()
|
||||
return self.async_create_entry(
|
||||
title=info["ids"]["hardwareId"], data=user_input
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user", data_schema=USER_SCHEMA, errors=errors
|
||||
)
|
||||
|
||||
|
||||
class CannotConnect(exceptions.HomeAssistantError):
|
||||
"""Error to indicate we cannot connect."""
|
||||
|
||||
|
||||
class InvalidAuth(exceptions.HomeAssistantError):
|
||||
"""Error to indicate there is invalid auth."""
|
6
homeassistant/components/nuki/const.py
Normal file
6
homeassistant/components/nuki/const.py
Normal file
|
@ -0,0 +1,6 @@
|
|||
"""Constants for Nuki."""
|
||||
DOMAIN = "nuki"
|
||||
|
||||
# Defaults
|
||||
DEFAULT_PORT = 8080
|
||||
DEFAULT_TIMEOUT = 20
|
|
@ -11,10 +11,9 @@ from homeassistant.components.lock import PLATFORM_SCHEMA, SUPPORT_OPEN, LockEnt
|
|||
from homeassistant.const import CONF_HOST, CONF_PORT, CONF_TOKEN
|
||||
from homeassistant.helpers import config_validation as cv, entity_platform
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
from .const import DEFAULT_PORT, DEFAULT_TIMEOUT
|
||||
|
||||
DEFAULT_PORT = 8080
|
||||
DEFAULT_TIMEOUT = 20
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
ATTR_BATTERY_CRITICAL = "battery_critical"
|
||||
ATTR_NUKI_ID = "nuki_id"
|
||||
|
@ -38,6 +37,15 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|||
|
||||
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
|
||||
"""Set up the Nuki lock platform."""
|
||||
_LOGGER.warning(
|
||||
"Loading Nuki by lock platform configuration is deprecated and will be removed in the future"
|
||||
)
|
||||
|
||||
|
||||
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||
"""Set up the Nuki lock platform."""
|
||||
config = config_entry.data
|
||||
_LOGGER.debug("Config: %s", config)
|
||||
|
||||
def get_entities():
|
||||
bridge = NukiBridge(
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
{
|
||||
"domain": "nuki",
|
||||
"name": "Nuki",
|
||||
"documentation": "https://www.home-assistant.io/integrations/nuki",
|
||||
"requirements": ["pynuki==1.3.8"],
|
||||
"codeowners": ["@pschmitt", "@pvizeli"]
|
||||
}
|
||||
"domain": "nuki",
|
||||
"name": "Nuki",
|
||||
"documentation": "https://www.home-assistant.io/integrations/nuki",
|
||||
"requirements": ["pynuki==1.3.8"],
|
||||
"codeowners": ["@pschmitt", "@pvizeli", "@pree"],
|
||||
"config_flow": true
|
||||
}
|
18
homeassistant/components/nuki/strings.json
Normal file
18
homeassistant/components/nuki/strings.json
Normal file
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"host": "[%key:common::config_flow::data::host%]",
|
||||
"port": "[%key:common::config_flow::data::port%]",
|
||||
"token": "[%key:common::config_flow::data::access_token%]"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
|
||||
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
|
||||
"unknown": "[%key:common::config_flow::error::unknown%]"
|
||||
}
|
||||
}
|
||||
}
|
18
homeassistant/components/nuki/translations/en.json
Normal file
18
homeassistant/components/nuki/translations/en.json
Normal file
|
@ -0,0 +1,18 @@
|
|||
{
|
||||
"config": {
|
||||
"error": {
|
||||
"cannot_connect": "Failed to connect",
|
||||
"invalid_auth": "Could not login with provided token",
|
||||
"unknown": "Unknown error"
|
||||
},
|
||||
"step": {
|
||||
"user": {
|
||||
"data": {
|
||||
"token": "Access Token",
|
||||
"host": "Host",
|
||||
"port": "Port"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -141,6 +141,7 @@ FLOWS = [
|
|||
"nightscout",
|
||||
"notion",
|
||||
"nuheat",
|
||||
"nuki",
|
||||
"nut",
|
||||
"nws",
|
||||
"nzbget",
|
||||
|
|
|
@ -804,6 +804,9 @@ pymonoprice==0.3
|
|||
# homeassistant.components.myq
|
||||
pymyq==2.0.14
|
||||
|
||||
# homeassistant.components.nuki
|
||||
pynuki==1.3.8
|
||||
|
||||
# homeassistant.components.nut
|
||||
pynut2==2.1.2
|
||||
|
||||
|
|
1
tests/components/nuki/__init__.py
Normal file
1
tests/components/nuki/__init__.py
Normal file
|
@ -0,0 +1 @@
|
|||
"""The tests for nuki integration."""
|
93
tests/components/nuki/test_config_flow.py
Normal file
93
tests/components/nuki/test_config_flow.py
Normal file
|
@ -0,0 +1,93 @@
|
|||
"""Test the nuki config flow."""
|
||||
from unittest.mock import patch
|
||||
|
||||
from homeassistant import config_entries, setup
|
||||
from homeassistant.components.nuki.config_flow import CannotConnect, InvalidAuth
|
||||
from homeassistant.components.nuki.const import DOMAIN
|
||||
|
||||
|
||||
async def test_form(hass):
|
||||
"""Test we get the form."""
|
||||
await setup.async_setup_component(hass, "persistent_notification", {})
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
assert result["type"] == "form"
|
||||
assert result["errors"] == {}
|
||||
|
||||
mock_info = {"ids": {"hardwareId": "0001"}}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.nuki.config_flow.NukiBridge.info",
|
||||
return_value=mock_info,
|
||||
), patch(
|
||||
"homeassistant.components.nuki.async_setup", return_value=True
|
||||
) as mock_setup, patch(
|
||||
"homeassistant.components.nuki.async_setup_entry",
|
||||
return_value=True,
|
||||
) as mock_setup_entry:
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
"host": "1.1.1.1",
|
||||
"port": 8080,
|
||||
"token": "test-token",
|
||||
},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result2["type"] == "create_entry"
|
||||
assert result2["title"] == "0001"
|
||||
assert result2["data"] == {
|
||||
"host": "1.1.1.1",
|
||||
"port": 8080,
|
||||
"token": "test-token",
|
||||
}
|
||||
assert len(mock_setup.mock_calls) == 1
|
||||
assert len(mock_setup_entry.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_form_invalid_auth(hass):
|
||||
"""Test we handle invalid auth."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.nuki.config_flow.NukiBridge.info",
|
||||
side_effect=InvalidAuth,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
"host": "1.1.1.1",
|
||||
"port": 8080,
|
||||
"token": "test-token",
|
||||
},
|
||||
)
|
||||
|
||||
assert result2["type"] == "form"
|
||||
assert result2["errors"] == {"base": "invalid_auth"}
|
||||
|
||||
|
||||
async def test_form_cannot_connect(hass):
|
||||
"""Test we handle cannot connect error."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
DOMAIN, context={"source": config_entries.SOURCE_USER}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.nuki.config_flow.NukiBridge.info",
|
||||
side_effect=CannotConnect,
|
||||
):
|
||||
result2 = await hass.config_entries.flow.async_configure(
|
||||
result["flow_id"],
|
||||
{
|
||||
"host": "1.1.1.1",
|
||||
"port": 8080,
|
||||
"token": "test-token",
|
||||
},
|
||||
)
|
||||
|
||||
assert result2["type"] == "form"
|
||||
assert result2["errors"] == {"base": "cannot_connect"}
|
Loading…
Add table
Reference in a new issue