4
4
from logging import getLogger
5
5
from typing import TYPE_CHECKING
6
6
7
- from websockets .exceptions import ConnectionClosed , ConnectionClosedError , ConnectionClosedOK
7
+ from websockets .exceptions import ConnectionClosed , ConnectionClosedOK
8
8
from websockets .sync .client import ClientConnection , connect
9
9
10
10
11
11
if TYPE_CHECKING :
12
12
from collections .abc import Generator
13
13
from typing import Any
14
14
15
- from typing_extensions import Self
15
+ from typing_extensions import Self # noqa: UP035
16
16
17
17
18
18
logger = getLogger ("streamdeck.websocket" )
@@ -38,10 +38,14 @@ def send_event(self, data: dict[str, Any]) -> None:
38
38
Args:
39
39
data (dict[str, Any]): The event data to send.
40
40
"""
41
+ if self ._client is None :
42
+ msg = "WebSocket connection not established yet."
43
+ raise ValueError (msg )
44
+
41
45
data_str = json .dumps (data )
42
46
self ._client .send (message = data_str )
43
47
44
- def listen_forever (self ) -> Generator [str | bytes , Any , None ]:
48
+ def listen (self ) -> Generator [str | bytes , Any , None ]:
45
49
"""Listen for messages from the WebSocket server indefinitely.
46
50
47
51
TODO: implement more concise error-handling.
@@ -55,20 +59,34 @@ def listen_forever(self) -> Generator[str | bytes, Any, None]:
55
59
message : str | bytes = self ._client .recv ()
56
60
yield message
57
61
62
+ except ConnectionClosedOK :
63
+ logger .debug ("Connection was closed normally, stopping the client." )
64
+
65
+ except ConnectionClosed :
66
+ logger .exception ("Connection was closed with an error." )
67
+
58
68
except Exception :
59
- logger .exception ("Failed to receive messages from websocket server." )
69
+ logger .exception ("Failed to receive messages from websocket server due to unexpected error." )
70
+
71
+ def start (self ) -> None :
72
+ """Start the connection to the websocket server."""
73
+ self ._client = connect (uri = f"ws://localhost:{ self ._port } " )
74
+
75
+ def stop (self ) -> None :
76
+ """Close the WebSocket connection, if open."""
77
+ if self ._client is not None :
78
+ self ._client .close ()
60
79
61
80
def __enter__ (self ) -> Self :
62
81
"""Start the connection to the websocket server.
63
82
64
83
Returns:
65
84
Self: The WebSocketClient instance after connecting to the WebSocket server.
66
85
"""
67
- self ._client = connect ( uri = f"ws://localhost: { self . _port } " )
86
+ self .start ( )
68
87
return self
69
88
70
89
def __exit__ (self , * args , ** kwargs ) -> None :
71
90
"""Close the WebSocket connection, if open."""
72
- if self ._client is not None :
73
- self ._client .close ()
91
+ self .stop ()
74
92
0 commit comments