Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
0358e9c
Add reolink
starkillerOG Dec 11, 2022
185eb6c
fix yamllint
starkillerOG Dec 15, 2022
f2f1347
fix prettier
starkillerOG Dec 15, 2022
ebd67cd
use RTSP as default protocol
starkillerOG Dec 20, 2022
bc68ab6
Update homeassistant/components/reolink/__init__.py
starkillerOG Dec 20, 2022
a3de06f
Update homeassistant/components/reolink/__init__.py
starkillerOG Dec 20, 2022
398a1a5
Update homeassistant/components/reolink/manifest.json
starkillerOG Dec 20, 2022
37e2d5e
Update manifest.json
starkillerOG Dec 20, 2022
f3478a4
Remove custom services
starkillerOG Dec 20, 2022
47d6877
use dataclass
starkillerOG Dec 20, 2022
d857016
Only raise ConfigEntryNotReady for expected errors
starkillerOG Dec 20, 2022
b821275
fix styling
starkillerOG Dec 20, 2022
937f0f3
Update homeassistant/components/reolink/camera.py
starkillerOG Dec 23, 2022
37ae5a7
Update homeassistant/components/reolink/host.py
starkillerOG Dec 23, 2022
9b371b0
use data_entry_flow.FlowResultType
starkillerOG Dec 23, 2022
150f8ba
reduce loglevel to debug
starkillerOG Dec 23, 2022
637b40f
remove request_refresh since async_update is already implemented
starkillerOG Dec 23, 2022
6a4ea6f
Use DeviceInfo class
starkillerOG Dec 23, 2022
a5d86c9
Update homeassistant/components/reolink/entity.py
starkillerOG Dec 23, 2022
058d736
Update homeassistant/components/reolink/entity.py
starkillerOG Dec 23, 2022
dc40864
simplify
starkillerOG Dec 23, 2022
aff4c37
remove unneeded exception
starkillerOG Dec 23, 2022
64428d3
pass around host instead of unpacking
starkillerOG Dec 23, 2022
38e89bf
use _attr_supported_features
starkillerOG Dec 23, 2022
198b143
Update camera.py
starkillerOG Dec 23, 2022
8e88ec6
do not catch broad exception during disconnect
starkillerOG Dec 23, 2022
3b44314
Update homeassistant/components/reolink/config_flow.py
starkillerOG Dec 26, 2022
1ac08ff
improve error message in config flow
starkillerOG Dec 26, 2022
1131d46
Merge branch 'reolink_2' of https://github.com/starkillerOG/home-assi…
starkillerOG Dec 26, 2022
9f50428
use aiohttp_session from upstream lib instead of HASS
starkillerOG Dec 26, 2022
53d4d6d
fix styling
starkillerOG Dec 26, 2022
8e2646f
adjust tests
starkillerOG Dec 26, 2022
ac39bf7
Update homeassistant/components/reolink/__init__.py
starkillerOG Dec 27, 2022
1df83cd
Update homeassistant/components/reolink/__init__.py
starkillerOG Dec 27, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .coveragerc
Original file line number Diff line number Diff line change
Expand Up @@ -1047,6 +1047,11 @@ omit =
homeassistant/components/rejseplanen/sensor.py
homeassistant/components/remember_the_milk/__init__.py
homeassistant/components/remote_rpi_gpio/*
homeassistant/components/reolink/__init__.py
homeassistant/components/reolink/camera.py
homeassistant/components/reolink/const.py
homeassistant/components/reolink/entity.py
homeassistant/components/reolink/host.py
homeassistant/components/repetier/__init__.py
homeassistant/components/repetier/sensor.py
homeassistant/components/rest/notify.py
Expand Down
2 changes: 2 additions & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -942,6 +942,8 @@ build.json @home-assistant/supervisor
/tests/components/remote/ @home-assistant/core
/homeassistant/components/renault/ @epenet
/tests/components/renault/ @epenet
/homeassistant/components/reolink/ @starkillerOG @JimStar
/tests/components/reolink/ @starkillerOG @JimStar
/homeassistant/components/repairs/ @home-assistant/core
/tests/components/repairs/ @home-assistant/core
/homeassistant/components/repetier/ @MTrab @ShadowBr0ther
Expand Down
98 changes: 98 additions & 0 deletions homeassistant/components/reolink/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
"""Reolink integration for HomeAssistant."""

from __future__ import annotations

import asyncio
from dataclasses import dataclass
from datetime import timedelta
import logging

from aiohttp import ClientConnectorError
import async_timeout
from reolink_ip.exceptions import ApiError, InvalidContentTypeError

from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EVENT_HOMEASSISTANT_STOP
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator

from .const import DEVICE_UPDATE_INTERVAL, DOMAIN, PLATFORMS
from .host import ReolinkHost

_LOGGER = logging.getLogger(__name__)


@dataclass
class ReolinkData:
"""Data for the Reolink integration."""

host: ReolinkHost
device_coordinator: DataUpdateCoordinator


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Reolink from a config entry."""
host = ReolinkHost(hass, dict(entry.data), dict(entry.options))

try:
if not await host.async_init():
raise ConfigEntryNotReady(
f"Error while trying to setup {host.api.host}:{host.api.port}: failed to obtain data from device."
Comment thread
starkillerOG marked this conversation as resolved.
)
except (
ClientConnectorError,
asyncio.TimeoutError,
ApiError,
InvalidContentTypeError,
) as err:
raise ConfigEntryNotReady(
f'Error while trying to setup {host.api.host}:{host.api.port}: "{str(err)}".'
) from err

entry.async_on_unload(
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, host.stop)
)

async def async_device_config_update():
"""Perform the update of the host config-state cache, and renew the ONVIF-subscription."""
Comment thread
starkillerOG marked this conversation as resolved.
async with async_timeout.timeout(host.api.timeout):
await host.update_states() # Login session is implicitly updated here, so no need to explicitly do it in a timer
Comment thread
starkillerOG marked this conversation as resolved.

coordinator_device_config_update = DataUpdateCoordinator(
hass,
_LOGGER,
name=f"reolink.{host.api.nvr_name}",
update_method=async_device_config_update,
update_interval=timedelta(seconds=DEVICE_UPDATE_INTERVAL),
)
# Fetch initial data so we have data when entities subscribe
await coordinator_device_config_update.async_config_entry_first_refresh()

hass.data.setdefault(DOMAIN, {})[entry.entry_id] = ReolinkData(
host=host,
device_coordinator=coordinator_device_config_update,
)

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)

entry.async_on_unload(entry.add_update_listener(entry_update_listener))

return True


async def entry_update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Update the configuration of the host entity."""
await hass.config_entries.async_reload(entry.entry_id)


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
host: ReolinkHost = hass.data[DOMAIN][entry.entry_id].host

await host.stop()

if unload_ok := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)

return unload_ok
63 changes: 63 additions & 0 deletions homeassistant/components/reolink/camera.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
"""This component provides support for Reolink IP cameras."""
from __future__ import annotations

import logging

from homeassistant.components.camera import Camera, CameraEntityFeature
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback

from .const import DOMAIN
from .entity import ReolinkCoordinatorEntity
from .host import ReolinkHost

_LOGGER = logging.getLogger(__name__)


async def async_setup_entry(
hass: HomeAssistant,
config_entry: ConfigEntry,
async_add_devices: AddEntitiesCallback,
Comment thread
starkillerOG marked this conversation as resolved.
) -> None:
"""Set up a Reolink IP Camera."""
host: ReolinkHost = hass.data[DOMAIN][config_entry.entry_id].host

cameras = []
for channel in host.api.channels:
streams = ["sub", "main", "snapshots"]
if host.api.protocol == "rtmp":
streams.append("ext")

for stream in streams:
cameras.append(ReolinkCamera(hass, config_entry, channel, stream))

async_add_devices(cameras, update_before_add=True)


class ReolinkCamera(ReolinkCoordinatorEntity, Camera):
"""An implementation of a Reolink IP camera."""

_attr_supported_features: CameraEntityFeature = CameraEntityFeature.STREAM

def __init__(self, hass, config, channel, stream):
Comment thread
starkillerOG marked this conversation as resolved.
"""Initialize Reolink camera stream."""
ReolinkCoordinatorEntity.__init__(self, hass, config)
Comment thread
starkillerOG marked this conversation as resolved.
Camera.__init__(self)

self._channel = channel
self._stream = stream

self._attr_name = f"{self._host.api.camera_name(self._channel)} {self._stream}"
Comment thread
starkillerOG marked this conversation as resolved.
self._attr_unique_id = f"{self._host.unique_id}_{self._channel}_{self._stream}"
self._attr_entity_registry_enabled_default = stream == "sub"

async def stream_source(self) -> str | None:
"""Return the source of the stream."""
return await self._host.api.get_stream_source(self._channel, self._stream)

async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
"""Return a still image response from the camera."""
return await self._host.api.get_snapshot(self._channel)
137 changes: 137 additions & 0 deletions homeassistant/components/reolink/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
"""Config flow for the Reolink camera component."""
Comment thread
starkillerOG marked this conversation as resolved.
from __future__ import annotations

import logging
from typing import cast

from reolink_ip.exceptions import ApiError, CredentialsInvalidError
import voluptuous as vol

from homeassistant import config_entries, core, exceptions
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT, CONF_USERNAME
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import config_validation as cv

from .const import CONF_PROTOCOL, CONF_USE_HTTPS, DEFAULT_PROTOCOL, DOMAIN
from .host import ReolinkHost

_LOGGER = logging.getLogger(__name__)


class ReolinkOptionsFlowHandler(config_entries.OptionsFlow):
"""Handle Reolink options."""

def __init__(self, config_entry):
"""Initialize ReolinkOptionsFlowHandler."""
self.config_entry = config_entry

async def async_step_init(self, user_input=None) -> FlowResult:
Comment thread
starkillerOG marked this conversation as resolved.
"""Manage the Reolink options."""
if user_input is not None:
return self.async_create_entry(title="", data=user_input)
Comment thread
starkillerOG marked this conversation as resolved.

return self.async_show_form(
step_id="init",
data_schema=vol.Schema(
{
vol.Required(
CONF_PROTOCOL,
default=self.config_entry.options.get(
CONF_PROTOCOL, DEFAULT_PROTOCOL
),
): vol.In(["rtsp", "rtmp"]),
}
),
)


class ReolinkFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for Reolink device."""

VERSION = 1

host: ReolinkHost | None = None

@staticmethod
@callback
def async_get_options_flow(
config_entry: config_entries.ConfigEntry,
) -> ReolinkOptionsFlowHandler:
"""Options callback for Reolink."""
return ReolinkOptionsFlowHandler(config_entry)

async def async_step_user(self, user_input=None) -> FlowResult:
"""Handle the initial step."""
errors = {}
placeholders = {}

if user_input is not None:
try:
await self.async_obtain_host_settings(self.hass, user_input)
except CannotConnect:
errors[CONF_HOST] = "cannot_connect"
except CredentialsInvalidError:
errors[CONF_HOST] = "invalid_auth"
except ApiError as err:
placeholders["error"] = str(err)
errors[CONF_HOST] = "api_error"
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("Unexpected exception")
placeholders["error"] = str(err)
errors[CONF_HOST] = "unknown"

self.host = cast(ReolinkHost, self.host)

if not errors:
user_input[CONF_PORT] = self.host.api.port
user_input[CONF_USE_HTTPS] = self.host.api.use_https

await self.async_set_unique_id(
self.host.unique_id, raise_on_progress=False
)
self._abort_if_unique_id_configured(updates=user_input)

return self.async_create_entry(
title=str(self.host.api.nvr_name), data=user_input
)

data_schema = vol.Schema(
{
vol.Required(CONF_USERNAME, default="admin"): str,
vol.Required(CONF_PASSWORD): str,
vol.Required(CONF_HOST): str,
}
)
if errors:
data_schema = data_schema.extend(
{
vol.Optional(CONF_PORT): cv.positive_int,
vol.Optional(CONF_USE_HTTPS): bool,
}
)

return self.async_show_form(
step_id="user",
data_schema=data_schema,
errors=errors,
description_placeholders=placeholders,
)

async def async_obtain_host_settings(
self, hass: core.HomeAssistant, user_input: dict
):
"""Initialize the Reolink host and get the host information."""
host = ReolinkHost(hass, user_input, {})

try:
if not await host.async_init():
raise CannotConnect
finally:
await host.stop()

self.host = host
Comment thread
starkillerOG marked this conversation as resolved.


class CannotConnect(exceptions.HomeAssistantError):
"""Error to indicate we cannot connect."""
13 changes: 13 additions & 0 deletions homeassistant/components/reolink/const.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
"""Constants for the Reolink Camera integration."""

DOMAIN = "reolink"
PLATFORMS = ["camera"]
Comment thread
starkillerOG marked this conversation as resolved.

CONF_USE_HTTPS = "use_https"
CONF_PROTOCOL = "protocol"

DEFAULT_PROTOCOL = "rtsp"
DEFAULT_TIMEOUT = 60

HOST = "host"
DEVICE_UPDATE_INTERVAL = 60
54 changes: 54 additions & 0 deletions homeassistant/components/reolink/entity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"""Reolink parent entity class."""

from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from . import ReolinkData
from .const import DOMAIN


class ReolinkCoordinatorEntity(CoordinatorEntity):
"""Parent class for Reolink Entities."""

def __init__(self, hass, config):
"""Initialize ReolinkCoordinatorEntity."""
self._hass = hass
Comment thread
starkillerOG marked this conversation as resolved.
entry_data: ReolinkData = self._hass.data[DOMAIN][config.entry_id]
coordinator = entry_data.device_coordinator
super().__init__(coordinator)

self._host = entry_data.host
self._channel = None

@property
def device_info(self):
"""Information about this entity/device."""
http_s = "https" if self._host.api.use_https else "http"
conf_url = f"{http_s}://{self._host.api.host}:{self._host.api.port}"

if self._host.api.is_nvr and self._channel is not None:
return DeviceInfo(
identifiers={(DOMAIN, f"{self._host.unique_id}_ch{self._channel}")},
Comment thread
starkillerOG marked this conversation as resolved.
via_device=(DOMAIN, self._host.unique_id),
name=self._host.api.camera_name(self._channel),
model=self._host.api.camera_model(self._channel),
manufacturer=self._host.api.manufacturer,
configuration_url=conf_url,
)

return DeviceInfo(
identifiers={(DOMAIN, self._host.unique_id)},
connections={(CONNECTION_NETWORK_MAC, self._host.api.mac_address)},
name=self._host.api.nvr_name,
model=self._host.api.model,
manufacturer=self._host.api.manufacturer,
hw_version=self._host.api.hardware_version,
sw_version=self._host.api.sw_version,
configuration_url=conf_url,
)

@property
def available(self) -> bool:
"""Return True if entity is available."""
return self._host.api.session_active
Comment thread
starkillerOG marked this conversation as resolved.
Loading