|
|
@@ -66,17 +66,33 @@ async def websocket_endpoint(websocket: WebSocket):
|
|
|
# 创建任务来启动 connect_listen
|
|
|
# listen_task = asyncio.create_task(restart_smart_shooter_listener())
|
|
|
# 等待所有任务完成
|
|
|
- await asyncio.gather(handler_task,listen_task)
|
|
|
+ await asyncio.gather(handler_task,listen_task, return_exceptions=True)
|
|
|
|
|
|
except WebSocketDisconnect:
|
|
|
print("Client disconnected")
|
|
|
+ except asyncio.CancelledError:
|
|
|
+ print("Connection cancelled")
|
|
|
finally:
|
|
|
- # 确保任务被正确取消
|
|
|
- if listen_task and not listen_task.done():
|
|
|
- listen_task.cancel()
|
|
|
+ # 确保任务被正确取消和清理
|
|
|
+ tasks_to_cancel = []
|
|
|
+
|
|
|
+ if handler_task and not handler_task.done():
|
|
|
+ tasks_to_cancel.append(handler_task)
|
|
|
+
|
|
|
if send_task and not send_task.done():
|
|
|
- send_task.cancel() # <--- 清理
|
|
|
+ tasks_to_cancel.append(send_task)
|
|
|
+
|
|
|
+ # 取消所有待处理的任务
|
|
|
+ for task in tasks_to_cancel:
|
|
|
+ task.cancel()
|
|
|
+
|
|
|
+ # 等待任务取消完成
|
|
|
+ if tasks_to_cancel:
|
|
|
+ await asyncio.gather(*tasks_to_cancel, return_exceptions=True)
|
|
|
+
|
|
|
+ # 清理连接
|
|
|
active_connections.discard(websocket)
|
|
|
+ print("WebSocket connection cleaned up")
|
|
|
|
|
|
|
|
|
async def start_smart_shooter_listen():
|
|
|
@@ -96,16 +112,9 @@ async def handler_messages(websocket):
|
|
|
socket_type = byteDats.get("type")
|
|
|
if socket_type == "websocket.disconnect":
|
|
|
print("socket_type===>", byteDats)
|
|
|
- smart_shooter.stop_listen = True
|
|
|
- smart_shooter.is_init_while = False
|
|
|
if byteDats.get("code") == 1006:
|
|
|
continue
|
|
|
- device_ctrl.close_connect()
|
|
|
- device_ctrl.close_lineConnect()
|
|
|
- device_ctrl.mcu_exit = True
|
|
|
- device_ctrl.p_list = []
|
|
|
- device_ctrl.temp_ports_dict = {}
|
|
|
- device_ctrl.clearMyInstance()
|
|
|
+ logger.info("socket强制断开")
|
|
|
diviceList = blue_tooth.devices
|
|
|
if len(diviceList) == 0:
|
|
|
blue_tooth.bluetooth_exit = True
|
|
|
@@ -136,24 +145,6 @@ async def handler_messages(websocket):
|
|
|
break
|
|
|
|
|
|
|
|
|
-# async def send_message(websocket):
|
|
|
-# print("构建消息监听 send_message")
|
|
|
-# while True:
|
|
|
-# try:
|
|
|
-# # 使用wait()而不是直接get()来避免阻塞
|
|
|
-# # 从异步队列中获取消息(在新事件循环中运行)
|
|
|
-# message = await message_queue.get()
|
|
|
-# # 发送消息
|
|
|
-# await websocket.send_json(message)
|
|
|
-# message_queue.task_done()
|
|
|
-# except asyncio.QueueEmpty:
|
|
|
-# continue
|
|
|
-# except asyncio.TimeoutError:
|
|
|
-# # 超时继续循环,避免永久阻塞
|
|
|
-# continue
|
|
|
-# except Exception as e:
|
|
|
-# print("socket报错",e)
|
|
|
-# break
|
|
|
async def message_generator():
|
|
|
"""异步生成器,用于从队列中获取消息"""
|
|
|
while True:
|