Add motion event entity to EZVIZ (#193271)

This commit is contained in:
caveman2024
2026-11-27 12:00:58 -05:00
committed by GitHub
parent e1f337f23b
commit ca73bd08a8
5 changed files with 503 additions and 0 deletions
@@ -40,6 +40,7 @@ PLATFORMS_BY_TYPE: dict[str, list] = {
Platform.BINARY_SENSOR,
Platform.BUTTON,
Platform.CAMERA,
Platform.EVENT,
Platform.IMAGE,
Platform.LIGHT,
Platform.NUMBER,
+116
View File
@@ -0,0 +1,116 @@
"""Support for EZVIZ motion events."""
from dataclasses import dataclass
from typing import override
from pyezvizapi.devices.intercom_events import intercom_event_type
from homeassistant.components.event import (
EventDeviceClass,
EventEntity,
EventEntityDescription,
EventExtraStoredData,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback
from .coordinator import EzvizConfigEntry, EzvizDataUpdateCoordinator
from .entity import EzvizEntity
PARALLEL_UPDATES = 0
EVENT_MOTION = "motion"
ATTR_ALARM_TIME = "alarm_time"
EVENT_TYPE = EventEntityDescription(
key="motion",
translation_key="motion",
device_class=EventDeviceClass.MOTION,
event_types=[EVENT_MOTION],
)
@dataclass
class EzvizEventExtraStoredData(EventExtraStoredData):
"""Event data plus the last alarm handled, fired or not."""
last_alarm_time: str | None = None
async def async_setup_entry(
hass: HomeAssistant,
entry: EzvizConfigEntry,
async_add_entities: AddConfigEntryEntitiesCallback,
) -> None:
"""Set up EZVIZ event entities based on a config entry."""
coordinator = entry.runtime_data
async_add_entities(
EzvizMotionEvent(coordinator, camera) for camera in coordinator.data
)
class EzvizMotionEvent(EzvizEntity, EventEntity):
"""Fires an event for each new alarm reported by an EZVIZ camera."""
entity_description = EVENT_TYPE
def __init__(self, coordinator: EzvizDataUpdateCoordinator, serial: str) -> None:
"""Initialize the event entity."""
super().__init__(coordinator, serial)
self._attr_unique_id = f"{serial}_{EVENT_TYPE.key}"
# The alarm that is already there at startup is not a new event.
self._last_alarm_time = self.data.get("last_alarm_time")
@override
async def async_added_to_hass(self) -> None:
"""Restore the last handled alarm when the camera does not report one yet."""
await super().async_added_to_hass()
if self._last_alarm_time is None and (
extra := await self.async_get_last_extra_data()
):
self._last_alarm_time = extra.as_dict().get("last_alarm_time")
@property
@override
def extra_restore_state_data(self) -> EzvizEventExtraStoredData:
"""Store the last handled alarm, also when it was not fired as an event.
The alarm already present at startup is handled without firing, so it
is not in the event attributes.
"""
event_data = super().extra_restore_state_data
return EzvizEventExtraStoredData(
event_data.last_event_type,
event_data.last_event_attributes,
self._last_alarm_time,
)
@callback
@override
def _handle_coordinator_update(self) -> None:
"""Fire the event when the camera reports a new alarm."""
# Write the availability first, so that an alarm that arrives with the
# first refresh after an outage is a separate state change and is not
# dropped by triggers that ignore changes from unavailable.
super()._handle_coordinator_update()
# Keep an alarm reported while the camera is offline until it is back,
# otherwise the event is written while unavailable and gets lost.
if not self.available:
return
last_alarm_time = self.data.get("last_alarm_time")
if last_alarm_time and last_alarm_time != self._last_alarm_time:
self._last_alarm_time = last_alarm_time
# Doorbell rings and unlocks are reported as alarms too: they are
# handled, so they do not fire later, but they are not motion.
if intercom_event_type(self.data.get("last_alarm_type_code")):
return
self._trigger_event(
EVENT_MOTION,
{
ATTR_ALARM_TIME: last_alarm_time,
"alarm_type_code": self.data.get("last_alarm_type_code"),
"alarm_type_name": self.data.get("last_alarm_type_name"),
},
)
self.async_write_ha_state()
@@ -91,6 +91,17 @@
"name": "PTZ up"
}
},
"event": {
"motion": {
"state_attributes": {
"event_type": {
"state": {
"motion": "Motion"
}
}
}
}
},
"image": {
"last_motion_image": {
"name": "Last motion image"
@@ -0,0 +1,81 @@
# serializer version: 1
# name: test_entities[event.camera_1_motion-entry]
EntityRegistryEntrySnapshot({
'aliases': list([
None,
]),
'area_id': None,
'capabilities': dict({
<EventEntityCapabilityAttribute.EVENT_TYPES: 'event_types'>: list([
'motion',
]),
}),
'config_entry_id': <ANY>,
'config_subentry_id': None,
'device_class': None,
'device_id': <DeviceEntry identifiers=[('ezviz', 'C123456789')]>,
'disabled_by': None,
'domain': 'event',
'entity_category': None,
'entity_id': 'event.camera_1_motion',
'has_entity_name': True,
'hidden_by': None,
'icon': None,
'id': <ANY>,
'labels': set({
}),
'name': None,
'object_id_base': 'Motion',
'options': dict({
}),
'original_device_class': <EventDeviceClass.MOTION: 'motion'>,
'original_icon': None,
'original_name': 'Motion',
'platform': 'ezviz',
'previous_unique_id': None,
'suggested_object_id': None,
'supported_features': 0,
'translation_key': 'motion',
'unique_id': 'C123456789_motion',
'unit_of_measurement': None,
})
# ---
# name: test_entities[event.camera_1_motion-state]
StateSnapshot({
'attributes': ReadOnlyDict({
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'motion',
<EventEntityStateAttribute.EVENT_TYPE: 'event_type'>: None,
<EventEntityCapabilityAttribute.EVENT_TYPES: 'event_types'>: list([
'motion',
]),
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Camera 1 Motion',
}),
'context': <ANY>,
'entity_id': 'event.camera_1_motion',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': 'unknown',
})
# ---
# name: test_event_on_new_alarm
StateSnapshot({
'attributes': ReadOnlyDict({
'alarm_time': '2026-11-17 12:00:20',
'alarm_type_code': '10079',
'alarm_type_name': 'Smart Detection Alarm',
<EntityStateAttribute.DEVICE_CLASS: 'device_class'>: 'motion',
<EventEntityStateAttribute.EVENT_TYPE: 'event_type'>: 'motion',
<EventEntityCapabilityAttribute.EVENT_TYPES: 'event_types'>: list([
'motion',
]),
<EntityStateAttribute.FRIENDLY_NAME: 'friendly_name'>: 'Camera 1 Motion',
}),
'context': <ANY>,
'entity_id': 'event.camera_1_motion',
'last_changed': <ANY>,
'last_reported': <ANY>,
'last_updated': <ANY>,
'state': '2026-11-17T12:01:00.000+00:00',
})
# ---
+294
View File
@@ -0,0 +1,294 @@
"""Tests for EZVIZ event entities."""
from collections.abc import Generator
from datetime import timedelta
from unittest.mock import AsyncMock, patch
from freezegun.api import FrozenDateTimeFactory
from pyezvizapi.exceptions import PyEzvizError
import pytest
from pytest_homeassistant.common import (
MockConfigEntry,
async_fire_time_changed,
mock_restore_cache_with_extra_data,
snapshot_platform,
)
from syrupy.assertion import SnapshotAssertion
from homeassistant.components.ezviz.const import ATTR_TYPE_CAMERA, ATTR_TYPE_CLOUD
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN, Platform
from homeassistant.core import (
Event,
EventStateChangedData,
HomeAssistant,
State,
callback,
)
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.event import async_track_state_change_event
from . import setup_integration
from .test_init import _mock_camera_data
ENTITY_ID = "event.camera_1_motion"
SERIAL = "C123456789"
def _camera(
last_alarm_time: str | None,
status: int = 1,
alarm_type_code: str | None = "10079",
) -> dict[str, dict[str, object]]:
"""Return coordinator data with the given last alarm."""
return {
SERIAL: _mock_camera_data(
status=status,
last_alarm_time=last_alarm_time,
last_alarm_type_code=alarm_type_code,
last_alarm_type_name="Smart Detection Alarm",
)
}
async def _refresh(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_ezviz_client: AsyncMock,
last_alarm_time: str | None,
status: int = 1,
alarm_type_code: str | None = "10079",
) -> None:
"""Let the coordinator fetch new camera data."""
mock_ezviz_client.load_cameras.return_value = _camera(
last_alarm_time, status, alarm_type_code
)
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()
@pytest.fixture
def platforms() -> Generator[None]:
"""Load only the event platform."""
with patch(
"homeassistant.components.ezviz.PLATFORMS_BY_TYPE",
{ATTR_TYPE_CAMERA: [], ATTR_TYPE_CLOUD: [Platform.EVENT]},
):
yield
@pytest.mark.usefixtures("platforms")
async def test_entities(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test the event entities."""
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
await snapshot_platform(hass, entity_registry, snapshot, mock_config_entry.entry_id)
async def test_event_on_new_alarm(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
snapshot: SnapshotAssertion,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test an event is fired only when the camera reports a new alarm."""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
# The alarm already there at startup is not a new event
state = hass.states.get(ENTITY_ID)
assert state is not None
assert state.state == STATE_UNKNOWN
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 10:00:00")
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20")
assert hass.states.get(ENTITY_ID) == snapshot
# A missing alarm time and the same alarm coming back do not fire again
await _refresh(hass, freezer, mock_ezviz_client, None)
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20")
assert hass.states.get(ENTITY_ID).state == "2026-11-17T12:01:00.000+00:00"
@pytest.mark.parametrize("alarm_type_code", ["2701", "10242"])
async def test_intercom_alarm_not_fired(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
alarm_type_code: str,
) -> None:
"""Test a doorbell ring or an unlock is handled without firing motion."""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
await _refresh(
hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20", 1, alarm_type_code
)
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN
# The handled ring does not fire later, when its type is no longer reported
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20", 1, None)
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN
# A motion alarm after it still fires
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:01:40")
assert hass.states.get(ENTITY_ID).state == "2026-11-17T12:01:30.000+00:00"
async def test_event_after_outage(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test a new alarm in the first refresh after an outage is a separate change."""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
mock_ezviz_client.load_cameras.side_effect = PyEzvizError("outage")
freezer.tick(timedelta(seconds=30))
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
changes: list[tuple[str | None, str]] = []
@callback
def _record(event: Event[EventStateChangedData]) -> None:
old_state = event.data["old_state"]
new_state = event.data["new_state"]
assert new_state is not None
changes.append((old_state.state if old_state else None, new_state.state))
async_track_state_change_event(hass, ENTITY_ID, _record)
mock_ezviz_client.load_cameras.side_effect = None
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:40")
assert changes == [
(STATE_UNAVAILABLE, STATE_UNKNOWN),
(STATE_UNKNOWN, "2026-11-17T12:01:00.000+00:00"),
]
async def test_event_kept_while_camera_offline(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test an alarm reported while the camera is offline fires when it is back."""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
changes: list[tuple[str | None, str]] = []
@callback
def _record(event: Event[EventStateChangedData]) -> None:
old_state = event.data["old_state"]
new_state = event.data["new_state"]
assert new_state is not None
changes.append((old_state.state if old_state else None, new_state.state))
async_track_state_change_event(hass, ENTITY_ID, _record)
# The camera is offline: the new alarm is not consumed yet
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20", status=2)
assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE
# Back online with the same alarm: it fires as a separate state change
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:20")
assert changes == [
(STATE_UNKNOWN, STATE_UNAVAILABLE),
(STATE_UNAVAILABLE, STATE_UNKNOWN),
(STATE_UNKNOWN, "2026-11-17T12:01:00.000+00:00"),
]
async def test_handled_alarm_restored_after_reload(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test an alarm handled before a reload does not fire again.
The first refresh after the reload has no alarm time, then the camera
reports the alarm that was already handled.
"""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_restore_cache_with_extra_data(
hass,
[
(
State(ENTITY_ID, "2026-11-17T11:00:00.000+00:00"),
{
"last_event_type": "motion",
"last_event_attributes": {
"alarm_time": "2026-11-17 11:00:00",
"alarm_type_code": "10079",
"alarm_type_name": "Smart Detection Alarm",
},
"last_alarm_time": "2026-11-17 11:00:00",
},
)
],
)
mock_ezviz_client.load_cameras.return_value = _camera(None)
await setup_integration(hass, mock_config_entry)
assert hass.states.get(ENTITY_ID).state == "2026-11-17T11:00:00.000+00:00"
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 11:00:00")
assert hass.states.get(ENTITY_ID).state == "2026-11-17T11:00:00.000+00:00"
# A new alarm still fires
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 12:00:30")
assert hass.states.get(ENTITY_ID).state == "2026-11-17T12:01:00.000+00:00"
async def test_startup_alarm_not_fired_after_reload(
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
mock_config_entry: MockConfigEntry,
mock_ezviz_client: AsyncMock,
) -> None:
"""Test the alarm skipped at startup does not fire after a reload.
It was never fired, so it is not in the event attributes: the handled
alarm is stored on its own.
"""
freezer.move_to("2026-11-17 12:00:00+00:00")
mock_ezviz_client.load_cameras.return_value = _camera("2026-11-17 10:00:00")
await setup_integration(hass, mock_config_entry)
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN
# The first refresh after the reload has no alarm time
mock_ezviz_client.load_cameras.return_value = _camera(None)
assert await hass.config_entries.async_reload(mock_config_entry.entry_id)
await hass.async_block_till_done()
await _refresh(hass, freezer, mock_ezviz_client, "2026-11-17 10:00:00")
assert hass.states.get(ENTITY_ID).state == STATE_UNKNOWN