| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- import json
- import asyncio
- from models import *
- from .connect_manager import ConnectionManager
- from .message_handler import *
- from mcu.DeviceControl import DeviceControl,checkMcuConnection
- from mcu.BlueToothMode import BlueToothMode
- from mcu.RemoteControlV2 import RemoteControlV2
- import time
- from .socket_client import socket_manager
- conn_manager = ConnectionManager()
- active_connections = set()
- device_ctrl = DeviceControl(websocket_manager=conn_manager)
- blue_tooth = BlueToothMode(websocket_manager=conn_manager)
- @app.websocket("/ws")
- async def websocket_endpoint(websocket: WebSocket):
- await conn_manager.connect(websocket)
- active_connections.add(websocket)
- try:
- # await socket_manager.connect()
- async def handler_messages():
- while True:
- try:
- byteDats = await websocket.receive()
- byteDats.get("type")
- print("byteDats", byteDats)
- await handlerSend(conn_manager, json.dumps(byteDats), websocket)
- except Exception as e:
- print(e)
- break
- async def checkConnMcu():
- await checkMcuConnection(device_ctrl)
- async def connectBlueTooth():
- await blue_tooth.main_func()
- await asyncio.gather(handler_messages(), checkConnMcu(), connectBlueTooth())
- except WebSocketDisconnect:
- # socket_manager.close()
- print("Client disconnected")
- finally:
- active_connections.discard(websocket)
- # if websocket:
- # await websocket.close()
- @app.on_event("shutdown")
- async def shutdown_event():
- print("Shutting down...")
- # socket_manager.close()
- # 清理操作
- for connection in list(active_connections):
- try:
- await connection.close()
- except Exception as e:
- print(f"Error closing connection: {e}")
|