Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add event callback to async connection #53

Merged
merged 1 commit into from
Feb 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions samsungtvws/async_connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@
from __future__ import annotations

import asyncio
import contextlib
import json
import logging
import ssl
from typing import Any, Awaitable, Callable

from websockets.client import WebSocketClientProtocol, connect
from websockets.exceptions import ConnectionClosed

from . import connection, exceptions, helper
from .command import SamsungTVCommand
Expand Down Expand Up @@ -62,9 +65,30 @@ async def open(self) -> WebSocketClientProtocol:
self.connection = connection
return connection

async def start_listening(
self, callback: Callable[[str, Any], Awaitable[None]]
) -> None:
"""Open, and start listening."""
if self.connection is None:
self.connection = await self.open()

self._recv_loop = asyncio.create_task(self._do_start_listening(callback))

async def _do_start_listening(
self, callback: Callable[[str, Any], Awaitable[None]]
) -> None:
"""Do start listening."""
with contextlib.suppress(ConnectionClosed):
while True:
data = await self.connection.recv()
response = helper.process_api_response(data)
await callback(response.get("event", "*"), response)

async def close(self):
if self.connection:
await self.connection.close()
if self._recv_loop:
await self._recv_loop

self.connection = None
_LOGGING.debug("Connection closed.")
Expand Down
1 change: 1 addition & 0 deletions samsungtvws/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ def __init__(
self.name = name
self.endpoint = endpoint
self.connection = None
self._recv_loop = None

def _is_ssl_connection(self):
return self.port == 8002
Expand Down