From fee9ecbca23fa0533b37fc69ff99d27d6d7a75b4 Mon Sep 17 00:00:00 2001 From: Raphael Hehl <7577984+RaHehl@users.noreply.github.com> Date: Sun, 22 Nov 2026 09:47:37 +0100 Subject: [PATCH] Replace UniFi Protect alarm hub state entities with event entities (#192368) --- .../components/unifiprotect/binary_sensor.py | 138 +-- .../components/unifiprotect/entity.py | 4 +- .../components/unifiprotect/event.py | 223 ++++- .../components/unifiprotect/icons.json | 6 + .../components/unifiprotect/sensor.py | 75 +- .../components/unifiprotect/strings.json | 44 +- .../fixtures/sample_alarm_hub.json | 43 + .../snapshots/test_alarm_hub.ambr | 830 +++++++++--------- .../components/unifiprotect/test_alarm_hub.py | 613 +++++++------ 9 files changed, 1076 insertions(+), 900 deletions(-) diff --git a/homeassistant/components/unifiprotect/binary_sensor.py b/homeassistant/components/unifiprotect/binary_sensor.py index a29082398c2c..2aa0075d570c 100644 --- a/homeassistant/components/unifiprotect/binary_sensor.py +++ b/homeassistant/components/unifiprotect/binary_sensor.py @@ -7,16 +7,9 @@ from typing import cast, override from uiprotect.data import ( NVR, - AlarmHubBatteryStatus, - AlarmHubCoverStatus, - AlarmHubInput, - AlarmHubInputStatus, - AlarmHubInputType, Fob, - LinkStation, ModelType, MountType, - OnOffState, ProtectAdoptableDeviceModel, PublicCamera, PublicHdrMode, @@ -65,16 +58,6 @@ from .migrate import async_is_new_ring_or_motion_sensor _KEY_DOOR = "door" PARALLEL_UPDATES = 0 -_ALARM_HUB_INPUT_DEVICE_CLASS: dict[AlarmHubInputType, BinarySensorDeviceClass] = { - AlarmHubInputType.MOTION: BinarySensorDeviceClass.MOTION, - AlarmHubInputType.ENTRY: BinarySensorDeviceClass.OPENING, - AlarmHubInputType.SMOKE: BinarySensorDeviceClass.SMOKE, - # No dedicated glass-break class; SOUND is the closest fit. - AlarmHubInputType.GLASS_BREAK: BinarySensorDeviceClass.SOUND, - AlarmHubInputType.EMERGENCY_BUTTON: BinarySensorDeviceClass.SAFETY, -} - - _RELAY_INPUT_STATE_MAP: dict[RelayInputState, bool] = { RelayInputState.ON: True, RelayInputState.OFF: False, @@ -764,43 +747,6 @@ def _async_nvr_entities( ] -@dataclasses.dataclass(frozen=True, kw_only=True) -class ProtectAlarmHubBinaryEntityDescription(BinarySensorEntityDescription): - """Describes a UniFi Protect alarm hub (public API) binary sensor.""" - - value_fn: Callable[[LinkStation], bool] - - -def _alarm_hub_tamper(hub: LinkStation) -> bool: - """Return whether the alarm hub tamper cover is open.""" - cover = hub.alarm_hub_cover - return cover is not None and cover.status is AlarmHubCoverStatus.OPEN - - -def _alarm_hub_battery_problem(hub: LinkStation) -> bool: - """Return whether the backup battery is low or critical.""" - battery = hub.alarm_hub_battery - return battery is not None and battery.battery_status in ( - AlarmHubBatteryStatus.LOW, - AlarmHubBatteryStatus.CRITICAL, - ) - - -ALARM_HUB_BINARY_SENSORS: tuple[ProtectAlarmHubBinaryEntityDescription, ...] = ( - ProtectAlarmHubBinaryEntityDescription( - key="tamper", - device_class=BinarySensorDeviceClass.TAMPER, - value_fn=_alarm_hub_tamper, - ), - ProtectAlarmHubBinaryEntityDescription( - key="battery", - device_class=BinarySensorDeviceClass.BATTERY, - entity_category=EntityCategory.DIAGNOSTIC, - value_fn=_alarm_hub_battery_problem, - ), -) - - def _fob_battery_low(fob: Fob) -> bool | None: """Return whether the key fob battery is low, if it has been reported.""" if (battery := fob.wireless_connection_state.battery_status) is not None: @@ -825,82 +771,6 @@ FOB_BINARY_SENSORS: tuple[ProtectFobBinaryEntityDescription, ...] = ( ) -class ProtectAlarmHubBinarySensor(ProtectDeviceEntity, BinarySensorEntity): - """A hub-level binary sensor for a UniFi Protect alarm hub.""" - - entity_description: ProtectAlarmHubBinaryEntityDescription - _state_attrs = ("_attr_available", "_attr_is_on") - _ufp_uses_public = True - - @callback - @override - def _async_update_device_from_protect(self, device: ProtectDeviceType) -> None: - super()._async_update_device_from_protect(device) - if (hub := self._ufp_public_obj) is not None: - self._attr_is_on = self.entity_description.value_fn(cast(LinkStation, hub)) - - -class ProtectAlarmHubZoneBinarySensor( - ProtectPublicChannelEntity[AlarmHubInput], BinarySensorEntity -): - """A wired-input (zone) binary sensor for a UniFi Protect alarm hub.""" - - _state_attrs = ("_attr_available", "_attr_is_on") - - def __init__( - self, data: ProtectData, hub: LinkStation, input_id: int, zone: AlarmHubInput - ) -> None: - """Initialize the zone binary sensor.""" - device_class = ( - _ALARM_HUB_INPUT_DEVICE_CLASS.get(zone.input_type) - if zone.input_type is not None - else None - ) - description = BinarySensorEntityDescription( - key=f"input_{input_id}", - device_class=device_class, - ) - super().__init__(data, hub, description, input_id) - if zone.name: - # Device-provided names take precedence over the translated default. - self._attr_name = zone.name - else: - self._attr_translation_key = "alarm_hub_zone" - self._attr_translation_placeholders = {"zone": str(input_id)} - - @callback - @override - def _async_get_channel(self, device: PublicDeviceModel) -> AlarmHubInput | None: - zone = cast(LinkStation, device).get_alarm_hub_input(self._channel_id) - # An unreadable zone is unavailable rather than a definite "not - # triggered". FAULT/SHORT/CUT are known states and read off. - if zone is None or zone.status is AlarmHubInputStatus.UNKNOWN: - return None - return zone - - @callback - @override - def _async_update_from_channel(self, channel: AlarmHubInput) -> None: - self._attr_is_on = channel.status is AlarmHubInputStatus.ALARM - - -@callback -def _async_alarm_hub_entities( - data: ProtectData, hub: LinkStation -) -> list[ProtectDeviceEntity]: - """Build the binary sensors for one alarm hub.""" - entities: list[ProtectDeviceEntity] = [ - ProtectAlarmHubBinarySensor(data, hub, description) - for description in ALARM_HUB_BINARY_SENSORS - ] - entities += [ - ProtectAlarmHubZoneBinarySensor(data, hub, input_id, zone) - for input_id, zone in hub.alarm_hub_inputs.items() - if zone.enable is OnOffState.ON and zone.input_type is not None - ] - return entities - - class ProtectFobBinarySensor(ProtectDeviceEntity, BinarySensorEntity): """A binary sensor entity for a UniFi Protect key fob (Public API).""" @@ -933,10 +803,6 @@ async def async_setup_entry( for description in FOB_BINARY_SENSORS ) return - if isinstance(device, LinkStation): - if device.is_alarm_hub: - async_add_entities(_async_alarm_hub_entities(data, device)) - return async_add_entities(_async_model_entities(data, public_device=device)) @callback @@ -956,7 +822,7 @@ async def async_setup_entry( ) # The public bootstrap is primed only with an API key and supported NVR - # firmware; without it there are no fobs or alarm hubs to expose. + # firmware; without it there are no fobs to expose. api = data.api if api.has_public_bootstrap: async_add_entities( @@ -964,8 +830,6 @@ async def async_setup_entry( for fob in api.public_bootstrap.fobs.values() for description in FOB_BINARY_SENSORS ) - for hub in api.public_bootstrap.alarm_hubs.values(): - async_add_entities(_async_alarm_hub_entities(data, hub)) @callback def _add_relay_inputs(relay: Relay) -> None: diff --git a/homeassistant/components/unifiprotect/entity.py b/homeassistant/components/unifiprotect/entity.py index e7ac3481c278..f8c4f507e9e0 100644 --- a/homeassistant/components/unifiprotect/entity.py +++ b/homeassistant/components/unifiprotect/entity.py @@ -558,8 +558,8 @@ class ProtectDeviceEntity(BaseProtectEntity): class ProtectPublicChannelEntity[ChannelT, ChannelIdT = int](ProtectDeviceEntity): """Base for an entity tracking one channel of a public device. - Alarm hub zones, relay inputs and outputs and chime ring settings are - channels of their device. The entity goes unavailable while its channel + Relay inputs and outputs and chime ring settings are channels of their + device. The entity goes unavailable while its channel cannot be read, on top of the device's availability. In hybrid the device can be the private one; the channel is read from its public mirror. """ diff --git a/homeassistant/components/unifiprotect/event.py b/homeassistant/components/unifiprotect/event.py index 0516b36c55c2..9ce966795cfc 100644 --- a/homeassistant/components/unifiprotect/event.py +++ b/homeassistant/components/unifiprotect/event.py @@ -10,7 +10,9 @@ from uiprotect.data import ( Bootstrap, EventType, Fob, + LinkStation, ModelType, + OnOffState, ProtectAdoptableDeviceModel, PublicCamera, PublicDeviceModel, @@ -18,7 +20,12 @@ from uiprotect.data import ( ) from uiprotect.data.nvr import Event, EventDetectedThumbnail from uiprotect.data.public_devices import PublicSensor, SensorFeatureCapability -from uiprotect.data.types import EventButtonType, SensorAlarmType +from uiprotect.data.types import ( + AlarmHubInputStatus, + AlarmHubTamperStatus, + EventButtonType, + SensorAlarmType, +) from homeassistant.components.event import ( DoorbellEventType, @@ -58,6 +65,9 @@ from .entity import ( PARALLEL_UPDATES = 0 +ATTR_INPUT = "input" +ATTR_STATUS = "status" + # Per-entity cap on tracked event ids for fire dedup (far above realistic # concurrent/recent events per camera per category). _MAX_TRACKED_EVENTS = 16 @@ -687,6 +697,200 @@ class ProtectFobButtonEventEntity( self._fire_once(event, button_type, {ATTR_EVENT_ID: event.id}) +_ALARM_HUB_INPUT_EVENT_TYPES: dict[EventType, str] = { + EventType.ALARM_HUB_MOTION: "motion", + EventType.ALARM_HUB_ENTRY_OPENED: "entry_opened", + EventType.ALARM_HUB_ENTRY_CLOSED: "entry_closed", + EventType.ALARM_HUB_SMOKE: "smoke", + EventType.ALARM_HUB_GLASS_BREAK: "glass_break", + EventType.ALARM_HUB_BUTTON_PRESS: "button_press", + EventType.ALARM_HUB_TAMPER: "tamper", +} + +_ALARM_HUB_EVENT_TYPES: dict[EventType, str] = { + **_ALARM_HUB_INPUT_EVENT_TYPES, + EventType.ALARM_HUB_DEVICE_TAMPER: "device_tamper", + EventType.ALARM_HUB_RELAY_SWITCHED: "relay_switched", + EventType.ALARM_HUB_BATTERY_LOW: "battery_low", + EventType.ALARM_HUB_BATTERY_CONNECTED: "battery_connected", +} + +_ALARM_HUB_EVENT_DESCRIPTION = EventEntityDescription( + key="alarm_hub", + translation_key="alarm_hub", + event_types=list(_ALARM_HUB_EVENT_TYPES.values()), +) + + +def _alarm_hub_terminals(hub: LinkStation) -> set[int] | None: + """Return the inputs that have a numbered terminal, if the hub lists them. + + The emergency input has its own connector and no number. + """ + connector = (hub.alarm_hub or {}).get("connector") + terminals = connector.get("tb") if isinstance(connector, dict) else None + if not isinstance(terminals, dict): + return None + return {int(terminal) for terminal in terminals if terminal.isdecimal()} + + +# Statuses that report an input or the hub going back to rest. Only entry +# inputs have an event type of their own for that. +_ALARM_HUB_REST_STATUSES = frozenset( + {AlarmHubInputStatus.NORMAL, AlarmHubTamperStatus.RESTORED} +) + + +def _alarm_hub_event_fires(event: ProtectEvent) -> bool: + """Return whether an alarm hub event is fired. + + A return to rest is skipped, except the closing of an entry input. + """ + if event.type is EventType.ALARM_HUB_ENTRY_CLOSED: + return True + metadata = event.metadata + return metadata is None or metadata.status_text not in _ALARM_HUB_REST_STATUSES + + +def _alarm_hub_event_data(event: ProtectEvent) -> dict[str, Any]: + """Return the event id and the reported status of an alarm hub event.""" + event_data: dict[str, Any] = {ATTR_EVENT_ID: event.id} + if (metadata := event.metadata) is not None and metadata.status_text is not None: + event_data[ATTR_STATUS] = metadata.status_text + return event_data + + +def _alarm_hub_event_input(event: ProtectEvent) -> int | None: + """Return the input an alarm hub event belongs to.""" + if ( + (metadata := event.metadata) is None + or (pin := metadata.pin) is None + or not pin.isdecimal() + ): + return None + return int(pin) + + +class ProtectAlarmHubEventEntity( + ProtectFireOnceMixin, ProtectPublicEventSubscriberEntity, EventEntity +): + """The event entity of a UniFi Protect alarm hub itself. + + Fires the events of the hub and those of inputs without an entity of + their own. + """ + + _attr_name = None # device name is the entity name + _unrecorded_attributes = frozenset({ATTR_EVENT_ID}) + _ufp_uses_public = True + _ufp_requires_events_ws = True + + def __init__( + self, data: ProtectData, hub: LinkStation, input_ids: frozenset[int] + ) -> None: + """Initialize the alarm hub event entity.""" + super().__init__(data, hub, _ALARM_HUB_EVENT_DESCRIPTION) + self._input_ids = input_ids + + @override + def _async_public_event_subscriptions( + self, + ) -> Iterable[tuple[EventType, Callable[[ProtectEvent], None]]]: + return ( + (event_type, self._async_hub_event) for event_type in _ALARM_HUB_EVENT_TYPES + ) + + @callback + def _async_hub_event(self, event: ProtectEvent) -> None: + if not _alarm_hub_event_fires(event): + return + input_id = _alarm_hub_event_input(event) + if event.type in _ALARM_HUB_INPUT_EVENT_TYPES and input_id in self._input_ids: + # The entity of that input fires it. + return + event_data = _alarm_hub_event_data(event) + hub = self._ufp_public_obj + terminals = _alarm_hub_terminals(hub) if isinstance(hub, LinkStation) else None + if input_id is not None and (terminals is None or input_id in terminals): + # Protect numbers the inputs from 1, the API from 0. + event_data[ATTR_INPUT] = input_id + 1 + self._fire_once(event, _ALARM_HUB_EVENT_TYPES[event.type], event_data) + + +class ProtectAlarmHubInputEventEntity( + ProtectFireOnceMixin, ProtectPublicEventSubscriberEntity, EventEntity +): + """The event entity of one input of a UniFi Protect alarm hub.""" + + _unrecorded_attributes = frozenset({ATTR_EVENT_ID}) + _ufp_uses_public = True + _ufp_requires_events_ws = True + + def __init__( + self, data: ProtectData, hub: LinkStation, input_id: int, name: str | None + ) -> None: + """Initialize the alarm hub input event entity.""" + # The input type can change in Protect, so every type is declared. + description = EventEntityDescription( + key=f"input_{input_id}", + translation_key="alarm_hub_input", + event_types=list(_ALARM_HUB_INPUT_EVENT_TYPES.values()), + ) + super().__init__(data, hub, description) + self._input_id = input_id + # Protect numbers the inputs from 1, the API from 0. + self._attr_translation_placeholders = {"input": str(input_id + 1)} + if name: + # Device-provided names take precedence over the translated default. + self._attr_name = name + + @override + def _async_public_event_subscriptions( + self, + ) -> Iterable[tuple[EventType, Callable[[ProtectEvent], None]]]: + return ( + (event_type, self._async_input_event) + for event_type in _ALARM_HUB_INPUT_EVENT_TYPES + ) + + @callback + def _async_input_event(self, event: ProtectEvent) -> None: + if _alarm_hub_event_input(event) != self._input_id: + return + if not _alarm_hub_event_fires(event): + return + self._fire_once( + event, + _ALARM_HUB_INPUT_EVENT_TYPES[event.type], + _alarm_hub_event_data(event), + ) + + +@callback +def _async_alarm_hub_event_entities( + data: ProtectData, hub: LinkStation +) -> list[ProtectDeviceEntity]: + """Build the event entities of one alarm hub. + + Every enabled input with a numbered terminal gets its own entity. A hub + that lists no terminals gets one for every enabled input. + """ + terminals = _alarm_hub_terminals(hub) + inputs = { + input_id: hub_input + for input_id, hub_input in hub.alarm_hub_inputs.items() + if hub_input.enable is OnOffState.ON + and (terminals is None or input_id in terminals) + } + return [ + ProtectAlarmHubEventEntity(data, hub, frozenset(inputs)), + *( + ProtectAlarmHubInputEventEntity(data, hub, input_id, hub_input.name) + for input_id, hub_input in inputs.items() + ), + ] + + @dataclasses.dataclass(frozen=True, kw_only=True) class ProtectSensorEventEntityDescription(ProtectPublicEventEntityDescription): """Describes a sensor event entity driven by the public events WS.""" @@ -891,6 +1095,8 @@ async def async_setup_entry( def _add_new_public_device(device: PublicDeviceModel) -> None: if isinstance(device, Fob): async_add_entities([ProtectFobButtonEventEntity(data, device)]) + elif isinstance(device, LinkStation) and device.is_alarm_hub: + async_add_entities(_async_alarm_hub_event_entities(data, device)) elif isinstance(device, PublicCamera): async_add_entities(_async_public_event_entities(data, device)) elif isinstance(device, PublicSensor): @@ -905,12 +1111,21 @@ async def async_setup_entry( ) # The public bootstrap is primed only with an API key and supported NVR - # firmware; without it there are no fobs to expose. + # firmware; without it there are no fobs or alarm hubs to expose. api = data.api if api.has_public_bootstrap: async_add_entities( - ProtectFobButtonEventEntity(data, fob) - for fob in api.public_bootstrap.fobs.values() + [ + *( + ProtectFobButtonEventEntity(data, fob) + for fob in api.public_bootstrap.fobs.values() + ), + *( + entity + for hub in api.public_bootstrap.alarm_hubs.values() + for entity in _async_alarm_hub_event_entities(data, hub) + ), + ] ) if api.is_public_only: diff --git a/homeassistant/components/unifiprotect/icons.json b/homeassistant/components/unifiprotect/icons.json index 2d1acf823aa7..1ffb726f2aa1 100644 --- a/homeassistant/components/unifiprotect/icons.json +++ b/homeassistant/components/unifiprotect/icons.json @@ -157,6 +157,12 @@ "alarm": { "default": "mdi:alarm-light" }, + "alarm_hub": { + "default": "mdi:alarm-panel" + }, + "alarm_hub_input": { + "default": "mdi:electric-switch" + }, "doorbell": { "default": "mdi:doorbell-video" }, diff --git a/homeassistant/components/unifiprotect/sensor.py b/homeassistant/components/unifiprotect/sensor.py index a2fa1a9355ec..31c40ff5186b 100644 --- a/homeassistant/components/unifiprotect/sensor.py +++ b/homeassistant/components/unifiprotect/sensor.py @@ -10,12 +10,10 @@ from typing import Any, cast, override from uiprotect.data import ( NVR, - AlarmHubConnectionState, Camera, Fob, FobAwayState, Light, - LinkStation, ModelType, ProtectAdoptableDeviceModel, ProtectDeviceModel, @@ -585,51 +583,6 @@ _MODEL_DESCRIPTIONS: dict[ModelType, Sequence[ProtectEntityDescription]] = { } -@dataclass(frozen=True, kw_only=True) -class ProtectAlarmHubSensorEntityDescription(SensorEntityDescription): - """Describes a UniFi Protect alarm hub (public API) sensor.""" - - value_fn: Callable[[LinkStation], datetime | float | str | None] - - -def _alarm_hub_battery_voltage(hub: LinkStation) -> float | None: - """Return the backup-battery voltage, or None when no battery is connected. - - A disconnected, removed or fully flat backup battery all report - ``connection: disconnected`` with ``voltage: 0``; reading unknown rather - than 0.0 V avoids implying a real measurement when there is no usable cell. - """ - battery = hub.alarm_hub_battery - if battery is None or battery.connection is not AlarmHubConnectionState.CONNECTED: - return None - return battery.voltage - - -def _alarm_hub_last_event(hub: LinkStation) -> datetime | None: - """Return the last-event timestamp, if reported.""" - return hub.last_event - - -ALARM_HUB_SENSORS: tuple[ProtectAlarmHubSensorEntityDescription, ...] = ( - ProtectAlarmHubSensorEntityDescription( - key="battery_voltage", - translation_key="alarm_hub_battery_voltage", - device_class=SensorDeviceClass.VOLTAGE, - native_unit_of_measurement=UnitOfElectricPotential.VOLT, - state_class=SensorStateClass.MEASUREMENT, - entity_category=EntityCategory.DIAGNOSTIC, - value_fn=_alarm_hub_battery_voltage, - ), - ProtectAlarmHubSensorEntityDescription( - key="last_event", - translation_key="alarm_hub_last_event", - device_class=SensorDeviceClass.TIMESTAMP, - entity_category=EntityCategory.DIAGNOSTIC, - value_fn=_alarm_hub_last_event, - ), -) - - def _fob_battery_level(fob: Fob) -> int | None: """Return the key fob battery percentage, if it has been reported.""" if (battery := fob.wireless_connection_state.battery_status) is not None: @@ -708,23 +661,6 @@ FOB_SENSORS: tuple[ProtectFobSensorEntityDescription, ...] = ( ) -class ProtectAlarmHubSensor(ProtectDeviceEntity, SensorEntity): - """A sensor entity for a UniFi Protect alarm hub.""" - - entity_description: ProtectAlarmHubSensorEntityDescription - _state_attrs = ("_attr_available", "_attr_native_value") - _ufp_uses_public = True - - @callback - @override - def _async_update_device_from_protect(self, device: ProtectDeviceType) -> None: - super()._async_update_device_from_protect(device) - if (hub := self._ufp_public_obj) is not None: - self._attr_native_value = self.entity_description.value_fn( - cast(LinkStation, hub) - ) - - class ProtectFobSensor(ProtectDeviceEntity, SensorEntity): """A sensor entity for a UniFi Protect key fob (Public API).""" @@ -749,13 +685,6 @@ def _async_public_entities( return [ ProtectFobSensor(data, device, description) for description in FOB_SENSORS ] - if isinstance(device, LinkStation): - if not device.is_alarm_hub: - return [] - return [ - ProtectAlarmHubSensor(data, device, description) - for description in ALARM_HUB_SENSORS - ] return list( async_all_device_entities( data, @@ -786,13 +715,11 @@ async def async_setup_entry( entities: list[Entity] = [] # The public bootstrap is primed only with an API key and supported NVR - # firmware; without it there are no fobs or alarm hubs to expose. + # firmware; without it there are no fobs to expose. api = data.api if api.has_public_bootstrap: for fob in api.public_bootstrap.fobs.values(): entities.extend(_async_public_entities(data, fob)) - for hub in api.public_bootstrap.alarm_hubs.values(): - entities.extend(_async_public_entities(data, hub)) if api.is_public_only: # The remaining sensors read the private bootstrap; the migrated ones diff --git a/homeassistant/components/unifiprotect/strings.json b/homeassistant/components/unifiprotect/strings.json index d84a035ab686..d61ae9e1ae3f 100644 --- a/homeassistant/components/unifiprotect/strings.json +++ b/homeassistant/components/unifiprotect/strings.json @@ -172,9 +172,6 @@ } }, "binary_sensor": { - "alarm_hub_zone": { - "name": "Zone {zone}" - }, "animal_detected": { "name": "Animal detected" }, @@ -337,6 +334,41 @@ } } }, + "alarm_hub": { + "state_attributes": { + "event_type": { + "state": { + "battery_connected": "Battery connected", + "battery_low": "[%key:component::unifiprotect::entity::event::maintenance::state_attributes::event_type::state::battery_low%]", + "button_press": "Button pressed", + "device_tamper": "Hub tampered", + "entry_closed": "Entry closed", + "entry_opened": "Entry opened", + "glass_break": "[%key:component::unifiprotect::entity::event::sound_detection::state_attributes::event_type::state::glass_break%]", + "motion": "[%key:component::unifiprotect::entity::event::motion_detection::state_attributes::event_type::state::motion%]", + "relay_switched": "Relay switched", + "smoke": "[%key:component::unifiprotect::entity::event::alarm::state_attributes::event_type::state::smoke%]", + "tamper": "Tampered" + } + } + } + }, + "alarm_hub_input": { + "name": "Input {input}", + "state_attributes": { + "event_type": { + "state": { + "button_press": "[%key:component::unifiprotect::entity::event::alarm_hub::state_attributes::event_type::state::button_press%]", + "entry_closed": "[%key:component::unifiprotect::entity::event::alarm_hub::state_attributes::event_type::state::entry_closed%]", + "entry_opened": "[%key:component::unifiprotect::entity::event::alarm_hub::state_attributes::event_type::state::entry_opened%]", + "glass_break": "[%key:component::unifiprotect::entity::event::sound_detection::state_attributes::event_type::state::glass_break%]", + "motion": "[%key:component::unifiprotect::entity::event::motion_detection::state_attributes::event_type::state::motion%]", + "smoke": "[%key:component::unifiprotect::entity::event::alarm::state_attributes::event_type::state::smoke%]", + "tamper": "[%key:component::unifiprotect::entity::event::alarm_hub::state_attributes::event_type::state::tamper%]" + } + } + } + }, "doorbell": { "state_attributes": { "event_type": { @@ -592,12 +624,6 @@ } }, "sensor": { - "alarm_hub_battery_voltage": { - "name": "Battery voltage" - }, - "alarm_hub_last_event": { - "name": "Last event" - }, "alarm_sound_detected": { "name": "Alarm sound detected" }, diff --git a/tests/components/unifiprotect/fixtures/sample_alarm_hub.json b/tests/components/unifiprotect/fixtures/sample_alarm_hub.json index bc4102e3a741..7a2dedde1fe4 100644 --- a/tests/components/unifiprotect/fixtures/sample_alarm_hub.json +++ b/tests/components/unifiprotect/fixtures/sample_alarm_hub.json @@ -25,6 +25,11 @@ "inputType": "SMOKE", "name": "Kitchen Smoke" }, + "6": { + "enable": "on", + "type": "no", + "status": "normal" + }, "8": { "enable": "on", "type": "nc", @@ -51,6 +56,44 @@ "type": "nc", "status": "normal", "inputType": "ENTRY" + }, + "32": { + "enable": "on", + "type": "no", + "status": "normal", + "inputType": "EMERGENCY_BUTTON" + } + }, + "connector": { + "emergency": { + "+": "disconnected", + "-": "disconnected" + }, + "tb": { + "4": { + "+": "disconnected", + "-": "disconnected" + }, + "6": { + "+": "connected", + "-": "connected" + }, + "8": { + "+": "disconnected", + "-": "disconnected" + }, + "16": { + "+": "disconnected", + "-": "disconnected" + }, + "24": { + "+": "disconnected", + "-": "disconnected" + }, + "25": { + "+": "disconnected", + "-": "disconnected" + } } } }, diff --git a/tests/components/unifiprotect/snapshots/test_alarm_hub.ambr b/tests/components/unifiprotect/snapshots/test_alarm_hub.ambr index 85f6fa19d82d..266c0321325c 100644 --- a/tests/components/unifiprotect/snapshots/test_alarm_hub.ambr +++ b/tests/components/unifiprotect/snapshots/test_alarm_hub.ambr @@ -1,368 +1,4 @@ # serializer version: 1 -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_24_hour_tamper-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'safety', - : 'Alarm Hub 24 Hour Tamper', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_24_hour_tamper', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_24_hour_tamper] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_24_hour_tamper', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': '24 Hour Tamper', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': '24 Hour Tamper', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_input_16', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_battery-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'battery', - : 'Alarm Hub Battery', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_battery', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_battery] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': , - 'entity_id': 'binary_sensor.alarm_hub_battery', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Battery', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Battery', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_battery', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_hallway-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'motion', - : 'Alarm Hub Hallway', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_hallway', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_hallway] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_hallway', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Hallway', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Hallway', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_input_24', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_kitchen_smoke-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'smoke', - : 'Alarm Hub Kitchen Smoke', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_kitchen_smoke', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'on', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_kitchen_smoke] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_kitchen_smoke', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Kitchen Smoke', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Kitchen Smoke', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_input_4', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_living_room_window-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'sound', - : 'Alarm Hub Living Room Window', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_living_room_window', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_living_room_window] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_living_room_window', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Living Room Window', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Living Room Window', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_input_8', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_tamper-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'tamper', - : 'Alarm Hub Tamper', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_tamper', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_tamper] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_tamper', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Tamper', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Tamper', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': None, - 'unique_id': 'AABBCCDDEEFF_tamper', - 'unit_of_measurement': None, - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_zone_25-state] - StateSnapshot({ - 'attributes': ReadOnlyDict({ - : 'Powered by UniFi Protect Server', - : 'opening', - : 'Alarm Hub Zone 25', - }), - 'context': , - 'entity_id': 'binary_sensor.alarm_hub_zone_25', - 'last_changed': , - 'last_reported': , - 'last_updated': , - 'state': 'off', - }) -# --- -# name: test_alarm_hub_device_and_entities[binary_sensor.alarm_hub_zone_25] - EntityRegistryEntrySnapshot({ - 'aliases': list([ - None, - ]), - 'area_id': None, - 'capabilities': None, - 'config_entry_id': , - 'config_subentry_id': None, - 'device_class': None, - 'device_id': , - 'disabled_by': None, - 'domain': 'binary_sensor', - 'entity_category': None, - 'entity_id': 'binary_sensor.alarm_hub_zone_25', - 'has_entity_name': True, - 'hidden_by': None, - 'icon': None, - 'id': , - 'labels': set({ - }), - 'name': None, - 'object_id_base': 'Zone 25', - 'options': dict({ - }), - 'original_device_class': , - 'original_icon': None, - 'original_name': 'Zone 25', - 'platform': 'unifiprotect', - 'previous_unique_id': None, - 'suggested_object_id': None, - 'supported_features': 0, - 'translation_key': 'alarm_hub_zone', - 'unique_id': 'AABBCCDDEEFF_input_25', - 'unit_of_measurement': None, - }) -# --- # name: test_alarm_hub_device_and_entities[device] DeviceRegistryEntrySnapshot({ 'area_id': None, @@ -393,40 +29,63 @@ 'via_device_id': , }) # --- -# name: test_alarm_hub_device_and_entities[sensor.alarm_hub_battery_voltage-state] +# name: test_alarm_hub_device_and_entities[event.alarm_hub-state] StateSnapshot({ 'attributes': ReadOnlyDict({ : 'Powered by UniFi Protect Server', - : 'voltage', - : 'Alarm Hub Battery voltage', - : , - : , + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + 'device_tamper', + 'relay_switched', + 'battery_low', + 'battery_connected', + ]), + : 'Alarm Hub', }), 'context': , - 'entity_id': 'sensor.alarm_hub_battery_voltage', + 'entity_id': 'event.alarm_hub', 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '12.108427', + 'state': 'unknown', }) # --- -# name: test_alarm_hub_device_and_entities[sensor.alarm_hub_battery_voltage] +# name: test_alarm_hub_device_and_entities[event.alarm_hub] EntityRegistryEntrySnapshot({ 'aliases': list([ None, ]), 'area_id': None, 'capabilities': dict({ - : , + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + 'device_tamper', + 'relay_switched', + 'battery_low', + 'battery_connected', + ]), }), 'config_entry_id': , 'config_subentry_id': None, 'device_class': None, 'device_id': , 'disabled_by': None, - 'domain': 'sensor', - 'entity_category': , - 'entity_id': 'sensor.alarm_hub_battery_voltage', + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub', 'has_entity_name': True, 'hidden_by': None, 'icon': None, @@ -434,54 +93,70 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Battery voltage', + 'object_id_base': None, 'options': dict({ - 'sensor': dict({ - 'suggested_display_precision': 0, - }), }), - 'original_device_class': , + 'original_device_class': None, 'original_icon': None, - 'original_name': 'Battery voltage', + 'original_name': None, 'platform': 'unifiprotect', 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'alarm_hub_battery_voltage', - 'unique_id': 'AABBCCDDEEFF_battery_voltage', - 'unit_of_measurement': , + 'translation_key': 'alarm_hub', + 'unique_id': 'AABBCCDDEEFF_alarm_hub', + 'unit_of_measurement': None, }) # --- -# name: test_alarm_hub_device_and_entities[sensor.alarm_hub_last_event-state] +# name: test_alarm_hub_device_and_entities[event.alarm_hub_24_hour_tamper-state] StateSnapshot({ 'attributes': ReadOnlyDict({ : 'Powered by UniFi Protect Server', - : 'timestamp', - : 'Alarm Hub Last event', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub 24 Hour Tamper', }), 'context': , - 'entity_id': 'sensor.alarm_hub_last_event', + 'entity_id': 'event.alarm_hub_24_hour_tamper', 'last_changed': , 'last_reported': , 'last_updated': , - 'state': '2026-06-02T15:58:03+00:00', + 'state': 'unknown', }) # --- -# name: test_alarm_hub_device_and_entities[sensor.alarm_hub_last_event] +# name: test_alarm_hub_device_and_entities[event.alarm_hub_24_hour_tamper] EntityRegistryEntrySnapshot({ 'aliases': list([ None, ]), 'area_id': None, - 'capabilities': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), 'config_entry_id': , 'config_subentry_id': None, 'device_class': None, 'device_id': , 'disabled_by': None, - 'domain': 'sensor', - 'entity_category': , - 'entity_id': 'sensor.alarm_hub_last_event', + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_24_hour_tamper', 'has_entity_name': True, 'hidden_by': None, 'icon': None, @@ -489,18 +164,373 @@ 'labels': set({ }), 'name': None, - 'object_id_base': 'Last event', + 'object_id_base': '24 Hour Tamper', 'options': dict({ }), - 'original_device_class': , + 'original_device_class': None, 'original_icon': None, - 'original_name': 'Last event', + 'original_name': '24 Hour Tamper', 'platform': 'unifiprotect', 'previous_unique_id': None, 'suggested_object_id': None, 'supported_features': 0, - 'translation_key': 'alarm_hub_last_event', - 'unique_id': 'AABBCCDDEEFF_last_event', + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_16', + 'unit_of_measurement': None, + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_hallway-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Powered by UniFi Protect Server', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub Hallway', + }), + 'context': , + 'entity_id': 'event.alarm_hub_hallway', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_hallway] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_hallway', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Hallway', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Hallway', + 'platform': 'unifiprotect', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_24', + 'unit_of_measurement': None, + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_input_26-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Powered by UniFi Protect Server', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub Input 26', + }), + 'context': , + 'entity_id': 'event.alarm_hub_input_26', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_input_26] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_input_26', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Input 26', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Input 26', + 'platform': 'unifiprotect', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_25', + 'unit_of_measurement': None, + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_input_7-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Powered by UniFi Protect Server', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub Input 7', + }), + 'context': , + 'entity_id': 'event.alarm_hub_input_7', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_input_7] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_input_7', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Input 7', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Input 7', + 'platform': 'unifiprotect', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_6', + 'unit_of_measurement': None, + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_kitchen_smoke-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Powered by UniFi Protect Server', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub Kitchen Smoke', + }), + 'context': , + 'entity_id': 'event.alarm_hub_kitchen_smoke', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_kitchen_smoke] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_kitchen_smoke', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Kitchen Smoke', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Kitchen Smoke', + 'platform': 'unifiprotect', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_4', + 'unit_of_measurement': None, + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_living_room_window-state] + StateSnapshot({ + 'attributes': ReadOnlyDict({ + : 'Powered by UniFi Protect Server', + : None, + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + : 'Alarm Hub Living Room Window', + }), + 'context': , + 'entity_id': 'event.alarm_hub_living_room_window', + 'last_changed': , + 'last_reported': , + 'last_updated': , + 'state': 'unknown', + }) +# --- +# name: test_alarm_hub_device_and_entities[event.alarm_hub_living_room_window] + EntityRegistryEntrySnapshot({ + 'aliases': list([ + None, + ]), + 'area_id': None, + 'capabilities': dict({ + : list([ + 'motion', + 'entry_opened', + 'entry_closed', + 'smoke', + 'glass_break', + 'button_press', + 'tamper', + ]), + }), + 'config_entry_id': , + 'config_subentry_id': None, + 'device_class': None, + 'device_id': , + 'disabled_by': None, + 'domain': 'event', + 'entity_category': None, + 'entity_id': 'event.alarm_hub_living_room_window', + 'has_entity_name': True, + 'hidden_by': None, + 'icon': None, + 'id': , + 'labels': set({ + }), + 'name': None, + 'object_id_base': 'Living Room Window', + 'options': dict({ + }), + 'original_device_class': None, + 'original_icon': None, + 'original_name': 'Living Room Window', + 'platform': 'unifiprotect', + 'previous_unique_id': None, + 'suggested_object_id': None, + 'supported_features': 0, + 'translation_key': 'alarm_hub_input', + 'unique_id': 'AABBCCDDEEFF_input_8', 'unit_of_measurement': None, }) # --- diff --git a/tests/components/unifiprotect/test_alarm_hub.py b/tests/components/unifiprotect/test_alarm_hub.py index c223002540c8..84d9dafcc1d9 100644 --- a/tests/components/unifiprotect/test_alarm_hub.py +++ b/tests/components/unifiprotect/test_alarm_hub.py @@ -1,5 +1,6 @@ """Tests for the UniFi Protect Alarm Hub (Public API) entities.""" +from datetime import datetime from unittest.mock import AsyncMock, Mock import pytest @@ -7,12 +8,17 @@ from pytest_homeassistant.common import load_json_object_fixture from pytest_homeassistant.components.diagnostics import get_diagnostics_for_config_entry from pytest_homeassistant.typing import ClientSessionGenerator from syrupy.assertion import SnapshotAssertion -from uiprotect.data import DeviceState, LinkStation, WSAction +from uiprotect import EventChange, ProtectEvent, ProtectEventChannel +from uiprotect.data import DeviceState, EventType, LinkStation, WSAction +from uiprotect.data.public_event import PublicEventMetadata from uiprotect.websocket import WebsocketState +from homeassistant.components.unifiprotect.const import ATTR_EVENT_ID +from homeassistant.components.unifiprotect.event import ATTR_INPUT, ATTR_STATUS from homeassistant.const import STATE_UNAVAILABLE -from homeassistant.core import HomeAssistant +from homeassistant.core import Event as HAEvent, HomeAssistant, callback from homeassistant.helpers import device_registry as dr, entity_registry as er +from homeassistant.helpers.event import async_track_state_change_event from .utils import ( MockUFPFixture, @@ -24,6 +30,9 @@ from .utils import ( DOMAIN = "unifiprotect" ALARM_HUB_MAC = "AABBCCDDEEFF" +HUB_EVENT = "event.alarm_hub" +INPUT_EVENT = "event.alarm_hub_input_7" +NAMED_INPUT_EVENT = "event.alarm_hub_hallway" def _make_alarm_hub() -> LinkStation: @@ -52,6 +61,26 @@ def _alarm_hub_fixture() -> LinkStation: return _make_alarm_hub() +def _hub_event( + hub: LinkStation, + event_type: EventType, + metadata: PublicEventMetadata | None, + event_id: str = "evt-1", +) -> ProtectEvent: + """Build an alarm hub ``ProtectEvent``; real ones have ``start == end``.""" + when = datetime(2026, 1, 1) + return ProtectEvent( + id=event_id, + type=event_type, + channel=ProtectEventChannel.ALARM_HUB, + device_id=hub.id, + device_mac=hub.mac, + start=when, + end=when, + metadata=metadata, + ) + + @pytest.fixture(name="ufp_with_alarm_hub") def _ufp_with_alarm_hub(ufp: MockUFPFixture, alarm_hub: LinkStation) -> MockUFPFixture: """Configure the ufp fixture with one alarm hub via the public API.""" @@ -60,161 +89,13 @@ def _ufp_with_alarm_hub(ufp: MockUFPFixture, alarm_hub: LinkStation) -> MockUFPF return ufp -async def test_sensors_not_created_without_public_bootstrap( - hass: HomeAssistant, ufp: MockUFPFixture +async def test_event_not_created_without_public_bootstrap( + hass: HomeAssistant, ufp_with_alarm_hub: MockUFPFixture ) -> None: - """No alarm hub sensors when the public bootstrap is unavailable.""" - ufp.api.has_public_bootstrap = False - await init_entry(hass, ufp, []) - assert hass.states.get("sensor.alarm_hub_battery_voltage") is None - - -async def test_alarm_hub_battery_voltage_sensor( - hass: HomeAssistant, - entity_registry: er.EntityRegistry, - ufp_with_alarm_hub: MockUFPFixture, -) -> None: - """Battery voltage sensor is created with the reported voltage.""" + """No alarm hub entity when the public bootstrap is unavailable.""" + ufp_with_alarm_hub.api.has_public_bootstrap = False await init_entry(hass, ufp_with_alarm_hub, []) - - entity_id = "sensor.alarm_hub_battery_voltage" - entity = entity_registry.async_get(entity_id) - assert entity is not None - assert entity.unique_id == f"{ALARM_HUB_MAC}_battery_voltage" - - state = hass.states.get(entity_id) - assert state is not None - assert state.state == "12.108427" - assert state.attributes["device_class"] == "voltage" - assert state.attributes["unit_of_measurement"] == "V" - - -async def test_alarm_hub_last_event_sensor( - hass: HomeAssistant, - entity_registry: er.EntityRegistry, - ufp_with_alarm_hub: MockUFPFixture, -) -> None: - """Last-event timestamp sensor is created.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - entity_id = "sensor.alarm_hub_last_event" - entity = entity_registry.async_get(entity_id) - assert entity is not None - assert entity.unique_id == f"{ALARM_HUB_MAC}_last_event" - - state = hass.states.get(entity_id) - assert state is not None - assert state.attributes["device_class"] == "timestamp" - - -async def test_alarm_hub_tamper_binary_sensor( - hass: HomeAssistant, - entity_registry: er.EntityRegistry, - ufp_with_alarm_hub: MockUFPFixture, -) -> None: - """Tamper cover binary sensor reflects the cover status.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - entity_id = "binary_sensor.alarm_hub_tamper" - entity = entity_registry.async_get(entity_id) - assert entity is not None - assert entity.unique_id == f"{ALARM_HUB_MAC}_tamper" - - state = hass.states.get(entity_id) - assert state is not None - assert state.attributes["device_class"] == "tamper" - assert state.state == "off" # cover closed - - -async def test_alarm_hub_battery_binary_sensor( - hass: HomeAssistant, - entity_registry: er.EntityRegistry, - ufp_with_alarm_hub: MockUFPFixture, -) -> None: - """Battery problem binary sensor is off when battery_status is ok.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - entity_id = "binary_sensor.alarm_hub_battery" - entity = entity_registry.async_get(entity_id) - assert entity is not None - assert entity.unique_id == f"{ALARM_HUB_MAC}_battery" - - state = hass.states.get(entity_id) - assert state is not None - assert state.attributes["device_class"] == "battery" - assert state.state == "off" - - -async def test_alarm_hub_zone_binary_sensors( - hass: HomeAssistant, - entity_registry: er.EntityRegistry, - ufp_with_alarm_hub: MockUFPFixture, -) -> None: - """One binary sensor per configured input, with mapped device classes.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - # Named motion zone. - hallway = hass.states.get("binary_sensor.alarm_hub_hallway") - assert hallway is not None - assert hallway.attributes["device_class"] == "motion" - assert hallway.state == "off" # status normal - - # Named emergency button -> safety. - tamper_btn = entity_registry.async_get("binary_sensor.alarm_hub_24_hour_tamper") - assert tamper_btn is not None - assert tamper_btn.unique_id == f"{ALARM_HUB_MAC}_input_16" - assert ( - hass.states.get("binary_sensor.alarm_hub_24_hour_tamper").attributes[ - "device_class" - ] - == "safety" - ) - - # Unnamed entry zone -> opening, fallback name "Zone 25". - entry = hass.states.get("binary_sensor.alarm_hub_zone_25") - assert entry is not None - assert entry.attributes["device_class"] == "opening" - - -async def test_alarm_hub_zone_triggered_state( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A zone in the ALARM status reports on.""" - # Mark the Hallway motion zone (input 24) as triggered. - alarm_hub.alarm_hub["input"]["24"]["status"] = "alarm" - await init_entry(hass, ufp_with_alarm_hub, []) - - state = hass.states.get("binary_sensor.alarm_hub_hallway") - assert state is not None - assert state.state == "on" - - -async def test_alarm_hub_zone_unknown_status_unavailable( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A zone with an unreadable (UNKNOWN) status is unavailable, not 'off'.""" - alarm_hub.alarm_hub["input"]["24"]["status"] = "unknown" - await init_entry(hass, ufp_with_alarm_hub, []) - - state = hass.states.get("binary_sensor.alarm_hub_hallway") - assert state is not None - assert state.state == STATE_UNAVAILABLE - - -async def test_alarm_hub_disabled_zone_not_created( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A disabled input is not surfaced as a zone entity.""" - alarm_hub.alarm_hub["input"]["24"]["enable"] = "off" - await init_entry(hass, ufp_with_alarm_hub, []) - - assert hass.states.get("binary_sensor.alarm_hub_hallway") is None + assert hass.states.get(HUB_EVENT) is None async def test_alarm_hub_in_diagnostics( @@ -271,7 +152,7 @@ async def test_alarm_hub_availability_follows_public_ws( """Availability tracks the public websocket health, not the private one.""" await init_entry(hass, ufp_with_alarm_hub, []) - entity_id = "sensor.alarm_hub_battery_voltage" + entity_id = HUB_EVENT assert hass.states.get(entity_id).state != STATE_UNAVAILABLE # Private connection drops: the public-only alarm hub stays available. @@ -292,73 +173,6 @@ async def test_alarm_hub_availability_follows_public_ws( assert hass.states.get(entity_id).state != STATE_UNAVAILABLE -async def test_alarm_hub_state_updates_from_public_ws( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A public devices WS update for the hub refreshes its entities.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - entity_id = "binary_sensor.alarm_hub_hallway" - assert hass.states.get(entity_id).state == "off" - - # Trigger the Hallway motion zone (input 24) on the cached hub object. - alarm_hub.alarm_hub["input"]["24"]["status"] = "alarm" - - mock_msg = Mock() - mock_msg.changed_data = {} - mock_msg.old_obj = alarm_hub - mock_msg.new_obj = alarm_hub - assert ufp_with_alarm_hub.devices_ws_subscription is not None - ufp_with_alarm_hub.devices_ws_subscription(mock_msg) - await hass.async_block_till_done() - - assert hass.states.get(entity_id).state == "on" - - -async def test_alarm_hub_values_update_from_public_ws( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """Hub-level values follow a public devices WS update.""" - await init_entry(hass, ufp_with_alarm_hub, []) - assert hass.states.get("binary_sensor.alarm_hub_tamper").state == "off" - assert hass.states.get("sensor.alarm_hub_battery_voltage").state == "12.108427" - - alarm_hub.alarm_hub["cover"]["status"] = "open" - alarm_hub.alarm_hub["battery"]["voltage"] = 11.5 - assert ufp_with_alarm_hub.devices_ws_subscription is not None - ufp_with_alarm_hub.devices_ws_subscription(public_device_ws_message(alarm_hub)) - await hass.async_block_till_done() - - assert hass.states.get("binary_sensor.alarm_hub_tamper").state == "on" - assert hass.states.get("sensor.alarm_hub_battery_voltage").state == "11.5" - - -async def test_alarm_hub_reads_replaced_object_after_resync( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A resync that replaces the hub object is picked up from the bootstrap.""" - await init_entry(hass, ufp_with_alarm_hub, []) - - replaced = _make_alarm_hub() - replaced.alarm_hub["cover"]["status"] = "open" - replaced.alarm_hub["battery"]["voltage"] = 11.5 - ufp_with_alarm_hub.api.public_bootstrap.alarm_hubs[alarm_hub.id] = replaced - msg = public_device_ws_message(None) - msg.old_obj = alarm_hub - assert ufp_with_alarm_hub.devices_ws_subscription is not None - ufp_with_alarm_hub.devices_ws_subscription(msg) - await hass.async_block_till_done() - - assert hass.states.get("binary_sensor.alarm_hub_tamper").state == "on" - assert hass.states.get("sensor.alarm_hub_battery_voltage").state == "11.5" - - async def test_alarm_hub_unavailable_while_disconnected( hass: HomeAssistant, ufp_with_alarm_hub: MockUFPFixture, @@ -366,23 +180,18 @@ async def test_alarm_hub_unavailable_while_disconnected( ) -> None: """A disconnected hub takes all of its entities offline until it is back.""" await init_entry(hass, ufp_with_alarm_hub, []) - entity_ids = ( - "binary_sensor.alarm_hub_tamper", - "sensor.alarm_hub_battery_voltage", - "binary_sensor.alarm_hub_hallway", - ) assert ufp_with_alarm_hub.devices_ws_subscription is not None alarm_hub.state = DeviceState.DISCONNECTED ufp_with_alarm_hub.devices_ws_subscription(public_device_ws_message(alarm_hub)) await hass.async_block_till_done() - for entity_id in entity_ids: + for entity_id in (HUB_EVENT, INPUT_EVENT): assert hass.states.get(entity_id).state == STATE_UNAVAILABLE alarm_hub.state = DeviceState.CONNECTED ufp_with_alarm_hub.devices_ws_subscription(public_device_ws_message(alarm_hub)) await hass.async_block_till_done() - for entity_id in entity_ids: + for entity_id in (HUB_EVENT, INPUT_EVENT): assert hass.states.get(entity_id).state != STATE_UNAVAILABLE @@ -394,7 +203,7 @@ async def test_alarm_hub_becomes_unavailable_when_removed( """A delete WS frame (new_obj=None) marks the hub's entities unavailable.""" await init_entry(hass, ufp_with_alarm_hub, []) - entity_id = "sensor.alarm_hub_battery_voltage" + entity_id = HUB_EVENT assert hass.states.get(entity_id).state != STATE_UNAVAILABLE # Drop the hub from the public bootstrap, then send a delete frame. @@ -411,40 +220,12 @@ async def test_alarm_hub_becomes_unavailable_when_removed( assert hass.states.get(entity_id).state == STATE_UNAVAILABLE -async def test_alarm_hub_disconnected_battery( - hass: HomeAssistant, - ufp_with_alarm_hub: MockUFPFixture, - alarm_hub: LinkStation, -) -> None: - """A disconnected backup battery degrades gracefully. - - Real hardware reports a disconnected, removed or fully flat backup battery - identically: ``connection: disconnected`` with ``voltage: 0`` and no - ``batteryStatus``. The battery is an optional add-on, so this is also the - steady state for a hub with no battery fitted and must not read as a problem. - """ - assert alarm_hub.alarm_hub is not None - alarm_hub.alarm_hub["battery"] = {"connection": "disconnected", "voltage": 0} - await init_entry(hass, ufp_with_alarm_hub, []) - - # An absent batteryStatus must not read as a problem (optional battery). - battery = hass.states.get("binary_sensor.alarm_hub_battery") - assert battery is not None - assert battery.state == "off" - - # Voltage reads unknown rather than a misleading 0.0 V. - voltage = hass.states.get("sensor.alarm_hub_battery_voltage") - assert voltage is not None - assert voltage.state == "unknown" - - @pytest.mark.parametrize( "is_public_only", [pytest.param(False, id="hybrid"), pytest.param(True, id="api_key_only")], ) async def test_alarm_hub_added_at_runtime( hass: HomeAssistant, - entity_registry: er.EntityRegistry, ufp: MockUFPFixture, alarm_hub: LinkStation, is_public_only: bool, @@ -457,7 +238,7 @@ async def test_alarm_hub_added_at_runtime( ufp.api.update_public = AsyncMock(return_value=pb) await init_entry(hass, ufp, []) - assert hass.states.get("sensor.alarm_hub_battery_voltage") is None + assert hass.states.get(HUB_EVENT) is None pb.alarm_hubs = {alarm_hub.id: alarm_hub} msg = public_device_ws_message(alarm_hub) @@ -466,13 +247,8 @@ async def test_alarm_hub_added_at_runtime( ufp.devices_ws_subscription(msg) await hass.async_block_till_done() - assert hass.states.get("sensor.alarm_hub_battery_voltage").state == "12.108427" - assert hass.states.get("binary_sensor.alarm_hub_tamper").state == "off" - assert hass.states.get("binary_sensor.alarm_hub_hallway") is not None - assert ( - entity_registry.async_get("sensor.alarm_hub_battery_voltage").unique_id - == f"{ALARM_HUB_MAC}_battery_voltage" - ) + for entity_id in (HUB_EVENT, INPUT_EVENT, NAMED_INPUT_EVENT): + assert hass.states.get(entity_id) is not None async def test_alarm_hub_known_at_setup_not_added_again( @@ -527,7 +303,7 @@ async def test_plain_link_station_added_at_runtime( ) is None ) - assert hass.states.get("sensor.alarm_hub_battery_voltage") is None + assert hass.states.get(HUB_EVENT) is None @pytest.mark.parametrize( @@ -560,10 +336,7 @@ async def test_alarm_hub_without_name( assert device.name == f"{model} {ALARM_HUB_MAC}" assert device.model == model assert device.model_id == device_type - assert ( - hass.states.get(f"sensor.{object_id}_{ALARM_HUB_MAC.lower()}_battery_voltage") - is not None - ) + assert hass.states.get(f"event.{object_id}_{ALARM_HUB_MAC.lower()}") is not None async def test_alarm_hub_unavailable_when_public_bootstrap_lost( @@ -574,8 +347,8 @@ async def test_alarm_hub_unavailable_when_public_bootstrap_lost( """Losing the public bootstrap marks alarm hub entities unavailable.""" await init_entry(hass, ufp_with_alarm_hub, []) - entity_id = "sensor.alarm_hub_battery_voltage" - assert hass.states.get(entity_id).state == "12.108427" + entity_id = HUB_EVENT + assert hass.states.get(entity_id).state != STATE_UNAVAILABLE ufp_with_alarm_hub.api.has_public_bootstrap = False # A frame without a merged object makes the entities re-read the bootstrap. @@ -586,3 +359,295 @@ async def test_alarm_hub_unavailable_when_public_bootstrap_lost( await hass.async_block_till_done() assert hass.states.get(entity_id).state == STATE_UNAVAILABLE + + +def _capture_events(hass: HomeAssistant, *entity_ids: str) -> list[HAEvent]: + """Collect the state changes of the given entities.""" + events: list[HAEvent] = [] + + @callback + def _capture(event: HAEvent) -> None: + events.append(event) + + async_track_state_change_event(hass, entity_ids, _capture) + return events + + +@pytest.mark.parametrize( + ("event_type", "status", "expected_type"), + [ + pytest.param(EventType.ALARM_HUB_MOTION, "alarm", "motion", id="motion"), + pytest.param( + EventType.ALARM_HUB_ENTRY_OPENED, "alarm", "entry_opened", id="entry_opened" + ), + pytest.param( + EventType.ALARM_HUB_ENTRY_CLOSED, + "normal", + "entry_closed", + id="entry_closed", + ), + pytest.param(EventType.ALARM_HUB_SMOKE, "alarm", "smoke", id="smoke"), + pytest.param( + EventType.ALARM_HUB_GLASS_BREAK, "alarm", "glass_break", id="glass_break" + ), + pytest.param( + EventType.ALARM_HUB_BUTTON_PRESS, "alarm", "button_press", id="button_press" + ), + pytest.param(EventType.ALARM_HUB_TAMPER, "alarm", "tamper", id="tamper"), + ], +) +async def test_alarm_hub_input_event_fires( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, + event_type: EventType, + status: str, + expected_type: str, +) -> None: + """An input event fires on the entity of that input only.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + # Input 6 of the API is input 7 in Protect. + events = _capture_events(hass, INPUT_EVENT, HUB_EVENT, NAMED_INPUT_EVENT) + metadata = PublicEventMetadata(pin="6", status_text=status) + # Protect dispatches every change of an event; it must fire only once. + for change in (EventChange.STARTED, EventChange.ENDED): + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, event_type, metadata), change + ) + await hass.async_block_till_done() + + assert len(events) == 1 + assert events[0].data["entity_id"] == INPUT_EVENT + attributes = events[0].data["new_state"].attributes + assert attributes["event_type"] == expected_type + assert attributes[ATTR_EVENT_ID] == "evt-1" + assert attributes[ATTR_STATUS] == status + assert ATTR_INPUT not in attributes + + +async def test_alarm_hub_named_input_event( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, +) -> None: + """An input named in Protect uses that name for its entity.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + events = _capture_events(hass, INPUT_EVENT, HUB_EVENT, NAMED_INPUT_EVENT) + metadata = PublicEventMetadata(pin="24", status_text="alarm") + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, EventType.ALARM_HUB_MOTION, metadata), + EventChange.STARTED, + ) + await hass.async_block_till_done() + + assert [event.data["entity_id"] for event in events] == [NAMED_INPUT_EVENT] + + +@pytest.mark.parametrize( + ("event_type", "metadata", "expected_type", "expected_status"), + [ + pytest.param( + EventType.ALARM_HUB_DEVICE_TAMPER, + PublicEventMetadata(status_text="tampered"), + "device_tamper", + "tampered", + id="device_tamper", + ), + pytest.param( + EventType.ALARM_HUB_RELAY_SWITCHED, + None, + "relay_switched", + None, + id="relay_switched", + ), + pytest.param( + EventType.ALARM_HUB_BATTERY_LOW, None, "battery_low", None, id="battery_low" + ), + pytest.param( + EventType.ALARM_HUB_BATTERY_CONNECTED, + PublicEventMetadata(), + "battery_connected", + None, + id="battery_connected", + ), + ], +) +async def test_alarm_hub_event_fires( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, + event_type: EventType, + metadata: PublicEventMetadata | None, + expected_type: str, + expected_status: str | None, +) -> None: + """An event of the hub itself fires on the hub entity.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + events = _capture_events(hass, INPUT_EVENT, HUB_EVENT, NAMED_INPUT_EVENT) + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, event_type, metadata), EventChange.STARTED + ) + await hass.async_block_till_done() + + assert len(events) == 1 + assert events[0].data["entity_id"] == HUB_EVENT + attributes = events[0].data["new_state"].attributes + assert attributes["event_type"] == expected_type + assert attributes.get(ATTR_STATUS) == expected_status + assert ATTR_INPUT not in attributes + + +async def test_alarm_hub_event_with_input_fires_on_hub( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, +) -> None: + """An event type no input entity has fires on the hub and names the input.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + events = _capture_events(hass, INPUT_EVENT, HUB_EVENT) + ufp_with_alarm_hub.events_msg( + _hub_event( + alarm_hub, EventType.ALARM_HUB_RELAY_SWITCHED, PublicEventMetadata(pin="6") + ), + EventChange.STARTED, + ) + await hass.async_block_till_done() + + assert [event.data["entity_id"] for event in events] == [HUB_EVENT] + assert events[0].data["new_state"].attributes[ATTR_INPUT] == 7 + + +async def test_alarm_hub_emergency_input_fires_on_hub( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, +) -> None: + """The emergency input has no numbered terminal and no entity of its own.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + assert ( + entity_registry.async_get_entity_id( + "event", DOMAIN, f"{ALARM_HUB_MAC}_input_32" + ) + is None + ) + + events = _capture_events(hass, HUB_EVENT) + metadata = PublicEventMetadata(pin="32", status_text="alarm") + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, EventType.ALARM_HUB_BUTTON_PRESS, metadata), + EventChange.STARTED, + ) + await hass.async_block_till_done() + + assert len(events) == 1 + attributes = events[0].data["new_state"].attributes + assert attributes["event_type"] == "button_press" + assert ATTR_INPUT not in attributes + + +@pytest.mark.parametrize( + ("event_type", "pin", "rest_status", "triggered_status"), + [ + pytest.param(EventType.ALARM_HUB_MOTION, "6", "normal", "alarm", id="input"), + pytest.param( + EventType.ALARM_HUB_BUTTON_PRESS, "32", "normal", "alarm", id="emergency" + ), + pytest.param( + EventType.ALARM_HUB_DEVICE_TAMPER, None, "restored", "tampered", id="hub" + ), + ], +) +async def test_alarm_hub_back_to_rest_does_not_fire( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, + event_type: EventType, + pin: str | None, + rest_status: str, + triggered_status: str, +) -> None: + """Going back to rest has no event type of its own, except for entry inputs.""" + await init_entry(hass, ufp_with_alarm_hub, []) + + events = _capture_events(hass, INPUT_EVENT, HUB_EVENT) + for event_id, status in (("rest", rest_status), ("triggered", triggered_status)): + metadata = PublicEventMetadata(pin=pin, status_text=status) + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, event_type, metadata, event_id=event_id), + EventChange.STARTED, + ) + await hass.async_block_till_done() + + assert len(events) == 1 + assert events[0].data["new_state"].attributes[ATTR_EVENT_ID] == "triggered" + + +async def test_alarm_hub_disabled_input_fires_on_hub( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, +) -> None: + """A disabled input has no entity; its events name the input on the hub.""" + alarm_hub.alarm_hub["input"]["24"]["enable"] = "off" + await init_entry(hass, ufp_with_alarm_hub, []) + + assert hass.states.get(NAMED_INPUT_EVENT) is None + + events = _capture_events(hass, HUB_EVENT) + metadata = PublicEventMetadata(pin="24", status_text="alarm") + ufp_with_alarm_hub.events_msg( + _hub_event(alarm_hub, EventType.ALARM_HUB_MOTION, metadata), + EventChange.STARTED, + ) + await hass.async_block_till_done() + + assert len(events) == 1 + attributes = events[0].data["new_state"].attributes + assert attributes["event_type"] == "motion" + assert attributes[ATTR_INPUT] == 25 + + +async def test_alarm_hub_inputs_without_terminal_list( + hass: HomeAssistant, + entity_registry: er.EntityRegistry, + ufp_with_alarm_hub: MockUFPFixture, + alarm_hub: LinkStation, +) -> None: + """Without a terminal list every enabled input gets an entity.""" + del alarm_hub.alarm_hub["connector"] + await init_entry(hass, ufp_with_alarm_hub, []) + + assert ( + entity_registry.async_get_entity_id( + "event", DOMAIN, f"{ALARM_HUB_MAC}_input_32" + ) + is not None + ) + + +async def test_alarm_hub_event_unavailable_on_events_ws_disconnect( + hass: HomeAssistant, + ufp_with_alarm_hub: MockUFPFixture, +) -> None: + """The event entities follow the events websocket they are fed from.""" + await init_entry(hass, ufp_with_alarm_hub, []) + entity_ids = (HUB_EVENT, INPUT_EVENT) + for entity_id in entity_ids: + assert hass.states.get(entity_id).state != STATE_UNAVAILABLE + + assert ufp_with_alarm_hub.events_ws_state_subscription is not None + ufp_with_alarm_hub.events_ws_state_subscription(WebsocketState.DISCONNECTED) + await hass.async_block_till_done() + for entity_id in entity_ids: + assert hass.states.get(entity_id).state == STATE_UNAVAILABLE + + ufp_with_alarm_hub.events_ws_state_subscription(WebsocketState.CONNECTED) + await hass.async_block_till_done() + for entity_id in entity_ids: + assert hass.states.get(entity_id).state != STATE_UNAVAILABLE