core/homeassistant/components/camera/__init__.py

989 lines
32 KiB
Python
Raw Normal View History

"""Component to interface with cameras."""
from __future__ import annotations
import asyncio
import collections
2022-02-08 22:32:02 +00:00
from collections.abc import Awaitable, Callable, Iterable
from contextlib import suppress
from dataclasses import dataclass
from datetime import datetime, timedelta
from enum import IntEnum
from functools import partial
import logging
import os
from random import SystemRandom
from typing import Any, Final, Optional, cast, final
from aiohttp import hdrs, web
import async_timeout
import attr
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
import voluptuous as vol
2015-11-29 21:49:05 +00:00
from homeassistant.components import websocket_api
from homeassistant.components.http import KEY_AUTHENTICATED, HomeAssistantView
2022-09-12 16:53:05 +00:00
from homeassistant.components.media_player import (
2019-07-31 19:25:30 +00:00
ATTR_MEDIA_CONTENT_ID,
ATTR_MEDIA_CONTENT_TYPE,
DOMAIN as DOMAIN_MP,
SERVICE_PLAY_MEDIA,
2019-07-31 19:25:30 +00:00
)
from homeassistant.components.stream import (
FORMAT_CONTENT_TYPE,
OUTPUT_FORMATS,
Orientation,
Stream,
create_stream,
)
from homeassistant.components.websocket_api import ActiveConnection
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_ENTITY_ID,
CONF_FILENAME,
CONTENT_TYPE_MULTIPART,
EVENT_HOMEASSISTANT_STARTED,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
)
from homeassistant.core import Event, HomeAssistant, ServiceCall, callback
from homeassistant.exceptions import HomeAssistantError
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import ( # noqa: F401
PLATFORM_SCHEMA,
PLATFORM_SCHEMA_BASE,
)
2022-02-08 22:32:02 +00:00
from homeassistant.helpers.entity import Entity, EntityDescription
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.helpers.event import async_track_time_interval
2020-05-08 19:53:28 +00:00
from homeassistant.helpers.network import get_url
from homeassistant.helpers.typing import ConfigType
from homeassistant.loader import bind_hass
2015-06-05 12:51:29 +00:00
from .const import ( # noqa: F401
CAMERA_IMAGE_TIMEOUT,
CAMERA_STREAM_SOURCE_TIMEOUT,
CONF_DURATION,
CONF_LOOKBACK,
DATA_CAMERA_PREFS,
DATA_RTSP_TO_WEB_RTC,
DOMAIN,
PREF_ORIENTATION,
PREF_PRELOAD_STREAM,
SERVICE_RECORD,
STREAM_TYPE_HLS,
STREAM_TYPE_WEB_RTC,
StreamType,
)
from .img_util import scale_jpeg_camera_image
from .prefs import CameraPreferences
_LOGGER = logging.getLogger(__name__)
SERVICE_ENABLE_MOTION: Final = "enable_motion_detection"
SERVICE_DISABLE_MOTION: Final = "disable_motion_detection"
SERVICE_SNAPSHOT: Final = "snapshot"
SERVICE_PLAY_STREAM: Final = "play_stream"
SCAN_INTERVAL: Final = timedelta(seconds=30)
ENTITY_ID_FORMAT: Final = DOMAIN + ".{}"
2015-06-05 12:51:29 +00:00
ATTR_FILENAME: Final = "filename"
ATTR_MEDIA_PLAYER: Final = "media_player"
ATTR_FORMAT: Final = "format"
STATE_RECORDING: Final = "recording"
STATE_STREAMING: Final = "streaming"
STATE_IDLE: Final = "idle"
2015-06-05 12:51:29 +00:00
class CameraEntityFeature(IntEnum):
"""Supported features of the camera entity."""
ON_OFF = 1
STREAM = 2
# These SUPPORT_* constants are deprecated as of Home Assistant 2022.5.
# Pleease use the CameraEntityFeature enum instead.
SUPPORT_ON_OFF: Final = 1
SUPPORT_STREAM: Final = 2
RTSP_PREFIXES = {"rtsp://", "rtsps://", "rtmp://"}
DEFAULT_CONTENT_TYPE: Final = "image/jpeg"
ENTITY_IMAGE_URL: Final = "/api/camera_proxy/{0}?token={1}"
2015-07-10 08:03:46 +00:00
TOKEN_CHANGE_INTERVAL: Final = timedelta(minutes=5)
_RND: Final = SystemRandom()
MIN_STREAM_INTERVAL: Final = 0.5 # seconds
CAMERA_SERVICE_SNAPSHOT: Final = {vol.Required(ATTR_FILENAME): cv.template}
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
CAMERA_SERVICE_PLAY_STREAM: Final = {
vol.Required(ATTR_MEDIA_PLAYER): cv.entities_domain(DOMAIN_MP),
vol.Optional(ATTR_FORMAT, default="hls"): vol.In(OUTPUT_FORMATS),
}
CAMERA_SERVICE_RECORD: Final = {
vol.Required(CONF_FILENAME): cv.template,
vol.Optional(CONF_DURATION, default=30): vol.Coerce(int),
vol.Optional(CONF_LOOKBACK, default=0): vol.Coerce(int),
}
@dataclass
class CameraEntityDescription(EntityDescription):
"""A class that describes camera entities."""
@attr.s
class Image:
"""Represent an image."""
2020-07-14 17:30:30 +00:00
content_type: str = attr.ib()
content: bytes = attr.ib()
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
@bind_hass
async def async_request_stream(hass: HomeAssistant, entity_id: str, fmt: str) -> str:
"""Request a stream for a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
return await _async_stream_endpoint_url(hass, camera, fmt)
async def _async_get_image(
camera: Camera,
timeout: int = 10,
width: int | None = None,
height: int | None = None,
) -> Image:
"""Fetch a snapshot image from a camera.
If width and height are passed, an attempt to scale
the image will be made on a best effort basis.
Not all cameras can scale images or return jpegs
that we can scale, however the majority of cases
are handled.
"""
with suppress(asyncio.CancelledError, asyncio.TimeoutError):
async with async_timeout.timeout(timeout):
if image_bytes := await camera.async_camera_image(
width=width, height=height
):
content_type = camera.content_type
image = Image(content_type, image_bytes)
if (
width is not None
and height is not None
and ("jpeg" in content_type or "jpg" in content_type)
):
assert width is not None
assert height is not None
return Image(
content_type, scale_jpeg_camera_image(image, width, height)
)
return image
2019-07-31 19:25:30 +00:00
raise HomeAssistantError("Unable to get image")
@bind_hass
async def async_get_image(
hass: HomeAssistant,
entity_id: str,
timeout: int = 10,
width: int | None = None,
height: int | None = None,
) -> Image:
"""Fetch an image from a camera entity.
width and height will be passed to the underlying camera.
"""
camera = _get_camera_from_entity_id(hass, entity_id)
return await _async_get_image(camera, timeout, width, height)
@bind_hass
async def async_get_stream_source(hass: HomeAssistant, entity_id: str) -> str | None:
"""Fetch the stream source for a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
return await camera.stream_source()
@bind_hass
async def async_get_mjpeg_stream(
hass: HomeAssistant, request: web.Request, entity_id: str
) -> web.StreamResponse | None:
"""Fetch an mjpeg stream from a camera entity."""
camera = _get_camera_from_entity_id(hass, entity_id)
try:
stream = await camera.handle_async_mjpeg_stream(request)
except ConnectionResetError:
stream = None
_LOGGER.debug("Error while writing MJPEG stream to transport")
return stream
async def async_get_still_stream(
request: web.Request,
image_cb: Callable[[], Awaitable[bytes | None]],
content_type: str,
interval: float,
) -> web.StreamResponse:
"""Generate an HTTP MJPEG stream from camera images.
This method must be run in the event loop.
"""
response = web.StreamResponse()
response.content_type = CONTENT_TYPE_MULTIPART.format("--frameboundary")
await response.prepare(request)
async def write_to_mjpeg_stream(img_bytes: bytes) -> None:
"""Write image to stream."""
2019-07-31 19:25:30 +00:00
await response.write(
bytes(
"--frameboundary\r\n"
"Content-Type: {}\r\n"
"Content-Length: {}\r\n\r\n".format(content_type, len(img_bytes)),
"utf-8",
)
+ img_bytes
+ b"\r\n"
)
last_image = None
while True:
img_bytes = await image_cb()
if not img_bytes:
break
if img_bytes != last_image:
await write_to_mjpeg_stream(img_bytes)
# Chrome seems to always ignore first picture,
# print it twice.
if last_image is None:
await write_to_mjpeg_stream(img_bytes)
last_image = img_bytes
await asyncio.sleep(interval)
return response
def _get_camera_from_entity_id(hass: HomeAssistant, entity_id: str) -> Camera:
"""Get camera component from entity_id."""
2021-10-17 18:19:56 +00:00
if (component := hass.data.get(DOMAIN)) is None:
2019-07-31 19:25:30 +00:00
raise HomeAssistantError("Camera integration not set up")
2021-10-30 14:33:42 +00:00
if (camera := component.get_entity(entity_id)) is None:
2019-07-31 19:25:30 +00:00
raise HomeAssistantError("Camera not found")
if not camera.is_on:
2019-07-31 19:25:30 +00:00
raise HomeAssistantError("Camera is off")
return cast(Camera, camera)
# An RtspToWebRtcProvider accepts these inputs:
# stream_source: The RTSP url
# offer_sdp: The WebRTC SDP offer
# stream_id: A unique id for the stream, used to update an existing source
# The output is the SDP answer, or None if the source or offer is not eligible.
# The Callable may throw HomeAssistantError on failure.
RtspToWebRtcProviderType = Callable[[str, str, str], Awaitable[Optional[str]]]
def async_register_rtsp_to_web_rtc_provider(
hass: HomeAssistant,
domain: str,
provider: RtspToWebRtcProviderType,
) -> Callable[[], None]:
"""Register an RTSP to WebRTC provider.
The first provider to satisfy the offer will be used.
"""
if DOMAIN not in hass.data:
raise ValueError("Unexpected state, camera not loaded")
def remove_provider() -> None:
if domain in hass.data[DATA_RTSP_TO_WEB_RTC]:
del hass.data[DATA_RTSP_TO_WEB_RTC]
hass.async_create_task(_async_refresh_providers(hass))
hass.data.setdefault(DATA_RTSP_TO_WEB_RTC, {})
hass.data[DATA_RTSP_TO_WEB_RTC][domain] = provider
hass.async_create_task(_async_refresh_providers(hass))
return remove_provider
async def _async_refresh_providers(hass: HomeAssistant) -> None:
"""Check all cameras for any state changes for registered providers."""
component: EntityComponent[Camera] = hass.data[DOMAIN]
await asyncio.gather(
*(camera.async_refresh_providers() for camera in component.entities)
)
def _async_get_rtsp_to_web_rtc_providers(
hass: HomeAssistant,
) -> Iterable[RtspToWebRtcProviderType]:
"""Return registered RTSP to WebRTC providers."""
providers: dict[str, RtspToWebRtcProviderType] = hass.data.get(
DATA_RTSP_TO_WEB_RTC, {}
)
return providers.values()
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up the camera component."""
component = hass.data[DOMAIN] = EntityComponent[Camera](
2019-07-31 19:25:30 +00:00
_LOGGER, DOMAIN, hass, SCAN_INTERVAL
)
2015-06-05 12:51:29 +00:00
prefs = CameraPreferences(hass)
await prefs.async_initialize()
hass.data[DATA_CAMERA_PREFS] = prefs
hass.http.register_view(CameraImageView(component))
hass.http.register_view(CameraMjpegStream(component))
2022-01-11 17:24:08 +00:00
websocket_api.async_register_command(hass, ws_camera_stream)
websocket_api.async_register_command(hass, ws_camera_web_rtc_offer)
websocket_api.async_register_command(hass, websocket_get_prefs)
websocket_api.async_register_command(hass, websocket_update_prefs)
2015-06-05 12:51:29 +00:00
await component.async_setup(config)
async def preload_stream(_event: Event) -> None:
for camera in component.entities:
camera_prefs = prefs.get(camera.entity_id)
if not camera_prefs.preload_stream:
continue
stream = await camera.async_create_stream()
if not stream:
continue
stream.keepalive = True
stream.add_provider("hls")
await stream.start()
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STARTED, preload_stream)
@callback
def update_tokens(time: datetime) -> None:
"""Update tokens of the entities."""
for entity in component.entities:
entity.async_update_token()
entity.async_write_ha_state()
async_track_time_interval(hass, update_tokens, TOKEN_CHANGE_INTERVAL)
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
component.async_register_entity_service(
SERVICE_ENABLE_MOTION, {}, "async_enable_motion_detection"
)
component.async_register_entity_service(
SERVICE_DISABLE_MOTION, {}, "async_disable_motion_detection"
)
component.async_register_entity_service(SERVICE_TURN_OFF, {}, "async_turn_off")
component.async_register_entity_service(SERVICE_TURN_ON, {}, "async_turn_on")
component.async_register_entity_service(
2019-07-31 19:25:30 +00:00
SERVICE_SNAPSHOT, CAMERA_SERVICE_SNAPSHOT, async_handle_snapshot_service
)
component.async_register_entity_service(
2019-07-31 19:25:30 +00:00
SERVICE_PLAY_STREAM,
CAMERA_SERVICE_PLAY_STREAM,
async_handle_play_stream_service,
)
component.async_register_entity_service(
2019-07-31 19:25:30 +00:00
SERVICE_RECORD, CAMERA_SERVICE_RECORD, async_handle_record_service
)
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
2015-07-10 09:42:22 +00:00
return True
2015-06-05 12:51:29 +00:00
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
2018-08-19 20:29:08 +00:00
"""Set up a config entry."""
component: EntityComponent[Camera] = hass.data[DOMAIN]
return await component.async_setup_entry(entry)
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
component: EntityComponent[Camera] = hass.data[DOMAIN]
return await component.async_unload_entry(entry)
2015-06-05 12:51:29 +00:00
class Camera(Entity):
2016-02-17 07:52:05 +00:00
"""The base class for camera entities."""
2016-03-07 19:29:54 +00:00
# Entity Properties
_attr_brand: str | None = None
_attr_frame_interval: float = MIN_STREAM_INTERVAL
_attr_frontend_stream_type: StreamType | None
_attr_is_on: bool = True
_attr_is_recording: bool = False
_attr_is_streaming: bool = False
_attr_model: str | None = None
_attr_motion_detection_enabled: bool = False
_attr_should_poll: bool = False # No need to poll cameras
_attr_state: None = None # State is determined by is_on
_attr_supported_features: int = 0
def __init__(self) -> None:
2016-02-17 07:52:05 +00:00
"""Initialize a camera."""
self.stream: Stream | None = None
self.stream_options: dict[str, str | bool | float] = {}
self.content_type: str = DEFAULT_CONTENT_TYPE
self.access_tokens: collections.deque = collections.deque([], 2)
self._warned_old_signature = False
self.async_update_token()
self._create_stream_lock: asyncio.Lock | None = None
self._rtsp_to_webrtc = False
2016-02-24 06:41:24 +00:00
@property
def entity_picture(self) -> str:
2016-02-24 06:41:24 +00:00
"""Return a link to the camera feed as entity picture."""
if self._attr_entity_picture is not None:
return self._attr_entity_picture
return ENTITY_IMAGE_URL.format(self.entity_id, self.access_tokens[-1])
2016-02-24 06:41:24 +00:00
@property
def supported_features(self) -> int:
"""Flag supported features."""
return self._attr_supported_features
2015-06-05 12:51:29 +00:00
@property
def is_recording(self) -> bool:
2016-02-17 07:52:05 +00:00
"""Return true if the device is recording."""
return self._attr_is_recording
@property
def is_streaming(self) -> bool:
"""Return true if the device is streaming."""
return self._attr_is_streaming
2015-06-05 12:51:29 +00:00
@property
def brand(self) -> str | None:
"""Return the camera brand."""
return self._attr_brand
2015-06-05 12:51:29 +00:00
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
@property
def motion_detection_enabled(self) -> bool:
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
"""Return the camera motion detection status."""
return self._attr_motion_detection_enabled
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
2015-06-05 12:51:29 +00:00
@property
def model(self) -> str | None:
"""Return the camera model."""
return self._attr_model
2015-06-05 12:51:29 +00:00
@property
def frame_interval(self) -> float:
"""Return the interval between frames of the mjpeg stream."""
return self._attr_frame_interval
@property
def frontend_stream_type(self) -> StreamType | None:
"""Return the type of stream supported by this camera.
A camera may have a single stream type which is used to inform the
frontend which camera attributes and player to use. The default type
is to use HLS, and components can override to change the type.
"""
if hasattr(self, "_attr_frontend_stream_type"):
return self._attr_frontend_stream_type
if not self.supported_features & CameraEntityFeature.STREAM:
return None
if self._rtsp_to_webrtc:
return StreamType.WEB_RTC
return StreamType.HLS
@property
def available(self) -> bool:
"""Return True if entity is available."""
if self.stream and not self.stream.available:
return self.stream.available
return super().available
async def async_create_stream(self) -> Stream | None:
"""Create a Stream for stream_source."""
# There is at most one stream (a decode worker) per camera
if not self._create_stream_lock:
self._create_stream_lock = asyncio.Lock()
async with self._create_stream_lock:
if not self.stream:
async with async_timeout.timeout(CAMERA_STREAM_SOURCE_TIMEOUT):
source = await self.stream_source()
if not source:
return None
self.stream = create_stream(
self.hass,
source,
options=self.stream_options,
stream_label=self.entity_id,
)
self.stream.set_update_callback(self.async_write_ha_state)
return self.stream
async def stream_source(self) -> str | None:
"""Return the source of the stream.
This is used by cameras with CameraEntityFeature.STREAM
and StreamType.HLS.
"""
return None
async def async_handle_web_rtc_offer(self, offer_sdp: str) -> str | None:
"""Handle the WebRTC offer and return an answer.
This is used by cameras with CameraEntityFeature.STREAM
and StreamType.WEB_RTC.
Integrations can override with a native WebRTC implementation.
"""
stream_source = await self.stream_source()
if not stream_source:
return None
for provider in _async_get_rtsp_to_web_rtc_providers(self.hass):
answer_sdp = await provider(stream_source, offer_sdp, self.entity_id)
if answer_sdp:
return answer_sdp
raise HomeAssistantError("WebRTC offer was not accepted by any providers")
def camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
2016-02-17 07:52:05 +00:00
"""Return bytes of camera image."""
2015-06-05 12:51:29 +00:00
raise NotImplementedError()
async def async_camera_image(
self, width: int | None = None, height: int | None = None
) -> bytes | None:
"""Return bytes of camera image."""
return await self.hass.async_add_executor_job(
partial(self.camera_image, width=width, height=height)
)
async def handle_async_still_stream(
self, request: web.Request, interval: float
) -> web.StreamResponse:
"""Generate an HTTP MJPEG stream from camera images."""
2019-07-31 19:25:30 +00:00
return await async_get_still_stream(
request, self.async_camera_image, self.content_type, interval
)
async def handle_async_mjpeg_stream(
self, request: web.Request
) -> web.StreamResponse | None:
"""Serve an HTTP MJPEG stream from the camera.
This method can be overridden by camera platforms to proxy
a direct stream from the camera.
"""
2019-07-31 19:25:30 +00:00
return await self.handle_async_still_stream(request, self.frame_interval)
2015-06-05 12:51:29 +00:00
@property
@final
def state(self) -> str:
"""Return the camera state."""
2015-06-05 12:51:29 +00:00
if self.is_recording:
return STATE_RECORDING
if self.is_streaming:
2015-06-05 12:51:29 +00:00
return STATE_STREAMING
return STATE_IDLE
2015-06-05 12:51:29 +00:00
@property
def is_on(self) -> bool:
"""Return true if on."""
return self._attr_is_on
def turn_off(self) -> None:
"""Turn off camera."""
raise NotImplementedError()
async def async_turn_off(self) -> None:
"""Turn off camera."""
await self.hass.async_add_executor_job(self.turn_off)
def turn_on(self) -> None:
"""Turn off camera."""
raise NotImplementedError()
async def async_turn_on(self) -> None:
"""Turn off camera."""
await self.hass.async_add_executor_job(self.turn_on)
def enable_motion_detection(self) -> None:
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
"""Enable motion detection in the camera."""
raise NotImplementedError()
async def async_enable_motion_detection(self) -> None:
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
"""Call the job and enable motion detection."""
await self.hass.async_add_executor_job(self.enable_motion_detection)
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
def disable_motion_detection(self) -> None:
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
"""Disable motion detection in camera."""
raise NotImplementedError()
async def async_disable_motion_detection(self) -> None:
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
"""Call the job and disable motion detection."""
await self.hass.async_add_executor_job(self.disable_motion_detection)
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
@final
2015-06-05 12:51:29 +00:00
@property
def state_attributes(self) -> dict[str, str | None]:
"""Return the camera state attributes."""
2019-07-31 19:25:30 +00:00
attrs = {"access_token": self.access_tokens[-1]}
2015-07-11 18:55:25 +00:00
if self.model:
2019-07-31 19:25:30 +00:00
attrs["model_name"] = self.model
2015-07-11 18:55:25 +00:00
if self.brand:
2019-07-31 19:25:30 +00:00
attrs["brand"] = self.brand
2015-07-11 18:55:25 +00:00
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
if self.motion_detection_enabled:
2019-07-31 19:25:30 +00:00
attrs["motion_detection"] = self.motion_detection_enabled
Camera services arm disarm including Netgear Arlo (#7961) * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Added camera service calls to arm/disarm the cameras. Entity id is optional so that with a single call we can arm all the cameras or specify a particular entity id to arm if applicable and possible in that camera type. * Fixed the spaces and indentation related issues that houndci found * Fixed the spaces and indentation related issues that houndci found * Missed the const file which has the macros defined. * Fixed the CI build error * Fixed the CI build error because of unused variable in exception case * Updating the arlo code based on comment from @balloob. Changed the arm and disarm to enable_motion_detection and disable_motion_detection respectively. Similarly fixed the AttributeError handling. Added dummy code to the demo camera also. Moved out the definitions in const.py into the camera __init__ file * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by houndci-bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot * Fixed the comments posted by travis-ci integration bot for demo.py: expected 2 lines, found 1 * Updated code in camera __init__.py to use the get function instead of directly calling the member in the structure. * Updated code in camera __init__.py * Posting the updated code for PR based on @balloob's suggestions/recommendations * Removed the arlo reference from demo code. Copy-paste error * Removed the unused import found by hound bot * Expected 2 lines before function, but found only 1. * Based on @balloob's comments, moved these constants to the camera/arlo.py * Added test_demo.py to test the motion enabled and motion disabled in camera component * Fixing issues found by houndci-bot * Fixing issues found by houndci-bot * Fixing the code as per @balloob's suggestions * Fixing the code as per @balloob's suggestions * Fixing the test_demo failure. Tried to rewrite a base function to enable the motion in __init__.py and missed to add it to as a job. * Fixing the hound bot comment * Update arlo.py * Update arlo.py
2017-07-01 04:06:56 +00:00
if self.frontend_stream_type:
attrs["frontend_stream_type"] = self.frontend_stream_type
return attrs
2016-05-14 07:58:36 +00:00
@callback
def async_update_token(self) -> None:
"""Update the used token."""
2022-06-05 22:28:57 +00:00
self.access_tokens.append(hex(_RND.getrandbits(256))[2:])
async def async_internal_added_to_hass(self) -> None:
"""Run when entity about to be added to hass."""
await super().async_internal_added_to_hass()
await self.async_refresh_providers()
async def async_refresh_providers(self) -> None:
"""Determine if any of the registered providers are suitable for this entity.
This affects state attributes, so it should be invoked any time the registered
providers or inputs to the state attributes change.
Returns True if any state was updated (and needs to be written)
"""
old_state = self._rtsp_to_webrtc
self._rtsp_to_webrtc = await self._async_use_rtsp_to_webrtc()
if old_state != self._rtsp_to_webrtc:
self.async_write_ha_state()
async def _async_use_rtsp_to_webrtc(self) -> bool:
"""Determine if a WebRTC provider can be used for the camera."""
if not self.supported_features & CameraEntityFeature.STREAM:
return False
if DATA_RTSP_TO_WEB_RTC not in self.hass.data:
return False
stream_source = await self.stream_source()
return any(
stream_source and stream_source.startswith(prefix)
for prefix in RTSP_PREFIXES
)
2016-05-14 07:58:36 +00:00
class CameraView(HomeAssistantView):
"""Base CameraView."""
requires_auth = False
def __init__(self, component: EntityComponent[Camera]) -> None:
2016-05-14 07:58:36 +00:00
"""Initialize a basic camera view."""
self.component = component
2016-05-14 07:58:36 +00:00
async def get(self, request: web.Request, entity_id: str) -> web.StreamResponse:
"""Start a GET request."""
2021-10-30 14:33:42 +00:00
if (camera := self.component.get_entity(entity_id)) is None:
raise web.HTTPNotFound()
2019-07-31 19:25:30 +00:00
authenticated = (
request[KEY_AUTHENTICATED]
or request.query.get("token") in camera.access_tokens
)
if not authenticated:
# Attempt with invalid bearer token, raise unauthorized
# so ban middleware can handle it.
if hdrs.AUTHORIZATION in request.headers:
raise web.HTTPUnauthorized()
# Invalid sigAuth or camera access token
raise web.HTTPForbidden()
if not camera.is_on:
_LOGGER.debug("Camera is off")
raise web.HTTPServiceUnavailable()
return await self.handle(request, camera)
async def handle(self, request: web.Request, camera: Camera) -> web.StreamResponse:
"""Handle the camera request."""
raise NotImplementedError()
2016-05-14 07:58:36 +00:00
class CameraImageView(CameraView):
"""Camera view to serve an image."""
2019-07-31 19:25:30 +00:00
url = "/api/camera_proxy/{entity_id}"
name = "api:camera:image"
2016-05-14 07:58:36 +00:00
async def handle(self, request: web.Request, camera: Camera) -> web.Response:
2016-05-14 07:58:36 +00:00
"""Serve camera image."""
width = request.query.get("width")
height = request.query.get("height")
try:
image = await _async_get_image(
camera,
CAMERA_IMAGE_TIMEOUT,
int(width) if width else None,
int(height) if height else None,
)
except (HomeAssistantError, ValueError) as ex:
raise web.HTTPInternalServerError() from ex
else:
return web.Response(body=image.content, content_type=image.content_type)
2016-05-14 07:58:36 +00:00
class CameraMjpegStream(CameraView):
"""Camera View to serve an MJPEG stream."""
2019-07-31 19:25:30 +00:00
url = "/api/camera_proxy_stream/{entity_id}"
name = "api:camera:stream"
2016-05-14 07:58:36 +00:00
async def handle(self, request: web.Request, camera: Camera) -> web.StreamResponse:
"""Serve camera stream, possibly with interval."""
2021-10-17 18:19:56 +00:00
if (interval_str := request.query.get("interval")) is None:
try:
stream = await camera.handle_async_mjpeg_stream(request)
except ConnectionResetError:
stream = None
_LOGGER.debug("Error while writing MJPEG stream to transport")
if stream is None:
raise web.HTTPBadGateway()
return stream
try:
# Compose camera stream from stills
interval = float(interval_str)
if interval < MIN_STREAM_INTERVAL:
raise ValueError(f"Stream interval must be be > {MIN_STREAM_INTERVAL}")
return await camera.handle_async_still_stream(request, interval)
except ValueError as err:
raise web.HTTPBadRequest() from err
2019-07-31 19:25:30 +00:00
@websocket_api.websocket_command(
{
vol.Required("type"): "camera/stream",
vol.Required("entity_id"): cv.entity_id,
vol.Optional("format", default="hls"): vol.In(OUTPUT_FORMATS),
}
)
@websocket_api.async_response
async def ws_camera_stream(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle get camera stream websocket command.
Async friendly.
"""
try:
2019-07-31 19:25:30 +00:00
entity_id = msg["entity_id"]
camera = _get_camera_from_entity_id(hass, entity_id)
url = await _async_stream_endpoint_url(hass, camera, fmt=msg["format"])
2019-07-31 19:25:30 +00:00
connection.send_result(msg["id"], {"url": url})
except HomeAssistantError as ex:
_LOGGER.error("Error requesting stream: %s", ex)
2019-07-31 19:25:30 +00:00
connection.send_error(msg["id"], "start_stream_failed", str(ex))
except asyncio.TimeoutError:
_LOGGER.error("Timeout getting stream source")
connection.send_error(
2019-07-31 19:25:30 +00:00
msg["id"], "start_stream_failed", "Timeout getting stream source"
)
@websocket_api.websocket_command(
{
vol.Required("type"): "camera/web_rtc_offer",
vol.Required("entity_id"): cv.entity_id,
vol.Required("offer"): str,
}
)
@websocket_api.async_response
async def ws_camera_web_rtc_offer(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle the signal path for a WebRTC stream.
This signal path is used to route the offer created by the client to the
camera device through the integration for negotiation on initial setup,
which returns an answer. The actual streaming is handled entirely between
the client and camera device.
Async friendly.
"""
entity_id = msg["entity_id"]
offer = msg["offer"]
camera = _get_camera_from_entity_id(hass, entity_id)
if camera.frontend_stream_type != StreamType.WEB_RTC:
connection.send_error(
msg["id"],
"web_rtc_offer_failed",
f"Camera does not support WebRTC, frontend_stream_type={camera.frontend_stream_type}",
)
return
try:
answer = await camera.async_handle_web_rtc_offer(offer)
except (HomeAssistantError, ValueError) as ex:
_LOGGER.error("Error handling WebRTC offer: %s", ex)
connection.send_error(msg["id"], "web_rtc_offer_failed", str(ex))
except asyncio.TimeoutError:
_LOGGER.error("Timeout handling WebRTC offer")
connection.send_error(
msg["id"], "web_rtc_offer_failed", "Timeout handling WebRTC offer"
)
else:
connection.send_result(msg["id"], {"answer": answer})
2019-07-31 19:25:30 +00:00
@websocket_api.websocket_command(
{vol.Required("type"): "camera/get_prefs", vol.Required("entity_id"): cv.entity_id}
)
@websocket_api.async_response
async def websocket_get_prefs(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for account info."""
2022-11-09 11:14:26 +00:00
prefs: CameraPreferences = hass.data[DATA_CAMERA_PREFS]
camera_prefs = prefs.get(msg["entity_id"])
connection.send_result(msg["id"], camera_prefs.as_dict())
2019-07-31 19:25:30 +00:00
@websocket_api.websocket_command(
{
vol.Required("type"): "camera/update_prefs",
vol.Required("entity_id"): cv.entity_id,
vol.Optional(PREF_PRELOAD_STREAM): bool,
vol.Optional(PREF_ORIENTATION): vol.Coerce(Orientation),
2019-07-31 19:25:30 +00:00
}
)
@websocket_api.async_response
async def websocket_update_prefs(
hass: HomeAssistant, connection: ActiveConnection, msg: dict[str, Any]
) -> None:
"""Handle request for account info."""
2022-11-09 11:14:26 +00:00
prefs: CameraPreferences = hass.data[DATA_CAMERA_PREFS]
changes = dict(msg)
2019-07-31 19:25:30 +00:00
changes.pop("id")
changes.pop("type")
entity_id = changes.pop("entity_id")
try:
entity_prefs = await prefs.async_update(entity_id, **changes)
except HomeAssistantError as ex:
_LOGGER.error("Error setting camera preferences: %s", ex)
connection.send_error(msg["id"], "update_failed", str(ex))
else:
connection.send_result(msg["id"], entity_prefs)
async def async_handle_snapshot_service(
camera: Camera, service_call: ServiceCall
) -> None:
"""Handle snapshot services calls."""
hass = camera.hass
filename = service_call.data[ATTR_FILENAME]
filename.hass = hass
2019-07-31 19:25:30 +00:00
snapshot_file = filename.async_render(variables={ATTR_ENTITY_ID: camera})
# check if we allow to access to that file
if not hass.config.is_allowed_path(snapshot_file):
2019-07-31 19:25:30 +00:00
_LOGGER.error("Can't write %s, no access to path!", snapshot_file)
return
image = await camera.async_camera_image()
if image is None:
return
def _write_image(to_file: str, image_data: bytes) -> None:
"""Executor helper to write image."""
os.makedirs(os.path.dirname(to_file), exist_ok=True)
2019-07-31 19:25:30 +00:00
with open(to_file, "wb") as img_file:
img_file.write(image_data)
try:
2019-07-31 19:25:30 +00:00
await hass.async_add_executor_job(_write_image, snapshot_file, image)
except OSError as err:
_LOGGER.error("Can't write image to file: %s", err)
async def async_handle_play_stream_service(
camera: Camera, service_call: ServiceCall
) -> None:
"""Handle play stream services calls."""
2022-02-08 22:32:02 +00:00
hass = camera.hass
fmt = service_call.data[ATTR_FORMAT]
url = await _async_stream_endpoint_url(camera.hass, camera, fmt)
2022-02-08 22:32:02 +00:00
url = f"{get_url(hass)}{url}"
await hass.services.async_call(
DOMAIN_MP,
SERVICE_PLAY_MEDIA,
{
ATTR_ENTITY_ID: service_call.data[ATTR_MEDIA_PLAYER],
ATTR_MEDIA_CONTENT_ID: url,
ATTR_MEDIA_CONTENT_TYPE: FORMAT_CONTENT_TYPE[fmt],
},
blocking=True,
context=service_call.context,
)
async def _async_stream_endpoint_url(
hass: HomeAssistant, camera: Camera, fmt: str
) -> str:
stream = await camera.async_create_stream()
if not stream:
raise HomeAssistantError(
f"{camera.entity_id} does not support play stream service"
)
# Update keepalive setting which manages idle shutdown
2022-11-09 11:14:26 +00:00
prefs: CameraPreferences = hass.data[DATA_CAMERA_PREFS]
camera_prefs = prefs.get(camera.entity_id)
stream.keepalive = camera_prefs.preload_stream
stream.orientation = camera_prefs.orientation
stream.add_provider(fmt)
await stream.start()
return stream.endpoint_url(fmt)
async def async_handle_record_service(
camera: Camera, service_call: ServiceCall
) -> None:
"""Handle stream recording service calls."""
stream = await camera.async_create_stream()
if not stream:
raise HomeAssistantError(f"{camera.entity_id} does not support record service")
hass = camera.hass
filename = service_call.data[CONF_FILENAME]
filename.hass = hass
2019-07-31 19:25:30 +00:00
video_path = filename.async_render(variables={ATTR_ENTITY_ID: camera})
await stream.async_record(
video_path,
duration=service_call.data[CONF_DURATION],
lookback=service_call.data[CONF_LOOKBACK],
2019-07-31 19:25:30 +00:00
)