Skip to content

Commit

Permalink
Add go2rtc workaround for HA managed one until upstream fixes it (#13…
Browse files Browse the repository at this point in the history
  • Loading branch information
edenhaus authored and frenck committed Nov 8, 2024
1 parent b71383c commit 22822cb
Show file tree
Hide file tree
Showing 5 changed files with 270 additions and 37 deletions.
75 changes: 60 additions & 15 deletions homeassistant/components/go2rtc/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
"""The go2rtc component."""

from __future__ import annotations

from dataclasses import dataclass
import logging
import shutil

Expand Down Expand Up @@ -38,7 +41,13 @@
from homeassistant.util.hass_dict import HassKey
from homeassistant.util.package import is_docker_env

from .const import CONF_DEBUG_UI, DEBUG_UI_URL_MESSAGE, DOMAIN, HA_MANAGED_URL
from .const import (
CONF_DEBUG_UI,
DEBUG_UI_URL_MESSAGE,
DOMAIN,
HA_MANAGED_RTSP_PORT,
HA_MANAGED_URL,
)
from .server import Server

_LOGGER = logging.getLogger(__name__)
Expand Down Expand Up @@ -85,13 +94,22 @@
extra=vol.ALLOW_EXTRA,
)

_DATA_GO2RTC: HassKey[str] = HassKey(DOMAIN)
_DATA_GO2RTC: HassKey[Go2RtcData] = HassKey(DOMAIN)
_RETRYABLE_ERRORS = (ClientConnectionError, ServerConnectionError)


@dataclass(frozen=True)
class Go2RtcData:
"""Data for go2rtc."""

url: str
managed: bool


async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Set up WebRTC."""
url: str | None = None
managed = False
if DOMAIN not in config and DEFAULT_CONFIG_DOMAIN not in config:
await _remove_go2rtc_entries(hass)
return True
Expand Down Expand Up @@ -126,8 +144,9 @@ async def on_stop(event: Event) -> None:
hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, on_stop)

url = HA_MANAGED_URL
managed = True

hass.data[_DATA_GO2RTC] = url
hass.data[_DATA_GO2RTC] = Go2RtcData(url, managed)
discovery_flow.async_create_flow(
hass, DOMAIN, context={"source": SOURCE_SYSTEM}, data={}
)
Expand All @@ -142,28 +161,32 @@ async def _remove_go2rtc_entries(hass: HomeAssistant) -> None:

async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up go2rtc from a config entry."""
url = hass.data[_DATA_GO2RTC]
data = hass.data[_DATA_GO2RTC]

# Validate the server URL
try:
client = Go2RtcRestClient(async_get_clientsession(hass), url)
client = Go2RtcRestClient(async_get_clientsession(hass), data.url)
await client.validate_server_version()
except Go2RtcClientError as err:
if isinstance(err.__cause__, _RETRYABLE_ERRORS):
raise ConfigEntryNotReady(
f"Could not connect to go2rtc instance on {url}"
f"Could not connect to go2rtc instance on {data.url}"
) from err
_LOGGER.warning("Could not connect to go2rtc instance on %s (%s)", url, err)
_LOGGER.warning(
"Could not connect to go2rtc instance on %s (%s)", data.url, err
)
return False
except Go2RtcVersionError as err:
raise ConfigEntryNotReady(
f"The go2rtc server version is not supported, {err}"
) from err
except Exception as err: # noqa: BLE001
_LOGGER.warning("Could not connect to go2rtc instance on %s (%s)", url, err)
_LOGGER.warning(
"Could not connect to go2rtc instance on %s (%s)", data.url, err
)
return False

provider = WebRTCProvider(hass, url)
provider = WebRTCProvider(hass, data)
async_register_webrtc_provider(hass, provider)
return True

Expand All @@ -181,12 +204,12 @@ async def _get_binary(hass: HomeAssistant) -> str | None:
class WebRTCProvider(CameraWebRTCProvider):
"""WebRTC provider."""

def __init__(self, hass: HomeAssistant, url: str) -> None:
def __init__(self, hass: HomeAssistant, data: Go2RtcData) -> None:
"""Initialize the WebRTC provider."""
self._hass = hass
self._url = url
self._data = data
self._session = async_get_clientsession(hass)
self._rest_client = Go2RtcRestClient(self._session, url)
self._rest_client = Go2RtcRestClient(self._session, data.url)
self._sessions: dict[str, Go2RtcWsClient] = {}

@property
Expand All @@ -208,7 +231,7 @@ async def async_handle_async_webrtc_offer(
) -> None:
"""Handle the WebRTC offer and return the answer via the provided callback."""
self._sessions[session_id] = ws_client = Go2RtcWsClient(
self._session, self._url, source=camera.entity_id
self._session, self._data.url, source=camera.entity_id
)

if not (stream_source := await camera.stream_source()):
Expand All @@ -219,8 +242,30 @@ async def async_handle_async_webrtc_offer(

streams = await self._rest_client.streams.list()

if (stream := streams.get(camera.entity_id)) is None or not any(
stream_source == producer.url for producer in stream.producers
if self._data.managed:
# HA manages the go2rtc instance
stream_org_name = camera.entity_id + "_orginal"
stream_redirect_sources = [
f"rtsp://127.0.0.1:{HA_MANAGED_RTSP_PORT}/{stream_org_name}",
f"ffmpeg:{stream_org_name}#audio=opus",
]

if (
(stream_org := streams.get(stream_org_name)) is None
or not any(
stream_source == producer.url for producer in stream_org.producers
)
or (stream_redirect := streams.get(camera.entity_id)) is None
or stream_redirect_sources != [p.url for p in stream_redirect.producers]
):
await self._rest_client.streams.add(stream_org_name, stream_source)
await self._rest_client.streams.add(
camera.entity_id, stream_redirect_sources
)

# go2rtc instance is managed outside HA
elif (stream_org := streams.get(camera.entity_id)) is None or not any(
stream_source == producer.url for producer in stream_org.producers
):
await self._rest_client.streams.add(
camera.entity_id,
Expand Down
1 change: 1 addition & 0 deletions homeassistant/components/go2rtc/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
DEBUG_UI_URL_MESSAGE = "Url and debug_ui cannot be set at the same time."
HA_MANAGED_API_PORT = 11984
HA_MANAGED_URL = f"http://localhost:{HA_MANAGED_API_PORT}/"
HA_MANAGED_RTSP_PORT = 18554
15 changes: 9 additions & 6 deletions homeassistant/components/go2rtc/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.aiohttp_client import async_get_clientsession

from .const import HA_MANAGED_API_PORT, HA_MANAGED_URL
from .const import HA_MANAGED_API_PORT, HA_MANAGED_RTSP_PORT, HA_MANAGED_URL

_LOGGER = logging.getLogger(__name__)
_TERMINATE_TIMEOUT = 5
Expand All @@ -24,15 +24,16 @@

# Default configuration for HA
# - Api is listening only on localhost
# - Disable rtsp listener
# - Enable rtsp for localhost only as ffmpeg needs it
# - Clear default ice servers
_GO2RTC_CONFIG_FORMAT = r"""
_GO2RTC_CONFIG_FORMAT = r"""# This file is managed by Home Assistant
# Do not edit it manually
api:
listen: "{api_ip}:{api_port}"
rtsp:
# ffmpeg needs rtsp for opus audio transcoding
listen: "127.0.0.1:18554"
listen: "127.0.0.1:{rtsp_port}"
webrtc:
listen: ":18555/tcp"
Expand Down Expand Up @@ -67,7 +68,9 @@ def _create_temp_file(api_ip: str) -> str:
with NamedTemporaryFile(prefix="go2rtc_", suffix=".yaml", delete=False) as file:
file.write(
_GO2RTC_CONFIG_FORMAT.format(
api_ip=api_ip, api_port=HA_MANAGED_API_PORT
api_ip=api_ip,
api_port=HA_MANAGED_API_PORT,
rtsp_port=HA_MANAGED_RTSP_PORT,
).encode()
)
return file.name
Expand Down
Loading

0 comments on commit 22822cb

Please sign in to comment.