Implement a basic retry system to avoid the app closing when disconnected from the server

This commit is contained in:
Logan Cusano
2025-05-28 22:18:10 -04:00
parent 6192f1d193
commit 54249016d3

View File

@@ -4,7 +4,7 @@ import json
import uuid import uuid
import os import os
from drb_cdb_api import DRBCDBAPI 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 server_api import RadioAPIClient
from enum import Enum from enum import Enum
from config import Config from config import Config
@@ -233,33 +233,29 @@ async def receive_commands(websocket):
async def main_client(): async def main_client():
"""Connects to the server and handles communication.""" """Connects to the server and handles communication with a robust retry system."""
print(f"Client {CLIENT_ID} connecting to {SERVER_WS_URI}...") retry_delay = 5 # seconds
try: while True:
async with websockets.connect(SERVER_WS_URI) as websocket: print(f"Client {CLIENT_ID} attempting to connect to {SERVER_WS_URI}...")
print("Connection established.") try:
async with websockets.connect(SERVER_WS_URI) as websocket:
print("Connection established.")
# Handshake: Send client ID immediately after connecting # Handshake: Send client ID immediately after connecting
handshake_message = json.dumps({"type": "handshake", "id": CLIENT_ID}) handshake_message = json.dumps({"type": "handshake", "id": CLIENT_ID})
await websocket.send(handshake_message) await websocket.send(handshake_message)
print(f"Sent handshake with ID: {CLIENT_ID}") print(f"Sent handshake with ID: {CLIENT_ID}")
# Start receiving commands and keep the connection alive # Start receiving commands and keep the connection alive
await receive_commands(websocket) await receive_commands(websocket)
except ConnectionRefusedError: except (ConnectionRefusedError, websockets.exceptions.ConnectionClosedOK, websockets.exceptions.ConnectionClosedError) as e:
print(f"Connection refused. Is the server running at {SERVER_WS_URI}?") print(f"Connection error: {e}. Retrying in {retry_delay} seconds...")
except websockets.exceptions.ConnectionClosedOK: await asyncio.sleep(retry_delay)
print("Connection closed gracefully by server.") except Exception as e:
except websockets.exceptions.ConnectionClosedError as e: print(f"An unexpected error occurred: {e}. Retrying in {retry_delay} seconds...")
print(f"Connection closed unexpectedly: {e}") await asyncio.sleep(retry_delay)
except Exception as e:
print(f"An error occurred: {e}")
print(f"Client {CLIENT_ID} stopped.")
if __name__ == "__main__": 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()) asyncio.run(main_client())