fix connection bug
This commit is contained in:
Binary file not shown.
@@ -35,17 +35,18 @@ class Device:
|
||||
)
|
||||
self.on_msg_callback = on_msg_callback if on_msg_callback is not None else lambda _, __ : None
|
||||
self.on_error_callback = on_error_callback if on_error_callback is not None else lambda _ : None
|
||||
self.is_connected = False
|
||||
|
||||
def _on_open(self, ws):
|
||||
print("open")
|
||||
self.is_connected = True
|
||||
def _on_close(self, ws, close_status_code, close_msg):
|
||||
print("close")
|
||||
self.is_connected = False
|
||||
|
||||
def _on_message(self, ws, message):
|
||||
try:
|
||||
message_str = json.loads(message)["payload"]
|
||||
self.on_msg_callback(message_str["point"], message_str["value"])
|
||||
except KeyError or JSONDecodeError:
|
||||
except (KeyError, JSONDecodeError):
|
||||
self.on_error_callback(ServerException("Page or server sent an invalid message"))
|
||||
except Exception as e:
|
||||
self.on_error_callback(e)
|
||||
@@ -63,15 +64,21 @@ class Device:
|
||||
"timestamp": int(time.time() * 1000)
|
||||
}))
|
||||
|
||||
def connect(self):
|
||||
def connect(self, timeout: float = 5.0):
|
||||
"""
|
||||
在新线程中运行客户端循环(推荐)
|
||||
"""
|
||||
wst = threading.Thread(target=self.ws.run_forever)
|
||||
wst.daemon = True
|
||||
wst.start()
|
||||
start_time = time.time()
|
||||
while not self.is_connected:
|
||||
if time.time() - start_time > timeout:
|
||||
if not self.is_connected:
|
||||
self.on_error_callback(TimeoutError(f"WebSocket connection timed out after {timeout} seconds"))
|
||||
time.sleep(0.05)
|
||||
|
||||
def main_loop(self):
|
||||
def main_loop(self):
|
||||
"""
|
||||
在当前线程中运行客户端循环(不推荐)
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user