core/homeassistant/components/onvif/__init__.py

157 lines
5.2 KiB
Python
Raw Normal View History

2020-05-01 06:15:40 +00:00
"""The ONVIF integration."""
import asyncio
from contextlib import suppress
from http import HTTPStatus
import logging
from httpx import RequestError
from onvif.exceptions import ONVIFError
from onvif.util import is_auth_error, stringify_onvif_error
from zeep.exceptions import Fault, TransportError
2020-05-01 06:15:40 +00:00
from homeassistant.components.ffmpeg import CONF_EXTRA_ARGUMENTS
from homeassistant.components.stream import CONF_RTSP_TRANSPORT, RTSP_TRANSPORTS
from homeassistant.config_entries import ConfigEntry
2020-05-01 18:35:30 +00:00
from homeassistant.const import (
EVENT_HOMEASSISTANT_STOP,
HTTP_BASIC_AUTHENTICATION,
HTTP_DIGEST_AUTHENTICATION,
2021-12-06 03:06:35 +00:00
Platform,
2020-05-01 18:35:30 +00:00
)
2020-05-01 06:15:40 +00:00
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
2020-05-01 06:15:40 +00:00
from .const import (
CONF_ENABLE_WEBHOOKS,
CONF_SNAPSHOT_AUTH,
DEFAULT_ARGUMENTS,
DEFAULT_ENABLE_WEBHOOKS,
DOMAIN,
)
2020-05-06 16:29:59 +00:00
from .device import ONVIFDevice
2020-05-01 06:15:40 +00:00
LOGGER = logging.getLogger(__name__)
2020-05-01 06:15:40 +00:00
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
2020-05-01 06:15:40 +00:00
"""Set up ONVIF from a config entry."""
2020-05-06 16:29:59 +00:00
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
2020-05-01 06:15:40 +00:00
if not entry.options:
await async_populate_options(hass, entry)
2020-05-06 16:29:59 +00:00
device = ONVIFDevice(hass, entry)
try:
await device.async_setup()
if not entry.data.get(CONF_SNAPSHOT_AUTH):
await async_populate_snapshot_auth(hass, device, entry)
except RequestError as err:
await device.device.close()
raise ConfigEntryNotReady(
f"Could not connect to camera {device.device.host}:{device.device.port}: {err}"
) from err
except Fault as err:
await device.device.close()
if is_auth_error(err):
raise ConfigEntryAuthFailed(
f"Auth Failed: {stringify_onvif_error(err)}"
) from err
raise ConfigEntryNotReady(
f"Could not connect to camera: {stringify_onvif_error(err)}"
) from err
except ONVIFError as err:
await device.device.close()
raise ConfigEntryNotReady(
f"Could not setup camera {device.device.host}:{device.device.port}: {stringify_onvif_error(err)}"
) from err
except TransportError as err:
await device.device.close()
stringified_onvif_error = stringify_onvif_error(err)
if err.status_code in (
HTTPStatus.UNAUTHORIZED.value,
HTTPStatus.FORBIDDEN.value,
):
raise ConfigEntryAuthFailed(
f"Auth Failed: {stringified_onvif_error}"
) from err
raise ConfigEntryNotReady(
f"Could not setup camera {device.device.host}:{device.device.port}: {stringified_onvif_error}"
) from err
except asyncio.CancelledError as err:
# After https://github.com/agronholm/anyio/issues/374 is resolved
# this may be able to be removed
await device.device.close()
raise ConfigEntryNotReady(f"Setup was unexpectedly canceled: {err}") from err
2020-05-06 16:29:59 +00:00
if not device.available:
raise ConfigEntryNotReady()
hass.data[DOMAIN][entry.unique_id] = device
2023-04-16 12:05:10 +00:00
device.platforms = [Platform.BUTTON, Platform.CAMERA]
if device.capabilities.events:
2023-04-16 12:05:10 +00:00
device.platforms += [Platform.BINARY_SENSOR, Platform.SENSOR]
if device.capabilities.imaging:
2023-04-16 12:05:10 +00:00
device.platforms += [Platform.SWITCH]
2023-04-16 12:05:10 +00:00
await hass.config_entries.async_forward_entry_setups(entry, device.platforms)
2020-05-01 06:15:40 +00:00
2021-04-20 16:15:17 +00:00
entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, device.async_stop)
)
2020-05-01 06:15:40 +00:00
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
2020-05-01 06:15:40 +00:00
"""Unload a config entry."""
2023-04-16 12:05:10 +00:00
device: ONVIFDevice = hass.data[DOMAIN][entry.unique_id]
if device.capabilities.events and device.events.started:
try:
await device.events.async_stop()
except (ONVIFError, Fault, RequestError, TransportError):
LOGGER.warning("Error while stopping events: %s", device.name)
2023-04-16 12:05:10 +00:00
return await hass.config_entries.async_unload_platforms(entry, device.platforms)
2020-05-01 06:15:40 +00:00
async def _get_snapshot_auth(device: ONVIFDevice) -> str | None:
"""Determine auth type for snapshots."""
if not device.capabilities.snapshot:
return None
for basic_auth in (False, True):
method = HTTP_BASIC_AUTHENTICATION if basic_auth else HTTP_DIGEST_AUTHENTICATION
with suppress(ONVIFError):
if await device.device.get_snapshot(device.profiles[0].token, basic_auth):
return method
return None
async def async_populate_snapshot_auth(
hass: HomeAssistant, device: ONVIFDevice, entry: ConfigEntry
) -> None:
"""Check if digest auth for snapshots is possible."""
if auth := await _get_snapshot_auth(device):
hass.config_entries.async_update_entry(
entry, data={**entry.data, CONF_SNAPSHOT_AUTH: auth}
)
async def async_populate_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
2020-05-01 06:15:40 +00:00
"""Populate default options for device."""
options = {
CONF_EXTRA_ARGUMENTS: DEFAULT_ARGUMENTS,
CONF_RTSP_TRANSPORT: next(iter(RTSP_TRANSPORTS)),
CONF_ENABLE_WEBHOOKS: DEFAULT_ENABLE_WEBHOOKS,
2020-05-01 06:15:40 +00:00
}
hass.config_entries.async_update_entry(entry, options=options)