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,32 @@ 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 ()
45
52
46
53
def _fail (self , ws , err ):
54
+ self .__connection_state = ConnectionState .FAILED
47
55
self .lock .release ()
48
56
raise err
49
57
50
58
def stop (self ):
51
59
if self .ws is not None :
52
60
with self .lock :
53
61
print ("Closing the connection." )
54
- self .running = False
62
+ self .__connection_state = ConnectionState . NONE
55
63
self .ws .close ()
56
64
self .ws = None
57
65
58
66
def _ready (self , ws ):
59
67
print (f"Connected to { self .address } ." )
60
- self .running = True
68
+ self .__connection_state = ConnectionState . CONNECTED
61
69
self .lock .release ()
62
70
71
+ @property
72
+ def connection_state (self ):
73
+ return self .__connection_state
74
+
63
75
def _handle_msg (self , ws , msg ):
64
76
if isinstance (msg , bytes ):
65
77
msg = unpackb (msg )
0 commit comments