core/homeassistant/components/onvif/config_flow.py

307 lines
10 KiB
Python
Raw Normal View History

2020-05-01 06:15:40 +00:00
"""Config flow for ONVIF."""
2021-03-18 12:21:46 +00:00
from __future__ import annotations
2020-05-01 06:15:40 +00:00
from pprint import pformat
from urllib.parse import urlparse
2020-05-06 16:29:59 +00:00
from onvif.exceptions import ONVIFError
2020-05-01 06:15:40 +00:00
import voluptuous as vol
from wsdiscovery.discovery import ThreadedWSDiscovery as WSDiscovery
from wsdiscovery.scope import Scope
from wsdiscovery.service import Service
from zeep.exceptions import Fault
from homeassistant import config_entries
from homeassistant.components.ffmpeg import CONF_EXTRA_ARGUMENTS
from homeassistant.const import (
CONF_HOST,
CONF_NAME,
CONF_PASSWORD,
CONF_PORT,
CONF_USERNAME,
)
from homeassistant.core import callback
from .const import (
CONF_DEVICE_ID,
CONF_RTSP_TRANSPORT,
DEFAULT_ARGUMENTS,
DEFAULT_PORT,
DOMAIN,
LOGGER,
RTSP_TRANS_PROTOCOLS,
)
2020-05-06 16:29:59 +00:00
from .device import get_device
2020-05-01 06:15:40 +00:00
CONF_MANUAL_INPUT = "Manually configure ONVIF device"
2021-03-18 12:21:46 +00:00
def wsdiscovery() -> list[Service]:
2020-05-01 06:15:40 +00:00
"""Get ONVIF Profile S devices from network."""
discovery = WSDiscovery(ttl=4)
discovery.start()
services = discovery.searchServices(
scopes=[Scope("onvif://www.onvif.org/Profile/Streaming")]
)
discovery.stop()
return services
async def async_discovery(hass) -> bool:
"""Return if there are devices that can be discovered."""
LOGGER.debug("Starting ONVIF discovery")
2020-05-01 06:15:40 +00:00
services = await hass.async_add_executor_job(wsdiscovery)
devices = []
for service in services:
url = urlparse(service.getXAddrs()[0])
device = {
CONF_DEVICE_ID: None,
CONF_NAME: service.getEPR(),
CONF_HOST: url.hostname,
CONF_PORT: url.port or 80,
}
for scope in service.getScopes():
scope_str = scope.getValue()
if scope_str.lower().startswith("onvif://www.onvif.org/name"):
device[CONF_NAME] = scope_str.split("/")[-1]
if scope_str.lower().startswith("onvif://www.onvif.org/mac"):
device[CONF_DEVICE_ID] = scope_str.split("/")[-1]
devices.append(device)
return devices
class OnvifFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a ONVIF config flow."""
VERSION = 1
@staticmethod
@callback
def async_get_options_flow(config_entry):
"""Get the options flow for this handler."""
return OnvifOptionsFlowHandler(config_entry)
def __init__(self):
"""Initialize the ONVIF config flow."""
self.device_id = None
self.devices = []
self.onvif_config = {}
async def async_step_user(self, user_input=None):
"""Handle user flow."""
if user_input:
if user_input["auto"]:
return await self.async_step_device()
return await self.async_step_configure()
2020-05-01 06:15:40 +00:00
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({vol.Required("auto", default=True): bool}),
)
2020-05-01 06:15:40 +00:00
async def async_step_device(self, user_input=None):
"""Handle WS-Discovery.
Let user choose between discovered devices and manual configuration.
If no device is found allow user to manually input configuration.
"""
if user_input:
if CONF_MANUAL_INPUT == user_input[CONF_HOST]:
return await self.async_step_configure()
2020-05-01 06:15:40 +00:00
for device in self.devices:
name = f"{device[CONF_NAME]} ({device[CONF_HOST]})"
if name == user_input[CONF_HOST]:
self.device_id = device[CONF_DEVICE_ID]
self.onvif_config = {
CONF_NAME: device[CONF_NAME],
CONF_HOST: device[CONF_HOST],
CONF_PORT: device[CONF_PORT],
}
return await self.async_step_configure()
2020-05-01 06:15:40 +00:00
discovery = await async_discovery(self.hass)
for device in discovery:
2020-05-01 18:35:30 +00:00
configured = any(
entry.unique_id == device[CONF_DEVICE_ID]
for entry in self._async_current_entries()
)
2020-05-01 06:15:40 +00:00
if not configured:
self.devices.append(device)
LOGGER.debug("Discovered ONVIF devices %s", pformat(self.devices))
if self.devices:
2020-05-01 18:35:30 +00:00
names = [
f"{device[CONF_NAME]} ({device[CONF_HOST]})" for device in self.devices
]
2020-05-01 06:15:40 +00:00
names.append(CONF_MANUAL_INPUT)
return self.async_show_form(
step_id="device",
data_schema=vol.Schema({vol.Optional(CONF_HOST): vol.In(names)}),
)
return await self.async_step_configure()
2020-05-01 06:15:40 +00:00
2021-06-29 07:30:56 +00:00
async def async_step_configure(self, user_input=None):
"""Device configuration."""
2021-06-29 07:30:56 +00:00
errors = {}
2020-05-01 06:15:40 +00:00
if user_input:
self.onvif_config = user_input
2021-06-29 07:30:56 +00:00
try:
return await self.async_setup_profiles()
except Fault:
errors["base"] = "cannot_connect"
2020-05-01 06:15:40 +00:00
def conf(name, default=None):
return self.onvif_config.get(name, default)
2020-08-30 21:39:33 +00:00
# Username and Password are optional and default empty
# due to some cameras not allowing you to change ONVIF user settings.
# See https://github.com/home-assistant/core/issues/39182
# and https://github.com/home-assistant/core/issues/35904
2020-05-01 06:15:40 +00:00
return self.async_show_form(
step_id="configure",
2020-05-01 06:15:40 +00:00
data_schema=vol.Schema(
{
vol.Required(CONF_NAME, default=conf(CONF_NAME)): str,
vol.Required(CONF_HOST, default=conf(CONF_HOST)): str,
vol.Required(CONF_PORT, default=conf(CONF_PORT, DEFAULT_PORT)): int,
vol.Optional(CONF_USERNAME, default=conf(CONF_USERNAME, "")): str,
vol.Optional(CONF_PASSWORD, default=conf(CONF_PASSWORD, "")): str,
}
2020-05-01 06:15:40 +00:00
),
errors=errors,
2020-05-01 06:15:40 +00:00
)
2021-06-29 07:30:56 +00:00
async def async_setup_profiles(self):
2020-05-01 06:15:40 +00:00
"""Fetch ONVIF device profiles."""
LOGGER.debug(
"Fetching profiles from ONVIF device %s", pformat(self.onvif_config)
)
device = get_device(
self.hass,
self.onvif_config[CONF_HOST],
self.onvif_config[CONF_PORT],
self.onvif_config[CONF_USERNAME],
self.onvif_config[CONF_PASSWORD],
)
try:
await device.update_xaddrs()
device_mgmt = device.create_devicemgmt_service()
2020-05-01 06:15:40 +00:00
# Get the MAC address to use as the unique ID for the config flow
if not self.device_id:
try:
network_interfaces = await device_mgmt.GetNetworkInterfaces()
interface = next(
filter(lambda interface: interface.Enabled, network_interfaces),
None,
)
if interface:
self.device_id = interface.Info.HwAddress
except Fault as fault:
if "not implemented" not in fault.message:
raise fault
LOGGER.debug(
"Couldn't get network interfaces from ONVIF deivice '%s'. Error: %s",
self.onvif_config[CONF_NAME],
fault,
)
2020-05-01 06:15:40 +00:00
# If no network interfaces are exposed, fallback to serial number
if not self.device_id:
device_info = await device_mgmt.GetDeviceInformation()
self.device_id = device_info.SerialNumber
if not self.device_id:
2020-05-01 06:15:40 +00:00
return self.async_abort(reason="no_mac")
await self.async_set_unique_id(self.device_id, raise_on_progress=False)
self._abort_if_unique_id_configured(
updates={
CONF_HOST: self.onvif_config[CONF_HOST],
CONF_PORT: self.onvif_config[CONF_PORT],
CONF_NAME: self.onvif_config[CONF_NAME],
}
)
2020-05-06 16:29:59 +00:00
# Verify there is an H264 profile
media_service = device.create_media_service()
profiles = await media_service.GetProfiles()
h264 = any(
profile.VideoEncoderConfiguration
and profile.VideoEncoderConfiguration.Encoding == "H264"
2020-05-06 16:29:59 +00:00
for profile in profiles
)
if not h264:
2020-05-01 06:15:40 +00:00
return self.async_abort(reason="no_h264")
title = f"{self.onvif_config[CONF_NAME]} - {self.device_id}"
return self.async_create_entry(title=title, data=self.onvif_config)
2020-05-06 16:29:59 +00:00
except ONVIFError as err:
2020-05-01 06:15:40 +00:00
LOGGER.error(
"Couldn't setup ONVIF device '%s'. Error: %s",
self.onvif_config[CONF_NAME],
err,
)
return self.async_abort(reason="onvif_error")
finally:
await device.close()
2020-05-01 06:15:40 +00:00
async def async_step_import(self, user_input):
"""Handle import."""
2021-06-29 07:30:56 +00:00
return await self.async_step_configure(user_input)
2020-05-01 06:15:40 +00:00
class OnvifOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle ONVIF options."""
def __init__(self, config_entry):
"""Initialize ONVIF options flow."""
self.config_entry = config_entry
self.options = dict(config_entry.options)
async def async_step_init(self, user_input=None):
"""Manage the ONVIF options."""
return await self.async_step_onvif_devices()
async def async_step_onvif_devices(self, user_input=None):
"""Manage the ONVIF devices options."""
if user_input is not None:
self.options[CONF_EXTRA_ARGUMENTS] = user_input[CONF_EXTRA_ARGUMENTS]
self.options[CONF_RTSP_TRANSPORT] = user_input[CONF_RTSP_TRANSPORT]
return self.async_create_entry(title="", data=self.options)
return self.async_show_form(
step_id="onvif_devices",
data_schema=vol.Schema(
{
vol.Optional(
CONF_EXTRA_ARGUMENTS,
default=self.config_entry.options.get(
CONF_EXTRA_ARGUMENTS, DEFAULT_ARGUMENTS
),
): str,
vol.Optional(
CONF_RTSP_TRANSPORT,
default=self.config_entry.options.get(
CONF_RTSP_TRANSPORT, RTSP_TRANS_PROTOCOLS[0]
),
): vol.In(RTSP_TRANS_PROTOCOLS),
}
),
)