diff --git a/homeassistant/components/go2rtc/__init__.py b/homeassistant/components/go2rtc/__init__.py index 013c094dc23..5be1dbc1a48 100644 --- a/homeassistant/components/go2rtc/__init__.py +++ b/homeassistant/components/go2rtc/__init__.py @@ -203,15 +203,17 @@ class WebRTCProvider(CameraWebRTCProvider): self._session, self._url, source=camera.entity_id ) + if not (stream_source := await camera.stream_source()): + send_message( + WebRTCError("go2rtc_webrtc_offer_failed", "Camera has no stream source") + ) + return + streams = await self._rest_client.streams.list() - if camera.entity_id not in streams: - if not (stream_source := await camera.stream_source()): - send_message( - WebRTCError( - "go2rtc_webrtc_offer_failed", "Camera has no stream source" - ) - ) - return + + if (stream := streams.get(camera.entity_id)) is None or not any( + stream_source == producer.url for producer in stream.producers + ): await self._rest_client.streams.add(camera.entity_id, stream_source) @callback diff --git a/tests/components/go2rtc/conftest.py b/tests/components/go2rtc/conftest.py index 495d42114f1..87c68989fd2 100644 --- a/tests/components/go2rtc/conftest.py +++ b/tests/components/go2rtc/conftest.py @@ -21,7 +21,8 @@ def rest_client() -> Generator[AsyncMock]: patch("homeassistant.components.go2rtc.server.Go2RtcRestClient", mock_client), ): client = mock_client.return_value - client.streams = Mock(spec_set=_StreamClient) + client.streams = streams = Mock(spec_set=_StreamClient) + streams.list.return_value = {} client.webrtc = Mock(spec_set=_WebRTCClient) yield client diff --git a/tests/components/go2rtc/test_init.py b/tests/components/go2rtc/test_init.py index 1e73525fbe3..847de248aaf 100644 --- a/tests/components/go2rtc/test_init.py +++ b/tests/components/go2rtc/test_init.py @@ -239,6 +239,18 @@ async def _test_setup_and_signaling( rest_client.streams.add.assert_called_once_with(entity_id, "rtsp://stream") + # Stream exists but the source is different + rest_client.streams.add.reset_mock() + rest_client.streams.list.return_value = { + entity_id: Stream([Producer("rtsp://different")]) + } + + receive_message_callback.reset_mock() + ws_client.reset_mock() + await test() + + rest_client.streams.add.assert_called_once_with(entity_id, "rtsp://stream") + # If the stream is already added, the stream should not be added again. rest_client.streams.add.reset_mock() rest_client.streams.list.return_value = {