socket_server.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import json
  2. import asyncio
  3. from models import *
  4. from .connect_manager import ConnectionManager
  5. from .message_handler import *
  6. from mcu.DeviceControl import DeviceControl,checkMcuConnection
  7. from mcu.BlueToothMode import BlueToothMode
  8. from mcu.RemoteControlV2 import RemoteControlV2
  9. import time
  10. from .socket_client import socket_manager
  11. conn_manager = ConnectionManager()
  12. active_connections = set()
  13. device_ctrl = DeviceControl(websocket_manager=conn_manager)
  14. blue_tooth = BlueToothMode(websocket_manager=conn_manager)
  15. @app.websocket("/ws")
  16. async def websocket_endpoint(websocket: WebSocket):
  17. await conn_manager.connect(websocket)
  18. active_connections.add(websocket)
  19. try:
  20. # await socket_manager.connect()
  21. async def handler_messages():
  22. while True:
  23. try:
  24. byteDats = await websocket.receive()
  25. byteDats.get("type")
  26. print("byteDats", byteDats)
  27. await handlerSend(conn_manager, json.dumps(byteDats), websocket)
  28. except Exception as e:
  29. print(e)
  30. break
  31. async def checkConnMcu():
  32. await checkMcuConnection(device_ctrl)
  33. async def connectBlueTooth():
  34. await blue_tooth.main_func()
  35. await asyncio.gather(handler_messages(), checkConnMcu(), connectBlueTooth())
  36. except WebSocketDisconnect:
  37. # socket_manager.close()
  38. print("Client disconnected")
  39. finally:
  40. active_connections.discard(websocket)
  41. # if websocket:
  42. # await websocket.close()
  43. @app.on_event("shutdown")
  44. async def shutdown_event():
  45. print("Shutting down...")
  46. # socket_manager.close()
  47. # 清理操作
  48. for connection in list(active_connections):
  49. try:
  50. await connection.close()
  51. except Exception as e:
  52. print(f"Error closing connection: {e}")