diff --git a/homeassistant/components/unifiprotect/__init__.py b/homeassistant/components/unifiprotect/__init__.py index a69dec0e36e3..ec3ae8215f85 100644 --- a/homeassistant/components/unifiprotect/__init__.py +++ b/homeassistant/components/unifiprotect/__init__.py @@ -346,8 +346,8 @@ async def async_unload_entry(hass: HomeAssistant, entry: UFPConfigEntry) -> None platforms = ( PUBLIC_ONLY_PLATFORMS if entry.runtime_data.api.is_public_only else PLATFORMS ) - await hass.config_entries.async_unload_platforms_or_raise(entry, platforms) await entry.runtime_data.async_stop() + await hass.config_entries.async_unload_platforms_or_raise(entry, platforms) async def async_remove_entry(hass: HomeAssistant, entry: UFPConfigEntry) -> None: diff --git a/homeassistant/components/unifiprotect/data.py b/homeassistant/components/unifiprotect/data.py index 05b238808519..ab3e697e144d 100644 --- a/homeassistant/components/unifiprotect/data.py +++ b/homeassistant/components/unifiprotect/data.py @@ -311,13 +311,16 @@ class ProtectData: # arriving while update_public() primes are buffered and replayed by # the library, so the subscribe/prime order is not load-bearing. self._unsubs = [ - api.subscribe_devices_websocket( - self._async_process_public_devices_ws_message - ), + # State callbacks first: unsubscribing the last message callback + # stops the websocket, and its disconnect would mark the entities + # unavailable at shutdown. api.subscribe_devices_websocket_state(self._async_public_ws_state_changed), # The events websocket is public in both modes (see # ``async_subscribe_public_events``), so track its state in both. api.subscribe_events_websocket_state(self._async_events_ws_state_changed), + api.subscribe_devices_websocket( + self._async_process_public_devices_ws_message + ), api.subscribe_public_resync(self._async_public_resync_done), ] if api.is_public_only: @@ -669,6 +672,9 @@ class ProtectData: self._auth_failures += 1 else: await self.async_stop() + # The stopped public websockets no longer report their state. + self.last_public_update_success = False + self._async_process_public_updates() _LOGGER.exception("Reauthentication required") self._entry.async_start_reauth(self._hass) self._async_update_change(False, exception=ex) diff --git a/tests/components/unifiprotect/test_event.py b/tests/components/unifiprotect/test_event.py index af10fa34c876..d0ace0c70c60 100644 --- a/tests/components/unifiprotect/test_event.py +++ b/tests/components/unifiprotect/test_event.py @@ -22,6 +22,7 @@ from uiprotect.data import ( SmartDetectAudioType, SmartDetectObjectType, WSAction, + WSSubscriptionMessage, ) from uiprotect.data.public_devices import SensorFeatureCapability from uiprotect.data.types import SensorAlarmType @@ -41,7 +42,13 @@ from homeassistant.components.unifiprotect.event import ( EVENT_DESCRIPTIONS, SENSOR_EVENT_DESCRIPTIONS, ) -from homeassistant.const import ATTR_ATTRIBUTION, STATE_UNAVAILABLE, Platform +from homeassistant.const import ( + ATTR_ATTRIBUTION, + EVENT_HOMEASSISTANT_STOP, + STATE_UNAVAILABLE, + STATE_UNKNOWN, + Platform, +) from homeassistant.core import Event as HAEvent, HomeAssistant, callback from homeassistant.helpers.entity_registry import EntityRegistry from homeassistant.helpers.event import async_track_state_change_event @@ -3245,3 +3252,65 @@ async def test_public_only_sensor_added_after_setup( assert registered_keys(entity_registry, Platform.EVENT, sensor.mac) == ( _SENSOR_EVENT_KEYS ) + + +async def test_event_keeps_timestamp_when_hass_stops( + hass: HomeAssistant, + ufp: MockUFPFixture, + doorbell: Camera, + unadopted_camera: Camera, + fixed_now: datetime, +) -> None: + """Stopping Home Assistant leaves the event timestamp for the restore dump.""" + setup_public_camera(ufp) + subscribe_messages = ufp.api.subscribe_devices_websocket + subscribe_state = ufp.api.subscribe_devices_websocket_state + state_callbacks: list[Callable[[WebsocketState], None]] = [] + + def subscribe_devices_websocket_state( + state_callback: Callable[[WebsocketState], None], + ) -> Callable[[], None]: + subscribe_state(state_callback) + state_callbacks.append(state_callback) + return lambda: state_callbacks.remove(state_callback) + + def subscribe_devices_websocket( + ws_callback: Callable[[WSSubscriptionMessage], None], + ) -> Callable[[], None]: + subscribe_messages(ws_callback) + + # The library stops the websocket with its last message subscriber + # and reports the disconnect to the remaining state subscribers. + def unsubscribe() -> None: + for state_callback in state_callbacks: + state_callback(WebsocketState.DISCONNECTED) + + return unsubscribe + + ufp.api.subscribe_devices_websocket = subscribe_devices_websocket + ufp.api.subscribe_devices_websocket_state = subscribe_devices_websocket_state + await init_entry(hass, ufp, [doorbell, unadopted_camera]) + _, entity_id = await ids_from_device_description( + hass, Platform.EVENT, doorbell, EVENT_DESCRIPTIONS[0] + ) + ufp.events_msg( + ProtectEvent( + id="test_ring_event", + type=EventType.RING, + channel=ProtectEventChannel.DETECTION, + device_id=doorbell.id, + device_mac=doorbell.mac, + start=fixed_now - timedelta(seconds=1), + end=fixed_now, + ), + EventChange.STARTED, + ) + await hass.async_block_till_done() + state = hass.states.get(entity_id) + assert state is not None + assert state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE) + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + + assert hass.states.get(entity_id) == state diff --git a/tests/components/unifiprotect/test_init.py b/tests/components/unifiprotect/test_init.py index 40c6c8a819c3..ba1e9ce42713 100644 --- a/tests/components/unifiprotect/test_init.py +++ b/tests/components/unifiprotect/test_init.py @@ -434,6 +434,7 @@ async def test_setup_failed_update_reauth( await time_changed(hass, DEVICE_UPDATE_INTERVAL) assert ufp.api.update.call_count == AUTH_RETRIES + 1 assert len(hass.config_entries.flow._progress) == 1 + assert ufp.entry.runtime_data.last_public_update_success is False async def test_setup_failed_error(hass: HomeAssistant, ufp: MockUFPFixture) -> None: diff --git a/tests/components/unifiprotect/test_number.py b/tests/components/unifiprotect/test_number.py index 961a5de2c229..c3a25b810fce 100644 --- a/tests/components/unifiprotect/test_number.py +++ b/tests/components/unifiprotect/test_number.py @@ -1517,3 +1517,29 @@ async def test_number_camera_read_only_user( assert entity_registry.async_get_entity_id( Platform.NUMBER, DOMAIN, f"{doorbell.mac}_mic_level" ) + + +async def test_chime_ring_volume_survives_reload( + hass: HomeAssistant, + caplog: pytest.LogCaptureFixture, + ufp: MockUFPFixture, + chime: Chime, + doorbell: Camera, +) -> None: + """A chime update arriving while the entry unloads does not orphan the entity.""" + setup_public_chime(ufp, _paired_ring_settings(doorbell, volume=75)) + await init_entry(hass, ufp, [chime, doorbell], regenerate_ids=False) + assert hass.states.get(RING_VOLUME_ENTITY).state == "75" + public = ufp.api.public_bootstrap.chimes[chime.id] + + async def disconnect_ws() -> None: + ufp.devices_ws_subscription( + public_device_ws_message(public, changed_data={"ringSettings": []}) + ) + + ufp.api.async_disconnect_ws = disconnect_ws + await hass.config_entries.async_reload(ufp.entry.entry_id) + await hass.async_block_till_done() + + assert hass.states.get(RING_VOLUME_ENTITY).state == "75" + assert "does not generate unique IDs" not in caplog.text