1
+ from enum import Enum
1
2
from threading import Thread , Lock
2
3
from websocket import WebSocketApp , setdefaulttimeout , ABNF
3
4
from msgpack import packb , unpackb
4
5
from ssl import CERT_NONE
5
6
6
7
8
+ class ConnectionState (Enum ):
9
+ NONE = 0
10
+ CONNECTING = 1
11
+ CONNECTED = 2
12
+ FAILED = 3
7
13
class WSConnector :
8
14
9
15
class REID :
@@ -26,7 +32,7 @@ def __init__(self, username: str, token: str, address: str, on_msg=None, ignore_
26
32
self .ws = None
27
33
self .lock = Lock ()
28
34
self .reid = self .REID ()
29
- self .running = False
35
+ self .__connection_state = ConnectionState . NONE
30
36
self .ignore_ssl_cert = ignore_ssl_cert
31
37
setdefaulttimeout (60 )
32
38
@@ -40,26 +46,33 @@ def start(self):
40
46
on_message = None if self .on_msg is None else self ._handle_msg ,
41
47
on_open = self ._ready , on_error = self ._fail )
42
48
self .lock .acquire () # wait for connection to be established
49
+ self .__connection_state = ConnectionState .CONNECTING
43
50
kwargs = {"sslopt" : {"cert_reqs" : CERT_NONE }} if self .ignore_ssl_cert else None
44
51
Thread (target = self .ws .run_forever , kwargs = kwargs ).start ()
52
+
45
53
46
54
def _fail (self , ws , err ):
55
+ self .__connection_state = ConnectionState .FAILED
47
56
self .lock .release ()
48
57
raise err
49
58
50
59
def stop (self ):
51
60
if self .ws is not None :
52
61
with self .lock :
53
62
print ("Closing the connection." )
54
- self .running = False
63
+ self .__connection_state = ConnectionState . NONE
55
64
self .ws .close ()
56
65
self .ws = None
57
66
58
67
def _ready (self , ws ):
59
68
print (f"Connected to { self .address } ." )
60
- self .running = True
69
+ self .__connection_state = ConnectionState . CONNECTED
61
70
self .lock .release ()
62
71
72
+ @property
73
+ def connection_state (self ):
74
+ return self .__connection_state
75
+
63
76
def _handle_msg (self , ws , msg ):
64
77
if isinstance (msg , bytes ):
65
78
msg = unpackb (msg )
0 commit comments