Implement a basic retry system to avoid the app closing when disconnected from the server
This commit is contained in:
@@ -4,7 +4,7 @@ import json
|
||||
import uuid
|
||||
import os
|
||||
from drb_cdb_api import DRBCDBAPI
|
||||
from drb_cdb_types import ConfigGenerator
|
||||
from drb_cdb_types import ConfigGenerator, TalkgroupTag
|
||||
from server_api import RadioAPIClient
|
||||
from enum import Enum
|
||||
from config import Config
|
||||
@@ -233,33 +233,29 @@ async def receive_commands(websocket):
|
||||
|
||||
|
||||
async def main_client():
|
||||
"""Connects to the server and handles communication."""
|
||||
print(f"Client {CLIENT_ID} connecting to {SERVER_WS_URI}...")
|
||||
try:
|
||||
async with websockets.connect(SERVER_WS_URI) as websocket:
|
||||
print("Connection established.")
|
||||
"""Connects to the server and handles communication with a robust retry system."""
|
||||
retry_delay = 5 # seconds
|
||||
while True:
|
||||
print(f"Client {CLIENT_ID} attempting to connect to {SERVER_WS_URI}...")
|
||||
try:
|
||||
async with websockets.connect(SERVER_WS_URI) as websocket:
|
||||
print("Connection established.")
|
||||
|
||||
# Handshake: Send client ID immediately after connecting
|
||||
handshake_message = json.dumps({"type": "handshake", "id": CLIENT_ID})
|
||||
await websocket.send(handshake_message)
|
||||
print(f"Sent handshake with ID: {CLIENT_ID}")
|
||||
# Handshake: Send client ID immediately after connecting
|
||||
handshake_message = json.dumps({"type": "handshake", "id": CLIENT_ID})
|
||||
await websocket.send(handshake_message)
|
||||
print(f"Sent handshake with ID: {CLIENT_ID}")
|
||||
|
||||
# Start receiving commands and keep the connection alive
|
||||
await receive_commands(websocket)
|
||||
# Start receiving commands and keep the connection alive
|
||||
await receive_commands(websocket)
|
||||
|
||||
except ConnectionRefusedError:
|
||||
print(f"Connection refused. Is the server running at {SERVER_WS_URI}?")
|
||||
except websockets.exceptions.ConnectionClosedOK:
|
||||
print("Connection closed gracefully by server.")
|
||||
except websockets.exceptions.ConnectionClosedError as e:
|
||||
print(f"Connection closed unexpectedly: {e}")
|
||||
except Exception as e:
|
||||
print(f"An error occurred: {e}")
|
||||
|
||||
print(f"Client {CLIENT_ID} stopped.")
|
||||
except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedOK, websockets.exceptions.ConnectionClosedError) as e:
|
||||
print(f"Connection error: {e}. Retrying in {retry_delay} seconds...")
|
||||
await asyncio.sleep(retry_delay)
|
||||
except Exception as e:
|
||||
print(f"An unexpected error occurred: {e}. Retrying in {retry_delay} seconds...")
|
||||
await asyncio.sleep(retry_delay)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Note: In a real application, you'd want a more robust way
|
||||
# to manage the event loop and handle potential reconnections.
|
||||
asyncio.run(main_client())
|
||||
Reference in New Issue
Block a user