|
| 1 | +"""Websocket client for go2rtc server.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +from collections.abc import Callable |
| 5 | +import logging |
| 6 | +from typing import TYPE_CHECKING, Any |
| 7 | +from urllib.parse import urljoin |
| 8 | + |
| 9 | +from aiohttp import ( |
| 10 | + ClientError, |
| 11 | + ClientSession, |
| 12 | + ClientWebSocketResponse, |
| 13 | + WSMsgType, |
| 14 | + WSServerHandshakeError, |
| 15 | +) |
| 16 | + |
| 17 | +from go2rtc_client.exceptions import Go2RtcClientError |
| 18 | +from go2rtc_client.ws.messages import BaseMessage |
| 19 | + |
| 20 | +_LOGGER = logging.getLogger(__name__) |
| 21 | + |
| 22 | + |
| 23 | +class Go2RtcWsClient: |
| 24 | + """Websocket client for go2rtc server.""" |
| 25 | + |
| 26 | + def __init__( |
| 27 | + self, |
| 28 | + session: ClientSession, |
| 29 | + server_url: str, |
| 30 | + *, |
| 31 | + source: str | None = None, |
| 32 | + destination: str | None = None, |
| 33 | + ) -> None: |
| 34 | + """Initialize Client.""" |
| 35 | + if source: |
| 36 | + if destination: |
| 37 | + msg = "Source and destination cannot be set at the same time" |
| 38 | + raise ValueError(msg) |
| 39 | + params = {"src": source} |
| 40 | + elif destination: |
| 41 | + params = {"dst": destination} |
| 42 | + else: |
| 43 | + msg = "Source or destination must be set" |
| 44 | + raise ValueError(msg) |
| 45 | + |
| 46 | + self._server_url = server_url |
| 47 | + self._session = session |
| 48 | + self._params = params |
| 49 | + self._client: ClientWebSocketResponse | None = None |
| 50 | + self._rx_task: asyncio.Task[None] | None = None |
| 51 | + self._subscribers: list[Callable[[BaseMessage], None]] = [] |
| 52 | + self._connect_lock = asyncio.Lock() |
| 53 | + |
| 54 | + @property |
| 55 | + def connected(self) -> bool: |
| 56 | + """Return if we're currently connected.""" |
| 57 | + return self._client is not None and not self._client.closed |
| 58 | + |
| 59 | + async def connect(self) -> None: |
| 60 | + """Connect to device.""" |
| 61 | + async with self._connect_lock: |
| 62 | + if self.connected: |
| 63 | + return |
| 64 | + |
| 65 | + _LOGGER.debug("Trying to connect to %s", self._server_url) |
| 66 | + try: |
| 67 | + self._client = await self._session.ws_connect( |
| 68 | + urljoin(self._server_url, "/api/ws"), params=self._params |
| 69 | + ) |
| 70 | + except ( |
| 71 | + WSServerHandshakeError, |
| 72 | + ClientError, |
| 73 | + ) as err: |
| 74 | + raise Go2RtcClientError(err) from err |
| 75 | + |
| 76 | + self._rx_task = asyncio.create_task(self._receive_messages()) |
| 77 | + _LOGGER.info("Connected to %s", self._server_url) |
| 78 | + |
| 79 | + async def close(self) -> None: |
| 80 | + """Close connection.""" |
| 81 | + if self.connected: |
| 82 | + if TYPE_CHECKING: |
| 83 | + assert self._client is not None |
| 84 | + client = self._client |
| 85 | + self._client = None |
| 86 | + await client.close() |
| 87 | + |
| 88 | + async def send(self, message: BaseMessage) -> None: |
| 89 | + """Send a message.""" |
| 90 | + if not self.connected: |
| 91 | + await self.connect() |
| 92 | + |
| 93 | + if TYPE_CHECKING: |
| 94 | + assert self._client is not None |
| 95 | + |
| 96 | + await self._client.send_str(message.to_json()) |
| 97 | + |
| 98 | + def _process_text_message(self, data: Any) -> None: |
| 99 | + """Process text message.""" |
| 100 | + try: |
| 101 | + message = BaseMessage.from_json(data) |
| 102 | + except Exception: # pylint: disable=broad-except |
| 103 | + _LOGGER.exception("Invalid message received: %s", data) |
| 104 | + else: |
| 105 | + for subscriber in self._subscribers: |
| 106 | + try: |
| 107 | + subscriber(message) |
| 108 | + except Exception: # pylint: disable=broad-except |
| 109 | + _LOGGER.exception("Error on subscriber callback") |
| 110 | + |
| 111 | + async def _receive_messages(self) -> None: |
| 112 | + """Receive messages.""" |
| 113 | + if TYPE_CHECKING: |
| 114 | + assert self._client |
| 115 | + |
| 116 | + try: |
| 117 | + while self.connected: |
| 118 | + msg = await self._client.receive() |
| 119 | + match msg.type: |
| 120 | + case ( |
| 121 | + WSMsgType.CLOSE |
| 122 | + | WSMsgType.CLOSED |
| 123 | + | WSMsgType.CLOSING |
| 124 | + | WSMsgType.PING |
| 125 | + | WSMsgType.PONG |
| 126 | + ): |
| 127 | + break |
| 128 | + case WSMsgType.ERROR: |
| 129 | + _LOGGER.error("Error received: %s", msg.data) |
| 130 | + case WSMsgType.TEXT: |
| 131 | + self._process_text_message(msg.data) |
| 132 | + case _: |
| 133 | + _LOGGER.warning("Received unknown message: %s", msg) |
| 134 | + except Exception: |
| 135 | + _LOGGER.exception("Unexpected error while receiving message") |
| 136 | + raise |
| 137 | + finally: |
| 138 | + _LOGGER.debug( |
| 139 | + "Websocket client connection from %s closed", self._server_url |
| 140 | + ) |
| 141 | + |
| 142 | + if self.connected: |
| 143 | + await self.close() |
| 144 | + |
| 145 | + def subscribe(self, callback: Callable[[BaseMessage], None]) -> Callable[[], None]: |
| 146 | + """Subscribe to messages.""" |
| 147 | + |
| 148 | + def _unsubscribe() -> None: |
| 149 | + self._subscribers.remove(callback) |
| 150 | + |
| 151 | + self._subscribers.append(callback) |
| 152 | + return _unsubscribe |
0 commit comments