raise timeout errors.

added some error/exception logging.

added timeout parameter to repr methods.
This commit is contained in:
onyx-and-iris 2023-06-19 17:45:49 +01:00
parent 82b6cdcd04
commit 9e3c1d3f37
3 changed files with 34 additions and 12 deletions

View File

@ -7,15 +7,22 @@ from random import randint
from typing import Optional from typing import Optional
import websocket import websocket
from websocket._exceptions import WebSocketTimeoutException from websocket import WebSocketTimeoutException
from .error import OBSSDKError
from .error import OBSSDKError, OBSSDKTimeoutError
class ObsClient: class ObsClient:
logger = logging.getLogger("baseclient.obsclient") logger = logging.getLogger("baseclient.obsclient")
def __init__(self, **kwargs): def __init__(self, **kwargs):
defaultkwargs = {"host": "localhost", "port": 4455, "password": "", "subs": 0, "timeout":None} defaultkwargs = {
"host": "localhost",
"port": 4455,
"password": "",
"subs": 0,
"timeout": None,
}
if not any(key in kwargs for key in ("host", "port", "password")): if not any(key in kwargs for key in ("host", "port", "password")):
kwargs |= self._conn_from_toml() kwargs |= self._conn_from_toml()
kwargs = defaultkwargs | kwargs kwargs = defaultkwargs | kwargs
@ -23,14 +30,21 @@ class ObsClient:
setattr(self, attr, val) setattr(self, attr, val)
self.logger.info( self.logger.info(
"Connecting with parameters: host='{host}' port={port} password='{password}' subs={subs}".format( "Connecting with parameters: host='{host}' port={port} password='{password}' subs={subs} timeout={timeout}".format(
**self.__dict__ **self.__dict__
) )
) )
self.ws = websocket.WebSocket() try:
self.ws.connect(f"ws://{self.host}:{self.port}", timeout=self.timeout) self.ws = websocket.WebSocket()
self.server_hello = json.loads(self.ws.recv()) self.ws.connect(f"ws://{self.host}:{self.port}", timeout=self.timeout)
self.server_hello = json.loads(self.ws.recv())
except ValueError as e:
self.logger.error(f"{type(e).__name__}: {e}")
raise
except (ConnectionRefusedError, WebSocketTimeoutException) as e:
self.logger.exception(f"{type(e).__name__}: {e}")
raise
def _conn_from_toml(self) -> dict: def _conn_from_toml(self) -> dict:
try: try:
@ -108,7 +122,8 @@ class ObsClient:
try: try:
self.ws.send(json.dumps(payload)) self.ws.send(json.dumps(payload))
response = json.loads(self.ws.recv()) response = json.loads(self.ws.recv())
except WebSocketTimeoutException : except WebSocketTimeoutException as e:
raise OBSSDKError("Timeout while trying to send the request") self.logger.exception(f"{type(e).__name__}: {e}")
raise OBSSDKTimeoutError("Timeout while trying to send the request") from e
self.logger.debug(f"Response received {response}") self.logger.debug(f"Response received {response}")
return response["d"] return response["d"]

View File

@ -3,8 +3,11 @@ import logging
import time import time
from threading import Thread from threading import Thread
from websocket import WebSocketTimeoutException
from .baseclient import ObsClient from .baseclient import ObsClient
from .callback import Callback from .callback import Callback
from .error import OBSSDKTimeoutError
from .subs import Subs from .subs import Subs
""" """
@ -30,7 +33,7 @@ class EventClient:
def __repr__(self): def __repr__(self):
return type( return type(
self self
).__name__ + "(host='{host}', port={port}, password='{password}', subs={subs})".format( ).__name__ + "(host='{host}', port={port}, password='{password}', subs={subs}, timeout={timeout})".format(
**self.base_client.__dict__, **self.base_client.__dict__,
) )
@ -49,7 +52,11 @@ class EventClient:
""" """
self.running = True self.running = True
while self.running: while self.running:
event = json.loads(self.base_client.ws.recv()) try:
event = json.loads(self.base_client.ws.recv())
except WebSocketTimeoutException as e:
self.logger.exception(f"{type(e).__name__}: {e}")
raise OBSSDKTimeoutError("Timeout while waiting for event") from e
self.logger.debug(f"Event received {event}") self.logger.debug(f"Event received {event}")
type_, data = ( type_, data = (
event["d"].get("eventType"), event["d"].get("eventType"),

View File

@ -28,7 +28,7 @@ class ReqClient:
def __repr__(self): def __repr__(self):
return type( return type(
self self
).__name__ + "(host='{host}', port={port}, password='{password}')".format( ).__name__ + "(host='{host}', port={port}, password='{password}', timeout={timeout})".format(
**self.base_client.__dict__, **self.base_client.__dict__,
) )